@ethersproject/providers#JsonRpcProvider TypeScript Examples

The following examples show how to use @ethersproject/providers#JsonRpcProvider. 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: index.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
MultichainProvider = ({ children }) => {
  const rpcUrls = useRpcUrls();

  const providers = useMemo(() => {
    if (!rpcUrls) return null;

    return Object.entries(rpcUrls).reduce((acc, [networkId, rpcUrl]) => {
      acc[Number.parseInt(networkId)] = new JsonRpcProvider(rpcUrl);
      return acc;
    }, {} as Record<number, JsonRpcProvider>);
  }, [rpcUrls]);

  if (!providers) return null;

  return (
    <MultichainContext.Provider
      value={{
        providers,
      }}
    >
      {children}
    </MultichainContext.Provider>
  );
}
Example #2
Source File: uniswapV3Fixture.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
/**
   * Instantiates a new UniswapV3Fixture
   *
   * @param provider      the ethers web3 provider to use
   * @param ownerAddress  the address of the owner
   */
  constructor(provider: Web3Provider | JsonRpcProvider, ownerAddress: Address) {
    this._ownerSigner = provider.getSigner(ownerAddress);
    this._deployer = new DeployHelper(this._ownerSigner);
  }
Example #3
Source File: get-gas-price.ts    From lobis-frontend with MIT License 6 votes vote down vote up
getGasPrice = async (provider: JsonRpcProvider) => {
    const feeData = await provider.getFeeData();

    return !feeData.maxFeePerGas
        ? {
              gasPrice: feeData.gasPrice,
          }
        : {
              maxFeePerGas: feeData.maxFeePerGas?.mul(80).div(100),
              maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
          };
}
Example #4
Source File: get-treasury.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
export async function getTreasuryBalance() {
  let result = 0;
  for (let i = 0; i < treasury_assets.length; i++) {
    result +=
      (await getBalance(DEFAULD_NETWORK, new JsonRpcProvider(getMainnetURI()), treasury_assets[i])) *
      (await obtainTokenPrice(treasury_assets[i]));
  }
  return result;
}
Example #5
Source File: ContractWrapper.ts    From set.js with Apache License 2.0 6 votes vote down vote up
/**
   * Load Controller contract
   *
   * @param  controllerAddress  Address of the Controller contract
   * @param  signer             Caller of the methods
   * @return                    The Controller Contract
   */
  public async loadControllerContractAsync(
    controllerAddress: Address,
    callerAddress?: Address,
  ): Promise<Controller> {
    const signer = (this.provider as JsonRpcProvider).getSigner(callerAddress);
    const cacheKey = `Controller_${controllerAddress}_${await signer.getAddress()}`;

    if (cacheKey in this.cache) {
      return this.cache[cacheKey] as Controller;
    } else {
      const controllerContract = Controller__factory.connect(
        controllerAddress,
        signer
      );

      this.cache[cacheKey] = controllerContract;
      return controllerContract;
    }
  }
Example #6
Source File: uniswap.currency.service.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
/**
     * Fetches information about a liquidity pair and constructs a pair from the given two tokens.
     */
  private async fetchPairData(tokenA: Token, tokenB: Token, provider: JsonRpcProvider, factoryAddress: string, initCodeHash: string): Promise<Pair> {
    // Can't fetch a pair made of a single token...
    if (tokenA.address === tokenB.address) {
      return null;
    }

    try {
      const { Pair } = await lazyCustomUniswapSDKImport();

      var address = Pair.getAddress(tokenA, tokenB, factoryAddress, initCodeHash);

      const Contract = await lazyEthersContractImport();
      let _ref = await new Contract(address, IUniswapV2Pair.abi, provider).getReserves();

      var reserves0 = _ref[0],
        reserves1 = _ref[1];
      var balances = tokenA.sortsBefore(tokenB) ? [reserves0, reserves1] : [reserves1, reserves0];

      const { CurrencyAmount } = await lazyUniswapSDKCoreImport();
      let currencyAmount0 = CurrencyAmount.fromRawAmount(tokenA, balances[0]);
      let currencyAmount1 = CurrencyAmount.fromRawAmount(tokenB, balances[1]);

      return new Pair(currencyAmount0, currencyAmount1, factoryAddress, initCodeHash);
    } catch (e) {
      //Logger.log('walletdebug', 'fetchPairData error', tokenA, tokenB, e);
      return null;
    }
  }
Example #7
Source File: service.ts    From data-transport-layer with MIT License 6 votes vote down vote up
protected async _init(): Promise<void> {
    if (this.options.legacySequencerCompatibility) {
      this.logger.info(
        'Using legacy sync, this will be quite a bit slower than normal'
      )
    }

    this.state.db = new TransportDB(this.options.db)

    this.state.l2RpcProvider =
      typeof this.options.l2RpcProvider === 'string'
        ? new JsonRpcProvider(this.options.l2RpcProvider)
        : this.options.l2RpcProvider
  }
