@ethersproject/units#formatUnits TypeScript Examples

The following examples show how to use @ethersproject/units#formatUnits. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TokenList.tsx    From useDApp with MIT License 6 votes vote down vote up
export function TokenList() {
  const { account, chainId } = useEthers()
  const { name, logoURI, tokens } = useTokenList(UNISWAP_DEFAULT_TOKEN_LIST_URI, chainId) || {}
  const balances = useTokensBalance(tokens, account)

  return (
    <List>
      <ListTitleRow>
        <ListTitle>{name}</ListTitle>
        {logoURI && <ListLogo src={toHttpPath(logoURI)} alt={`${name} logo`} />}
      </ListTitleRow>
      {tokens &&
        tokens.map((token, idx) => {
          const balance = balances[idx]
          return (
            <TokenItem key={token.address}>
              <TokenIconContainer>
                {token.logoURI && <TokenIcon src={token.logoURI} alt={`${token.symbol} logo`} />}
              </TokenIconContainer>
              <TokenName>{token.name}</TokenName>
              <TokenTicker>{token.symbol}</TokenTicker>
              {balance && !balance.error && (
                <TokenBalance>{formatUnits(balance.value[0], token.decimals)}</TokenBalance>
              )}
            </TokenItem>
          )
        })}
    </List>
  )
}
Example #2
Source File: utils.ts    From core with GNU General Public License v3.0 6 votes vote down vote up
export function toNumWei(val: BigNumber) {
  return parseFloat(formatUnits(val, 'wei'));
}
Example #3
Source File: utils.ts    From zora-v1-subgraph with MIT License 6 votes vote down vote up
export function toNumWei(val: BigNumber) {
  return parseFloat(formatUnits(val, 'wei'))
}
Example #4
Source File: index.ts    From snapshot-strategies with MIT License 6 votes vote down vote up
export async function strategy(
  space,
  network,
  provider,
  addresses,
  options,
  snapshot
) {
  const blockTag =
    typeof snapshot === 'number'
      ? snapshot
      : await provider.getBlockNumber(snapshot);

  // Early return 0 voting power if governanceStrategy or powerType is not correctly set
  if (!options.governanceStrategy || !powerTypesToMethod[options.powerType]) {
    return Object.fromEntries(addresses.map((address) => [address, '0']));
  }

  const response: BigNumber[] = await multicall(
    network,
    provider,
    abi,
    addresses.map((address: any) => [
      options.governanceStrategy,
      powerTypesToMethod[options.powerType],
      [address.toLowerCase(), blockTag]
    ]),
    { blockTag }
  );
  return Object.fromEntries(
    response.map((value, i) => [
      addresses[i],
      parseFloat(formatUnits(value.toString(), options.decimals))
    ])
  );
}
Example #5
Source File: transactions.ts    From pownft-miner with Apache License 2.0 6 votes vote down vote up
export async function mineAtom(instance: Contract, targetAtom: TargetAtom, gasPrice: BigNumber, dryRun: boolean) : Promise<TransactionResponse | false> {
    
    const value = targetAtom.cost;

    const prefix = dryRun ? '[DRY RUN] ' : '';

    console.log(`${prefix}Issuing tx to mine atom ${targetAtom.tokenId} for ${formatEther(value)} eth using gas ${formatUnits(gasPrice, 'gwei')} using nonce ${targetAtom.nonce.toString()}`);

    // this will simulate the tx on chain, if anyone has mined a block it will fail with a "revert: difficulty" message
    const gasLimit = await instance.estimateGas.mine(targetAtom.nonce, {value, gasPrice});

    if (dryRun) {
        return false;
    } else {
        return instance.mine(targetAtom.nonce, {value, gasPrice, gasLimit});
    }
    
}
Example #6
Source File: App.tsx    From ether-swr with MIT License 5 votes vote down vote up
TokenBalance = ({
  symbol,
  address,
  decimals
}: {
  symbol: string
  address: string
  decimals: number
}) => {
  const { account } = useWeb3React<Web3Provider>()

  const { data: balance, mutate } = useEtherSWR(
    [address, 'balanceOf', account],
    {
      subscribe: [
        // A filter from anyone to me
        {
          name: 'Transfer',
          topics: [null, account],
          on: (
            state: BigNumber,
            fromAddress: string,
            toAddress: string,
            amount: BigNumber,
            event: any
          ) => {
            console.log('receive', { event })
            const update = state.add(amount)
            mutate(update, false) // optimistic update skip re-fetch
          }
        },
        // A filter from me to anyone
        {
          name: 'Transfer',
          topics: [account, null],
          on: (
            state: BigNumber,
            fromAddress: string,
            toAddress: string,
            amount: BigNumber,
            event: any
          ) => {
            console.log('send', { event })
            const update = state.sub(amount)
            mutate(update, false) // optimistic update skip re-fetch
          }
        }
      ]
    }
  )

  if (!balance) {
    return <div>...</div>
  }

  return (
    <div>
      {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}
    </div>
  )
}
Example #7
Source File: index.ts    From snapshot-strategies with MIT License 5 votes vote down vote up
export async function strategy(_space, network, provider, addresses) {
  const walletQueryParams = {
    users: {
      __args: {
        where: {
          id_in: addresses.map((addr: string) => addr.toLowerCase())
        },
        first: 1000
      },
      id: true,
      gotchisOwned: {
        baseRarityScore: true,
        equippedWearables: true
      }
    }
  };
  const result = await subgraphRequest(AAVEGOTCHI_SUBGRAPH_URL[network], {
    ...itemPriceParams,
    ...walletQueryParams
  });
  const prices = {};
  result.itemTypes.map((itemInfo) => {
    const itemValue = parseFloat(formatUnits(itemInfo.ghstPrice, 18));
    if (itemValue > 0) prices[parseInt(itemInfo.svgId)] = itemValue;
  });

  const itemVotingPower = { '239': 100, '240': 100, '241': 100 };

  const walletScores = {};
  result.users.map((addrInfo) => {
    let gotchiWagieValue = 0;

    const { id, gotchisOwned } = addrInfo;

    if (gotchisOwned.length > 0)
      gotchisOwned.map((gotchi) => {
        gotchi.equippedWearables
          .filter(
            (itemId: number) => itemId == 239 || itemId == 240 || itemId == 241
          )
          .map((itemId) => {
            const votes = itemVotingPower[itemId.toString()];
            gotchiWagieValue += votes;
          });
      });

    const addr = addresses.find(
      (addrOption: string) => addrOption.toLowerCase() === id
    );
    walletScores[addr] = gotchiWagieValue;
  });
  addresses.map((addr) => {
    if (!walletScores[addr]) walletScores[addr] = 0;
  });

  return walletScores;
}