@ethersproject/bignumber#BigNumberish TypeScript Examples

The following examples show how to use @ethersproject/bignumber#BigNumberish. 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: utils.ts    From bodhi.js with Apache License 2.0 7 votes vote down vote up
export function toBN(bigNumberis: BigNumberish = 0): BN {
  if (isU8a(bigNumberis)) {
    return u8aToBn(bigNumberis);
  }
  if (isHex(bigNumberis)) {
    return hexToBn(bigNumberis);
  }

  if (BigNumber.isBigNumber(bigNumberis)) {
    const hex = bigNumberis.toHexString();
    if (hex[0] === '-') {
      return new BN('-' + hex.substring(3), 16);
    }
    return new BN(hex.substring(2), 16);
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return new BN(bigNumberis as any);
}
Example #2
Source File: utils.ts    From nouns-monorepo with GNU General Public License v3.0 7 votes vote down vote up
getNounSeedFromBlockHash = (nounId: BigNumberish, blockHash: string): NounSeed => {
  const pseudorandomness = solidityKeccak256(['bytes32', 'uint256'], [blockHash, nounId]);
  return {
    background: getPseudorandomPart(pseudorandomness, bgcolors.length, 0),
    body: getPseudorandomPart(pseudorandomness, bodies.length, 48),
    accessory: getPseudorandomPart(pseudorandomness, accessories.length, 96),
    head: getPseudorandomPart(pseudorandomness, heads.length, 144),
    glasses: getPseudorandomPart(pseudorandomness, glasses.length, 192),
  };
}
Example #3
Source File: utils.ts    From evm-provider.js with Apache License 2.0 7 votes vote down vote up
export function toBN(bigNumberis: BigNumberish = 0): BN {
  if (isU8a(bigNumberis)) {
    return u8aToBn(bigNumberis);
  }
  if (isHex(bigNumberis)) {
    return hexToBn(bigNumberis);
  }

  if (BigNumber.isBigNumber(bigNumberis)) {
    const hex = bigNumberis.toHexString();
    if (hex[0] === '-') {
      return new BN('-' + hex.substring(3), 16);
    }
    return new BN(hex.substring(2), 16);
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return new BN(bigNumberis as any);
}
Example #4
Source File: DeployUtil.ts    From clarity with Apache License 2.0 6 votes vote down vote up
/**
   * Constructor for Transfer deploy item.
   * @param amount The number of motes to transfer
   * @param target URef of the target purse or the public key of target account. You could generate this public key from accountHex by PublicKey.fromHex
   * @param sourcePurse URef of the source purse. If this is omitted, the main purse of the account creating this \
   * transfer will be used as the source purse
   * @param id user-defined transfer id
   */
  public static newTransfer(
    amount: BigNumberish,
    target: URef | PublicKey,
    sourcePurse?: URef,
    id: number | null = null
  ) {
    const runtimeArgs = RuntimeArgs.fromMap({});
    runtimeArgs.insert('amount', CLValue.u512(amount));
    if (sourcePurse) {
      runtimeArgs.insert('source', CLValue.uref(sourcePurse));
    }
    if (target instanceof URef) {
      runtimeArgs.insert('target', CLValue.uref(target));
    } else if (target instanceof PublicKey) {
      runtimeArgs.insert('target', CLValue.byteArray(target.toAccountHash()));
    } else {
      throw new Error('Please specify target');
    }
    if (!id) {
      runtimeArgs.insert('id', CLValue.option(null, CLTypeHelper.u64()));
    } else {
      runtimeArgs.insert(
        'id',
        CLValue.option(CLTypedAndToBytesHelper.u64(id), CLTypeHelper.u64())
      );
    }
    return ExecutableDeployItem.fromExecutableDeployItemInternal(
      new Transfer(runtimeArgs)
    );
  }
Example #5
Source File: deployExternal.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
public async deployCERc20(
    underlying: Address,
    comptroller: Address,
    interestRateModel: Address,
    initialExchangeRateMantissa: BigNumberish,
    name: string,
    symbol: string,
    decimals: BigNumberish
  ): Promise<CERc20> {
    return await new CERc20__factory(this._deployerSigner).deploy(
      underlying,
      comptroller,
      interestRateModel,
      initialExchangeRateMantissa,
      name,
      symbol,
      decimals,
    );
  }
Example #6
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function formatCompact(
  unformatted: number | string | BigNumber | BigNumberish | undefined | null,
  decimals = 18,
  maximumFractionDigits: number | undefined = 3,
  maxPrecision: number | undefined = 4,
): string {
  const formatter = Intl.NumberFormat('en', {
    notation: 'compact',
    maximumFractionDigits,
  });

  if (!unformatted) return '0';

  if (unformatted === Infinity) return '∞';

  let formatted: string | number = Number(unformatted);

  if (unformatted instanceof BigNumber) {
    formatted = Number(formatUnits(unformatted.toString(), decimals));
  }

  return formatter.format(Number(formatted.toPrecision(maxPrecision)));
}
Example #7
Source File: itemTypeHelpers.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
export function getItemTypes(
  itemTypes: ItemTypeInputNew[],
  ethers: any
): ItemTypeOutput[] {
  const result = [];
  for (const itemType of itemTypes) {
    let maxQuantity: number = rarityLevelToMaxQuantity(itemType.rarityLevel);

    let itemTypeOut: ItemTypeOutput = {
      ...itemType,
      slotPositions: stringToSlotPositions(itemType.slotPositions),
      ghstPrice: ethers.utils.parseEther(
        rarityLevelToGhstPrice(itemType.rarityLevel)
      ),
      rarityScoreModifier: calculateRarityScoreModifier(maxQuantity),
      maxQuantity: maxQuantity,
      totalQuantity: 0, //New items always start at 0
      name: itemType.name.trim(), //Trim the name to remove empty spaces
    };

    const reducer = (prev: BigNumberish, cur: BigNumberish) =>
      Number(prev) + Math.abs(Number(cur));
    let traitBoosters = itemType.traitModifiers.reduce(reducer, 0);

    if (itemType.category !== 1) {
      if (traitBoosters !== rarityLevelToTraitBoosters(itemType.rarityLevel)) {
        throw Error(`Trait Booster for ${itemType.name} does not match rarity`);
      }
    }

    if (!Array.isArray(itemType.allowedCollaterals)) {
      throw Error("Is not array.");
    }
    result.push(itemTypeOut);
  }
  return result;
}
Example #8
Source File: encoder.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Encodes the userData parameter for joining a StablePool with exact token inputs
   * @param amountsIn - the amounts each of token to deposit in the pool as liquidity
   * @param minimumBPT - the minimum acceptable BPT to receive in return for deposited tokens
   */
  static joinExactTokensInForBPTOut = (amountsIn: BigNumberish[], minimumBPT: BigNumberish): string =>
    defaultAbiCoder.encode(
      ['uint256', 'uint256[]', 'uint256'],
      [StablePoolJoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, minimumBPT]
    );
Example #9
Source File: Numeric.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
constructor(
    bitSize: number,
    isSigned: boolean,
    value: BigNumberish,
    originalBytes?: Uint8Array
  ) {
    super();
    if (isSigned === false && Math.sign(value as number) < 0) {
      throw new Error("Can't provide negative numbers with isSigned=false");
    }
    if (originalBytes) {
      this.originalBytes = originalBytes;
    }
    this.bitSize = bitSize;
    this.signed = isSigned;
    this.data = BigNumber.from(value);
  }
Example #10
Source File: deployOz.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
async function deployTimelock(
  signer: Signer | providers.JsonRpcSigner,
  minDelay: BigNumberish,
  proposers: string[],
  executors: string[]
): Promise<TimelockController> {
  const factory = new TimelockControllerFactory(signer);
  return factory.deploy(minDelay, proposers, executors);
}
Example #11
Source File: utils.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
shiftRightAndCast = (
  value: BigNumberish,
  shiftAmount: number,
  uintSize: number,
): string => {
  const shifted = BigNumber.from(value).shr(shiftAmount).toHexString();
  return `0x${shifted.substring(shifted.length - uintSize / 4)}`;
}
Example #12
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the storage from a block.
   * @param addressOrName The address to retrieve the storage from
   * @param position
   * @param blockTag The block to retrieve the storage from, defaults to head
   * @returns The storage data as a hash
   */
  async getStorageAt(
    addressOrName: string | Promise<string>,
    position: BigNumberish | Promise<BigNumberish>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    await this.resolveApi;

    const address = await this._resolveEvmAddress(addressOrName);
    const blockHash = await this._resolveBlockHash(blockTag);

    const code = blockHash
      ? await this.api.query.evm.accountStorages.at(blockHash, address)
      : await this.api.query.evm.accountStorages(address);

    return code.toHex();
  }
Example #13
Source File: abi.ts    From snapshot-plugins with MIT License 6 votes vote down vote up
export function getERC20TokenTransferTransactionData(
  recipientAddress: string,
  amount: BigNumberish
): string {
  const contractInterface = new Interface(ERC20_ABI);
  return contractInterface.encodeFunctionData('transfer', [
    recipientAddress,
    amount
  ]);
}
Example #14
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
): Promise<Record<string, number>> {
  const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';

  const multi = new Multicaller(network, provider, abi, { blockTag });
  addresses.forEach((address) =>
    multi.call(address, options.vault, 'getInternalBalance', [
      address,
      [options.token]
    ])
  );
  const result: Record<string, BigNumberish> = await multi.execute();

  return Object.fromEntries(
    Object.entries(result).map(([address, balance]) => [
      address,
      parseFloat(formatUnits(balance[0], options.decimals))
    ])
  );
}
Example #15
Source File: amounts.ts    From sdk with ISC License 6 votes vote down vote up
export function valueEther(wei: BigNumberish, opts?: RoundingOptions): string {
    const weiVal = BigNumber.from(wei);
    let amtEther: string = formatEther(weiVal);

    opts = opts ?? { round: false, places: PLACES };
    const {round, places=PLACES} = opts;

    if (round) {
        let exp = 18-places;
        let pow = BigNumber.from(10).pow(exp);

        let remainder = weiVal.mod(pow);
        amtEther = formatEther(weiVal.sub(remainder));
    }

    return amtEther
}
Example #16
Source File: serializeTransaction.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
function formatNumber(value: BigNumberish, name: string): Uint8Array {
  const result = stripZeros(BigNumber.from(value).toHexString());
  if (result.length > 32) {
    logger.throwArgumentError('invalid length for ' + name, 'transaction:' + name, value);
  }
  return result;
}
Example #17
Source File: CLValue.ts    From clarity with Apache License 2.0 5 votes vote down vote up
protected constructor(bitSize: number, signed: boolean, value: BigNumberish) {
    super();
    this.name = (signed ? 'i' : 'u') + bitSize;
    this.bitSize = bitSize;
    this.signed = signed;
    this.val = BigNumber.from(value);
  }
Example #18
Source File: deployExternal.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
public async deployWhitePaperInterestRateModel(
    baseRate: BigNumberish,
    multiplier: BigNumberish
  ): Promise<WhitePaperInterestRateModel> {
    return await new WhitePaperInterestRateModel__factory(this._deployerSigner).deploy(baseRate, multiplier);
  }
Example #19
Source File: encoder.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Encodes the userData parameter for providing the initial liquidity to a StablePool
   * @param initialBalances - the amounts of tokens to send to the pool to form the initial balances
   */
  static joinInit = (amountsIn: BigNumberish[]): string =>
    defaultAbiCoder.encode(['uint256', 'uint256[]'], [StablePoolJoinKind.INIT, amountsIn]);
Example #20
Source File: ByteConverters.ts    From casper-js-sdk with Apache License 2.0 5 votes vote down vote up
toBytesNumber = (bitSize: number, signed: boolean) => (
  value: BigNumberish
): Uint8Array => {
  const val = BigNumber.from(value);

  // Check bounds are safe for encoding
  const maxUintValue = MaxUint256.mask(bitSize);

  if (signed) {
    const bounds = maxUintValue.mask(bitSize - 1); // 1 bit for signed
    if (val.gt(bounds) || val.lt(bounds.add(One).mul(NegativeOne))) {
      throw new Error('value out-of-bounds, value: ' + value);
    }
  } else if (val.lt(Zero) || val.gt(maxUintValue.mask(bitSize))) {
    throw new Error('value out-of-bounds, value: ' + value);
  }

  const valTwos = val.toTwos(bitSize).mask(bitSize);

  const bytes = arrayify(valTwos);

  if (valTwos.gte(0)) {
    // for positive number, we had to deal with paddings
    if (bitSize > 64) {
      // if zero just return zero
      if (valTwos.eq(0)) {
        return bytes;
      }
      // for u128, u256, u512, we have to and append extra byte for length
      return concat([bytes, Uint8Array.from([bytes.length])])
        .slice()
        .reverse();
    } else {
      // for other types, we have to add padding 0s
      const byteLength = bitSize / 8;
      return concat([
        bytes.slice().reverse(),
        new Uint8Array(byteLength - bytes.length)
      ]);
    }
  } else {
    return bytes.reverse();
  }
}