ethers#BigNumber TypeScript Examples

The following examples show how to use ethers#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: utilities.ts    From apeswap-swap-core with GNU General Public License v3.0 7 votes vote down vote up
export async function getApprovalDigest(
  token: Contract,
  approve: {
    owner: string
    spender: string
    value: BigNumber
  },
  nonce: BigNumber,
  deadline: BigNumber
): Promise<string> {
  const name = await token.name()
  const DOMAIN_SEPARATOR = getDomainSeparator(name, token.address)
  return keccak256(
    solidityPack(
      ['bytes1', 'bytes1', 'bytes32', 'bytes32'],
      [
        '0x19',
        '0x01',
        DOMAIN_SEPARATOR,
        keccak256(
          defaultAbiCoder.encode(
            ['bytes32', 'address', 'address', 'uint256', 'uint256', 'uint256'],
            [PERMIT_TYPEHASH, approve.owner, approve.spender, approve.value, nonce, deadline]
          )
        )
      ]
    )
  )
}
Example #2
Source File: submitting.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
task("submit-proposal", "Executes a Safe transaction")
    .addPositionalParam("hash", "Hash of Safe transaction to display", undefined, types.string)
    .addParam("signerIndex", "Index of the signer to use", 0, types.int, true)
    .addParam("signatures", "Comma seperated list of signatures", undefined, types.string, true)
    .addParam("gasPrice", "Gas price to be used", undefined, types.int, true)
    .addParam("gasLimit", "Gas limit to be used", undefined, types.int, true)
    .addFlag("buildOnly", "Flag to only output the final transaction")
    .setAction(async (taskArgs, hre) => {
        console.log(`Running on ${hre.network.name}`)
        const proposal: SafeTxProposal = await readFromCliCache(proposalFile(taskArgs.hash))
        const signers = await hre.ethers.getSigners()
        const signer = signers[taskArgs.signerIndex]
        const safe = await safeSingleton(hre, proposal.safe)
        const safeAddress = await safe.resolvedAddress
        console.log(`Using Safe at ${safeAddress} with ${signer.address}`)
        const currentNonce = await safe.nonce()
        if (!BigNumber.from(proposal.tx.nonce).eq(currentNonce)) {
            throw Error("Proposal does not have correct nonce!")
        }
        const signatureStrings: Record<string, string> = await loadSignatures(taskArgs.hash)
        const signatureArray = Object.values(signatureStrings)
        if (taskArgs.signatures) {
            signatureArray.push(taskArgs.signatures)
        }
        const signatures = await prepareSignatures(safe, proposal.tx, signatureArray.join(","), signer, taskArgs.hash)
        const populatedTx: PopulatedTransaction = await populateExecuteTx(safe, proposal.tx, signatures, { gasLimit: taskArgs.gasLimit, gasPrice: taskArgs.gasPrice })
        
        if (taskArgs.buildOnly) {
            console.log("Ethereum transaction:", populatedTx)
            return
        }
        
        const receipt = await signer.sendTransaction(populatedTx).then(tx => tx.wait())
        console.log("Ethereum transaction hash:", receipt.transactionHash)
        return receipt.transactionHash
    });
