ethers#providers TypeScript Examples

The following examples show how to use ethers#providers. 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 walletconnect-v2-monorepo with Apache License 2.0 7 votes vote down vote up
export async function verifySignature(
  address: string,
  sig: string,
  hash: string,
  rpcUrl: string,
): Promise<boolean> {
  const provider = new providers.JsonRpcProvider(rpcUrl);
  const bytecode = await provider.getCode(address);
  if (!bytecode || bytecode === "0x" || bytecode === "0x0" || bytecode === "0x00") {
    const signer = recoverAddress(sig, hash);
    return signer.toLowerCase() === address.toLowerCase();
  } else {
    return eip1271.isValidSignature(address, sig, hash, provider);
  }
}
Example #2
Source File: utils.ts    From optimism-dai-bridge with GNU Affero General Public License v3.0 7 votes vote down vote up
export async function printRollupStatus(l1Provider: providers.BaseProvider) {
  const CTC = new ethers.Contract(
    optimismConfig.CanonicalTransactionChain,
    artifacts.l1.canonicalTxChain.abi,
    l1Provider,
  )
  const STC = new ethers.Contract(
    optimismConfig.StateCommitmentChain,
    artifacts.l1.stateCommitmentChain.abi,
    l1Provider,
  )

  const ctcAllElements = await CTC.getTotalElements()
  const ctcQueuedElement = await CTC.getNumPendingQueueElements()
  const stcAllElements = await STC.getTotalElements()

  console.log('Canonical Tx Chain all elements: ', ctcAllElements.toString())
  console.log('Canonical Tx Chain queued elements: ', ctcQueuedElement.toString())
  console.log('State Commitment Chain all elements: ', stcAllElements.toString())
}
Example #3
Source File: sniper.ts    From pool-sniper with The Unlicense 6 votes vote down vote up
/**
   * Updates token and purchase details + sets up RPC
   * @param {string} tokenAddress of token to purchase
   * @param {string} factoryAddress of Uniswap V2 Factory
   * @param {string} rpcEndpoint for network
   * @param {string} privateKey of purchasing wallet
   * @param {string} purchaseAmount to swap with (input)
   * @param {string} gasPrice to pay
   * @param {number} slippage for trade execution
   * @param {boolean} testnet true if testnet
   */
  constructor(
    tokenAddress: string,
    factoryAddress: string,
    rpcEndpoint: string,
    privateKey: string,
    purchaseAmount: string,
    gasPrice: string,
    slippage: number,
    testnet: boolean
  ) {
    // Setup networking + wallet
    this.rpc = new providers.JsonRpcProvider(rpcEndpoint);
    this.wallet = new Wallet(privateKey, this.rpc);

    // Setup token details
    this.tokenAddress = utils.getAddress(tokenAddress); // Normalize address
    this.factory = new Contract(factoryAddress, ABI_UniswapV2Factory, this.rpc);
    this.purchaseAmount = purchaseAmount;
    this.gasPrice = utils.parseUnits(gasPrice, "gwei");
    this.slippage = slippage;
    this.testnet = testnet;
  }
Example #4
Source File: scraper.ts    From tweetdrop with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Setup scraper
   * @param {string} conversationID to scrape
   * @param {string} twitterBearer 2.0 token
   * @param {number} numTokens to distribute per address
   * @param {string?} rpcProvider optional rpc endpoint to convert ENS names
   */
  constructor(
    conversationID: string,
    twitterBearer: string,
    numTokens: number,
    rpcProvider?: string
  ) {
    this.conversationID = conversationID;
    this.twitterBearer = twitterBearer;
    this.numTokens = numTokens;

    if (rpcProvider) {
      this.rpc = new providers.JsonRpcProvider(rpcProvider);
    }
  }
