@web3-react/core/dist/types#Web3ReactContextInterface TypeScript Examples

The following examples show how to use @web3-react/core/dist/types#Web3ReactContextInterface. 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: Provider.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
getContract(
    web3React: Web3ReactContextInterface,
    type: ContractType,
    address: string,
    signerAccount?: string
  ): ethers.Contract {
    const { library } = web3React;

    if (signerAccount) {
      return new library.eth.Contract(schema[type], address, {
        from: signerAccount,
      });
    }

    return new library.eth.Contract(schema[type], address);
  }
Example #2
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
sign = (
    web3React: Web3ReactContextInterface,
    dataToSign: any
  ): Promise<any> => {
    const { chainId, account } = web3React;

    if (!account) {
      throw new Error(ERRORS.BlockchainActionNoAccount);
    }

    if (!chainId) {
      throw new Error(ERRORS.BlockchainActionNoChainId);
    }
    return new Promise((resolve, reject) => {
      web3React.library.eth.currentProvider.sendAsync(
        {
          method: 'eth_sign',
          params: [account, dataToSign],
          from: account,
        },
        function (err, result) {
          if (err) console.error(err);
          resolve(result);
        }
      );
    });
  };
Example #3
Source File: Transaction.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
async checkPendingTransactions(
    web3React: Web3ReactContextInterface,
    account
  ): Promise<FetchCode> {
    const { providerStore } = this.context;
    const currentBlock = providerStore.getCurrentBlockNumber();

    const { library } = web3React;
    if (this.txRecords[account]) {
      const records = this.txRecords[account];
      records.forEach(value => {
        if (this.isTxPending(value) && this.isStale(value, currentBlock)) {
          library.eth
            .getTransactionReceipt(value.hash)
            .then(receipt => {
              value.blockNumberChecked = currentBlock;
              if (receipt) {
                value.receipt = receipt;
              }
            })
            .catch(() => {
              value.blockNumberChecked = currentBlock;
            });
        }
      });
    }

    return FetchCode.SUCCESS;
  }
Example #4
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<
  Web3Provider
> & {
  chainId?: ChainId;
} {
  const context = useWeb3ReactCore<Web3Provider>();
  const contextNetwork = useWeb3ReactCore<Web3Provider>(
    GlobalConst.utils.NetworkContextName,
  );
  return context.active ? context : contextNetwork;
}
Example #5
Source File: useActiveWeb3React.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
useActiveWeb3React = (): Web3ReactContextInterface<Web3Provider> => {
  const { library, chainId, ...web3React } = useWeb3React()
  const refEth = useRef(library)
  const [provider, setprovider] = useState(library || simpleRpcProvider)

  useEffect(() => {
    if (library !== refEth.current) {
      setprovider(library || simpleRpcProvider)
      refEth.current = library
    }
  }, [library])

  return { library: provider, chainId: chainId ?? parseInt(process.env.REACT_APP_CHAIN_ID, 10), ...web3React }
}
Example #6
Source File: index.ts    From pancakeswap-testnet with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #7
Source File: index.ts    From luaswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #8
Source File: index.ts    From forward.swaps with GNU General Public License v3.0 5 votes vote down vote up
// import { Biconomy } from "@biconomy/mexa";