Example #3
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
getBalance = async (
    addressOrName: string | Promise<string>,
    _blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<BigNumber> => {
    await this.getNetwork();
    const blockTag = await this._ensureSafeModeBlockTagFinalization(_blockTag);

    const { address, blockHash } = await resolveProperties({
      address: this._getAddress(addressOrName),
      blockHash: this._getBlockHash(blockTag)
    });

    const substrateAddress = await this.getSubstrateAddress(address, blockHash);

    const accountInfo = await this.queryStorage<FrameSystemAccountInfo>(
      'system.account',
      [substrateAddress],
      blockHash
    );

    return convertNativeToken(BigNumber.from(accountInfo.data.free.toBigInt()), this.chainDecimal);
  };
Example #4
Source File: utilities.ts    From apeswap-swap-core with GNU General Public License v3.0 6 votes vote down vote up
export function expandTo18Decimals(n: number): BigNumber {
  return BigNumber.from(n).mul(BigNumber.from(10).pow(18))
}
Example #5
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
defaultValues: Record<
  SupportedAction,
  DeepPartial<DecodedAction>
> = {
  [SupportedAction.ERC20_TRANSFER]: {
    contract: ERC20Contract,
    decodedCall: {
      function: ERC20Contract.getFunction('transfer'),
      to: '',
      value: BigNumber.from(0),
      args: {
        _to: '',
        _value: BigNumber.from(0),
      },
    },
  },
  [SupportedAction.REP_MINT]: {
    contract: ERC20SnapshotRepContract,
    decodedCall: {
      function: ERC20SnapshotRepContract.getFunction('mint'),
      to: '',
      value: BigNumber.from(0),
      args: {
        to: '',
        amount: BigNumber.from(0),
      },
    },
  },

  [SupportedAction.GENERIC_CALL]: {},
}
Example #6
Source File: index.ts    From defillama-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function totalSupply(params: {
  target: Address;
  block?: number;
  decimals?: number;
  chain?: Chain;
}) {
  const contract = getContract(params.target, params.chain);
  const supply: BigNumber = await contract.totalSupply({
    blockTag: params.block ?? "latest",
  });
  return {
    output: handleDecimals(supply, params.decimals),
  };
}
Example #7
Source File: calculateEIGasCosts.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
async function getQuotes(
  positions: any[],
  inputToken: string,
  setAmount: number,
  wethStage: boolean,
) {
  const componentSwapInputToken = wethStage ? "WETH" : inputToken;
  const componentInputTokenAddress = TOKEN_ADDRESSES[componentSwapInputToken];
  const quotes = await getPositionQuotes(positions, componentInputTokenAddress, setAmount);
  if (wethStage) {
    const wethBuyAmount = quotes.reduce(
      (sum: BigNumber | number, quote: any) => BigNumber.from(quote.sellAmount).add(sum),
      0,
    );
    const wethQuote = await getQuote({
      buyToken: TOKEN_ADDRESSES["WETH"],
      sellToken: TOKEN_ADDRESSES[inputToken],
      buyAmount: wethBuyAmount.toString(),
    });
    quotes.push(wethQuote);
  }
  return quotes;
}
Example #8
Source File: index.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
indices: Indices = {
  "DPI": {
    "address": "0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b",
    "strategyInfo": dpiStrategyInfo,
    "path": buildPath("dpi"),
    calculateAssetAllocation(
      setToken: SetToken,
      strategyConstants: StrategyObject,
      setTokenValue: BigNumber
    ): Promise<RebalanceSummary[]> {
      return dpiAssetAllocation(setToken, strategyConstants, setTokenValue);
    },
  } as IndexInfo,
  "MVI": {
    address: "0x72e364f2abdc788b7e918bc238b21f109cd634d7",
    strategyInfo: mviStrategyInfo,
    path: buildPath("mvi"),
    calculateAssetAllocation(
      setToken: SetToken,
      strategyConstants: StrategyObject,
      setTokenValue: BigNumber
    ): Promise<RebalanceSummary[]> {
      return mviAssetAllocation(setToken, strategyConstants, setTokenValue);
    },
  } as IndexInfo,
}
Example #9
Source File: tally-poll.ts    From panvala with Apache License 2.0 6 votes vote down vote up
async function getZkSyncAccountBalance(address) {
  const provider = await getDefaultProvider('mainnet');
  let accountState = null;
  try {
    accountState = await zkSyncLimiter.schedule(() => provider.getState(address));
  } catch (err) {
    console.log(`Error while fetching zksync balance: ${err}`);
    throw err;
  }
  const balance = accountState.verified.balances.PAN;
  console.log(`Got zksync balance for ${address}`);
  return BigNumber.from(balance || 0);
}
Example #10
Source File: useTransactionDeadline.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
// combines the block timestamp with the user setting to give the deadline that should be used for any submitted transaction
export default function useTransactionDeadline(): BigNumber | undefined {
  const ttl = useSelector<AppState, number>((state) => state.user.userDeadline);
  const blockTimestamp = useCurrentBlockTimestamp();
  return useMemo(() => {
    if (blockTimestamp && ttl) return blockTimestamp.add(ttl);
    return undefined;
  }, [blockTimestamp, ttl]);
}
Example #11
Source File: Auth.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
estimateGas: {
    authority(overrides?: CallOverrides): Promise<BigNumber>;

    owner(overrides?: CallOverrides): Promise<BigNumber>;

    setAuthority(
      newAuthority: string,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<BigNumber>;

    setOwner(
      newOwner: string,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<BigNumber>;
  };
Example #12
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
getGasPrice = async (): Promise<BigNumber> => {
    // tx_fee_per_gas + (current_block / 30 + 5) << 16 + 10
    const txFeePerGas = BigNumber.from((this.api.consts.evm.txFeePerGas as UInt).toBigInt());
    const currentHeader = await this.api.rpc.chain.getHeader();
    const currentBlockNumber = BigNumber.from(currentHeader.number.toBigInt());

    return txFeePerGas.add(currentBlockNumber.div(30).add(5).shl(16)).add(10);
  };
Example #13
Source File: loans.ts    From pawnft with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Collects data about all loans
 * @returns {Promise<LoanWithMetadata[]>}
 */
async function collectAllLoans(): Promise<LoanWithMetadata[]> {
  // FIXME: hack to bypass OpenSea depencency
  // Retrieve metadata for all NFTs
  const client = new Redis(process.env.REDIS_URL);
  let request = await client.get("metadata");
  let metadata: Record<string, Record<string, string>> = {};
  if (request) {
    metadata = JSON.parse(request);
  }

  // Collect number of created loans
  const numLoans: BigNumber = await PawnBankRPC.numLoans();
  const numLoansInt: number = numLoans.toNumber();

  // Temporary array to store loan data
  let loans: LoanWithMetadata[] = [];

  // For each loan
  for (let i = 0; i < numLoansInt; i++) {
    // Collect loan information from contract
    const loan: any[] = await PawnBankRPC.pawnLoans(i);
    // Collect loan metadata from temporary Redis store
    const { name, description, imageURL } =
      metadata[`${loan[0].toLowerCase()}-${loan[3].toString()}`];

    // Push loan data
    loans.push({
      loanId: i,
      name,
      description,
      imageURL,
      tokenAddress: loan[0],
      tokenOwner: loan[1],
      lender: loan[2],
      tokenId: loan[3].toNumber(),
      interestRate: loan[4].toNumber(),
      loanAmount: parseEther(loan[5]),
      maxLoanAmount: parseEther(loan[6]),
      loanAmountDrawn: parseEther(loan[7]),
      firstBidTime: loan[8].toNumber(),
      lastBidTime: loan[9].toNumber(),
      historicInterest: parseEther(loan[10]),
      loanCompleteTime: loan[11].toNumber(),
    });
  }

  // Return loans (ordered by recency in creation)
  return loans.reverse();
}
Example #14
Source File: sniper.ts    From pool-sniper with The Unlicense 5 votes vote down vote up
// Maximum gas price to pay for tx inclusion
  gasPrice: BigNumber;
Example #15
Source File: ApeFactory.spec.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
describe('ApeFactory', () => {
  const provider = new MockProvider(
    { 
      ganacheOptions: {
        hardfork: 'istanbul',
        mnemonic: 'horn horn horn horn horn horn horn horn horn horn horn horn',
        gasLimit: 9999999
    }
  })
  const [wallet, other] = provider.getWallets()
  const loadFixture = createFixtureLoader([wallet], provider)

  let factory: Contract
  beforeEach(async () => {
    const fixture = await loadFixture(factoryFixture)
    factory = fixture.factory
  })

  it('feeTo, feeToSetter, allPairsLength', async () => {
    expect(await factory.feeTo()).to.eq(AddressZero)
    expect(await factory.feeToSetter()).to.eq(wallet.address)
    expect(await factory.allPairsLength()).to.eq(0)
  })

  async function createPair(tokens: [string, string]) {
    const bytecode = `0x${ApePair.bytecode}`
    const create2Address = getCreate2Address(factory.address, tokens, bytecode)
    await expect(factory.createPair(...tokens))
      .to.emit(factory, 'PairCreated')
      .withArgs(TEST_ADDRESSES[0], TEST_ADDRESSES[1], create2Address, BigNumber.from(1))

    await expect(factory.createPair(...tokens)).to.be.reverted // ApeSwap: PAIR_EXISTS
    await expect(factory.createPair(...tokens.slice().reverse())).to.be.reverted // ApeSwap: PAIR_EXISTS
    expect(await factory.getPair(...tokens)).to.eq(create2Address)
    expect(await factory.getPair(...tokens.slice().reverse())).to.eq(create2Address)
    expect(await factory.allPairs(0)).to.eq(create2Address)
    expect(await factory.allPairsLength()).to.eq(1)

    const pair = new Contract(create2Address, JSON.stringify(ApePair.abi), provider as any)
    expect(await pair.factory()).to.eq(factory.address)
    expect(await pair.token0()).to.eq(TEST_ADDRESSES[0])
    expect(await pair.token1()).to.eq(TEST_ADDRESSES[1])
  }

  it('createPair', async () => {
    await createPair(TEST_ADDRESSES)
  })

  it('createPair:reverse', async () => {
    await createPair(TEST_ADDRESSES.slice().reverse() as [string, string])
  })

  it('createPair:gas', async () => {
    const tx = await factory.createPair(...TEST_ADDRESSES)
    const receipt = await tx.wait()
    expect(receipt.gasUsed).to.eq(2505099)
  })

  it('setFeeTo', async () => {
    await expect(factory.connect(other).setFeeTo(other.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
    await factory.setFeeTo(wallet.address)
    expect(await factory.feeTo()).to.eq(wallet.address)
  })

  it('setFeeToSetter', async () => {
    await expect(factory.connect(other).setFeeToSetter(other.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
    await factory.setFeeToSetter(other.address)
    expect(await factory.feeToSetter()).to.eq(other.address)
    await expect(factory.setFeeToSetter(wallet.address)).to.be.revertedWith('ApeSwap: FORBIDDEN')
  })
})
Example #16
Source File: mainnet-deploy.ts    From BarnBridge-Barn with Apache License 2.0 5 votes vote down vote up
rewardsAmount = BigNumber.from(610000).mul(helpers.tenPow18)
Example #17
Source File: CommunityVault.test.ts    From BarnBridge-YieldFarming with Apache License 2.0 5 votes vote down vote up
describe("CommunityVault", function () {
    let bondToken: ERC20Mock;
    let communityVault: CommunityVault;
    let creator: Signer, owner: Signer, user: Signer;
    let creatorAddr: string, ownerAddr: string, userAddr: string;

    const distributedAmount: BigNumber = BigNumber.from(800000).mul(tenPow18);

    let snapshotId: any;

    before(async () => {
        [creator, owner, user] = await ethers.getSigners();
        creatorAddr = await creator.getAddress();
        ownerAddr = await owner.getAddress();
        userAddr = await user.getAddress();

        bondToken = (await deployContract("ERC20Mock")) as ERC20Mock;
        communityVault = (await deployContract("CommunityVault", [bondToken.address])) as CommunityVault;
    });

    beforeEach(async function () {
        snapshotId = await ethers.provider.send("evm_snapshot", []);
    });

    afterEach(async function () {
        await ethers.provider.send("evm_revert", [snapshotId]);
    });

    describe("General Contract checks", function () {
        it("should be deployed", async function () {
            expect(communityVault.address).to.not.equal(0);
            expect(bondToken.address).to.not.equal(0);
        });
    });

    describe("Contract Tests", function () {
        it("Mint bond tokens in community vault address", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            expect(await bondToken.balanceOf(communityVault.address)).to.be.equal(distributedAmount);
        });

        it("should fail if no owner tries to set allowance", async function () {
            await expect(communityVault.connect(user).setAllowance(userAddr, distributedAmount)).to.be.revertedWith(
                "Ownable: caller is not the owner"
            );
        });

        it("should set allowance as owner", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            await communityVault.connect(creator).setAllowance(userAddr, distributedAmount);
            expect(await bondToken.allowance(communityVault.address, userAddr)).to.be.equal(distributedAmount);
        });

        it("should transfer ownership", async function () {
            expect(await communityVault.owner()).to.be.equal(creatorAddr);
            await expect(communityVault.connect(creator).transferOwnership(ownerAddr)).to.emit(
                communityVault, "OwnershipTransferred");
            expect(await communityVault.owner()).to.be.equal(ownerAddr);
        });
    });

    describe("Events", function () {
        it("setAllowance emits SetAllowance", async function () {
            await bondToken.mint(communityVault.address, distributedAmount);
            await expect(communityVault.connect(creator).setAllowance(userAddr, distributedAmount))
                .to.emit(communityVault, "SetAllowance");
        });
    });
});
Example #18
Source File: updates.ts    From cookietrack-api with MIT License 5 votes vote down vote up
fetchPoolIDsFromFactory = async (factory: Address, currentBlock: number, ftm: ethers.providers.JsonRpcProvider, ftmBackup: ethers.providers.JsonRpcProvider) => {

  // Initializations:
  let creationEvents;
  let batchSize = 50;
  let startBatch = 0;
  let endBatch = batchSize;

  // Events Setup:
  let factoryEvents = new ethers.Contract(factory, ['event PoolCreated(address indexed pool)'], ftm);
  let factoryEventsBackup = new ethers.Contract(factory, ['event PoolCreated(address indexed pool)'], ftmBackup);

  // Fetching Pool IDs:
  try {
    while(!creationEvents) {
      try {
        creationEvents = await factoryEvents.queryFilter(factoryEvents.filters.PoolCreated());
      } catch {
        console.warn(`Retrying Pool Creation Query: ${factory}...`);
        creationEvents = await factoryEventsBackup.queryFilter(factoryEventsBackup.filters.PoolCreated());
      }
    }
    if(creationEvents.length <= batchSize) {
      let promises = creationEvents.map(event => (async () => {
        if(event.args) {
          let address: Address = event.args[0];
          let poolID = await query('ftm', address, beethovenx.poolABI, 'getPoolId', []);
          let lastChangeBlock = (<BigNumber>(await query('ftm', beethovenxVault, beethovenx.vaultABI, 'getPoolTokens', [poolID])).lastChangeBlock).toNumber();
          if(lastChangeBlock > currentBlock - beethovenMaxInactiveBlocks) {
            beethovenxPools.pools.push(poolID);
          }
        }
      })());
      await Promise.all(promises);
    } else {
      while(endBatch < creationEvents.length + batchSize) {
        let promises = creationEvents.slice(startBatch, endBatch).map(event => (async () => {
          if(event.args) {
            let address: Address = event.args[0];
            let poolID = await query('ftm', address, beethovenx.poolABI, 'getPoolId', []);
            let lastChangeBlock = (<BigNumber>(await query('ftm', beethovenxVault, beethovenx.vaultABI, 'getPoolTokens', [poolID])).lastChangeBlock).toNumber();
            if(lastChangeBlock > currentBlock - beethovenMaxInactiveBlocks) {
              beethovenxPools.pools.push(poolID);
            }
          }
        })());
        await Promise.all(promises);
        startBatch += batchSize;
        endBatch += batchSize;
      }
    }
    console.info(`Successfully fetched pool IDs for factory: ${factory}`);
  } catch(err) {
    console.error(err);
  }
}
Example #19
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
CallDetails: React.FC<ActionViewProps> = ({ decodedCall }) => {
  const theme = useTheme();

  function renderByParamType(type: string, value: any) {
    if (!type || !value) return null;

    if (type === 'address') {
      return (
        <UnstyledLink href="#">
          <ParamDetail>
            {value} <FiExternalLink size={16} />
          </ParamDetail>
        </UnstyledLink>
      );
    }

    if (type.startsWith('uint') || type.startsWith('int')) {
      return <ParamDetail>{BigNumber.from(value).toString()}</ParamDetail>;
    }

    return <ParamDetail>{value}</ParamDetail>;
  }

  return (
    <>
      <ActionParamRow>
        <Box>
          {decodedCall?.function?.name} (
          {decodedCall?.function?.inputs.map((param, index, params) => (
            <span key={index}>
              <ParamTag color={theme?.colors?.params?.[index]}>
                {param?.type}
              </ParamTag>
              {index < params.length - 1 && <span> , </span>}
            </span>
          ))}
          )
        </Box>
      </ActionParamRow>

      {decodedCall?.function?.inputs?.map((param, index) => (
        <ActionParamRow key={index}>
          <ParamTitleRow>
            <ParamTitleTag color={theme?.colors?.params?.[index]}>
              {param.name} <em>({param.type})</em>
            </ParamTitleTag>
            {param.type === 'bytes' && (
              <Button variant="secondary">Decode</Button>
            )}
          </ParamTitleRow>

          {renderByParamType(param.type, decodedCall?.args?.[param.name])}
        </ActionParamRow>
      ))}
    </>
  );
}
Example #20
Source File: general.ts    From defillama-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
export function handleDecimals(num: BigNumber, decimals?: number): string {
  if (decimals === undefined) {
    return num.toString();
  } else {
    return num.div(TEN.pow(decimals)).toString();
  }
}
Example #21
Source File: exchangeIssuanceUtils.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
getAllowances = async (tokens: (StandardTokenMock | WETH9)[], owner: string, spenders: string[]) => {
  const allowances: BigNumber[] = [];
  tokens.forEach(async token => {
    allowances.push(...await Promise.all(spenders.map(async address => await token.allowance(owner, address))));
  });
  return allowances;
}