Example #5
Source File: useJsonRpcProvider.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function useJsonRpcProvider(chainId?: number) {
  const { providers: multichainProviders } = useContext(MultichainContext);

  const { library, chainId: walletChainId } = useWeb3React();

  return useMemo(
    () =>
      (!chainId || walletChainId === chainId) && library
        ? new providers.Web3Provider(library.currentProvider)
        : multichainProviders[chainId],
    [library, chainId, walletChainId, multichainProviders]
  );
}
Example #6
Source File: provider.ts    From panvala with Apache License 2.0 6 votes vote down vote up
async function checkNetwork(provider: providers.Web3Provider): Promise<boolean> {
  let targetNetwork;
  if (publicRuntimeConfig.panvalaEnv === 'production') {
    targetNetwork = networks.MAINNET;
  } else if (publicRuntimeConfig.panvalaEnv === 'staging') {
    targetNetwork = networks.RINKEBY;
  }

  let connectedNetwork = await provider.getNetwork();

  if (targetNetwork && targetNetwork.chainId !== connectedNetwork.chainId) {
    const msg = `Wrong network: connected to ${connectedNetwork.name}, should be ${
      targetNetwork.name
    }`;
    throw new Error(msg);
  }

  return true;
}
Example #7
Source File: injectedProvider.ts    From useDApp with MIT License 6 votes vote down vote up
export async function getInjectedProvider(pollingInterval: number) {
  const injectedProvider: any = await detectEthereumProvider()
  if (!injectedProvider) {
    return undefined
  }

  const provider = new providers.Web3Provider(injectedProvider, 'any')
  provider.pollingInterval = pollingInterval
  return provider
}
Example #8
Source File: eip1271.ts    From walletconnect-v2-monorepo with Apache License 2.0 6 votes vote down vote up
async function isValidSignature(
  address: string,
  sig: string,
  data: string,
  provider: providers.Provider,
  abi = eip1271.spec.abi,
  magicValue = eip1271.spec.magicValue,
): Promise<boolean> {
  let returnValue;
  try {
    returnValue = await new Contract(address, abi, provider).isValidSignature(
      utils.arrayify(data),
      sig,
    );
  } catch (e) {
    return false;
  }
  return returnValue.toLowerCase() === magicValue.toLowerCase();
}
Example #9
Source File: provider.ts    From celo-web-wallet with MIT License 6 votes vote down vote up
function isProviderSynced(block?: providers.Block, network?: providers.Network) {
  return (
    block &&
    block.number &&
    block.timestamp &&
    !isStale(block.timestamp * 1000, STALE_BLOCK_TIME * 6) &&
    network &&
    network.chainId === config.chainId
  )
}
Example #10
Source File: ContractsAPI.ts    From client with GNU General Public License v3.0 6 votes vote down vote up
/**
   * This function is called by {@link TxExecutor} before a transaction is queued.
   * It gives the client an opportunity to prevent a transaction from being queued based
   * on business logic or user interaction.
   *
   * Reject the promise to prevent the queued transaction from being queued.
   */
  private async beforeQueued(
    id: TransactionId,
    intent: TxIntent,
    overrides?: providers.TransactionRequest
  ): Promise<void> {
    const address = this.ethConnection.getAddress();
    if (!address) throw new Error("can't send a transaction, no signer");

    const balance = await this.ethConnection.loadBalance(address);

    if (balance.lt(ContractsAPI.MIN_BALANCE)) {
      const notifsManager = NotificationManager.getInstance();
      notifsManager.balanceEmpty();
      throw new Error('xDAI balance too low!');
    }

    const gasFeeGwei = EthersBN.from(overrides?.gasPrice || '1000000000');

    await openConfirmationWindowForTransaction({
      contractAddress: this.contractAddress,
      connection: this.ethConnection,
      id,
      intent,
      overrides,
      from: address,
      gasFeeGwei,
    });
  }