export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  // console.log('context.active ? context : contextNetwork: ', contextNetwork)
  return context.active ? context : contextNetwork
}
Example #9
Source File: index.ts    From panther-frontend-dex with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #10
Source File: index.ts    From pancake-swap-testnet with MIT License 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #11
Source File: index.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #12
Source File: index.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #13
Source File: index.ts    From goose-frontend-amm with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #14
Source File: index.ts    From dyp with Do What The F*ck You Want To Public License 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #15
Source File: index.ts    From cheeseswap-interface with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #16
Source File: index.ts    From sybil-interface with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #17
Source File: index.ts    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
  const context = useWeb3ReactCore<Web3Provider>()
  const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
  return context.active ? context : contextNetwork
}
Example #18
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
sendRawTransaction = (
    web3React: Web3ReactContextInterface,
    to: string,
    data: string,
    value: string
  ): PromiEvent<any> => {
    const { transactionStore } = this.context;
    const { chainId, account } = web3React;

    if (!account) {
      throw new Error(ERRORS.BlockchainActionNoAccount);
    }

    if (!chainId) {
      throw new Error(ERRORS.BlockchainActionNoChainId);
    }

    const promiEvent = new PromiEvent<any>(() => {
      web3React.library.eth
        .sendTransaction({ from: account, to: to, data: data, value: value })
        .once('transactionHash', hash => {
          transactionStore.addTransactionRecord(account, hash);
          promiEvent.emit(TXEvents.TX_HASH, hash);
          console.debug(TXEvents.TX_HASH, hash);
        })
        .once('receipt', receipt => {
          promiEvent.emit(TXEvents.RECEIPT, receipt);
          console.debug(TXEvents.RECEIPT, receipt);
        })
        .once('confirmation', (confNumber, receipt) => {
          promiEvent.emit(TXEvents.CONFIRMATION, {
            confNumber,
            receipt,
          });
          console.debug(TXEvents.CONFIRMATION, {
            confNumber,
            receipt,
          });
        })
        .on('error', error => {
          console.debug(error.code);
          promiEvent.emit(TXEvents.INVARIANT, error);
          console.debug(TXEvents.INVARIANT, error);
        })
        .then(receipt => {
          promiEvent.emit(TXEvents.FINALLY, receipt);
          console.debug(TXEvents.FINALLY, receipt);
        })
        .catch(e => {
          console.debug('rejected', e);
        });
    });

    return promiEvent;
  };
Example #19
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
signTypedV3 = (
    web3React: Web3ReactContextInterface,
    dataToSign: any
  ): Promise<any> => {
    const { chainId, account } = web3React;

    if (!account) {
      throw new Error(ERRORS.BlockchainActionNoAccount);
    }

    if (!chainId) {
      throw new Error(ERRORS.BlockchainActionNoChainId);
    }
    const msgParams = JSON.stringify({
      types: {
        EIP712Domain: [
          { name: 'name', type: 'string' },
          { name: 'version', type: 'string' },
          { name: 'chainId', type: 'uint256' },
          { name: 'verifyingContract', type: 'address' },
        ],
        Broadcast: [
          { name: 'topic', type: 'bytes32' },
          { name: 'message', type: 'string' },
        ],
      },
      primaryType: 'Broadcast',
      domain: {
        name: 'MessageLogger',
        version: '1',
        chainId: '0x04',
        verifyingContract: '0x0c850e40f72bdc012578788e25a02aadc0da85da',
      },
      message: dataToSign,
    });

    return new Promise((resolve, reject) => {
      web3React.library.eth.currentProvider.sendAsync(
        {
          method: 'eth_signTypedData_v3',
          params: [account, msgParams],
          from: account,
        },
        function (err, result) {
          if (err) console.error(err);
          resolve(result);
        }
      );
    });
  };
Example #20
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
sendTransaction = (
    web3React: Web3ReactContextInterface,
    contractType: ContractType,
    contractAddress: string,
    action: string,
    params: any[],
    overrides?: any
  ): PromiEvent<any> => {
    const { transactionStore } = this.context;
    const { chainId, account } = web3React;

    overrides = overrides ? overrides : {};

    if (!account) {
      throw new Error(ERRORS.BlockchainActionNoAccount);
    }

    if (!chainId) {
      throw new Error(ERRORS.BlockchainActionNoChainId);
    }

    const contract = this.getContract(
      web3React,
      contractType,
      contractAddress,
      account
    );

    const response = sendAction({
      contract,
      action,
      sender: account,
      data: params,
      overrides,
    }).on(TXEvents.TX_HASH, hash => {
      transactionStore.addTransactionRecord(account, hash);
    });

    return response;
  };
Example #21
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
web3Context: Web3ReactContextInterface;
Example #22
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
setWeb3Context(context: Web3ReactContextInterface) {
    console.debug('[ProviderStore] Setting Web3 context', context);
    this.web3Context = context;
  }
Example #23
Source File: Provider.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
getActiveWeb3React(): Web3ReactContextInterface {
    return this.web3Context;
  }