Example #8
Source File: common.ts    From integration-tests with MIT License 6 votes vote down vote up
getl2Provider = (): JsonRpcProvider => {
  if (!l2Provider) {
    l2Provider = new JsonRpcProvider(Config.L2NodeUrlWithPort())
    l2Provider.getGasPrice = async () => {
      return BigNumber.from(0)
    }
  }
  return l2Provider
}
Example #9
Source File: deployKovan.ts    From optimism-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
async function main() {
  console.log('Deploying on kovan')
  const l1Provider = new JsonRpcProvider(L1_KOVAN_RPC_URL)
  const l1Deployer = new hre.ethers.Wallet(L1_KOVAN_DEPLOYER_PRIV_KEY, l1Provider)

  const l2Provider = new JsonRpcProvider(L2_KOVAN_RPC_URL)
  const l2Deployer = new hre.ethers.Wallet(L2_KOVAN_DEPLOYER_PRIV_KEY, l2Provider)

  const deploymentInfo = await deploy({
    desiredL2DaiAddress: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',
    l1Deployer: l1Deployer,
    l2Deployer: l2Deployer,
    L1_DAI_ADDRESS: L1_KOVAN_DAI_ADDRESS,
    L1_PAUSE_PROXY_ADDRESS: L1_KOVAN_PAUSE_PROXY_ADDRESS,
    L1_ESM_ADDRESS: L1_KOVAN_ESM_ADDRESS,
    L2_XDOMAIN_MESSENGER: L2_KOVAN_XDOMAIN_MESSENGER,
    L1_XDOMAIN_MESSENGER: L1_KOVAN_XDOMAIN_MESSENGER,
    L1_TX_OPTS: {
      gasPrice: 3000000000, // 3 gwei
    },
    L2_TX_OPTS: {},
  })

  const allContractInfo = {
    l1Dai: L1_KOVAN_DAI_ADDRESS,
    ...mapValues(deploymentInfo, (v) => v.address),
  }

  console.log(JSON.stringify(allContractInfo, null, 2))
}
Example #10
Source File: mediaInfo.ts    From core with GNU General Public License v3.0 6 votes vote down vote up
async function start() {
  const args = require('minimist')(process.argv.slice(2), {
    string: ['tokenURI', 'metadataURI', 'contentHash', 'metadataHash'],
  });

  if (!args.chainId) {
    throw new Error('--chainId chain ID is required');
  }
  if (!args.tokenId && args.tokenId !== 0) {
    throw new Error('--tokenId token ID is required');
  }
  const path = `${process.cwd()}/.env${
    args.chainId === 1 ? '.prod' : args.chainId === 4 ? '.dev' : '.local'
  }`;
  await require('dotenv').config({ path });
  const provider = new JsonRpcProvider(process.env.RPC_ENDPOINT);
  const wallet = new Wallet(`0x${process.env.PRIVATE_KEY}`, provider);
  const sharedAddressPath = `${process.cwd()}/addresses/${args.chainId}.json`;
  // @ts-ignore
  const addressBook = JSON.parse(await fs.readFileSync(sharedAddressPath));
  if (!addressBook.media) {
    throw new Error(`Media contract has not yet been deployed`);
  }

  const media = MediaFactory.connect(addressBook.media, wallet);

  const tokenURI = await media.tokenURI(args.tokenId);
  const contentHash = await media.tokenContentHashes(args.tokenId);
  const metadataURI = await media.tokenMetadataURI(args.tokenId);
  const metadataHash = await media.tokenMetadataHashes(args.tokenId);

  console.log(`Media Information for token ${args.tokenId}`);
  console.log({ tokenURI, contentHash, metadataURI, metadataHash });
}
Example #11
Source File: seed.ts    From zora-v1-subgraph with MIT License 6 votes vote down vote up
async function setUpNewCurrency(
  provider: JsonRpcProvider,
  masterWallet: Wallet,
  marketAddress: string,
  name: string,
  symbol: string
) {
  let currencyAddress = await deployCurrency(masterWallet, name, symbol)

  // mint 100,000 BRECK for each wallet
  console.log('Currency Address: ', currencyAddress)

  console.log('Minting Currency for Each Generated Wallet')
  for (const wallet of generatedWallets(provider)) {
    await mintCurrency(
      masterWallet,
      currencyAddress,
      wallet.address,
      BigNumber.from('100000000000000000000000')
    )
  }

  // for each address approve the market max uint256
  console.log('Granting Approval to Market Contract for each Generated Wallet')
  for (const wallet of generatedWallets(provider)) {
    await approveCurrency(wallet, currencyAddress, marketAddress)
  }
}
Example #12
Source File: index.ts    From snapshot-plugins with MIT License 6 votes vote down vote up
mustBeEthereumContractAddress = memoize(
  async (network: string, address: string) => {
    const provider = getProvider(network) as JsonRpcProvider;
    const contractCode = await provider.getCode(address);

    return (
      contractCode && contractCode.replace('0x', '').replace(/0/g, '') !== ''
    );
  },
  (url, contractAddress) => `${url}_${contractAddress}`
)
Example #13
Source File: index.ts    From pownft-miner with Apache License 2.0 6 votes vote down vote up
function loadConfig() : Config {

    const targetFile = join(__dirname, '..', 'config.json');
    const config = JSON.parse(readFileSync(targetFile) as any);
    const accountPath = `m/44'/60'/0'/0/${config.index}`;

    const provider = new JsonRpcProvider(config.provider);
    const wallet = Wallet.fromMnemonic(config.mnemonic, accountPath).connect(provider);

    const gasLimit = parseUnits(BigNumber.from(config.gasLimit).toString(), 'gwei');

    return {
        provider,
        signer: wallet,
        numCores: config.numCores,
        gasLimit,
        chunkSize: config.chunkSize,
        dryRun: config.dryRun,
    }    
}
Example #14
Source File: ethers.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
getFantomProvider = (): JsonRpcProvider => {
    const { fantomNode } = getEnv();
    let rpcUrl: string;
    if (fantomNode === undefined) {
        rpcUrl = 'https://rpc.ftm.tools/';
    } else {
        rpcUrl = fantomNode;
    }
    const provider = new JsonRpcProvider(rpcUrl);

    return provider;
}
Example #15
Source File: blockchainUtils.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
constructor(_provider: Web3Provider | JsonRpcProvider) {
    this._provider = _provider;

    this._snapshotId = 0;
  }
