@ethersproject/units#parseUnits TypeScript Examples

The following examples show how to use @ethersproject/units#parseUnits. 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: index.ts    From pownft-miner with Apache License 2.0 6 votes vote down vote up
function loadConfig() : Config {

    const targetFile = join(__dirname, '..', 'config.json');
    const config = JSON.parse(readFileSync(targetFile) as any);
    const accountPath = `m/44'/60'/0'/0/${config.index}`;

    const provider = new JsonRpcProvider(config.provider);
    const wallet = Wallet.fromMnemonic(config.mnemonic, accountPath).connect(provider);

    const gasLimit = parseUnits(BigNumber.from(config.gasLimit).toString(), 'gwei');

    return {
        provider,
        signer: wallet,
        numCores: config.numCores,
        gasLimit,
        chunkSize: config.chunkSize,
        dryRun: config.dryRun,
    }    
}
Example #2
Source File: graphUtils.ts    From snapshot-strategies with MIT License 6 votes vote down vote up
// mapping of addresses to scores

/**
 * Pass in a BigDecimal and BigNumber from a subgraph query, and return the multiplication of
 * them as a BigNumber
 * */
export function bdMulBn(bd: string, bn: string): BigNumber {
  const splitDecimal = bd.split('.');
  let split;
  // Truncate the BD so it can be converted to a BN (no decimals) when multiplied by WEI
  if (splitDecimal.length > 1) {
    split = `${splitDecimal[0]}.${splitDecimal[1].slice(0, 18)}`;
  } else {
    // Didn't have decimals, even though it was BigDecimal (i.e. "2")
    return BigNumber.from(bn).mul(BigNumber.from(bd));
  }

  // Convert it to BN
  const bdWithWEI = parseUnits(split, 18);

  // Multiple, then divide by WEI to have it back in BN
  return BigNumber.from(bn).mul(bdWithWEI).div(bnWEI);
}
Example #3
Source File: index.ts    From snapshot-strategies with MIT License 6 votes vote down vote up
// Returns a BigDecimal as a BigNumber with 10^decimals extra zeros
export function bdToBn(bd, decimals) {
  let bn;
  const splitDecimal = bd.split('.');

  if (splitDecimal.length > 1) {
    bn = `${splitDecimal[0]}.${splitDecimal[1].slice(
      0,
      decimals - splitDecimal[0].length - 1
    )}`;
  } else {
    bn = `${splitDecimal[0]}`;
  }

  const bn2 = parseUnits(bn, decimals);
  return bn2;
}
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 : 'latest';

  const queries: any[] = [];

  addresses.forEach((voter) => {
    queries.push([options.address, 'sharesOf', [voter]]);
  });
  queries.push([options.address, 'getPricePerFullShare']);

  const response = (
    await multicall(network, provider, abi, queries, { blockTag })
  ).map((r) => r[0]);
  const sharePrice = response[response.length - 1];

  return Object.fromEntries(
    Array(addresses.length)
      .fill('x')
      .map((_, i) => {
        const balanceBN = response[i].mul(sharePrice).div(parseUnits('1', 18));
        return [addresses[i], parseFloat(formatUnits(balanceBN, 18))];
      })
  );
}
Example #5
Source File: hooks.ts    From sushiswap-exchange with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #6
Source File: useGetBridgeEstimate.ts    From sdk with ISC License 6 votes vote down vote up
function fixAmt(ether: BigNumber, token: Token, chainId: number): BigNumber {
    const decimals = token.decimals(chainId) ?? 18;

    if (decimals === 18) {
        return parseEther(ether.toString())
    }

    const unit = unitNames[decimals];

    return parseUnits(ether.toString(), unit)
}
Example #7
Source File: hooks.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return
}
Example #8
Source File: hooks.ts    From luaswap-interface with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : currency === TOMO
        ? CurrencyAmount.tomo(JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #9
Source File: hooks.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #10
Source File: hooks.ts    From panther-frontend-dex with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #11
Source File: hooks.ts    From pancake-swap-interface-v1 with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #12
Source File: hooks.ts    From pancakeswap-testnet with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #13
Source File: hooks.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #14
Source File: hooks.ts    From pancake-swap-testnet with MIT License 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #15
Source File: hooks.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #16
Source File: hooks.ts    From goose-frontend-amm with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.info(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #17
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(
  value?: string,
  currency?: Currency,
): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined;
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString();
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed));
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error);
  }
  // necessary for all paths to return a value
  return undefined;
}
Example #18
Source File: hooks.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #19
Source File: hooks.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #20
Source File: hooks.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount<T extends Currency>(
  value?: string,
  currency?: T
): CurrencyAmount<T> | undefined {
  if (!value || !currency) {
    return undefined;
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString();

    if (typedValueParsed !== "0") {
      return CurrencyAmount.fromRawAmount(
        currency,
        JSBI.BigInt(typedValueParsed)
      );
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error);
  }
  // necessary for all paths to return a value
  return undefined;
}
Example #21
Source File: EthService.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
async getSafeGasPrice(): Promise<BigNumber> {
        for (let i = 0; i < 3; i++) {
            const gasPrice = Big((await this.provider.getGasPrice()).toString())
            if (gasPrice.gt(Big(0))) {
                return parseUnits(
                    gasPrice
                        .mul(1.0001) // add 20% markup so the tx is more likely to pass
                        .toFixed(0),
                    0,
                )
            }
        }
        throw new Error("GasPrice is 0")
    }
