@ethersproject/contracts#Contract TypeScript Examples

The following examples show how to use @ethersproject/contracts#Contract. 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 ether-swr with MIT License 7 votes vote down vote up
multiCall = (
  parameters: string | any[],
  provider: providers.MulticallProvider,
  ABIs
) => {
  const {
    params: [address, method, otherParams],
    extended
  } = parseParams(parameters)

  // it's a contract
  if (isAddress(address)) {
    if (!ABIs) throw new ABIError(`ABI repo not found`)
    if (!ABIs.get) throw new ABIError(`ABI repo isn't a Map`)
    const abi = ABIs.get(address)
    if (!abi) throw new ABINotFound(`ABI not found for ${address}`)
    const contract = new Contract(address, abi, provider)
    return contract[method](...otherParams, extended)
  }
  const param2 = method
  const baseMethod = address
  return provider[baseMethod](param2, ...otherParams, extended.blockTag)
}
Example #2
Source File: fetcher.ts    From QuickSwap-sdk with MIT License 7 votes vote down vote up
/**
   * Fetch information for a given token on the given chain, using the given ethers provider.
   * @param chainId chain of the token
   * @param address address of the token on the chain
   * @param provider provider used to fetch the token
   * @param symbol optional symbol of the token
   * @param name optional name of the token
   */
  public static async fetchTokenData(
    chainId: ChainId,
    address: string,
    provider = getDefaultProvider(getNetwork(chainId)),
    symbol?: string,
    name?: string
  ): Promise<Token> {
    const parsedDecimals =
      typeof TOKEN_DECIMALS_CACHE?.[chainId]?.[address] === 'number'
        ? TOKEN_DECIMALS_CACHE[chainId][address]
        : await new Contract(address, ERC20, provider).decimals().then((decimals: number): number => {
            TOKEN_DECIMALS_CACHE = {
              ...TOKEN_DECIMALS_CACHE,
              [chainId]: {
                ...TOKEN_DECIMALS_CACHE?.[chainId],
                [address]: decimals
              }
            }
            return decimals
          })
    return new Token(chainId, address, parsedDecimals, symbol, name)
  }
Example #3
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function useSingleContractMultipleData(
  contract: Contract | null | undefined,
  methodName: string,
  callInputs: OptionalMethodInputs[],
  options?: ListenerOptions,
): CallState[] {
  const fragment = useMemo(() => contract?.interface?.getFunction(methodName), [
    contract,
    methodName,
  ]);

  const calls = useMemo(
    () =>
      contract && fragment && callInputs && callInputs.length > 0
        ? callInputs.map<Call>((inputs) => {
            return {
              address: contract.address,
              callData: contract.interface.encodeFunctionData(fragment, inputs),
            };
          })
        : [],
    [callInputs, contract, fragment],
  );

  const results = useCallsData(calls, options);

  const latestBlockNumber = useBlockNumber();

  return useMemo(() => {
    return results.map((result) =>
      toCallState(result, contract?.interface, fragment, latestBlockNumber),
    );
  }, [fragment, contract, results, latestBlockNumber]);
}
Example #4
Source File: useContract.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export function useENSRegistrarContract(withSignerIfPossible?: boolean): Contract | null {
  const { chainId } = useActiveWeb3React()
  let address: string | undefined
  if (chainId) {
    switch (chainId) {
      case ChainId.MAINNET:
      case ChainId.BSCTESTNET:
    }
  }
  return useContract(address, ENS_ABI, withSignerIfPossible)
}
Example #5
Source File: call.ts    From ethers-multicall with MIT License 6 votes vote down vote up
export async function all<T extends any[] = any[]>(
  calls: ContractCall[],
  multicallAddress: string,
  provider: Provider,
): Promise<T> {
  const multicall = new Contract(multicallAddress, multicallAbi, provider);
  const callRequests = calls.map(call => {
    const callData = Abi.encode(call.name, call.inputs, call.params);
    return {
      target: call.contract.address,
      callData,
    };
  });
  const response = await multicall.aggregate(callRequests);
  const callCount = calls.length;
  const callResult = [] as T;
  for (let i = 0; i < callCount; i++) {
    const outputs = calls[i].outputs;
    const returnData = response.returnData[i];
    const params = Abi.decode(outputs, returnData);
    const result = outputs.length === 1 ? params[0] : params;
    callResult.push(result);
  }
  return callResult;
}
Example #6
Source File: hooks.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export function useSingleContractMultipleData(
  contract: Contract | null | undefined,
  methodName: string,
  callInputs: OptionalMethodInputs[],
  options?: ListenerOptions
): CallState[] {
  const fragment = useMemo(() => contract?.interface?.getFunction(methodName), [contract, methodName])

  const calls = useMemo(
    () =>
      contract && fragment && callInputs && callInputs.length > 0
        ? callInputs.map<Call>(inputs => {
            return {
              address: contract.address,
              callData: contract.interface.encodeFunctionData(fragment, inputs)
            }
          })
        : [],
    [callInputs, contract, fragment]
  )

  const results = useCallsData(calls, options)

  const latestBlockNumber = useBlockNumber()

  return useMemo(() => {
    return results.map(result => toCallState(result, contract?.interface, fragment, latestBlockNumber))
  }, [fragment, contract, results, latestBlockNumber])
}
Example #7
Source File: signatures.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
static signSetRelayerApprovalAuthorization = (
    validator: Contract,
    user: Signer & TypedDataSigner,
    allowedSender: Account,
    allowedCalldata: string,
    deadline?: BigNumberish,
    nonce?: BigNumberish
  ): Promise<string> =>
    RelayerAuthorization.signAuthorizationFor(
      RelayerAction.SetRelayerApproval,
      validator,
      user,
      allowedSender,
      allowedCalldata,
      deadline,
      nonce
    );