Example #16
Source File: get-gas-price.ts    From rugenerous-frontend with MIT License 5 votes vote down vote up
getGasPrice = async (provider: JsonRpcProvider) => {
  const gasPrice = await provider.getGasPrice();
  const convertGas = utils.parseUnits(GAS, "gwei");
  return gasPrice.add(convertGas);
}
Example #17
Source File: get-gas-price.ts    From wonderland-frontend with MIT License 5 votes vote down vote up
getGasPrice = async (provider: JsonRpcProvider) => {
    const gasPrice = await provider.getGasPrice();
    const convertGas = utils.parseUnits(GAS, "gwei");
    return gasPrice.add(convertGas);
}
Example #18
Source File: ethereum.service.ts    From runebot with MIT License 5 votes vote down vote up
constructor(protected readonly configService: AppConfigService) {
    const { url, network } = this.configService.ethereum;
    this.provider = new JsonRpcProvider(url, network);
  }
Example #19
Source File: import.helper.ts    From Elastos.Essentials.App with MIT License 5 votes vote down vote up
lazyEthersJsonRPCProviderImport = async (): Promise<typeof JsonRpcProvider> => {
  if (!importsCache["@ethersproject/providers"])
    importsCache["@ethersproject/providers"] = await import("@ethersproject/providers");

  return importsCache["@ethersproject/providers"].JsonRpcProvider;
}
Example #20
Source File: service.ts    From data-transport-layer with MIT License 5 votes vote down vote up
protected async _init(): Promise<void> {
    this.state.db = new TransportDB(this.options.db)

    this.state.l1RpcProvider =
      typeof this.options.l1RpcProvider === 'string'
        ? new JsonRpcProvider(this.options.l1RpcProvider)
        : this.options.l1RpcProvider

    this.logger.info('Using AddressManager', {
      addressManager: this.options.addressManager,
    })

    const Lib_AddressManager = loadContract(
      'Lib_AddressManager',
      this.options.addressManager,
      this.state.l1RpcProvider
    )

    const code = await this.state.l1RpcProvider.getCode(
      Lib_AddressManager.address
    )
    if (fromHexString(code).length === 0) {
      throw new Error(
        `Provided AddressManager doesn't have any code: ${Lib_AddressManager.address}`
      )
    }

    try {
      // Just check to make sure this doesn't throw. If this is a valid AddressManager, then this
      // call should succeed. If it throws, then our AddressManager is broken. We don't care about
      // the result.
      await Lib_AddressManager.getAddress(
        `Here's a contract name that definitely doesn't exist.`
      )
    } catch (err) {
      throw new Error(
        `Seems like your AddressManager is busted: ${Lib_AddressManager.address}`
      )
    }

    // Would be nice if this weren't necessary, maybe one day.
    // TODO: Probably just assert inside here that all of the contracts have code in them.
    this.state.contracts = await loadOptimismContracts(
      this.state.l1RpcProvider,
      this.options.addressManager
    )

    const startingL1BlockNumber = await this.state.db.getStartingL1Block()
    if (startingL1BlockNumber) {
      this.state.startingL1BlockNumber = startingL1BlockNumber
    } else {
      this.logger.info(
        'Attempting to find an appropriate L1 block height to begin sync...'
      )
      this.state.startingL1BlockNumber = await this._findStartingL1BlockNumber()
      this.logger.info('Starting sync', {
        startingL1BlockNumber: this.state.startingL1BlockNumber,
      })

      await this.state.db.setStartingL1Block(this.state.startingL1BlockNumber)
    }

    // Store the total number of submitted transactions so the server can tell clients if we're
    // done syncing or not
    const totalElements = await this.state.contracts.OVM_CanonicalTransactionChain.getTotalElements()
    if (totalElements > 0) {
      await this.state.db.putHighestL2BlockNumber(totalElements - 1)
    }
  }
