ethers#constants TypeScript Examples

The following examples show how to use ethers#constants. 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: commonUtils.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
displayAmount = (
    amount: string,
    decimals: number,
    precision = 5,
    stripTrailingZeros = true
): string => {
    if (amount === constants.MaxUint256.toString()) return ' ∞';
    const tokenBits = BigNumber.from(10).pow(decimals);
    const display = new BN(amount)
        .div(tokenBits.toString())
        .toFormat(precision);

    if (stripTrailingZeros) {
        const trailingZeros = '.' + '0'.repeat(precision);
        return display.replace(trailingZeros, '').toString();
    }
    return display.toString();
}
Example #2
Source File: walkConfig.ts    From l2beat with MIT License 6 votes vote down vote up
export async function walkConfig(
  provider: providers.Provider,
  addressAnalyzer: AddressAnalyzer,
  config: Config,
  startingPoints: string[]
) {
  const resolved = new Map<string, Record<string, unknown>>()

  const stack = [...startingPoints]
  while (stack.length !== 0) {
    const address = stack.pop()
    if (
      !address ||
      address === constants.AddressZero ||
      resolved.has(address)
    ) {
      continue
    }
    const { analyzed, relatives } = await analyzeItem(
      provider,
      addressAnalyzer,
      config,
      address
    )
    console.log('Analyzed', address)
    resolved.set(address, analyzed)
    stack.push(...relatives)
  }

  prettyPrint(resolved)
}
Example #3
Source File: faucet.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates two transaction: one that sends ETH to the address
 * and a second one which sends HOPR tokens to that address
 * @param token instance of the HOPR token
 * @param address where to send the HOPR tokens and ETH to
 * @param amountEth how many ETH
 * @param amountHopr how many HOPR
 * @param networkName which network to use
 * @returns
 */
async function createTransaction(
  token: HoprToken,
  address: string,
  amountEth: BigNumber,
  amountHopr: BigNumber,
  networkName: string
): Promise<UnsignedTransaction[]> {
  const txs: UnsignedTransaction[] = [
    await token.populateTransaction.mint(address.toString(), amountHopr, constants.HashZero, constants.HashZero, {
      gasLimit: 200e3
    }),
    {
      to: address,
      value: amountEth
    }
  ]

  console.log(`?? Sending ${utils.formatEther(amountEth)} ETH to ${address} on network ${networkName}`)
  console.log(`?? Sending ${utils.formatEther(amountHopr)} HOPR to ${address} on network ${networkName}`)

  return txs
}
Example #4
Source File: EthBalanceCall.ts    From l2beat with MIT License 6 votes vote down vote up
EthBalanceCall = {
  encode(holder: string): MulticallRequest {
    return {
      address: MULTICALL,
      data: coder.encodeFunctionData('getEthBalance', [holder]),
    }
  },
  decode(result: MulticallResponse | undefined) {
    if (!result?.success) {
      return
    }
    const decoded = coder.decodeFunctionResult('getEthBalance', result.data)
    return decoded[0] as BigNumber
  },
  decodeOrZero(result: MulticallResponse | undefined) {
    return this.decode(result) ?? constants.Zero
  },
}
Example #5
Source File: index.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
public async encodeLimitOrderCancellation(
    order: Order,
    checkIsActiveOrder?: boolean
  ): Promise<TransactionData> {
    if (!this._gelatoLimitOrders)
      throw new Error("No gelato limit orders contract");

    if (!order.inputToken) throw new Error("No input token in order");
    if (!order.witness) throw new Error("No witness in order");
    if (!order.outputToken) throw new Error("No output token in order");
    if (!order.minReturn) throw new Error("No minReturn in order");
    if (!order.owner) throw new Error("No owner");
    if (!order.module) throw new Error("No module in order");

    if (checkIsActiveOrder) {
      const isActiveOrder = await this.isActiveOrder(order);
      if (!isActiveOrder)
        throw new Error("Order not found. Please review your order data.");
    }

    const data = this._gelatoLimitOrders.interface.encodeFunctionData(
      "cancelOrder",
      [order.module, order.inputToken, order.owner, order.witness, order.data]
    );

    return {
      data,
      to: this._gelatoLimitOrders.address,
      value: constants.Zero,
    };
  }
