@ethersproject/bignumber#BigNumber TypeScript Examples

The following examples show how to use @ethersproject/bignumber#BigNumber. 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: util.test.ts    From bodhi.js with Apache License 2.0 7 votes vote down vote up
describe('utils', () => {
  it('works with positive numbers', () => {
    expect(toBN('1').toString()).to.equal('1');
    expect(toBN('0xff').toString()).to.equal('255');
    expect(toBN(123).toString()).to.equal('123');
    expect(toBN(BigNumber.from(123)).toString()).to.equal('123');
  });

  it('works with negative numbers', () => {
    expect(toBN('-1').toString()).to.equal('-1');
    expect(toBN(-123).toString()).to.equal('-123');
    expect(toBN(BigNumber.from(-123)).toString()).to.equal('-123');
  });
});
Example #2
Source File: limit-order-protocol.facade.ts    From limit-order-protocol-utils with MIT License 6 votes vote down vote up
nonce(makerAddress: string): Promise<number> {
        const callData = this.getContractCallData(
            LimitOrderProtocolMethods.nonce,
            [makerAddress]
        );

        return this.providerConnector
            .ethCall(this.contractAddress, callData)
            .then((nonce) => BigNumber.from(nonce).toNumber());
    }
Example #3
Source File: proposing.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
task("propose-multi", "Create a Safe tx proposal json file")
    .addPositionalParam("address", "Address or ENS name of the Safe to check", undefined, types.string)
    .addPositionalParam("txs", "Json file with transactions", undefined, types.inputFile)
    .addParam("multiSend", "Set to overwrite which multiSend address to use", "", types.string, true)
    .addParam("nonce", "Set nonce to use (will default to on-chain nonce)", "", types.string, true)
    .addParam("export", "If specified instead of executing the data will be exported as a json file for the transaction builder", undefined, types.string)
    .addParam("name", "Name to be used for the transaction builder json", undefined, types.string, true)
    .addFlag("onChainHash", "Get hash from chain (required for pre-1.3.0 version)")
    .setAction(async (taskArgs, hre) => {
        console.log(`Running on ${hre.network.name}`)
        const safe = await safeSingleton(hre, taskArgs.address)
        const safeAddress = await safe.resolvedAddress
        console.log(`Using Safe at ${safeAddress}`)
        const nonce = taskArgs.nonce || await safe.nonce()
        const txs = await loadMetaTransactions(taskArgs.txs)
        const chainId = (await safe.provider.getNetwork()).chainId
        if (taskArgs.export) {
            await writeTxBuilderJson(taskArgs.export, chainId.toString(), txs, taskArgs.name || "Custom Transactions")
            return
        } 
        const tx = await parseMultiSendJsonFile(hre, txs, BigNumber.from(nonce).toNumber(), taskArgs.multiSend)
        console.log("Safe transaction", tx)
        const safeTxHash = await calcSafeTxHash(safe, tx, chainId, taskArgs.onChainHash)
        const proposal: SafeTxProposal = {
            safe: safeAddress,
            chainId,
            safeTxHash,
            tx
        }
        await writeToCliCache(proposalFile(safeTxHash), proposal)
        console.log("Safe transaction hash:", safeTxHash)
        return safeTxHash
    });
Example #4
Source File: utils.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
U32MAX = BigNumber.from('0xffffffff')
Example #5
Source File: balanceOf.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export async function erc2020BalanceQuery<T extends Token>(
  tokenAddress: ERC20Addr | undefined,
  walletAddress: EVMAddr | undefined,
  fetcher: BalanceOfFetcher,
): Promise<T | undefined> {
  if (!walletAddress || !tokenAddress || !fetcher) {
    return;
  }

  const balance: BigNumber | undefined = await fetcher(
    tokenAddress,
    walletAddress,
  );

  if (!balance) {
    return;
  }

  return balance.toString() as u<T>;
}
Example #6
Source File: CLValue.ts    From clarity with Apache License 2.0 6 votes vote down vote up
public static fromBytes(bytes: Uint8Array): Result<U64> {
    const tmp = Uint8Array.from(bytes);
    if (bytes.length < 8) {
      return Result.Err(FromBytesError.EarlyEndOfStream);
    }
    const u64Bytes = tmp.subarray(0, 8);
    const rem = tmp.subarray(8);
    return Result.Ok(new U64(BigNumber.from(u64Bytes.reverse())), rem);
  }