Example #21
Source File: common.ts    From integration-tests with MIT License 5 votes vote down vote up
l1Provider: JsonRpcProvider
Example #22
Source File: deploy.ts    From core with GNU General Public License v3.0 5 votes vote down vote up
async function start() {
  const args = require('minimist')(process.argv.slice(2));

  if (!args.chainId) {
    throw new Error('--chainId chain ID is required');
  }
  const path = `${process.cwd()}/.env${
    args.chainId === 1 ? '.prod' : args.chainId === 4 ? '.dev' : '.local'
  }`;
  await require('dotenv').config({ path });
  const provider = new JsonRpcProvider(process.env.RPC_ENDPOINT);
  const wallet = new Wallet(`0x${process.env.PRIVATE_KEY}`, provider);
  const sharedAddressPath = `${process.cwd()}/addresses/${args.chainId}.json`;
  // @ts-ignore
  const addressBook = JSON.parse(await fs.readFileSync(sharedAddressPath));
  if (addressBook.market) {
    throw new Error(
      `market already exists in address book at ${sharedAddressPath}. Please move it first so it is not overwritten`
    );
  }
  if (addressBook.media) {
    throw new Error(
      `media already exists in address book at ${sharedAddressPath}. Please move it first so it is not overwritten`
    );
  }

  console.log('Deploying Market...');
  const deployTx = await new MarketFactory(wallet).deploy();
  console.log('Deploy TX: ', deployTx.deployTransaction.hash);
  await deployTx.deployed();
  console.log('Market deployed at ', deployTx.address);
  addressBook.market = deployTx.address;

  console.log('Deploying Media...');
  const mediaDeployTx = await new MediaFactory(wallet).deploy(
    addressBook.market
  );
  console.log(`Deploy TX: ${mediaDeployTx.deployTransaction.hash}`);
  await mediaDeployTx.deployed();
  console.log(`Media deployed at ${mediaDeployTx.address}`);
  addressBook.media = mediaDeployTx.address;

  console.log('Configuring Market...');
  const market = MarketFactory.connect(addressBook.market, wallet);
  const tx = await market.configure(addressBook.media);
  console.log(`Market configuration tx: ${tx.hash}`);
  await tx.wait();
  console.log(`Market configured.`);

  await fs.writeFile(sharedAddressPath, JSON.stringify(addressBook, null, 2));
  console.log(`Contracts deployed and configured. ☼☽`);
}
Example #23
Source File: auctionHouse.ts    From zora-v1-subgraph with MIT License 5 votes vote down vote up
async function runAuction() {
  const args = require('minimist')(process.argv.slice(2))

  if (!args.chainId) {
    throw new Error('--chainId chain ID is required')
  }
  if(!args.tokenId && args.tokenId !==  0) {
    throw new Error('--tokenId is required')
  }
  const path = `${process.cwd()}/.env${
    args.chainId === 1 ? '.prod' : args.chainId === 4 ? '.dev' : '.local'
  }`
  await require('dotenv').config({path})

  const provider = new JsonRpcProvider(process.env.RPC_ENDPOINT)

  let [creator, curator, bidder1, bidder2] = privateKeys.map((pk) => new Wallet(pk, provider))

  const sharedAddressPath = `${process.cwd()}/config/${args.chainId}.json`
  // @ts-ignore
  const config = JSON.parse(await fs.readFile(sharedAddressPath))

  if (config.mediaAddress === null) {
    throw new Error('media address not specified in config')
  }

  if (config.marketAddress === null) {
    throw new Error('market address not specified in config')
  }

  if(config.auctionHouseAddress === null) {
    throw new Error('auctionHouse address not specified in config')
  }

  const { mediaAddress, marketAddress, auctionHouseAddress} = config;

  const TENTH_ETH = ethers.utils.parseUnits("0.1", "ether") as BigNumber;
  const ONE_ETH = ethers.utils.parseUnits("1", "ether") as BigNumber;
  const TWO_ETH = ethers.utils.parseUnits("2", "ether") as BigNumber;
  const ONE_DAY = 24 * 60 * 60;

  const media = MediaFactory.connect(mediaAddress, creator)
  // @ts-ignore
  const auction = AuctionHouse__factory.connect(auctionHouseAddress, creator)

  // Approve the auction
  console.log('approving transfer to auction')
  await (await media.approve(auctionHouseAddress, args.tokenId)).wait()


  // Create the auction
  console.log('creating auction')
  await (await auction.createAuction(args.tokenId, mediaAddress, ONE_DAY, TENTH_ETH.toString(), curator.address, 15, ethers.constants.AddressZero)).wait()

  console.log('approving auction as curator')
  // @ts-ignore
  await (await auction.connect(curator).setAuctionApproval(mediaAddress, args.tokenId, true)).wait()

  console.log('Creating first bid')
  await auction
    // @ts-ignore
    .connect(bidder1)
    .createBid(media.address, 0, ONE_ETH.toString(), { value: ONE_ETH.toString() });

  console.log('Creating second bid')
  await auction
    // @ts-ignore
    .connect(bidder2)
    .createBid(media.address, 0, TWO_ETH.toString(), { value: TWO_ETH.toString() });

  console.log('fast forwarding time')
  await provider.send("evm_increaseTime", [
    ONE_DAY
  ]);

  await auction.endAuction(media.address, args.tokenId);
}
Example #24
Source File: index.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
protected provider: JsonRpcProvider;
Example #25
Source File: web3-context.tsx    From lobis-frontend with MIT License 4 votes vote down vote up
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
    const dispatch = useDispatch();

    const [connected, setConnected] = useState(false);
    const [chainID, setChainID] = useState(DEFAULD_NETWORK);
    const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
    const [address, setAddress] = useState("");

    const [uri, setUri] = useState(getMainnetURI());
    const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));

    const [web3Modal] = useState<Web3Modal>(
        new Web3Modal({
            cacheProvider: true,
            providerOptions: {
                walletconnect: {
                    package: WalletConnectProvider,
                    options: {
                        rpc: {
                            [Networks.MAINNET]: getMainnetURI(),
                        },
                    },
                },
            },
        }),
    );

    const hasCachedProvider = (): boolean => {
        if (!web3Modal) return false;
        if (!web3Modal.cachedProvider) return false;
        return true;
    };

    const _initListeners = useCallback(
        (rawProvider: JsonRpcProvider) => {
            if (!rawProvider.on) {
                return;
            }

            rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));

            rawProvider.on("chainChanged", async (chain: number) => {
                changeNetwork(chain);
            });

            rawProvider.on("network", (_newNetwork, oldNetwork) => {
                if (!oldNetwork) return;
                window.location.reload();
            });
        },
        [provider],
    );

    const changeNetwork = async (otherChainID: number) => {
        const network = Number(otherChainID);

        setProviderChainID(network);
    };

    const connect = useCallback(async () => {
        const rawProvider = await web3Modal.connect();

        _initListeners(rawProvider);

        const connectedProvider = new Web3Provider(rawProvider, "any");

        const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
        const connectedAddress = await connectedProvider.getSigner().getAddress();

        setAddress(connectedAddress);

        setProviderChainID(chainId);

        if (chainId === Networks.MAINNET) {
            setProvider(connectedProvider);
        }

        setConnected(true);

        return connectedProvider;
    }, [provider, web3Modal, connected]);

    const checkWrongNetwork = async (): Promise<boolean> => {
        if (providerChainID !== DEFAULD_NETWORK) {
            const shouldSwitch = window.confirm(messages.switch_to_avalanche);
            if (shouldSwitch) {
                await swithNetwork();
                window.location.reload();
            }
            return true;
        }

        return false;
    };

    const disconnect = useCallback(async () => {
        web3Modal.clearCachedProvider();
        setConnected(false);

        setTimeout(() => {
            window.location.reload();
        }, 1);
    }, [provider, web3Modal, connected]);

    const onChainProvider = useMemo(
        () => ({
            connect,
            disconnect,
            hasCachedProvider,
            provider,
            connected,
            address,
            chainID,
            web3Modal,
            providerChainID,
            checkWrongNetwork,
        }),
        [connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
    );
    //@ts-ignore
    return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}