Example #24
Source File: BlockchainStore.ts    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
async fetchData(web3React: Web3ReactContextInterface, reset: boolean) {
    if (
      (!this.activeFetchLoop || reset) &&
      web3React &&
      web3React.active &&
      isChainIdSupported(web3React.chainId)
    ) {
      const {
        providerStore,
        configStore,
        daoStore,
        notificationStore,
        cacheService,
      } = this.context;

      this.initialLoadComplete = reset ? false : this.initialLoadComplete;
      this.activeFetchLoop = true;
      if (reset) notificationStore.reset();

      try {
        const { library, chainId } = web3React;

        const networkName = configStore.getActiveChainName();

        notificationStore.setGlobalLoading(
          true,
          'Looking for latest chain configurations'
        );
        const networkConfig = await configStore.loadNetworkConfig();

        notificationStore.setGlobalLoading(
          true,
          'Looking for existing cache data'
        );
        const cache = await caches.open(`dxvote-cache`);
        let match = await cache.match(networkName);
        let networkCache: DaoNetworkCache & { baseCacheIpfsHash?: string } =
          null;
        if (match) {
          networkCache = JSON.parse(await match.text());
        }

        if (networkName === 'localhost') {
          networkCache = {
            networkId: 1337,
            version: 1,
            blockNumber: 1,
            address: '0xf89f66329e7298246de22D210Ac246DCddff4621',
            reputation: {
              events: [],
              total: bnum(0),
            },
            schemes: {},
            proposals: {},
            callPermissions: {},
            votingMachines: {},
            ipfsHashes: [],
            vestingContracts: [],
          };
        }

        if (
          networkCache &&
          (!networkCache?.version ||
            networkCache?.version !== targetCacheVersion)
        ) {
          console.log('[Upgrade Cache]');
          networkCache = null;
        }

        const blockNumber = (await library.eth.getBlockNumber()) - 5;

        const newestCacheIpfsHash = networkConfig.cache.ipfsHash;

        if (
          networkName !== 'localhost' &&
          (!networkCache ||
            !(newestCacheIpfsHash === networkCache.baseCacheIpfsHash))
        ) {
          console.debug('[IPFS Cache Fetch]', networkName, newestCacheIpfsHash);
          notificationStore.setGlobalLoading(
            true,
            'Fetching cached data from IPFS'
          );
          const ipfsCache = await cacheService.getCacheFromIPFS(
            newestCacheIpfsHash
          );
          networkCache = daoStore.parseCache(ipfsCache);
          networkCache.baseCacheIpfsHash = newestCacheIpfsHash;
        }

        const lastCheckedBlockNumber = networkCache.blockNumber;

        if (blockNumber > lastCheckedBlockNumber + 1) {
          console.debug(
            '[Fetch Loop] Fetch Blockchain Data',
            blockNumber,
            chainId
          );

          const toBlock = blockNumber;
          const networkContracts = configStore.getNetworkContracts();

          networkCache = await cacheService.getUpdatedCache(
            networkCache,
            networkContracts,
            toBlock,
            library
          );

          notificationStore.setGlobalLoading(
            true,
            `Getting proposal titles form ipfs`
          );
          const proposalTitles = await cacheService.updateProposalTitles(
            networkCache,
            getProposalTitles()
          );

          Object.keys(networkCache.proposals).map(proposalId => {
            networkCache.proposals[proposalId].title =
              networkCache.proposals[proposalId].title ||
              proposalTitles[proposalId] ||
              '';
          });

          networkCache.blockNumber = toBlock;
          providerStore.setCurrentBlockNumber(toBlock);

          notificationStore.setGlobalLoading(true, 'Saving updated cache');
          await cache.put(
            networkName,
            new Response(JSON.stringify(networkCache))
          );
        }
        daoStore.setCache(networkCache);
        this.initialLoadComplete = true;
        notificationStore.setFirstLoadComplete();
        this.activeFetchLoop = false;
      } catch (error) {
        console.error(error);
        if (!this.initialLoadComplete) {
          notificationStore.setGlobalError(true, (error as Error).message);
        } else {
          throw new CacheLoadError(error.message);
        }
        this.activeFetchLoop = false;
      }
    }
  }