Example #22
Source File: hooks.ts    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #23
Source File: hooks.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
// try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined {
  if (!value || !currency) {
    return undefined
  }
  try {
    const typedValueParsed = parseUnits(value, currency.decimals).toString()
    if (typedValueParsed !== '0') {
      return currency instanceof Token
        ? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
        : CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
    }
  } catch (error) {
    // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
    console.debug(`Failed to parse input amount: "${value}"`, error)
  }
  // necessary for all paths to return a value
  return undefined
}
Example #24
Source File: index.ts    From snapshot-strategies with MIT License 5 votes vote down vote up
export async function strategy(
  space,
  network,
  provider,
  addresses,
  options,
  snapshot
) {
  const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';

  const multi = new Multicaller(network, provider, abi, { blockTag });

  multi.call('cafeswapBalance', options.token, 'balanceOf', [options.cafeswap]);
  multi.call('jetfuelBalance', options.token, 'balanceOf', [options.jetfuel]);
  multi.call('jetfuelTotalSupply', options.jetfuel, 'totalSupply');
  multi.call('autofarmBalance', options.token, 'balanceOf', [options.autofarm]);
  multi.call('pancakeBalance', options.token, 'balanceOf', [options.pancake]);
  multi.call('pancakeTotalSupply', options.pancake, 'totalSupply');
  multi.call('pricePerFullShare', options.jetfuel, 'getPricePerFullShare');
  addresses.forEach((address) => {
    multi.call(
      `scores.${address}.totalStaked`,
      options.sharePool,
      'totalStakedFor',
      [address]
    );
    multi.call(`scores.${address}.pancake`, options.pancake, 'balanceOf', [
      address
    ]);
    multi.call(`scores.${address}.jetfuel`, options.jetfuel, 'balanceOf', [
      address
    ]);
    multi.call(`scores.${address}.balance`, options.token, 'balanceOf', [
      address
    ]);
  });

  const result = await multi.execute();
  const dittoPerLP = result.pancakeBalance;
  const autofarmBalance = result.autofarmBalance;
  const cafeswapBalance = result.cafeswapBalance;
  const pricePerFullShare = result.pricePerFullShare;

  return Object.fromEntries(
    Array(addresses.length)
      .fill('')
      .map((_, i) => {
        const lpBalances = result.scores[addresses[i]].pancake;
        const lpBalancesJetFuel = result.scores[addresses[i]].jetfuel;
        const stakedLpBalances = result.scores[addresses[i]].totalStaked;
        const tokenBalances = result.scores[addresses[i]].balance;
        const lpBalance = lpBalances.add(stakedLpBalances);
        const dittoLpBalance = lpBalance
          .add(tokenBalances)
          .mul(dittoPerLP)
          .div(parseUnits('1', 9));
        const dittoFuelBalance = lpBalancesJetFuel.mul(pricePerFullShare);
        return [
          addresses[i],
          parseFloat(
            formatUnits(
              dittoLpBalance
                .add(dittoFuelBalance)
                .add(autofarmBalance)
                .add(cafeswapBalance),
              options.decimals
            )
          )
        ];
      })
  );
}
Example #25
Source File: index.ts    From snapshot-strategies with MIT License 5 votes vote down vote up
export async function strategy(
  space,
  network,
  provider,
  addresses,
  options,
  snapshot
) {
  const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';

  const multi = new Multicaller(network, provider, abi, { blockTag });
  multi.call('micLP.phoon', options.token, 'balanceOf', [options.micLP]);
  multi.call('micLP.totalSupply', options.micLP, 'totalSupply');
  multi.call('usdtLP.phoon', options.token, 'balanceOf', [options.usdtLP]);
  multi.call('usdtLP.totalSupply', options.usdtLP, 'totalSupply');
  addresses.forEach((address) => {
    multi.call(`balance.${address}`, options.token, 'balanceOf', [address]);
    multi.call(`micLP.${address}.balance`, options.micLP, 'balanceOf', [
      address
    ]);
    multi.call(`micLP.${address}.staked`, options.micRewardPool, 'balanceOf', [
      address
    ]);
    multi.call(`usdtLP.${address}.balance`, options.usdtLP, 'balanceOf', [
      address
    ]);
    multi.call(
      `usdtLP.${address}.staked`,
      options.usdtRewardPool,
      'balanceOf',
      [address]
    );
  });
  const result = await multi.execute();

  const phoonPerMicLP = parseUnits(result.micLP.phoon.toString(), 18).div(
    result.micLP.totalSupply
  );
  const phoonPerUsdtLP = parseUnits(result.usdtLP.phoon.toString(), 18).div(
    result.usdtLP.totalSupply
  );

  return Object.fromEntries(
    Array(addresses.length)
      .fill('')
      .map((_, i) => {
        const micPhoon = result.micLP[addresses[i]].balance
          .add(result.micLP[addresses[i]].staked)
          .mul(phoonPerMicLP)
          .div(parseUnits('1', 18));
        const usdtPhoon = result.usdtLP[addresses[i]].balance
          .add(result.usdtLP[addresses[i]].staked)
          .mul(phoonPerUsdtLP)
          .div(parseUnits('1', 18));
        const score = result.balance[addresses[i]].add(micPhoon).add(usdtPhoon);
        return [addresses[i], parseFloat(formatUnits(score, 18))];
      })
  );
}
Example #26
Source File: amounts.ts    From sdk with ISC License 5 votes vote down vote up
export function valueWei(ether: BigNumberish, decimals: number): BigNumber {
    return parseUnits(
        BigNumber.from(ether).toString(),
        decimals
    )
}
Example #27
Source File: token.ts    From sdk with ISC License 5 votes vote down vote up
etherToWei(amt: BigNumberish, chainId: number): BigNumber {
        let etherStr: string = amt instanceof BigNumber
            ? amt.toString()
            : BigNumber.from(amt).toString();

        return parseUnits(etherStr, this.decimals(chainId) ?? 18)
    }
Example #28
Source File: config.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
MINT_COST = parseUnits('1')
Example #29
Source File: config.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
REGISTER_COST = parseUnits('0.5')