Example #26
Source File: web3-context.tsx    From rugenerous-frontend with MIT License 4 votes vote down vote up
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
  const dispatch = useDispatch();

  const [connected, setConnected] = useState(false);
  const [chainID, setChainID] = useState(DEFAULD_NETWORK);
  const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
  const [address, setAddress] = useState("");

  const [uri, setUri] = useState(getMainnetURI());
  const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));

  const [web3Modal] = useState<Web3Modal>(
    new Web3Modal({
      cacheProvider: true,
      providerOptions: {
        walletconnect: {
          package: WalletConnectProvider,
          options: {
            rpc: {
              [Networks.AVAX]: getMainnetURI(),
            },
          },
        },
      },
    }),
  );

  const hasCachedProvider = (): boolean => {
    if (!web3Modal) return false;
    if (!web3Modal.cachedProvider) return false;
    return true;
  };

  const _initListeners = useCallback(
    (rawProvider: JsonRpcProvider) => {
      if (!rawProvider.on) {
        return;
      }

      rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));

      rawProvider.on("chainChanged", async (chain: number) => {
        changeNetwork(chain);
      });

      rawProvider.on("network", (_newNetwork, oldNetwork) => {
        if (!oldNetwork) return;
        window.location.reload();
      });
    },
    [provider],
  );

  const changeNetwork = async (otherChainID: number) => {
    const network = Number(otherChainID);

    setProviderChainID(network);
  };

  const connect = useCallback(async () => {
    const rawProvider = await web3Modal.connect();

    _initListeners(rawProvider);

    const connectedProvider = new Web3Provider(rawProvider, "any");

    const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
    const connectedAddress = await connectedProvider.getSigner().getAddress();

    setAddress(connectedAddress);

    setProviderChainID(chainId);

    if (chainId === Networks.AVAX) {
      setProvider(connectedProvider);
    }

    setConnected(true);

    return connectedProvider;
  }, [provider, web3Modal, connected]);

  const checkWrongNetwork = async (): Promise<boolean> => {
    if (providerChainID !== DEFAULD_NETWORK) {
      const shouldSwitch = window.confirm(messages.switch_to_avalanche);
      if (shouldSwitch) {
        await swithNetwork();
        window.location.reload();
      }
      return true;
    }

    return false;
  };

  const disconnect = useCallback(async () => {
    web3Modal.clearCachedProvider();
    setConnected(false);

    setTimeout(() => {
      window.location.reload();
    }, 1);
  }, [provider, web3Modal, connected]);

  const onChainProvider = useMemo(
    () => ({
      connect,
      disconnect,
      hasCachedProvider,
      provider,
      connected,
      address,
      chainID,
      web3Modal,
      providerChainID,
      checkWrongNetwork,
    }),
    [connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
  );
  //@ts-ignore
  return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}