Example #11
Source File: web3.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useEthereum = (
  defaultSigner: boolean = true,
): {
  chainId: 1 | 42;
  provider: providers.JsonRpcProvider;
} => {
  // Default to mainnet
  const { chainId, library } = useWeb3React();

  let ethChainId: 1 | 42 = 1;
  if (!chainId || chainId === 10) {
    ethChainId = 1;
  } else if (chainId === 1 || chainId === 42) {
    ethChainId = chainId;
  } else if (chainId === 69) {
    ethChainId = 42;
  }

  const rpcProvider = useRPCProvider(ethChainId);
  const [provider, setProvider] = useState<providers.JsonRpcProvider>(rpcProvider);

  useEffect(() => {
    if (chainId && defaultSigner && chainId === ethChainId) {
      setProvider(library.getSigner());
    } else {
      setProvider(rpcProvider);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chainId, defaultSigner, ethChainId, rpcProvider]);

  return { provider, chainId: ethChainId };
}
Example #12
Source File: helpers.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
function getProvider(networkName: NetworkNames = NetworkNames.LocalA): providers.JsonRpcProvider {
  let result: providers.JsonRpcProvider = null;

  switch (networkName) {
    case NetworkNames.LocalA:
      result = localAProvider;
      break;

    case NetworkNames.LocalB:
      result = localBProvider;
      break;
  }

  return result;
}
Example #13
Source File: get.block.with.transactions.ts    From forta-bot-sdk with MIT License 6 votes vote down vote up
export default function provideGetBlockWithTransactions(
  ethersProvider: providers.JsonRpcProvider,
  cache: Cache
) {
  assertExists(ethersProvider, 'ethersProvider')
  assertExists(cache, 'cache')

  return async function getBlockWithTransactions(blockHashOrNumber: string | number) {
    // check the cache first
    const cachedBlock = cache.getKey(blockHashOrNumber.toString().toLowerCase())
    if (cachedBlock) return cachedBlock

    // determine whether to call getBlockByNumber (default) or getBlockByHash based on input
    let methodName = "eth_getBlockByNumber"
    if (typeof blockHashOrNumber === "string") {
      if (!blockHashOrNumber.startsWith("0x")) {
        blockHashOrNumber = parseInt(blockHashOrNumber)
      } else {
        methodName = "eth_getBlockByHash"
      }
    }

    // fetch the block
    const block = await ethersProvider.send(
      methodName,
      [ethers.utils.hexValue(blockHashOrNumber), true]
    )
    cache.setKey(block.hash.toLowerCase(), block)
    cache.setKey(parseInt(block.number).toString(), block)
    return block
  }
}
Example #14
Source File: tokenBalanceCache.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public async getEthTokenBalance(url: string, network: string,
  tokenAddress: string, userAddress: string): Promise<BN> {
    const provider = new Web3.providers.WebsocketProvider(url);
    let api;
    if(network === ChainNetwork.ERC20) {
      api = ERC20__factory.connect(tokenAddress, new providers.Web3Provider(provider as any));
    }
    else if(network === ChainNetwork.ERC721) {
      api = ERC721__factory.connect(tokenAddress, new providers.Web3Provider(provider as any));
    }
    else {
      throw new Error('Invalid token chain network');
    }
    await api.deployed();
    const balanceBigNum = await api.balanceOf(userAddress);
    provider.disconnect(1000, 'finished');
    return new BN(balanceBigNum.toString());
  }
Example #15
Source File: faucet.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Takes an array of transactions, signs them and
 * broadcasts them.
 * @param signer Used to sign transactions
 * @param txparams the transaction
 */
async function send(signer: providers.JsonRpcSigner, txparams: UnsignedTransaction): Promise<void> {
  try {
    const tx = await signer.sendTransaction(txparams)
    const txReceipt = await tx.wait()
    console.log(`Funding transaction included on-chain in block #${txReceipt.blockNumber}`)
  } catch (err) {
    console.log(`Error: ${err}`)
  }
}
Example #16
Source File: ethers-provider.ts    From simple-uniswap-sdk with MIT License 6 votes vote down vote up
/**
   * Get the network
   */
  public network(): providers.Network {
    if (this._ethersProvider.network) {
      return this._ethersProvider.network;
    }

    // @ts-ignore
    if (this._ethersProvider.provider) {
      // @ts-ignore
      const chainId = this._ethersProvider.provider.chainId;
      if (chainId) {
        const chainIdNumber = new BigNumber(chainId).toNumber();
        const chainName = ChainNames.get(chainIdNumber);
        if (chainName) {
          return {
            chainId: chainIdNumber,
            name: chainName,
          };
        }
      }
    }

    throw new UniswapError(
      'chainId can not be found on the provider',
      ErrorCodes.chainIdCanNotBeFound
    );
  }
Example #17
Source File: analyzeEip1967Proxy.ts    From l2beat with MIT License 6 votes vote down vote up
export async function analyzeEip1967Proxy(
  provider: providers.Provider,
  addressAnalyzer: AddressAnalyzer,
  proxyAddress: string
) {
  const [implementationSlot, adminSlot] = await Promise.all([
    provider.getStorageAt(proxyAddress, IMPLEMENTATION_SLOT),
    provider.getStorageAt(proxyAddress, ADMIN_SLOT),
  ])
  if (implementationSlot === '0x' + '0'.repeat(64)) {
    return undefined
  }
  const implementation = wordToAddress(implementationSlot)
  const admin = wordToAddress(adminSlot)
  const { name } = await addressAnalyzer.analyze(
    EthereumAddress(implementation)
  )
  return {
    name,
    eip1967Implementation: implementation,
    eip1967Admin: admin,
  }
}
Example #18
Source File: messaging.ts    From arbitrum-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function waitToRelayTxsToL2(
  inProgressL1Tx: Promise<providers.TransactionReceipt>,
  inboxAddress: string,
  l1: ethers.providers.BaseProvider,
  l2: ethers.providers.BaseProvider,
) {
  const l1Tx = await inProgressL1Tx
  const seqNums = await getInboxSeqNumFromContractTransaction(l1Tx, inboxAddress, l1)
  const seqNum = seqNums && seqNums[0]
  if (!seqNum) {
    throw new Error('Seq num not found')
  }
  const retryableTicket = await calculateL2TransactionHash(seqNum, l2)
  const autoRedeem = calculateRetryableAutoRedeemTxnHash(retryableTicket)
  const redeemTransaction = calculateL2RetryableTransactionHash(retryableTicket)

  console.log(
    `Waiting for xchain messages to be relayed... L1 hash: ${l1Tx.transactionHash}, L2 tx hash: ${retryableTicket}, L2 auto redeem tx: ${redeemTransaction}`,
  )

  const retryableTicketReceipt = await l2.waitForTransaction(retryableTicket, undefined, 1000 * 60 * 15)
  expect(retryableTicketReceipt.status).to.equal(1)

  const autoRedeemReceipt = await l2.waitForTransaction(autoRedeem, undefined, 1000 * 60)
  expect(autoRedeemReceipt.status).to.equal(1)

  const redemptionReceipt = await l2.getTransactionReceipt(redeemTransaction)
  expect(redemptionReceipt.status).equals(1)
  console.log('Xchain message arrived')
}
Example #19
Source File: NetworkProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
JsonRpcProvider: FC = ({ children }) => {
  const network = useContext(networkCtx)

  const value = useMemo(() => {
    if (!network) return undefined

    const { rpcEndpoints, parentChainId } = network
    const provider = new providers.FallbackProvider(rpcEndpoints.map(e => new providers.JsonRpcProvider(e)))

    let parentChainProvider
    if (parentChainId) {
      const { rpcEndpoints: parentRpcEndpoints } = getNetwork(parentChainId)
      parentChainProvider = new providers.FallbackProvider(parentRpcEndpoints.map(e => new providers.JsonRpcProvider(e)))
    }

    return { provider, parentChainProvider }
  }, [network])

  return <jsonRpcCtx.Provider value={value}>{children}</jsonRpcCtx.Provider>
}
Example #20
Source File: useReadonlyProvider.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a provider that's constructed using the readonly RPC URL.
 */
export function useReadonlyProvider(): providers.JsonRpcProvider | undefined {
  const config = useConfig();
  const rpcURL = config?.readOnlyUrls?.[CHAIN_ID] as string | undefined;
  return useMemo(() => {
    if (!rpcURL) {
      return;
    }
    return new providers.JsonRpcProvider(rpcURL);
  }, [rpcURL]);
}
Example #21
Source File: fixtures.ts    From staking-factory with MIT License 6 votes vote down vote up
export async function stakingRewardsFactoryFixture(
  [wallet]: Wallet[],
  provider: providers.Web3Provider
): Promise<StakingRewardsFactoryFixture> {
  const rewardsToken = await deployContract(wallet, TestERC20, [expandTo18Decimals(1_000_000_000)])

  // deploy staking tokens
  const stakingTokens = []
  for (let i = 0; i < NUMBER_OF_STAKING_TOKENS; i++) {
    const stakingToken = await deployContract(wallet, TestERC20, [expandTo18Decimals(1_000_000_000)])
    stakingTokens.push(stakingToken)
  }

  // deploy the staking rewards factory
  const { timestamp: now } = await provider.getBlock('latest')
  const genesis = now + 60 * 60
  const rewardAmounts: BigNumber[] = new Array(stakingTokens.length).fill(expandTo18Decimals(10))
  const stakingRewardsFactory = await deployContract(wallet, StakingRewardsFactory, [rewardsToken.address, genesis])

  return { rewardsToken, stakingTokens, genesis, rewardAmounts, stakingRewardsFactory }
}
Example #22
Source File: eip1271.ts    From snapshot-hub with MIT License 6 votes vote down vote up
export async function isValidSignature(
  address: string,
  sig: string,
  data: string,
  provider: providers.Provider,
  abi = spec.abi,
  magicValue = spec.magicValue
): Promise<boolean> {
  let returnValue;
  try {
    returnValue = await new Contract(address, abi, provider).isValidSignature(
      utils.arrayify(data),
      sig
    );
  } catch (e) {
    // if failed is latest then it might be older implementation
    if (magicValue === spec.magicValue) {
      return isValidSignature(
        address,
        sig,
        data,
        provider,
        spec_oldVersion.abi, // old spec version abi
        spec_oldVersion.magicValue // old spec version magicValue
      );
    }

    return false;
  }
  return returnValue.toLowerCase() === magicValue.toLowerCase();
}
Example #23
Source File: App.tsx    From js-examples with MIT License 6 votes vote down vote up
getSigner = async () => {
    if (!(window as WindowInstanceWithEthereum).ethereum) {
      throw new Error(
        'Ethereum is not connected. Please download Metamask from https://metamask.io/download.html'
      );
    }

    console.debug('Initializing web3 provider...');
    // @ts-ignore
    const provider = new providers.Web3Provider((window as WindowInstanceWithEthereum).ethereum);
    const signer = provider.getSigner();
    return signer
  }
Example #24
Source File: keyless.ts    From hubble-contracts with MIT License 6 votes vote down vote up
async function main() {
    const provider = new ethers.providers.JsonRpcProvider(argv.url);
    if (argv.check) {
        if (argv.offline) {
            await checkKeylessDeploymentSetup();
        } else {
            await checkKeylessDeploymentSetup(provider);
        }
    } else if (argv.deploy) {
        await deploy(provider);
    }
}
Example #25
Source File: sniper.ts    From pool-sniper with The Unlicense 5 votes vote down vote up
// Ethers provider
  rpc: providers.JsonRpcProvider;
Example #26
Source File: scraper.ts    From tweetdrop with GNU Affero General Public License v3.0 5 votes vote down vote up
// Optional RPC to resolve ENS names to addresses
  rpc?: providers.JsonRpcProvider | null;
Example #27
Source File: ENSService.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
setWeb3Provider(web3Provider: providers.JsonRpcProvider) {
    console.debug('[ENSService] Setting Mainnet Web3 provider', web3Provider);
    this.web3Provider = web3Provider;
  }
Example #28
Source File: provider.ts    From panvala with Apache License 2.0 5 votes vote down vote up
// contract abstractions for gate_keeper and token_capacitor
export async function connectContracts(provider: providers.Web3Provider): Promise<IContracts> {
  // Check that we're connected to the expected network
  await checkNetwork(provider);

  const [tcAbi, tokenAbi, paramsAbi]: [any[], any[], any[]] = [
    abis.TokenCapacitor.abi,
    abis.BasicToken.abi,
    abis.ParameterStore.abi,
  ];
  const gkAbi: any[] =
    publicRuntimeConfig.panvalaEnv !== 'production'
      ? abis.TimeTravelingGatekeeper.abi
      : abis.Gatekeeper.abi;

  // read addresses from env vars
  const gkAddress: string =
    publicRuntimeConfig.gatekeeperAddress || process.env.STORYBOOK_GATEKEEPER_ADDRESS;
  const tcAddress: string =
    publicRuntimeConfig.tokenCapacitorAddress || process.env.STORYBOOK_TOKEN_CAPACITOR_ADDRESS;

  try {
    await provider.getCode(tcAddress);
  } catch (error) {
    throw new Error(`ERROR contract not deployed: TokenCapacitor at ${tcAddress}`);
  }

  try {
    await provider.getCode(gkAddress);
  } catch (error) {
    throw new Error(`ERROR contract not deployed: Gatekeeper at ${gkAddress}`);
  }

  // init ethers contract abstractions
  const gk: ethers.Contract = new ethers.Contract(gkAddress, gkAbi, provider);
  const tc: ethers.Contract = new ethers.Contract(tcAddress, tcAbi, provider);

  // connect metamask wallet/signer to contracts
  const signer: providers.JsonRpcSigner = provider.getSigner();
  const tokenCapacitor: TokenCapacitor = tc.connect(signer) as TokenCapacitor;
  const gatekeeper: Gatekeeper = gk.connect(signer) as Gatekeeper;

  // get the token and parameter_store associated with the gate_keeper
  try {
    const tokenAddress: string = await gatekeeper.functions.token();
    const tokenContract: ethers.Contract = new ethers.Contract(tokenAddress, tokenAbi, provider);
    // connect metamask wallet/signer to token contract
    const token: BasicToken = tokenContract.connect(signer) as BasicToken;

    const paramsAddress: string = await gatekeeper.functions.parameters();
    const parameterStoreContract: ethers.Contract = new ethers.Contract(
      paramsAddress,
      paramsAbi,
      provider
    );
    const parameterStore: ParameterStore = parameterStoreContract.connect(signer) as ParameterStore;

    return { tokenCapacitor, gatekeeper, token, parameterStore };
  } catch (error) {
    console.error(`ERROR while attempting to connect token or parameter store: ${error.message}`);
    throw error;
  }
}
Example #29
Source File: performMulticall.ts    From useDApp with MIT License 5 votes vote down vote up
export function performMulticall(
  provider: providers.BaseProvider,
  multicallExecutor: (
    provider: providers.BaseProvider,
    multicallAddress: string,
    blockNumber: number,
    uniqueCalls: RawCall[]
  ) => Promise<any>,
  multicallAddress: string,
  blockNumber: number,
  uniqueCalls: RawCall[],
  dispatchState: Dispatch<ChainStateAction>,
  chainId: ChainId,
  reportError: (error: Error) => void
) {
  if (uniqueCalls.length === 0) {
    return
  }

  const start = Date.now()
  multicallExecutor(provider, multicallAddress, blockNumber, uniqueCalls)
    .then((state) => {
      dispatchState({ type: 'FETCH_SUCCESS', blockNumber, chainId, state })
      notifyDevtools({
        type: 'MULTICALL_SUCCESS',
        duration: Date.now() - start,
        chainId,
        blockNumber,
        multicallAddress,
        state,
      })
    })
    .catch((error) => {
      reportError(error)
      dispatchState({ type: 'FETCH_ERROR', blockNumber, chainId, error })
      notifyDevtools({
        type: 'MULTICALL_ERROR',
        duration: Date.now() - start,
        chainId,
        blockNumber,
        multicallAddress,
        calls: uniqueCalls,
        error,
      })
    })
}