Example #6
Source File: TokenBalanceCall.ts    From l2beat with MIT License 6 votes vote down vote up
TokenBalanceCall = {
  encode(token: string, holder: string): MulticallRequest {
    return {
      address: token,
      data: coder.encodeFunctionData('balanceOf', [holder]),
    }
  },
  decode(result: MulticallResponse | undefined) {
    if (!result?.success) {
      return
    }
    const decoded = coder.decodeFunctionResult('balanceOf', result.data)
    return decoded[0] as BigNumber
  },
  decodeOrZero(result: MulticallResponse | undefined) {
    return this.decode(result) ?? constants.Zero
  },
}
Example #7
Source File: prepare-address.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
/**
 * @ignore
 */
export function prepareAddress(value: string, zeroAddressAsNull = false): string {
  let result: string = null;

  try {
    result = utils.getAddress(value);

    if (result === constants.AddressZero) {
      result = null;
    }
  } catch (err) {
    //
  }

  if (!result && zeroAddressAsNull) {
    result = constants.AddressZero;
  }

  return result;
}
Example #8
Source File: UniV1ExchangeCall.ts    From l2beat with MIT License 6 votes vote down vote up
UniV1ExchangeCall = {
  encode(token: string): MulticallRequest {
    return {
      address: UNISWAP_V1_FACTORY,
      data: coder.encodeFunctionData('getExchange', [token]),
    }
  },
  decode(result: MulticallResponse | undefined) {
    if (!result?.success) {
      return
    }
    const decoded = coder.decodeFunctionResult('getExchange', result.data)
    return decoded[0] as string
  },
  decodeOrZero(result: MulticallResponse | undefined) {
    return this.decode(result) ?? constants.AddressZero
  },
}
Example #9
Source File: contracts.ts    From data-transport-layer with MIT License 6 votes vote down vote up
loadProxyFromManager = async (
  name: string,
  proxy: string,
  Lib_AddressManager: Contract,
  provider: JsonRpcProvider
): Promise<Contract> => {
  const address = await Lib_AddressManager.getAddress(proxy)

  if (address === constants.AddressZero) {
    throw new Error(
      `Lib_AddressManager does not have a record for a contract named: ${proxy}`
    )
  }

  return loadContract(name, address, provider)
}
Example #10
Source File: UniV3PriceCall.ts    From l2beat with MIT License 6 votes vote down vote up
UniV3PriceCall = {
  encode(pool: string): MulticallRequest {
    return {
      address: pool,
      data: coder.encodeFunctionData('slot0'),
    }
  },
  decode(result: MulticallResponse | undefined) {
    if (!result?.success) {
      return
    }
    const decoded = coder.decodeFunctionResult('slot0', result.data)
    return decoded[0] as BigNumber
  },
  decodeOrZero(result: MulticallResponse | undefined) {
    return this.decode(result) ?? constants.Zero
  },
}
Example #11
Source File: service.ts    From data-transport-layer with MIT License 6 votes vote down vote up
/**
   * Gets the address of a contract at a particular block in the past.
   * @param contractName Name of the contract to get an address for.
   * @param blockNumber Block at which to get an address.
   * @return Contract address.
   */
  private async _getContractAddressAtBlock(
    contractName: string,
    blockNumber: number
  ): Promise<string> {
    // TODO: Should be much easier than this. Need to change the params of this event.
    const relevantAddressSetEvents = (
      await this.state.contracts.Lib_AddressManager.queryFilter(
        this.state.contracts.Lib_AddressManager.filters.AddressSet(),
        this.state.startingL1BlockNumber
      )
    ).filter((event) => {
      return (
        event.args._name === contractName && event.blockNumber < blockNumber
      )
    })

    if (relevantAddressSetEvents.length > 0) {
      return relevantAddressSetEvents[relevantAddressSetEvents.length - 1].args
        ._newAddress
    } else {
      // Address wasn't set before this.
      return constants.AddressZero
    }
  }