Example #27
Source File: web3-context.tsx    From wonderland-frontend with MIT License 4 votes vote down vote up
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
    const dispatch = useDispatch();

    const [connected, setConnected] = useState(false);
    const [chainID, setChainID] = useState(DEFAULD_NETWORK);
    const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
    const [address, setAddress] = useState("");

    const [uri, setUri] = useState(getMainnetURI());
    const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));

    const [web3Modal] = useState<Web3Modal>(
        new Web3Modal({
            cacheProvider: true,
            providerOptions: {
                walletconnect: {
                    package: WalletConnectProvider,
                    options: {
                        rpc: {
                            [Networks.AVAX]: getMainnetURI(),
                        },
                    },
                },
            },
        }),
    );

    const hasCachedProvider = (): boolean => {
        if (!web3Modal) return false;
        if (!web3Modal.cachedProvider) return false;
        return true;
    };

    const _initListeners = useCallback(
        (rawProvider: JsonRpcProvider) => {
            if (!rawProvider.on) {
                return;
            }

            rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));

            rawProvider.on("chainChanged", async (chain: number) => {
                changeNetwork(chain);
            });

            rawProvider.on("network", (_newNetwork, oldNetwork) => {
                if (!oldNetwork) return;
                window.location.reload();
            });
        },
        [provider],
    );

    const changeNetwork = async (otherChainID: number) => {
        const network = Number(otherChainID);

        setProviderChainID(network);
    };

    const connect = useCallback(async () => {
        const rawProvider = await web3Modal.connect();

        _initListeners(rawProvider);

        const connectedProvider = new Web3Provider(rawProvider, "any");

        const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
        const connectedAddress = await connectedProvider.getSigner().getAddress();

        setAddress(connectedAddress);

        setProviderChainID(chainId);

        if (chainId === Networks.AVAX) {
            setProvider(connectedProvider);
        }

        setConnected(true);

        return connectedProvider;
    }, [provider, web3Modal, connected]);

    const checkWrongNetwork = async (): Promise<boolean> => {
        if (providerChainID !== DEFAULD_NETWORK) {
            const shouldSwitch = window.confirm(messages.switch_to_avalanche);
            if (shouldSwitch) {
                await swithNetwork();
                window.location.reload();
            }
            return true;
        }

        return false;
    };

    const disconnect = useCallback(async () => {
        web3Modal.clearCachedProvider();
        setConnected(false);

        setTimeout(() => {
            window.location.reload();
        }, 1);
    }, [provider, web3Modal, connected]);

    const onChainProvider = useMemo(
        () => ({
            connect,
            disconnect,
            hasCachedProvider,
            provider,
            connected,
            address,
            chainID,
            web3Modal,
            providerChainID,
            checkWrongNetwork,
        }),
        [connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
    );
    //@ts-ignore
    return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}