Example #8
Source File: resolveENSContentHash.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetches and decodes the result of an ENS contenthash lookup on mainnet to a URI
 * @param ensName to resolve
 * @param provider provider to use to fetch the data
 */
export default async function resolveENSContentHash(ensName: string, provider: Provider): Promise<string> {
  const ensRegistrarContract = new Contract(REGISTRAR_ADDRESS, REGISTRAR_ABI, provider)
  const hash = namehash(ensName)
  const resolverAddress = await ensRegistrarContract.resolver(hash)
  return resolverContract(resolverAddress, provider).contenthash(hash)
}
Example #9
Source File: useContract.ts    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
// returns null on errors
function useContract(address: string | undefined, ABI: any, withSignerIfPossible = true): Contract | null {
  const { library, account } = useActiveWeb3React()

  return useMemo(() => {
    if (!address || !ABI || !library) return null
    try {
      return getContract(address, ABI, library, withSignerIfPossible && account ? account : undefined)
    } catch (error) {
      console.error('Failed to get contract', error)
      return null
    }
  }, [address, ABI, library, withSignerIfPossible, account])
}
Example #10
Source File: utils.ts    From ether-swr with MIT License 6 votes vote down vote up
contracts = new Map<string, Contract>()
Example #11
Source File: helperFunctions.ts    From ghst-staking with MIT License 6 votes vote down vote up
export function getSelectors(contract: Contract) {
  const signatures = Object.keys(contract.interface.functions);
  const selectors = signatures.reduce((acc: string[], val: string) => {
    if (val !== "init(bytes)") {
      acc.push(contract.interface.getSighash(val));
    }
    return acc;
  }, []);
  return selectors;
}
Example #12
Source File: helperFunctions.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
export function getSelectors(contract: Contract) {
  const signatures = Object.keys(contract.interface.functions);
  const selectors = signatures.reduce((acc: string[], val: string) => {
    if (val !== "init(bytes)") {
      acc.push(contract.interface.getSighash(val));
    }
    return acc;
  }, []);
  return selectors;
}
Example #13
Source File: resolveENSContentHash.ts    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetches and decodes the result of an ENS contenthash lookup on mainnet to a URI
 * @param ensName to resolve
 * @param provider provider to use to fetch the data
 */
