ethers#BigNumberish TypeScript Examples

The following examples show how to use ethers#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: utilities.ts    From hypervisor with The Unlicense 7 votes vote down vote up
export function encodePriceSqrt(reserve1: BigNumberish, reserve0: BigNumberish): BigNumber {
    return BigNumber.from(
        new bn(reserve1.toString())
            .div(reserve0.toString())
            .sqrt()
            .multipliedBy(new bn(2).pow(96))
            .integerValue(3)
            .toString()
    )
}
Example #2
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
getStorageAt = async (
    addressOrName: string | Promise<string>,
    position: BigNumberish | Promise<BigNumberish>,
    _blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> => {
    await this.getNetwork();
    const blockTag = await this._ensureSafeModeBlockTagFinalization(_blockTag);

    // @TODO resolvedPosition
    const { address, blockHash, resolvedPosition } = await resolveProperties({
      address: this._getAddress(addressOrName),
      blockHash: this._getBlockHash(blockTag),
      resolvedPosition: Promise.resolve(position).then((p) => hexValue(p))
    });

    const code = await this.queryStorage('evm.accountStorages', [address, position], blockHash);

    return code.toHex();
  };
Example #3
Source File: IssuanceExtensionAPI.ts    From set.js with Apache License 2.0 6 votes vote down vote up
/**
   * Generates `moduleAndExtensionInitialization` bytecode to be passed as an element in the
   * `initializeBytecode` array for the `initializeAsync` method.
   *
   * @param delegatedManagerAddress      Instance of deployed delegatedManager to initialize the IssuanceExtension for
   * @param maxManagerFee                Maximum fee that can be charged on issue and redeem
   * @param managerIssueFee              Fee to charge on issuance
   * @param managerRedeemFee             Fee to charge on redemption
   * @param feeRecipient                 Address to send fees to
   * @param managerIssuanceHook          Address of contract implementing pre-issuance hook function (ex: SupplyCapHook)
   *
   * @return                             Initialization bytecode
   */
  public getIssuanceModuleAndExtensionInitializationBytecode(
    delegatedManagerAddress: Address,
    maxManagerFee: BigNumberish,
    managerIssueFee: BigNumberish,
    managerRedeemFee: BigNumberish,
    feeRecipientAddress: Address,
    managerIssuanceHookAddress: Address
  ): BytesLike {
    this.assert.schema.isValidAddress('delegatedManagerAddress', delegatedManagerAddress);
    this.assert.schema.isValidNumber('maxManagerFee', maxManagerFee);
    this.assert.schema.isValidNumber('managerIssueFee', managerIssueFee);
    this.assert.schema.isValidNumber('managerRedeemFee', managerRedeemFee);
    this.assert.schema.isValidAddress('feeRecipientAddress', feeRecipientAddress);
    this.assert.schema.isValidAddress('managerIssuanceHookAddress', managerIssuanceHookAddress);

    const moduleInterface = new EthersUtils.Interface(IssuanceExtension__factory.abi);
    return moduleInterface.encodeFunctionData('initializeModuleAndExtension', [
      delegatedManagerAddress,
      maxManagerFee,
      managerIssueFee,
      managerRedeemFee,
      feeRecipientAddress,
      managerIssuanceHookAddress,
    ]);
  }
Example #4
Source File: ISwapRouter.d.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
exactInput(
    params: {
      path: BytesLike
      recipient: string
      deadline: BigNumberish
      amountIn: BigNumberish
      amountOutMinimum: BigNumberish
    },
    overrides?: PayableOverrides
  ): Promise<ContractTransaction>
Example #5
Source File: registry.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks that locally generated input tokens array matches one returned from ethers
 * Difficult to compare BNs in an array like this to numbers which is why you need this function.
 */
export function assertInputTokensMatch(
  inputTokens: {
    l2Token: string;
    amount: BigNumberish;
  }[],
  requestInputTokens: {
    l2Token: string;
    amount: BigNumber;
  }[]
) {
  inputTokens.length.should.equal(requestInputTokens.length);

  for (let i = 0; i < inputTokens.length; i++) {
    const inputToken = inputTokens[i];
    const requestInputToken = requestInputTokens[i];

    inputToken.amount.toString().should.equal(requestInputToken.amount.toString());

    inputToken.l2Token.should.equal(requestInputToken.l2Token);
  }
}
Example #6
Source File: ISwapRouter.d.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
'exactInput(tuple)'(
    params: {
      path: BytesLike
      recipient: string
      deadline: BigNumberish
      amountIn: BigNumberish
      amountOutMinimum: BigNumberish
    },
    overrides?: PayableOverrides
  ): Promise<ContractTransaction>
Example #7
Source File: MockStrategy__factory.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
getDeployTransaction(
    _executionManager: string,
    _riskLevel: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): TransactionRequest {
    return super.getDeployTransaction(
      _executionManager,
      _riskLevel,
      overrides || {}
    );
  }
Example #8
Source File: ISwapRouter.d.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
exactInputSingle(
    params: {
      tokenIn: string
      tokenOut: string
      fee: BigNumberish
      recipient: string
      deadline: BigNumberish
      amountIn: BigNumberish
      amountOutMinimum: BigNumberish
      sqrtPriceLimitX96: BigNumberish
    },
    overrides?: PayableOverrides
  ): Promise<ContractTransaction>
Example #9
Source File: MockStrategy.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
callStatic: {
    counter(overrides?: CallOverrides): Promise<BigNumber>;

    registerSelfAsStrategy(
      _riskLevel: BigNumberish,
      overrides?: CallOverrides
    ): Promise<void>;

    thisFunctionWillEmulateAMaliciousExternalContractTryingToStealRelayerTokens(
      token: string,
      amount: BigNumberish,
      overrides?: CallOverrides
    ): Promise<void>;

    thisFunctionWillHardRevert(overrides?: CallOverrides): Promise<void>;

    thisFunctionWillModifyState(overrides?: CallOverrides): Promise<void>;

    thisFunctionWillNotRevert(overrides?: CallOverrides): Promise<void>;

    thisFunctionWillRevert(overrides?: CallOverrides): Promise<void>;

    thisFunctionWillTransferFromRelayer(
      token: string,
      amount: BigNumberish,
      overrides?: CallOverrides
    ): Promise<void>;

    thisFunctionWillTransferFromRelayerAndExpectUnsupportedRiskLevel(
      token: string,
      amount: BigNumberish,
      overrides?: CallOverrides
    ): Promise<void>;

    thisFunctionWillTryToReenter(overrides?: CallOverrides): Promise<void>;
  };
Example #10
Source File: IWETH9.d.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
callStatic: {
    allowance(owner: string, spender: string, overrides?: CallOverrides): Promise<BigNumber>

    'allowance(address,address)'(owner: string, spender: string, overrides?: CallOverrides): Promise<BigNumber>

    approve(spender: string, amount: BigNumberish, overrides?: CallOverrides): Promise<boolean>

    'approve(address,uint256)'(spender: string, amount: BigNumberish, overrides?: CallOverrides): Promise<boolean>

    balanceOf(account: string, overrides?: CallOverrides): Promise<BigNumber>

    'balanceOf(address)'(account: string, overrides?: CallOverrides): Promise<BigNumber>

    deposit(overrides?: CallOverrides): Promise<void>

    'deposit()'(overrides?: CallOverrides): Promise<void>

    totalSupply(overrides?: CallOverrides): Promise<BigNumber>

    'totalSupply()'(overrides?: CallOverrides): Promise<BigNumber>

    transfer(recipient: string, amount: BigNumberish, overrides?: CallOverrides): Promise<boolean>

    'transfer(address,uint256)'(recipient: string, amount: BigNumberish, overrides?: CallOverrides): Promise<boolean>

    transferFrom(sender: string, recipient: string, amount: BigNumberish, overrides?: CallOverrides): Promise<boolean>

    'transferFrom(address,address,uint256)'(
      sender: string,
      recipient: string,
      amount: BigNumberish,
      overrides?: CallOverrides
    ): Promise<boolean>

    withdraw(arg0: BigNumberish, overrides?: CallOverrides): Promise<void>

    'withdraw(uint256)'(arg0: BigNumberish, overrides?: CallOverrides): Promise<void>
  }
Example #11
Source File: MockCrossDomainMessenger.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
populateTransaction: {
    relayMessage(
      target: string,
      message: BytesLike,
      sender: string,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<PopulatedTransaction>;

    sendMessage(
      arg0: string,
      arg1: BytesLike,
      arg2: BigNumberish,
      overrides?: CallOverrides
    ): Promise<PopulatedTransaction>;

    xDomainMessageSender(
      overrides?: CallOverrides
    ): Promise<PopulatedTransaction>;
  };
Example #12
Source File: utils.ts    From hypervisor with The Unlicense 6 votes vote down vote up
signPermitEIP2612 = async (
  owner: Wallet,
  token: Contract,
  spenderAddress: string,
  value: BigNumberish,
  deadline: BigNumberish,
  nonce?: BigNumberish,
) => {
  // get nonce
  nonce = nonce || (await token.nonces(owner.address))
  // get chainId
  const chainId = (await token.provider.getNetwork()).chainId
  // get domain
  const domain = {
    name: 'Uniswap V2',
    version: '1',
    chainId: chainId,
    verifyingContract: token.address,
  }
  // get types
  const types = {} as Record<string, TypedDataField[]>
  types['Permit'] = [
    { name: 'owner', type: 'address' },
    { name: 'spender', type: 'address' },
    { name: 'value', type: 'uint256' },
    { name: 'nonce', type: 'uint256' },
    { name: 'deadline', type: 'uint256' },
  ]
  // get values
  const values = {
    owner: owner.address,
    spender: spenderAddress,
    value: value,
    nonce: nonce,
    deadline: deadline,
  }
  // sign permission
  // todo: add fallback if wallet does not support eip 712 rpc
  const signedPermission = await owner._signTypedData(domain, types, values)
  // split signature
  const sig = splitSignature(signedPermission)
  // return
  return [
    values.owner,
    values.spender,
    values.value,
    values.deadline,
    sig.v,
    sig.r,
    sig.s,
  ]
}
Example #13
Source File: L2NovaRegistry.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
requestExecWithTimeout(
    strategy: string,
    l1Calldata: BytesLike,
    gasLimit: BigNumberish,
    gasPrice: BigNumberish,
    tip: BigNumberish,
    inputTokens: { l2Token: string; amount: BigNumberish }[],
    autoUnlockDelaySeconds: BigNumberish,
    overrides?: PayableOverrides & { from?: string | Promise<string> }
  ): Promise<ContractTransaction>;
Example #14
Source File: ERC20Permit.d.ts    From hypervisor with The Unlicense 6 votes vote down vote up
permit(
    owner: string,
    spender: string,
    value: BigNumberish,
    deadline: BigNumberish,
    v: BigNumberish,
    r: BytesLike,
    s: BytesLike,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<ContractTransaction>;
Example #15
Source File: Hevm.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
functions: {
    load(
      arg0: string,
      arg1: BytesLike,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    roll(
      arg0: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    store(
      arg0: string,
      arg1: BytesLike,
      arg2: BytesLike,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    warp(
      arg0: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;
  };
Example #16
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * helper to get ETH gas when don't know the whole transaction
   * default to return big enough gas for contract deployment
   * @returns The gas used by eth transaction
   */
  _getEthGas = async ({
    gasLimit = 21000000,
    storageLimit = 64100,
    validUntil: _validUntil
  }: {
    gasLimit?: BigNumberish;
    storageLimit?: BigNumberish;
    validUntil?: BigNumberish;
  } = {}): Promise<{
    gasPrice: BigNumber;
    gasLimit: BigNumber;
  }> => {
    const validUntil = _validUntil || (await this.getBlockNumber()) + 150; // default 150 * 12 / 60 = 30min
    const storageByteDeposit = (this.api.consts.evm.storageDepositPerByte as UInt).toBigInt();
    const txFeePerGas = (this.api.consts.evm.txFeePerGas as UInt).toBigInt();

    const { txGasLimit, txGasPrice } = calcEthereumTransactionParams({
      gasLimit,
      storageLimit,
      validUntil,
      storageByteDeposit,
      txFeePerGas
    });

    return {
      gasLimit: txGasLimit,
      gasPrice: txGasPrice
    };
  };
Example #17
Source File: deployKeepers.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
public async deployFliRebalanceKeeper(
    fliExtension: Address,
    registry: Address,
    exchangeIndex: BigNumberish,
    leverageSettings: {
      customMinLeverageRatio: BigNumberish;
      customMaxLeverageRatio: BigNumberish;
    }
  ): Promise<FliRebalanceKeeper> {
    return new FliRebalanceKeeper__factory(this._deployerSigner).deploy(fliExtension, registry, exchangeIndex, leverageSettings);
  }
Example #18
Source File: EchidnaL2NovaRegistry.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
populateTransaction: {
    requestExec_and_unlock_and_withdraw_tokens_should_work(
      strategy: string,
      l1Calldata: BytesLike,
      gasLimit: BigNumberish,
      gasPrice: BigNumberish,
      tip: BigNumberish,
      unlockDelay: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<PopulatedTransaction>;

    should_always_be_able_connect_execution_manager(
      newExecutionManager: string,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<PopulatedTransaction>;

    speeding_up_a_request_multiple_times_should_fail(
      strategy: string,
      l1Calldata: BytesLike,
      gasLimit: BigNumberish,
      gasPrice: BigNumberish,
      tip: BigNumberish,
      gasDelta1: BigNumberish,
      gasDelta2: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<PopulatedTransaction>;
  };
Example #19
Source File: deployStaking.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
public async deployStakingRewardsV2(
    owner: Address,
    rewardToken: Address,
    stakingToken: Address,
    duration: BigNumberish
  ): Promise<StakingRewardsV2> {
    return await new StakingRewardsV2__factory(this._deployerSigner).deploy(
      owner,
      rewardToken,
      stakingToken,
      duration
    );
  }
Example #20
Source File: EchidnaL2NovaRegistry.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
speeding_up_a_request_multiple_times_should_fail(
    strategy: string,
    l1Calldata: BytesLike,
    gasLimit: BigNumberish,
    gasPrice: BigNumberish,
    tip: BigNumberish,
    gasDelta1: BigNumberish,
    gasDelta2: BigNumberish,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<ContractTransaction>;
Example #21
Source File: uniswapV3Fixture.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
/**
   * Creates and initializes a new pool
   *
   * @param _token0         address of the first token
   * @param _token1         address of the second token
   * @param _fee            fee tier of either 500, 3000, or 10000
   * @param _ratio          the initial price ratio of the pool equal to priceToken0 / priceToken1
   * @returns               a new Uniswap V3 pool
   */
  public async createNewPair(
    _token0: Token,
    _token1: Token,
    _fee: BigNumberish,
    _ratio: number,
  ): Promise<UniswapV3Pool> {


    let ratio = _ratio * (10 ** (await _token1.decimals() - await _token0.decimals()));

    if (_token0.address.toLowerCase() > _token1.address.toLowerCase()) {
      ratio = 1 / ratio;
    }

    const [ token0Ordered, token1Ordered ] = this.getTokenOrder(_token0, _token1);

    const sqrtPrice = this._getSqrtPriceX96(ratio);

    await this.nftPositionManager.createAndInitializePoolIfNecessary(token0Ordered.address, token1Ordered.address, _fee, sqrtPrice);

    return this.getPool(_token0, _token1, _fee);
  }
Example #22
Source File: EchidnaL1NovaExecutionManager.d.ts    From nova with GNU Affero General Public License v3.0 6 votes vote down vote up
functions: {
    exec_should_not_affect_currentExecHash(
      nonce: BigNumberish,
      strategy: string,
      l1Calldata: BytesLike,
      gasLimit: BigNumberish,
      recipient: string,
      deadline: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    registerSelfAsStrategy_should_never_be_callable_twice(
      riskLevel1: BigNumberish,
      riskLevel2: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    should_always_be_able_to_update_gas_config(
      newGasConfig: {
        calldataByteGasEstimate: BigNumberish;
        missingGasEstimate: BigNumberish;
        strategyCallGasBuffer: BigNumberish;
        execCompletedMessageGasLimit: BigNumberish;
      },
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;

    transferFromRelayer_should_always_be_not_executable(
      token: string,
      amount: BigNumberish,
      overrides?: Overrides & { from?: string | Promise<string> }
    ): Promise<ContractTransaction>;
  };
Example #23
Source File: Hypervisor.d.ts    From hypervisor with The Unlicense 6 votes vote down vote up
permit(
    owner: string,
    spender: string,
    value: BigNumberish,
    deadline: BigNumberish,
    v: BigNumberish,
    r: BytesLike,
    s: BytesLike,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<ContractTransaction>;
Example #24
Source File: TradeExtensionWrapper.ts    From set.js with Apache License 2.0 5 votes vote down vote up
/**
   * Executes a trade on a supported DEX. Must be called an address authorized for the `operator` role
   * on the TradeExtension
   *
   * NOTE: Although SetToken units are passed in for the send and receive quantities, the total quantity
   * sent and received is the quantity of SetToken units multiplied by the SetToken totalSupply.
   *
   * @param setTokenAddress      Address of the deployed SetToken to trade on behalf of
   * @param exchangeName         Human readable name of the exchange in the integrations registry
   * @param sendToken            Address of the token to be sent to the exchange
   * @param sendQuantity         Units of token in SetToken sent to the exchange
   * @param receiveToken         Address of the token that will be received from the exchange
   * @param minReceiveQuantity   Min units of token in SetToken to be received from the exchange
   * @param data                 Arbitrary bytes to be used to construct trade call data
   * @param callerAddress        Address of caller (optional)
   * @param txOptions            Overrides for transaction (optional)
   */
  public async tradeWithOperator(
    setTokenAddress: Address,
    exchangeName: Address,
    sendToken: Address,
    sendQuantity: BigNumberish,
    receiveToken: Address,
    minReceiveQuantity: BigNumberish,
    data: BytesLike,
    callerAddress: Address = undefined,
    txOpts: TransactionOverrides = {}
  ): Promise<ContractTransaction> {
    const txOptions = await generateTxOpts(txOpts);
    const tradeExtensionInstance = await this.contracts.loadTradeExtensionAsync(
      this.tradeExtensionAddress,
      callerAddress
    );

    return await tradeExtensionInstance.trade(
      setTokenAddress,
      exchangeName,
      sendToken,
      sendQuantity,
      receiveToken,
      minReceiveQuantity,
      data,
      txOptions
    );
  }
Example #25
Source File: CurrencyValue.ts    From useDApp with MIT License 5 votes vote down vote up
mul(value: BigNumberish) {
    return this.map((x) => x.mul(value))
  }
Example #26
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
/**
   * Get the gas for eth transactions
   * @returns The gas used by eth transaction
   */
  getEthResources = async (
    transaction: Deferrable<TransactionRequest>,
    {
      gasLimit,
      storageLimit,
      validUntil
    }: {
      gasLimit?: BigNumberish;
      storageLimit?: BigNumberish;
      validUntil?: BigNumberish;
    } = {}
  ): Promise<{
    gasPrice: BigNumber;
    gasLimit: BigNumber;
  }> => {
    if (!gasLimit || !storageLimit) {
      const { gas, storage } = await this.estimateResources(transaction);
      gasLimit = gasLimit ?? gas;
      storageLimit = storageLimit ?? storage;
    }

    if (!validUntil) {
      const blockNumber = await this.getBlockNumber();
      // Expires after 100 blocks by default
      validUntil = blockNumber + 100;
    }

    const storageByteDeposit = (this.api.consts.evm.storageDepositPerByte as UInt).toBigInt();
    const txFeePerGas = (this.api.consts.evm.txFeePerGas as UInt).toBigInt();

    const { txGasLimit, txGasPrice } = calcEthereumTransactionParams({
      gasLimit,
      storageLimit,
      validUntil,
      storageByteDeposit,
      txFeePerGas
    });

    return {
      gasLimit: txGasLimit,
      gasPrice: txGasPrice
    };
  };
Example #27
Source File: CurrencyValue.ts    From useDApp with MIT License 5 votes vote down vote up
mod(value: BigNumberish) {
    return this.map((x) => x.mod(value))
  }
Example #28
Source File: Hypervisor.d.ts    From hypervisor with The Unlicense 5 votes vote down vote up
withdraw(
    shares: BigNumberish,
    to: string,
    from: string,
    overrides?: Overrides & { from?: string | Promise<string> }
  ): Promise<ContractTransaction>;
Example #29
Source File: ISwapRouter.d.ts    From hardhat-v3-deploy with MIT License 5 votes vote down vote up
uniswapV3SwapCallback(
    amount0Delta: BigNumberish,
    amount1Delta: BigNumberish,
    data: BytesLike,
    overrides?: Overrides
  ): Promise<ContractTransaction>