Example #28
Source File: uniswap.currency.service.ts    From Elastos.Essentials.App with MIT License 4 votes vote down vote up
/**
   * Approximate USD valuation of a given token.
   *
   * - Objective:
   *    We try to make a trade of X USDT (or other relevant USD 1:1 stable coin) and see how many
   *    tokens Y we can get. This gives us the current approximate USD price of token Y.
   * - Algorithm:
   *    - Build the list of all potential liquidity pool pairs that can lead from Token Y to USDT.
   *      - To build a Pair, we need to know the current amount of each token in the pool (call to getReserve())
   *      - As most tokens won't have a LP to USDT, we add Pairs that could lead to that. For instance, we may
   *        not be able to trade TELOS -> USDT directly, but if we add pairs TELOS-BNB and BNB-USDT, we can get a TELOS -> BNB -> USDT route for a trade.
   *
   * Note: trades use the wrapped versions of the native currency (ether, bnb, etc), not directly the native token.
   */
  async getTokenUSDValue(network: EVMNetwork, erc20coin: ERC20Coin): Promise<number> {
    let currencyProvider = network.getUniswapCurrencyProvider();
    if (!currencyProvider)
      return 0;

    //Logger.log('walletdebug', "getTokenUSDValue", erc20coin.getName(), erc20coin.getContractAddress());

    let chainId = network.getMainChainID();
    let swapFactoryAddress = currencyProvider.getFactoryAddress();
    let swapFactoryInitCodeHash = currencyProvider.getFactoryInitCodeHash();
    let referenceUSDcoin = currencyProvider.getReferenceUSDCoin();
    let wrappedNativeCoin = currencyProvider.getWrappedNativeCoin();

    const { Token } = await lazyUniswapSDKCoreImport();
    let evaluatedToken = new Token(chainId, erc20coin.getContractAddress(), erc20coin.getDecimals(), erc20coin.getID(), erc20coin.getName());
    let stableCoinUSDToken = new Token(chainId, referenceUSDcoin.getContractAddress(), referenceUSDcoin.getDecimals(), referenceUSDcoin.getID(), referenceUSDcoin.getName());
    let wrappedNativeCoinToken = new Token(chainId, wrappedNativeCoin.getContractAddress(), wrappedNativeCoin.getDecimals(), wrappedNativeCoin.getID(), wrappedNativeCoin.getName());

    const JsonRpcProvider = await lazyEthersJsonRPCProviderImport();
    let etherjsProvider = new JsonRpcProvider({ url: network.getRPCUrl() });

    let tradingPairs: Pair[] = [];

    try {
      // Direct pair: Evaluated coin <-> USD stable coin
      await this.fetchAndAddPair(evaluatedToken, stableCoinUSDToken, tradingPairs, etherjsProvider, swapFactoryAddress, swapFactoryInitCodeHash);
      // Evaluated token against wrapped native token (ex: ADA <-> WBNB).
      // Note: later we can add more liquidity pairs here, not only including the wrapped native token, in order
      // to increase the possible routes.
      await this.fetchAndAddPair(evaluatedToken, wrappedNativeCoinToken, tradingPairs, etherjsProvider, swapFactoryAddress, swapFactoryInitCodeHash);
      // USD stable coin against wrapped native token (ex: USDT <-> WBNB).
      await this.fetchAndAddPair(stableCoinUSDToken, wrappedNativeCoinToken, tradingPairs, etherjsProvider, swapFactoryAddress, swapFactoryInitCodeHash);
      //Logger.log('walletdebug', "Computed Trading Pairs:", tradingPairs);
    }
    catch (e) {
      Logger.warn("wallet", "Failed to fetch uniswap pairs to get token pricing:", evaluatedToken, network);
      return 0;
    }

    if (tradingPairs.length == 0)
      return 0; // No appropriate pairs could be built - should not happen

    // Fictive trade: purchase 10 USD worth of the token
    let readableAmountOut = 10;

    const { Trade } = await lazyCustomUniswapSDKImport();

    const { CurrencyAmount } = await lazyUniswapSDKCoreImport();
    let currencyAmountOut = CurrencyAmount.fromRawAmount(stableCoinUSDToken, new BigNumber(readableAmountOut).times(new BigNumber(10).pow(stableCoinUSDToken.decimals)).toFixed());
    let trades = Trade.bestTradeExactOut(tradingPairs, evaluatedToken, currencyAmountOut, { maxHops: 3, maxNumResults: 1 });
    //Logger.log('walletdebug', "TOKENS:", evaluatedToken.name, stableCoinUSDToken.name, wrappedNativeCoinToken.name);
    if (trades.length > 0) {
      /* trades.forEach(trade => {
        Logger.log('walletdebug', "------");
        Logger.log('walletdebug', "TRADE:", trade);
        Logger.log('walletdebug', "TRADE ROUTE MIDPRICE:", trade.route.midPrice.toSignificant(6)) // 201.306
        Logger.log('walletdebug', "TRADE EXECPRICE:", trade.executionPrice.toSignificant(6)) // 201.306
        Logger.log('walletdebug', "TRADE IN AMOUNT:", trade.inputAmount.toSignificant(6)) // 201.306
        Logger.log('walletdebug', "TRADE OUT AMOUNT:", trade.outputAmount.toSignificant(6)) // 201.306
        Logger.log('walletdebug', "TRADE PRICE IMPACT:", trade.priceImpact.toSignificant(6), "%") // 201.306
      }); */

      let tradeImpactDecimal = parseFloat(trades[0].priceImpact.toSignificant(2));
      if (tradeImpactDecimal > 10) { // Slippage more than 10%? There is a problem...
        //Logger.warn("walletdebug", `Trade impact of ${tradeImpactDecimal}% is too high, skipping this valuation. Worthless token, or not enough liquidity`);
        return 0;
      }

      return parseFloat(trades[0].executionPrice.toSignificant(6)); // NOTE: For display only! Not accurate
    }
    else {
      //Logger.log("walletdebug", "No trade found using pairs", tradingPairs);
    }

    return 0; // No info found
  }