export default async function resolveENSContentHash(ensName: string, provider: Provider): Promise<string> {
  const ensRegistrarContract = new Contract(REGISTRAR_ADDRESS, REGISTRAR_ABI, provider)
  const hash = namehash(ensName)
  const resolverAddress = await ensRegistrarContract.resolver(hash)
  return resolverContract(resolverAddress, provider).contenthash(hash)
}
Example #14
Source File: useContract.ts    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
export function useENSRegistrarContract(withSignerIfPossible?: boolean): Contract | null {
  const { chainId } = useActiveWeb3React()
  let address: string | undefined
  if (chainId) {
    switch (chainId) {
      case ChainId.MAINNET:
      case ChainId.GĂ–RLI:
      case ChainId.ROPSTEN:
      case ChainId.RINKEBY:
        address = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'
        break
    }
  }
  return useContract(address, ENS_ABI, withSignerIfPossible)
}
Example #15
Source File: useContract.ts    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
export function useGovernanceContractBravo(): Contract | null {
  const [activeProtocol] = useActiveProtocol()

  return useContract(
    activeProtocol ? activeProtocol.governanceAddressBravo : undefined,
    activeProtocol?.id === AAVE_GOVERNANCE.id ? GOVERNANCE_AAVE_ABI : GOVERNANCE_ABI,
    true
  )
}
Example #16
Source File: TokenList.tsx    From useDApp with MIT License 6 votes vote down vote up
function useTokensBalance(tokenList?: any[], account?: string | null) {
  return useCalls(
    tokenList && account
      ? tokenList.map((token: any) => ({
          contract: new Contract(token.address, ERC20Interface),
          method: 'balanceOf',
          args: [account],
        }))
      : []
  )
}
Example #17
Source File: updater.tsx    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
/**
 * Fetches a chunk of calls, enforcing a minimum block number constraint
 * @param multicallContract multicall contract to fetch against
 * @param chunk chunk of calls to make
 * @param minBlockNumber minimum block number of the result set
 */
async function fetchChunk(
  multicallContract: Contract,
  chunk: Call[],
  minBlockNumber: number
): Promise<{ results: string[]; blockNumber: number }> {
  console.debug('Fetching chunk', multicallContract, chunk, minBlockNumber)
  let resultsBlockNumber, returnData
  try {
    ;[resultsBlockNumber, returnData] = await multicallContract.aggregate(chunk.map(obj => [obj.address, obj.callData]))
  } catch (error) {
    console.debug('Failed to fetch chunk inside retry', error)
    throw error
  }
  if (resultsBlockNumber.toNumber() < minBlockNumber) {
    console.debug(`Fetched results for old block number: ${resultsBlockNumber.toString()} vs. ${minBlockNumber}`)
    throw new RetryableError('Fetched for old block number')
  }
  return { results: returnData, blockNumber: resultsBlockNumber.toNumber() }
}
Example #18
Source File: ContractFunction.tsx    From useDApp with MIT License 6 votes vote down vote up
export function App() {
  const { account, chainId } = useEthers()
  const isSupportedChain = SUPPORTED_TEST_CHAINS.includes(chainId)

  const WrapEtherComponent = () => {
    const wethAddress = WETH_ADDRESSES[chainId]
    const wethInterface = new utils.Interface(WethAbi)
    const contract = new Contract(wethAddress, wethInterface) as any

    const { state, send } = useContractFunction(contract, 'deposit', { transactionName: 'Wrap' })
    const { status } = state

    const wrapEther = () => {
      void send({ value: 1 })
    }

    return (
      <div>
        <button onClick={() => wrapEther()}>Wrap ether</button>
        <p>Status: {status}</p>
      </div>
    )
  }

  const ChainFilter = () => {
    return isSupportedChain ? <WrapEtherComponent /> : <p>Set network to: Ropsten, Kovan, Rinkeby or Goerli</p>
  }

  return <div>{!account ? <MetamaskConnect /> : <ChainFilter />}</div>
}
Example #19
Source File: fetcher.ts    From spookyswap-sdk with MIT License 6 votes vote down vote up
/**
   * Fetches information about a pair and constructs a pair from the given two tokens.
   * @param tokenA first token
   * @param tokenB second token
   * @param provider the provider to use to fetch the data
   */
  public static async fetchPairData(
    tokenA: Token,
    tokenB: Token,
    provider = getDefaultProvider(getNetwork(tokenA.chainId))
  ): Promise<Pair> {
    invariant(tokenA.chainId === tokenB.chainId, 'CHAIN_ID')
    const address = Pair.getAddress(tokenA, tokenB)
    const [reserves0, reserves1] = await new Contract(address, IUniswapV2Pair, provider).getReserves()
    const balances = tokenA.sortsBefore(tokenB) ? [reserves0, reserves1] : [reserves1, reserves0]
    return new Pair(new TokenAmount(tokenA, balances[0]), new TokenAmount(tokenB, balances[1]))
  }