Example #12
Source File: TokensProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
getInitialState = ({ addresses, nativeToken }: AllNetworks): State => {
  // FIXME: - Consider decimal mapping to catch outliers in ERC20 object (ie. WBTC != 18dp)
  // const decimalMap = {[addresses.WBTC]: 8}
  return {
    tokens: Object.fromEntries(
      ([[nativeToken.symbol, constants.AddressZero], ...Object.entries(addresses.ERC20)] as [string, string][]).map(
        ([symbol, address]): [string, SubscribedToken] => [
          address,
          {
            address,
            decimals: 18,
            symbol,
            name: symbol,
            allowances: {},
            balance: new BigDecimal(0, 18),
            totalSupply: new BigDecimal(0, 18),
          },
        ],
      ),
    ),
    subscriptions: {},
  }
}
Example #13
Source File: commonUtils.test.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('#displayAmount', () => {
    it.each([
        ['61776792004700431', 18, undefined, '0.06178'],
        ['559434119616550549964644', 18, undefined, '559,434.11962'],
        ['0', 18, undefined, '0'],
        ['553183935', 8, undefined, '5.53184'],
        ['20819427', 8, undefined, '0.20819'],
        ['1554848178', 18, undefined, '0'],
        [constants.MaxUint256.toString(), 18, undefined, ' ∞'],
        [constants.One.toString(), 18, undefined, '0'],
        [constants.One.toString(), 18, 18, '0.000000000000000001'],
    ])(
        'should display %s with %d decimals and precision %d to be %s',
        (amt, decimals, precision, expected) => {
            const res = displayAmount(amt, decimals, precision);
            expect(res).toBe(expected);
        }
    );
});
Example #14
Source File: contracts.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
export function getContract(
  address: string,
  ABI: any,
  library: providers.JsonRpcProvider,
  account?: string
): Contract {
  if (!isAddress(address) || address === constants.AddressZero) {
    return null;
  }

  return new Contract(
    address,
    ABI,
    getProviderOrSigner(library, account) as any
  );
}
Example #15
Source File: orders.ts    From perp-vault-templates with MIT License 6 votes vote down vote up
getAirSwapOrder = async (
  sender: string,
  senderToken: string,
  senderTokenAmount: BigNumber | number,
  signer: string,
  signerToken: string,
  signerTokenAmount: string | number,
  swapContract: string,
  privateKey: any
) => {
  const order = createOrder({
    signer: {
      wallet: signer,
      token: signerToken,
      amount: signerTokenAmount,
    },
    sender: {
      wallet: sender,
      token: senderToken,
      amount: senderTokenAmount,
    },
    affiliate: {
      wallet: constants.AddressZero,
    },
    expiry: parseInt((Date.now() / 1000).toString(10)) + 86400 * 100,
  });
  const signedOrder = await signTypedDataOrder(order, privateKey, swapContract);
  return signedOrder;
}
Example #16
Source File: Transfer.test.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
describe("Transfer", () => {
  let transferMock: TransferMock;
  let erc20Fallback: ERC20Fallback;
  let erc20Noncompliant: ERC20Noncompliant;
  let erc20Compliant: ERC20Compliant;
  before(async () => {
    const TransferMock = await ethers.getContractFactory<TransferMock__factory>("TransferMock");
    transferMock = await TransferMock.deploy(overrides);

    const ERC20Fallback = await ethers.getContractFactory<ERC20Fallback__factory>("ERC20Fallback");
    erc20Fallback = await ERC20Fallback.deploy(overrides);

    const ERC20Noncompliant = await ethers.getContractFactory<ERC20Noncompliant__factory>("ERC20Noncompliant");
    erc20Noncompliant = await ERC20Noncompliant.deploy(overrides);

    const ERC20Compliant = await ethers.getContractFactory<ERC20Compliant__factory>("ERC20Compliant");
    erc20Compliant = await ERC20Compliant.deploy(overrides);
  });

  // sets up the fixtures for each token situation that should be tested
  function harness({
    sendTx,
    expectedError,
  }: {
    sendTx: (tokenAddress: string) => Promise<ContractTransaction>;
    expectedError: string;
  }) {
    it("succeeds with compliant with no revert and true return", async () => {
      await erc20Compliant.setup(true, false);
      await sendTx(erc20Compliant.address);
    });
    it("fails with compliant with no revert and false return", async () => {
      await erc20Compliant.setup(false, false);
      await expect(sendTx(erc20Compliant.address)).to.be.revertedWith(expectedError);
    });
    it("fails with compliant with revert", async () => {
      await erc20Compliant.setup(false, true);
      await expect(sendTx(erc20Compliant.address)).to.be.revertedWith(expectedError);
    });
    it("succeeds with noncompliant (no return) with no revert", async () => {
      await erc20Noncompliant.setup(false);
      await sendTx(erc20Noncompliant.address);
    });
    it("fails with noncompliant (no return) with revert", async () => {
      await erc20Noncompliant.setup(true);
      await expect(sendTx(erc20Noncompliant.address)).to.be.revertedWith(expectedError);
    });
  }

  describe("#safeApprove", () => {
    harness({
      sendTx: (tokenAddress) => transferMock.safeApprove(tokenAddress, constants.AddressZero, constants.MaxUint256),
      expectedError: "SA",
    });
  });
  describe("#safeTransfer", () => {
    harness({
      sendTx: (tokenAddress) => transferMock.safeTransfer(tokenAddress, constants.AddressZero, constants.MaxUint256),
      expectedError: "ST",
    });
  });
  describe("#safeTransferFrom", () => {
    harness({
      sendTx: (tokenAddress) =>
        transferMock.safeTransferFrom(tokenAddress, constants.AddressZero, constants.AddressZero, constants.MaxUint256),
      expectedError: "STF",
    });
  });

  describe("#safeTransferETH", () => {
    it("succeeds call not reverted", async () => {
      await erc20Fallback.setup(false);
      await transferMock.safeTransferETH(erc20Fallback.address, 0);
    });
    it("fails if call reverts", async () => {
      await erc20Fallback.setup(true);
      await expect(transferMock.safeTransferETH(erc20Fallback.address, 0)).to.be.revertedWith("STE");
    });
  });
});
Example #17
Source File: ApeFactory.spec.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
{  AddressZero } = constants
Example #18
Source File: VvsPair.spec.ts    From vvs-swap-core with GNU General Public License v3.0 5 votes vote down vote up
{ AddressZero } = constants
Example #19
Source File: stateTree.ts    From hubble-contracts with MIT License 5 votes vote down vote up
PLACEHOLDER_PROOF_WITNESS = Array(STATE_WITNESS_LENGHT).fill(
    constants.HashZero
)
Example #20
Source File: permit.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
export async function getPermitSignature(
  wallet: Wallet,
  token: ERC20Mock | ERC20PermitAllowedMock,
  spender: string,
  value: BigNumberish = constants.MaxUint256,
  deadline = constants.MaxUint256,
  permitConfig?: { nonce?: BigNumberish; name?: string; chainId?: number; version?: string }
): Promise<Signature> {
  const [nonce, name, version, chainId] = await Promise.all([
    permitConfig?.nonce ?? token.nonces(wallet.address),
    permitConfig?.name ?? token.name(),
    permitConfig?.version ?? "1",
    permitConfig?.chainId ?? wallet.getChainId(),
  ]);

  return splitSignature(
    await wallet._signTypedData(
      {
        name,
        version,
        chainId,
        verifyingContract: token.address,
      },
      {
        Permit: [
          {
            name: "owner",
            type: "address",
          },
          {
            name: "spender",
            type: "address",
          },
          {
            name: "value",
            type: "uint256",
          },
          {
            name: "nonce",
            type: "uint256",
          },
          {
            name: "deadline",
            type: "uint256",
          },
        ],
      },
      {
        owner: wallet.address,
        spender,
        value,
        nonce,
        deadline,
      }
    )
  );
}
Example #21
Source File: TokensProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
useNativeToken = (): SubscribedToken => useTokensState().tokens[constants.AddressZero] as SubscribedToken
Example #22
Source File: erc20-approve.ts    From trident with GNU General Public License v3.0 5 votes vote down vote up
{ MaxUint256 } = constants
Example #23
Source File: AmmSpec2.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
describe("Amm Unit Test 2 (Waffle)", async () => {
    const [wallet1, wallet2] = new MockProvider().getWallets()
    let amm: Amm
    let l2PriceFeed: MockContract
    let quoteToken: MockContract
    let clearingHouse: MockContract

    const AmmArtifact = await artifacts.readArtifact(ContractFullyQualifiedName.Amm)
    const IERC20Artifact = await artifacts.readArtifact(ContractFullyQualifiedName.IERC20)
    const L2PriceFeedArtifact = await artifacts.readArtifact(ContractFullyQualifiedName.L2PriceFeed)

    beforeEach(async () => {
        quoteToken = await deployMockContract(wallet1, IERC20Artifact.abi)
        clearingHouse = await deployMockContract(wallet1, [])
        l2PriceFeed = await deployMockContract(wallet1, L2PriceFeedArtifact.abi)
        amm = ((await deployContract(wallet1, AmmArtifact, [], { gasLimit: 6000000 })) as unknown) as Amm
        await amm.initialize(
            parseEther("1000"),
            parseEther("100"),
            parseEther("0.9"), // tradeLimitRatio
            parseEther("3600"), // fundingPeriod - 1hr
            l2PriceFeed.address,
            utils.formatBytes32String("ETH"),
            quoteToken.address,
            BigNumber.from(0), // fluctuation
            BigNumber.from(0), // toll
            BigNumber.from(0), // spread
        )
        await amm.setCounterParty(clearingHouse.address)
        amm.connect(clearingHouse.address)
    })

    describe("price", () => {
        it("getUnderlyingPrice", async () => {
            const price = parseEther("1")
            const priceFeedKeyBytes32 = await amm.priceFeedKey()
            const priceFeedKeyStr = utils.parseBytes32String(priceFeedKeyBytes32)
            expect(priceFeedKeyStr).eq("ETH")
            await l2PriceFeed.mock.getPrice.withArgs(priceFeedKeyBytes32).returns(price)
            expect((await amm.getUnderlyingPrice()).d).deep.eq(price)
        })
    })

    describe("setCap", () => {
        it("change maxHoldingBaseAsset and openInterestNotionalCap", async () => {
            await expect(amm.setCap({ d: 100 }, { d: 200 }))
                .to.emit(amm, "CapChanged")
                .withArgs("100", "200")
            expect((await amm.getMaxHoldingBaseAsset()).d).deep.eq(BigNumber.from(100))
            expect((await amm.getOpenInterestNotionalCap()).d).deep.eq(BigNumber.from(200))
        })
    })

    describe("setPriceFeed", () => {
        it("set priceFeed correctly", async () => {
            const updatedPriceFeed = "0x77F9710E7d0A19669A13c055F62cd80d313dF022"
            expect(await amm.priceFeed()).to.eq(l2PriceFeed.address)
            await expect(amm.setPriceFeed(updatedPriceFeed))
                .to.emit(amm, "PriceFeedUpdated")
                .withArgs(updatedPriceFeed)
            expect(await amm.priceFeed()).to.eq(updatedPriceFeed)
        })

        it("set priceFeed via non-owner causes revert transaction", async () => {
            await expect(amm.connect(wallet2).setPriceFeed(l2PriceFeed.address)).to.be.revertedWith(
                "PerpFiOwnableUpgrade: caller is not the owner",
            )
        })

        it("revert if priceFeed address is zero", async () => {
            await expect(amm.setPriceFeed(constants.AddressZero)).to.be.revertedWith("invalid PriceFeed address")
        })
    })
})
Example #24
Source File: EthereumAddress.ts    From l2beat with MIT License 5 votes vote down vote up
EthereumAddress.ZERO = EthereumAddress(constants.AddressZero)
Example #25
Source File: DelegateeToggle.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
DelegateeToggle: FC<{ address?: string; stakedTokenSwitcher?: boolean }> = ({ address, stakedTokenSwitcher }) => {
  const propose = usePropose()
  const stakedTokenContract = useStakedTokenContract()
  const account = useOwnAccount()

  const stakedTokenQuery = useStakedTokenQuery()
  const delegatee = stakedTokenQuery.data?.stakedToken.accounts?.[0]?.delegatee
  const isDelegated = delegatee && address && delegatee.id.toLowerCase() === address.toLowerCase()

  return (
    <Container>
      {stakedTokenSwitcher && <StakedTokenSwitcher />}
      {address ? (
        isDelegated ? (
          <>
            <Delegated>
              <Check />
              Delegated
            </Delegated>
            <Button
              highlighted
              onClick={() => {
                if (!stakedTokenContract || !account || account === constants.AddressZero) return

                propose<Interfaces.StakedToken, 'delegate'>(
                  new TransactionManifest(stakedTokenContract, 'delegate', [account], {
                    present: 'Removing delegation',
                    past: 'Removed delegation',
                  }),
                )
              }}
            >
              Undelegate
            </Button>
          </>
        ) : (
          <Button
            highlighted
            onClick={() => {
              if (!stakedTokenContract || !address || address === constants.AddressZero) return

              propose<Interfaces.StakedToken, 'delegate'>(
                new TransactionManifest(stakedTokenContract, 'delegate', [address], {
                  present: `Delegating to ${truncateAddress(address)}`,
                  past: `Delegated to ${truncateAddress(address)}`,
                }),
              )
            }}
          >
            Delegate
          </Button>
        )
      ) : (
        <ThemedSkeleton height={40} width={110} />
      )}
    </Container>
  )
}
Example #26
Source File: ApeERC20.spec.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
{  MaxUint256 } = constants
Example #27
Source File: sendEmptyTx.ts    From useDApp with MIT License 5 votes vote down vote up
export async function sendEmptyTx(wallet: Wallet) {
  return wallet.sendTransaction({ to: constants.AddressZero })
}
Example #28
Source File: bond-slice.ts    From wonderland-frontend with MIT License 5 votes vote down vote up
changeApproval = createAsyncThunk("bonding/changeApproval", async ({ bond, provider, networkID, address }: IChangeApproval, { dispatch }) => {
    if (!provider) {
        dispatch(warning({ text: messages.please_connect_wallet }));
        return;
    }

    const signer = provider.getSigner();
    const reserveContract = bond.getContractForReserve(networkID, signer);

    let approveTx;
    try {
        const gasPrice = await getGasPrice(provider);
        const bondAddr = bond.getAddressForBond(networkID);
        approveTx = await reserveContract.approve(bondAddr, constants.MaxUint256, { gasPrice });
        dispatch(
            fetchPendingTxns({
                txnHash: approveTx.hash,
                text: "Approving " + bond.displayName,
                type: "approve_" + bond.name,
            }),
        );
        await approveTx.wait();
        dispatch(success({ text: messages.tx_successfully_send }));
    } catch (err: any) {
        metamaskErrorWrap(err, dispatch);
    } finally {
        if (approveTx) {
            dispatch(clearPendingTxn(approveTx.hash));
        }
    }

    await sleep(2);

    let allowance = "0";

    allowance = await reserveContract.allowance(address, bond.getAddressForBond(networkID));

    return dispatch(
        fetchAccountSuccess({
            bonds: {
                [bond.name]: {
                    allowance: Number(allowance),
                },
            },
        }),
    );
})
Example #29
Source File: mineBlock.ts    From useDApp with MIT License 5 votes vote down vote up
mineBlock = async (provider: MockProvider) => {
  const wallet = await getAdminWallet(provider)
  const tx = await wallet.sendTransaction({ to: constants.AddressZero, value: 0 })
  await tx.wait()
}