Example #7
Source File: convertResults.ts    From defillama-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
function stringifyBigNumbers(result: any, final: any) {
  Object.keys(result).forEach((key) => {
    try {
      final[key] = lodash.cloneDeep(result[key]);
      if (
        BigNumber.isBigNumber(result[key]) ||
        typeof result[key] === "number"
      ) {
        final[key] = result[key].toString();
      }
      if (typeof final[key] === "object") {
        stringifyBigNumbers(result[key], final[key]);
      }
    } catch (e) {
      console.log(e);
    }
  });
}
Example #8
Source File: TotalSupply.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined {
  const contract = useTokenContract(token?.address, false)

  const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]

  return token && totalSupply ? new TokenAmount(token, totalSupply.toString()) : undefined
}
Example #9
Source File: feeModuleUtils.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
getStreamingFee = async(
  feeModule: StreamingFeeModule,
  setToken: Address,
  previousAccrueTimestamp: BigNumber,
  recentAccrueTimestamp: BigNumber,
  streamingFee?: BigNumber
): Promise<BigNumber> => {
  const feeState = await feeModule.feeStates(setToken);
  const accrualRate = streamingFee ? streamingFee : feeState.streamingFeePercentage;

  const timeElapsed = recentAccrueTimestamp.sub(previousAccrueTimestamp);
  return timeElapsed.mul(accrualRate).div(ONE_YEAR_IN_SECONDS);
}
Example #10
Source File: airdrop-thunk.ts    From lobis-frontend with MIT License 6 votes vote down vote up
claim = createAsyncThunk("airdrop/claim", async ({ index, proof, amount, merkleIndex, provider, address, networkID }: IClaimAirdrop, { dispatch }) => {
    if (!provider) {
        dispatch(warning({ text: messages.please_connect_wallet }));
        return;
    }
    const signer = provider.getSigner();
    const merkleDistributorContract = new ethers.Contract(addresses.merkleDistributor, abis.merkleDistributor, signer);
    let claimTx;
    try {
        const gasOptions = await getGasPrice(provider);
        claimTx = await merkleDistributorContract.claim(merkleIndex, index, BigNumber.from(amount), proof, { ...gasOptions });
    } catch (err: any) {
        dispatch(error({ text: messages.something_wrong, error: err.message }));
        return;
    } finally {
        if (claimTx) {
            dispatch(clearPendingTxn(claimTx.hash));
        }
    }
    const text = "Claiming";
    dispatch(fetchPendingTxns({ txnHash: claimTx.hash, text, type: "Airdrop Claim" }));
    dispatch(success({ text: messages.tx_successfully_send }));
    await claimTx.wait();
})
Example #11
Source File: permits.ts    From hypertext with GNU General Public License v3.0 6 votes vote down vote up
DAIPermitGatherer: PermitGathererFunction = async (address, deadline, _, library) => {
  const Permit = [
    { name: 'holder', type: 'address' },
    { name: 'spender', type: 'address' },
    { name: 'nonce', type: 'uint256' },
    { name: 'expiry', type: 'uint256' },
    { name: 'allowed', type: 'bool' },
  ]
  const domain = {
    name: 'Dai Stablecoin',
    version: '1',
  }
  const DAIContract = new Contract(
    DAI.address,
    ['function nonces(address holder) view returns (uint256 nonce)'],
    library
  )
  const nonce: BigNumber = await DAIContract.nonces(address)
  const message = {
    holder: address,
    spender: PERMIT_AND_CALL_ADDRESS,
    nonce: await Promise.resolve(nonce.toNumber()).catch(() => nonce.toString()),
    expiry: deadline,
    allowed: true, // DAI only allows unlimited approves
  }
  const inputs = ['address', 'address', 'uint256', 'uint256', 'bool', 'uint8', 'bytes32', 'bytes32']
  return {
    types: {
      EIP712Domain,
      Permit,
    },
    domain,
    message,
    permitSelector: hexDataSlice(id(`permit(${inputs.join(',')})`), 0, 4),
    getPermitData: ({ v, r, s }) =>
      defaultAbiCoder.encode(inputs, [address, PERMIT_AND_CALL_ADDRESS, nonce, deadline, true, v, r, s]),
  }
}
Example #12
Source File: TotalSupply.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined {
  const contract = useTokenContract(token?.address, false);

  const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')
    ?.result?.[0];

  return token && totalSupply
    ? new TokenAmount(token, totalSupply.toString())
    : undefined;
}
Example #13
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 #14
Source File: wearableSets.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
function sixteenBitArrayToUint(array: number[] | string[]) {
  const uint = [];
  for (let item of array) {
    if (typeof item === "string") {
      item = parseInt(item);
    }
    uint.unshift(item.toString(16).padStart(4, "0"));
  }
  if (array.length > 0) return BigNumber.from("0x" + uint.join(""));
  return BigNumber.from(0);
}
Example #15
Source File: poolId.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
splitPoolId = (
  poolId: string
): { address: string; specialization: PoolSpecialization; nonce: BigNumber } => {
  return {
    address: getPoolAddress(poolId),
    specialization: getPoolSpecialization(poolId),
    nonce: getPoolNonce(poolId),
  };
}
Example #16
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 #17
Source File: TotalSupply.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined {
  const contract = useTokenContract(token?.address, false)

  const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]

  return token && totalSupply ? new TokenAmount(token, totalSupply.toString()) : undefined
}
Example #18
Source File: useTotalSupply.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
function useTotalSupply(token?: Token): TokenAmount | undefined {
  const contract = useTokenContract(token?.address, false)

  const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]

  return token && totalSupply ? new TokenAmount(token, totalSupply.toString()) : undefined
}
Example #19
Source File: TotalSupply.ts    From goose-frontend-amm with GNU General Public License v3.0 6 votes vote down vote up
// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined {
  const contract = useTokenContract(token?.address, false)

  const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]

  return token && totalSupply ? new TokenAmount(token, totalSupply.toString()) : undefined
}
Example #20
Source File: limit-order-protocol.facade.ts    From limit-order-protocol-utils with MIT License 5 votes vote down vote up
parseRemainingResponse(response: string): BigNumber | null {
        if (response.length === 66) {
            return BigNumber.from(response);
        }

        return null;
    }
Example #21
Source File: consts.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
BIGNUMBER_ONE = BigNumber.from(1)
Example #22
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 #23
Source File: aaveLeverageStrategyIntegration.spec.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
rebalanceInterval = BigNumber.from(86400)