Example #20
Source File: resolveENSContentHash.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetches and decodes the result of an ENS contenthash lookup on mainnet to a URI
 * @param ensName to resolve
 * @param provider provider to use to fetch the data
 */
export default async function resolveENSContentHash(
  ensName: string,
  provider: Provider,
): Promise<string> {
  const ensRegistrarContract = new Contract(
    REGISTRAR_ADDRESS,
    REGISTRAR_ABI,
    provider,
  );
  const hash = namehash(ensName);
  const resolverAddress = await ensRegistrarContract.resolver(hash);
  return resolverContract(resolverAddress, provider).contenthash(hash);
}
Example #21
Source File: useContract.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
// returns null on errors
export function useContract<T extends Contract = Contract>(
  addressOrAddressMap: string | { [chainId: number]: string } | undefined,
  ABI: any,
  withSignerIfPossible = true
): T | null {
  const { chainId, library, account } = useWeb3();
  return useMemo(() => {
    if (!addressOrAddressMap || !ABI || !library || !chainId) return null;
    let address: string | undefined;
    if (typeof addressOrAddressMap === "string") address = addressOrAddressMap;
    else address = addressOrAddressMap[chainId];
    if (!address) return null;
    try {
      return getContract(
        address,
        ABI,
        library,
        withSignerIfPossible && account ? account : undefined
      );
    } catch (error) {
      console.error("Failed to get contract", error);
      return null;
    }
  }, [
    addressOrAddressMap,
    ABI,
    library,
    chainId,
    withSignerIfPossible,
    account,
  ]) as T;
}
Example #22
Source File: useContract.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function useDualRewardsStakingContract(
  stakingAddress?: string,
  withSignerIfPossible?: boolean,
): Contract | null {
  return useContract(
    stakingAddress,
    STAKING_DUAL_REWARDS_INTERFACE,
    withSignerIfPossible,
  );
}
Example #23
Source File: useIsArgentWallet.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
export default function useIsArgentWallet(): boolean {
  const { account } = useWeb3();
  const argentWalletDetector = useArgentWalletDetectorContract();
  const inputs = useMemo(() => [account ?? undefined], [account]);
  const call = useSingleCallResult(
    (argentWalletDetector as unknown) as Contract,
    "isArgentWallet",
    inputs,
    NEVER_RELOAD
  );
  return call?.result?.[0] ?? false;
}
Example #24
Source File: useContract.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function useMerkleDistributorContract(): Contract | null {
  const { chainId } = useActiveWeb3React();
  return useContract(
    chainId
      ? GlobalConst.addresses.MERKLE_DISTRIBUTOR_ADDRESS[chainId]
      : undefined,
    MERKLE_DISTRIBUTOR_ABI,
    true,
  );
}
Example #25
Source File: hooks.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
export function useSingleCallResult(
  contract: Contract | null | undefined,
  methodName: string,
  inputs?: OptionalMethodInputs,
  options?: ListenerOptions,
  gasRequired?: number
): CallState {
  const { chainId } = useWeb3();
  const fragment = useMemo(() => contract?.interface?.getFunction(methodName), [
    contract,
    methodName,
  ]);

  const calls = useMemo<Call[]>(() => {
    return contract && fragment && isValidMethodArgs(inputs)
      ? [
          {
            address: contract.address,
            callData: contract.interface.encodeFunctionData(fragment, inputs),
            ...(gasRequired ? { gasRequired } : {}),
          },
        ]
      : [];
  }, [contract, fragment, inputs, gasRequired]);

  const result = useCallsData(calls, options)[0];

  const latestBlockNumber = useBlockNumber(chainId);

  return useMemo(() => {
    return toCallState(
      result,
      contract?.interface,
      fragment,
      latestBlockNumber
    );
  }, [result, contract, fragment, latestBlockNumber]);
}
Example #26
Source File: useContract.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function useENSRegistrarContract(
  withSignerIfPossible?: boolean,
): Contract | null {
  const { chainId } = useActiveWeb3React();
  let address: string | undefined;
  if (chainId) {
    switch (chainId) {
      case ChainId.MATIC:
        address = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'; //TODO: MATIC
        break;
    }
  }
  return useContract(address, ENS_ABI, withSignerIfPossible);
}
Example #27
Source File: hooks.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
export function useSingleContractMultipleData(
  contract: Contract | null | undefined,
  methodName: string,
  callInputs: OptionalMethodInputs[],
  options?: ListenerOptions,
): CallState[] {
  const fragment = useMemo(() => contract?.interface?.getFunction(methodName), [contract, methodName])

  const calls = useMemo(
    () =>
      contract && fragment && callInputs && callInputs.length > 0
        ? callInputs.map<Call>((inputs) => {
            return {
              address: contract.address,
              callData: contract.interface.encodeFunctionData(fragment, inputs),
            }
          })
        : [],
    [callInputs, contract, fragment],
  )

  const results = useCallsData(calls, options)

  const latestBlockNumber = useBlockNumber()
  // console.log('block number', latestBlockNumber)

  return useMemo(() => {
    return results.map((result) => toCallState(result, contract?.interface, fragment, latestBlockNumber))
  }, [fragment, contract, results, latestBlockNumber])
}
Example #28
Source File: information.ts    From safe-tasks with GNU Lesser General Public License v3.0 6 votes vote down vote up
getModules = async (hre: HRE, safe: Contract): Promise<string[]> => {
    try {
        return (await safe.getModulesPaginated(AddressOne, 10))[0]
    } catch (e) {
    }
    try {
        const compat = await compatHandler(hre, safe.address)
        return await compat.getModules()
    } catch (e) {
    }
    return ["Could not load modules"]
}
Example #29
Source File: getTransactionReceipt.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
it('getTransactionReceipt', async () => {
  const endpoint = process.env.ENDPOINT_URL || 'ws://127.0.0.1:9944';
  const account1 = evmAccounts[0];
  const account2 = evmAccounts[1];

  const provider = EvmRpcProvider.from(endpoint);

  const account1Wallet = new Wallet(account1.privateKey).connect(provider as any);

  const acaContract = new Contract(ADDRESS.ACA, ACAABI.abi, account1Wallet);

  await provider.isReady();
  const pairs = createTestPairs();
  const oneAca = 10n ** BigInt(provider.api.registry.chainDecimals[0]);
  const Alice = pairs.alice;

  /** transfer aca */
  console.log('transfer aca');
  const extrinsic = provider.api.tx.balances.transfer(account1.defaultSubstrateAddress, 100n * oneAca);
  await extrinsic.signAsync(Alice);
  await sendTx(provider.api, extrinsic);

  const result = await acaContract.functions.transfer(account2.evmAddress, 10n * oneAca, {
    gasLimit: BigNumber.from(34132001n),
    gasPrice: BigNumber.from(200786445289n),
    type: 0
  });

  const receipt = await provider.getTransactionReceiptAtBlock(result.hash, result.blockHash);

  expect(receipt.blockHash).equal(result.blockHash);
  expect(receipt.logs.length).equal(1);
  expect(receipt.logs[0].blockNumber).equal(result.blockNumber);
  expect(receipt.logs[0].topics.length).equal(3);

  await provider.disconnect();
});