Example #29
Source File: batch-append.spec.ts    From integration-tests with MIT License 4 votes vote down vote up
describe('Transaction Ingestion', () => {
  let l1Provider: JsonRpcProvider
  let l1Signer: Wallet
  let l2Signer
  let l2Provider: JsonRpcProvider
  let addressResolver: Contract

  let canonicalTransactionChain: Contract
  let ctcAddress: string

  const mnemonic = Config.Mnemonic()

  let pre

  before(async () => {
    l1Provider = new JsonRpcProvider(Config.L1NodeUrlWithPort())
    l1Signer = new Wallet(Config.DeployerPrivateKey()).connect(l1Provider)
    const web3 = new Web3Provider(
      ganache.provider({
        mnemonic,
      })
    )
    l2Provider = new OptimismProvider(Config.L2NodeUrlWithPort(), web3)
    l2Signer = await l2Provider.getSigner()

    const addressResolverAddress = add0x(Config.AddressResolverAddress())
    const AddressResolverFactory = getContractFactory('Lib_AddressManager')
    addressResolver = AddressResolverFactory.connect(l1Signer).attach(
      addressResolverAddress
    )

    ctcAddress = await addressResolver.getAddress(
      'OVM_CanonicalTransactionChain'
    )

    const CanonicalTransactionChainFactory = getContractFactory(
      'OVM_CanonicalTransactionChain'
    )

    canonicalTransactionChain = CanonicalTransactionChainFactory.connect(
      l1Signer
    ).attach(ctcAddress)
  })

  // The transactions are enqueue'd with a `to` address of i.repeat(40)
  // meaning that the `to` value is different each iteration in a deterministic
  // way. They need to be inserted into the L2 chain in an ascending order.
  // Keep track of the receipts so that the blockNumber can be compared
  // against the `L1BlockNumber` on the tx objects.
  const receipts = []
  it('should enqueue some transactions', async () => {
    // Keep track of the L2 tip before submitting any transactions so that
    // the subsequent transactions can be queried for in the next test
    pre = await l2Provider.getBlock('latest')

    // Enqueue some transactions by building the calldata and then sending
    // the transaction to Layer 1
    for (let i = 0; i < 5; i++) {
      const input = ['0x' + `${i + 1}`.repeat(40), 500_000, `0x0${i}`]
      const calldata = await canonicalTransactionChain.interface.encodeFunctionData(
        'enqueue',
        input
      )

      const txResponse = await l1Signer.sendTransaction({
        data: calldata,
        to: ctcAddress,
      })

      const receipt = await txResponse.wait()
      receipts.push(receipt)
    }

    for (const receipt of receipts) {
      receipt.should.be.a('object')
    }
  })

  // The batch submitter will notice that there are transactions
  // that are in the queue and submit them. L2 will pick up the
  // sequencer batch appended event and play the transactions.
  it('should order transactions correctly', async () => {
    // Wait until each tx from the previous test has
    // been executed
    let tip
    do {
      tip = await l2Provider.getBlock('latest')
      await sleep(5000)
    } while (tip.number !== pre.number + 5)

    const from = await l1Signer.getAddress()

    // Keep track of an index into the receipts list and
    // increment it for each block fetched.
    let receiptIndex = 0

    // Fetch blocks
    for (let i = pre.number + 1; i < pre.number + 5; i++) {
      const block = await l2Provider.getBlock(i)
      const hash = block.transactions[0]
      assert(typeof hash === 'string')
      // Use as any hack because additional properties are
      // added to the transaction response
      const tx = (await l2Provider.getTransaction(hash)) as any
      // The `to` addresses are defined in the previous test and
      // increment sequentially.
      assert.equal(tx.to, '0x' + `${i}`.repeat(40))
      // The transaction type is EIP155
      assert.equal(tx.txType, 'EIP155')
      // The queue origin is Layer 1
      assert.equal(tx.queueOrigin, 'l1')
      // the L1TxOrigin is equal to the Layer one from
      assert.equal(tx.l1TxOrigin, from.toLowerCase())
      assert.equal(typeof tx.l1BlockNumber, 'number')
      // Get the receipt and increment the recept index
      const receipt = receipts[receiptIndex++]
      assert.equal(tx.l1BlockNumber, receipt.blockNumber)
    }
  }).timeout(100000)
})