@ethersproject/providers#BaseProvider TypeScript Examples

The following examples show how to use @ethersproject/providers#BaseProvider. 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 ethcall with MIT License 6 votes vote down vote up
/**
   * Initialize the provider. Should be called once before making any requests.
   * @param provider ethers provider
   */
  async init(provider: BaseProvider): Promise<void> {
    this.provider = provider;
    const network = await provider.getNetwork();
    this.multicall = getMulticall(network.chainId);
    this.multicall2 = getMulticall2(network.chainId);
    this.multicall3 = getMulticall3(network.chainId);
  }
Example #2
Source File: kyberDMM.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
async function getKyberDMMPairs(provider: BaseProvider, tokens: kyberToken[]): Promise<kyberPair[][]> {
  const pairs: kyberPair[][] = [];
  for (let i = 0; i < tokens.length - 1; i++) {
    for (let j = 1; j < tokens.length - i - 1; j++) {
      const tokenOne = tokens[i];
      const tokenTwo = tokens[i + j];

      let assetPairs;
      try {
        assetPairs = await kyberFetcher.fetchPairData(tokenOne, tokenTwo, KYBER_FACTORY, provider);
      } catch (error) {
        continue;
      }
      if (assetPairs.length > 0) { pairs.push(assetPairs); }
    }
  }

  return pairs;
}
Example #3
Source File: uniswapV2.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
export async function getUniswapV2Quote(
  provider: BaseProvider,
  tokenAddress: Address,
  targetPriceImpact: BigNumber): Promise<ExchangeQuote> {
  const token: Token = await Fetcher.fetchTokenData(ChainId.MAINNET, tokenAddress, provider);
  const weth: Token = await Fetcher.fetchTokenData(ChainId.MAINNET, ETH_ADDRESS, provider);
  const wbtc: Token = await Fetcher.fetchTokenData(ChainId.MAINNET, BTC_ADDRESS, provider);
  const usdc: Token = await Fetcher.fetchTokenData(ChainId.MAINNET, USDC_ADDRESS, provider);

  const trades = Trade.bestTradeExactIn(
    await getUniswapV2Pairs(provider, [token, weth, wbtc, usdc]),
    new TokenAmount(weth, ether(1).toString()),
    token,
    {maxNumResults: 3, maxHops: 2},
  );

  if (trades.length != 0) {
    // Use linear approximation of price impact to find out how many 1 ETH trades add to 50 bps price impact (net of fees)
    const hops = trades[0].route.pairs.length;
    const priceImpactRatio = preciseDiv(
      hops > 1 ? targetPriceImpact.sub(TEN_BPS_IN_PERCENT) : targetPriceImpact,   // Subtract 10 bps from targetPriceImpact if extra hop used
      ether(parseFloat(trades[0].priceImpact.toSignificant(18))).sub(THIRTY_BPS_IN_PERCENT.mul(trades[0].route.pairs.length))
    );
    return {
      exchange: exchanges.UNISWAP,
      size: preciseMul(
        ether(parseFloat(trades[0].outputAmount.toExact())).div(BigNumber.from(10).pow(18 - token.decimals)),
        priceImpactRatio).toString(),
      data: hops > 1 ? trades[0].route.path[1].address : "0x",
    } as ExchangeQuote;
  }

  return {
    exchange: exchanges.UNISWAP,
    size: ZERO.toString(),
    data: "0x",
  } as ExchangeQuote;
}
Example #4
Source File: uniswapV2.ts    From index-rebalance-utils with Apache License 2.0 6 votes vote down vote up
async function getUniswapV2Pairs(provider: BaseProvider, tokens: Token[]): Promise<Pair[]> {
  const pairs: Pair[] = [];
  for (let i = 0; i < tokens.length - 1; i++) {
    for (let j = 1; j < tokens.length - i - 1; j++) {
      const tokenOne = tokens[i];
      const tokenTwo = tokens[i + j];

      let pair;
      try {
        pair = await Fetcher.fetchPairData(tokenOne, tokenTwo, provider);
      } catch (error) {
        continue;
      }

      pairs.push(pair);
    }
  }

  return pairs;
}
Example #5
Source File: index.ts    From ccip-read with MIT License 6 votes vote down vote up
/**
   * Constructor.
   * @param provider: The Ethers provider to wrap.
   */
  constructor(provider: BaseProvider, fetcher: Fetch = fetchJson) {
    super(provider.getNetwork());
    this.parent = provider;
    this.fetcher = fetcher;
  }
Example #6
Source File: provider.ts    From ethcall with MIT License 6 votes vote down vote up
/**
   * Aggregates multiple calls into one call.
   * If any of the calls that are allowed to fail do fail,
   * it returns a null value in place of the failed call's return data.
   * @param calls Array of Call objects containing information about each read call
   * @param canFail Array of booleans specifying whether each call can fail
   * @param block Block number for this call
   * @returns List of fetched data. Failed calls will result in null values.
   */
  async tryEach<T>(
    calls: Call[],
    canFail: boolean[],
    block?: number,
  ): Promise<(T | null)[]> {
    if (!this.provider) {
      throw Error('Provider should be initialized before use.');
    }
    const multicall = this.getContract('TRY_EACH', block);
    if (!multicall) {
      console.warn(
        'Multicall3 contract is not available on this network, using deployless version.',
      );
    }
    const provider = this.provider as BaseProvider;
    const failableCalls = calls.map((call, index) => {
      return {
        ...call,
        canFail: canFail[index],
      };
    });
    return await callTryEach<T>(provider, multicall, failableCalls, block);
  }
Example #7
Source File: provider.ts    From ethcall with MIT License 6 votes vote down vote up
/**
   * Aggregate multiple calls into one call.
   * If any of the calls fail, it returns a null value in place of the failed call's return data.
   * @param calls Array of Call objects containing information about each read call
   * @param block Block number for this call
   * @returns List of fetched data. Failed calls will result in null values.
   */
  async tryAll<T>(calls: Call[], block?: number): Promise<(T | null)[]> {
    if (!this.provider) {
      throw Error('Provider should be initialized before use.');
    }
    const multicall = this.getContract('TRY_ALL', block);
    if (!multicall) {
      console.warn(
        'Multicall2 contract is not available on this network, using deployless version.',
      );
    }
    const provider = this.provider as BaseProvider;
    return await callTryAll<T>(provider, multicall, calls, block);
  }
Example #8
Source File: provider.ts    From ethcall with MIT License 6 votes vote down vote up
/**
   * Aggregate multiple calls into one call.
   * Reverts when any of the calls fails.
   * For ignoring the success of each call, use {@link tryAll} instead.
   * @param calls Array of Call objects containing information about each read call
   * @param block Block number for this call
   * @returns List of fetched data
   */
  async all<T>(calls: Call[], block?: BlockTag): Promise<T[]> {
    if (!this.provider) {
      throw Error('Provider should be initialized before use.');
    }
    const multicall = this.getContract('BASIC', block);
    if (!multicall) {
      console.warn(
        'Multicall contract is not available on this network, using deployless version.',
      );
    }
    const provider = this.provider as BaseProvider;
    return await callAll<T>(provider, multicall, calls, block);
  }
Example #9
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function callDeployless3(
  provider: BaseProvider,
  callRequests: CallRequest[],
  block?: BlockTag,
): Promise<Result> {
  const inputAbi: JsonFragment[] = deploylessMulticall3Abi;
  const constructor = inputAbi.find((f) => f.type === 'constructor');
  const inputs = constructor?.inputs || [];
  const args = Abi.encodeConstructor(inputs, [callRequests]);
  const data = hexConcat([deploylessMulticall3Bytecode, args]);
  const callData = await provider.call(
    {
      data,
    },
    block,
  );
  const outputAbi: JsonFragment[] = multicall3Abi;
  const outputFunc = outputAbi.find(
    (f) => f.type === 'function' && f.name === 'aggregate3',
  );
  const name = outputFunc?.name || '';
  const outputs = outputFunc?.outputs || [];
  // Note "[0]": low-level calls don't automatically unwrap tuple output
  const response = Abi.decode(name, outputs, callData)[0];
  return response as CallResult[];
}
Example #10
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function callDeployless2(
  provider: BaseProvider,
  callRequests: CallRequest[],
  block?: BlockTag,
): Promise<Result> {
  const inputAbi: JsonFragment[] = deploylessMulticall2Abi;
  const constructor = inputAbi.find((f) => f.type === 'constructor');
  const inputs = constructor?.inputs || [];
  const args = Abi.encodeConstructor(inputs, [false, callRequests]);
  const data = hexConcat([deploylessMulticall2Bytecode, args]);
  const callData = await provider.call(
    {
      data,
    },
    block,
  );
  const outputAbi: JsonFragment[] = multicall2Abi;
  const outputFunc = outputAbi.find(
    (f) => f.type === 'function' && f.name === 'tryAggregate',
  );
  const name = outputFunc?.name || '';
  const outputs = outputFunc?.outputs || [];
  // Note "[0]": low-level calls don't automatically unwrap tuple output
  const response = Abi.decode(name, outputs, callData)[0];
  return response as CallResult[];
}
Example #11
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function callDeployless(
  provider: BaseProvider,
  callRequests: CallRequest[],
  block?: BlockTag,
): Promise<Result> {
  const inputAbi: JsonFragment[] = deploylessMulticallAbi;
  const constructor = inputAbi.find((f) => f.type === 'constructor');
  const inputs = constructor?.inputs || [];
  const args = Abi.encodeConstructor(inputs, [callRequests]);
  const data = hexConcat([deploylessMulticallBytecode, args]);
  const callData = await provider.call(
    {
      data,
    },
    block,
  );
  const outputAbi: JsonFragment[] = multicallAbi;
  const outputFunc = outputAbi.find(
    (f) => f.type === 'function' && f.name === 'aggregate',
  );
  const name = outputFunc?.name || '';
  const outputs = outputFunc?.outputs || [];
  const response = Abi.decode(name, outputs, callData);
  return response;
}
Example #12
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function tryEach<T>(
  provider: BaseProvider,
  multicall3: Multicall | null,
  calls: FailableCall[],
  block?: BlockTag,
): Promise<(T | null)[]> {
  const contract = multicall3
    ? new Contract(multicall3.address, multicall3Abi, provider)
    : null;
  const callRequests = calls.map((call) => {
    const callData = Abi.encode(call.name, call.inputs, call.params);
    return {
      target: call.contract.address,
      allowFailure: call.canFail,
      callData,
    };
  });
  const overrides = {
    blockTag: block,
  };
  const response: CallResult[] = contract
    ? await contract.aggregate3(callRequests, overrides)
    : await callDeployless3(provider, callRequests, block);
  const callCount = calls.length;
  const callResult: (T | null)[] = [];
  for (let i = 0; i < callCount; i++) {
    const name = calls[i].name;
    const outputs = calls[i].outputs;
    const result = response[i];
    if (!result.success) {
      callResult.push(null);
    } else {
      const params = Abi.decode(name, outputs, result.returnData);
      const data = outputs.length === 1 ? params[0] : params;
      callResult.push(data);
    }
  }
  return callResult;
}
Example #13
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function tryAll<T>(
  provider: BaseProvider,
  multicall2: Multicall | null,
  calls: Call[],
  block?: BlockTag,
): Promise<(T | null)[]> {
  const contract = multicall2
    ? new Contract(multicall2.address, multicall2Abi, provider)
    : null;
  const callRequests = calls.map((call) => {
    const callData = Abi.encode(call.name, call.inputs, call.params);
    return {
      target: call.contract.address,
      callData,
    };
  });
  const overrides = {
    blockTag: block,
  };
  const response: CallResult[] = contract
    ? await contract.tryAggregate(false, callRequests, overrides)
    : await callDeployless2(provider, callRequests, block);
  const callCount = calls.length;
  const callResult: (T | null)[] = [];
  for (let i = 0; i < callCount; i++) {
    const name = calls[i].name;
    const outputs = calls[i].outputs;
    const result = response[i];
    if (!result.success) {
      callResult.push(null);
    } else {
      const params = Abi.decode(name, outputs, result.returnData);
      const data = outputs.length === 1 ? params[0] : params;
      callResult.push(data);
    }
  }
  return callResult;
}
Example #14
Source File: call.ts    From ethcall with MIT License 6 votes vote down vote up
async function all<T>(
  provider: BaseProvider,
  multicall: Multicall | null,
  calls: Call[],
  block?: BlockTag,
): Promise<T[]> {
  const contract = multicall
    ? new Contract(multicall.address, multicallAbi, provider)
    : null;
  const callRequests = calls.map((call) => {
    const callData = Abi.encode(call.name, call.inputs, call.params);
    return {
      target: call.contract.address,
      callData,
    };
  });
  const overrides = {
    blockTag: block,
  };
  const response = contract
    ? await contract.aggregate(callRequests, overrides)
    : await callDeployless(provider, callRequests, block);
  const callCount = calls.length;
  const callResult: T[] = [];
  for (let i = 0; i < callCount; i++) {
    const name = calls[i].name;
    const outputs = calls[i].outputs;
    const returnData = response.returnData[i];
    const params = Abi.decode(name, outputs, returnData);
    const result = outputs.length === 1 ? params[0] : params;
    callResult.push(result);
  }
  return callResult;
}
Example #15
Source File: rpcCall.ts    From defillama-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function call(provider: BaseProvider, data: Deferrable<TransactionRequest>, block: BlockTag, chain?: string) {
  if (!chain) chain = 'noChain'
  const counter: Counter = getChainCounter(chain)
  const currentId = counter.requestCount++
  const eventId = `${chain}-${currentId}`

  if (counter.activeWorkers > maxParallelCalls) {
    counter.queue.push(eventId)
    await once(emitter, eventId)
  }

  counter.activeWorkers++

  if (DEBUG_MODE_ENABLED) {
    const showEveryX = counter.queue.length > 100 ? 50 : 10 // show log fewer times if lot more are queued up
    if (currentId % showEveryX === 0) console.log(`chain: ${chain} request #: ${currentId} queue: ${counter.queue.length} active requests: ${counter.activeWorkers}`)
  }

  let response
  try {
    response = await provider.call(data, block)
    onComplete()
  } catch (e) {
    onComplete()
    throw e
  }

  return response

  function onComplete() {
    counter.activeWorkers--
    if (counter.queue.length) {
      const nextRequestId = counter.pickFromTop ? counter.queue.shift() : counter.queue.pop()
      counter.pickFromTop = !counter.pickFromTop
      emitter.emit(<string> nextRequestId)
    }
  }
}
Example #16
Source File: avatar.ts    From ens-metadata-service with MIT License 5 votes vote down vote up
export async function getAvatarImage(
  provider: BaseProvider,
  name: string
): Promise<any> {
  const avatar = new AvatarMetadata(provider, name);
  return await avatar.getImage();
}
Example #17
Source File: Avatar.tsx    From davatar-helpers with MIT License 5 votes vote down vote up
export default function Avatar({
  size,
  address,
  provider,
  generatedAvatarType,
  defaultComponent,
  style,
  cacheTTL,
}: AvatarProps) {
  const [avatarUri, setAvatarUri] = useState<string | null>(null);
  const [ethersProvider, setEthersProvider] = useState<BaseProvider | null>(null);
  const avatarEthersProvider = useAvatarEthersProvider();

  useEffect(() => {
    let eth = avatarEthersProvider;
    let chainId = null;
    let isEthers = false;

    // carlos: Only use the provided provider if ENS is actually on that chain
    if (provider) {
      if (provider.currentProvider?.chainId) {
        chainId = parseInt(provider.currentProvider.chainId);
      } else if (provider.network?.chainId) {
        isEthers = true;
        chainId = provider.network.chainId;
      }

      if ([1, 3, 4, 5].includes(chainId)) {
        eth = isEthers ? (provider as BaseProvider) : new Web3Provider(provider.currentProvider);
      } else {
        chainId = 1;
      }
    }

    setEthersProvider(eth);

    if (!getCachedUrl(address)) {
      eth.lookupAddress(address).then(ensName => {
        if (ensName) {
          eth.getResolver(ensName).then(resolver => {
            resolver.getText('avatar').then(avatar => {
              if (avatar && avatar.length > 0) {
                setAvatarUri(avatar);
              }
            });
          });
        }
      });
    }
  }, [address, provider, avatarEthersProvider]);

  return (
    <Image
      size={size}
      address={address}
      uri={avatarUri}
      provider={ethersProvider}
      generatedAvatarType={generatedAvatarType}
      defaultComponent={defaultComponent}
      style={style}
      cacheTTL={cacheTTL}
    />
  );
}
Example #18
Source File: balancerV1.ts    From index-rebalance-utils with Apache License 2.0 5 votes vote down vote up
// Usage note, targetPriceImpact should be the impact including fees! Balancer pool fees can change and it's not easy to extract from the data
// we have so put in a number that is net of fees.
export async function getBalancerV1Quote(provider: BaseProvider, tokenAddress: Address, targetPriceImpact: BigNumber): Promise<ExchangeQuote> {
  const sor = new SOR(
    provider,
    toBigNumberJS(gWei(100)),
    3,      // Max 3 pools used
    1,      // ChainId = mainnet (1)
    "https://storageapi.fleek.co/balancer-bucket/balancer-exchange/pools"
  );
  await sor.fetchPools();
  await sor.setCostOutputToken(tokenAddress);   // Set cost to limit small trades

  const inputAmount = toBigNumberJS(ether(2));
  const [
    ,
    returnAmountV1,
    marketSpV1Scaled,
  ] = await sor.getSwaps(
    ETH_ADDRESS.toLowerCase(),
    tokenAddress.toLowerCase(),
    "swapExactIn",
    inputAmount
  );

  if (!returnAmountV1.eq(0)) {
    const effectivePrice = inputAmount.div(returnAmountV1);

    const priceImpact = ether(effectivePrice.div(marketSpV1Scaled.div(10 ** 18)).toNumber()).sub(ether(1));
    const priceImpactRatio = preciseDiv(targetPriceImpact, priceImpact.mul(100));

    return {
      exchange: exchanges.BALANCER,
      size: preciseMul(fromBigNumberJS(returnAmountV1), priceImpactRatio).toString(),
      data: "0x",
    } as ExchangeQuote;
  }

  return {
    exchange: exchanges.BALANCER,
    size: ZERO.toString(),
    data: "0x",
  } as ExchangeQuote;
}
Example #19
Source File: JsonRpcMulticallProvider.ts    From davatar-helpers with MIT License 5 votes vote down vote up
constructor(provider: BaseProvider) {
    super(provider.getNetwork());

    this.parent = provider;
  }
Example #20
Source File: JsonRpcMulticallProvider.ts    From davatar-helpers with MIT License 5 votes vote down vote up
readonly parent: BaseProvider;
Example #21
Source File: index.ts    From ccip-read with MIT License 5 votes vote down vote up
readonly parent: BaseProvider;
Example #22
Source File: index.ts    From ccip-read with MIT License 5 votes vote down vote up
/**
 * Ethers provider middleware that implements the offchain call pattern from EIP 3668.
 * Simply wrap your regular Ethers provider in this and CCIP-read operations will be
 * handled transparently.
 *
 * Example usage:
 * ```javascript
 * const outerProvider = new ethers.providers.JsonRpcProvider('http://localhost:8545/');
 * const provider = new CCIPReadProvider(outerProvier);
 * const contract = new ethers.Contract(address, abi, provider);
 * const result = await contract.someFunc(...);
 * ```
 */
export class CCIPReadProvider extends BaseProvider {
  readonly parent: BaseProvider;
  readonly fetcher: Fetch;

  /**
   * Constructor.
   * @param provider: The Ethers provider to wrap.
   */
  constructor(provider: BaseProvider, fetcher: Fetch = fetchJson) {
    super(provider.getNetwork());
    this.parent = provider;
    this.fetcher = fetcher;
  }

  getSigner(addressOrIndex?: string | number): CCIPReadSigner {
    if (!hasSigner(this.parent)) {
      return logger.throwError(
        'CCIPReadProvider only supports getSigner if the wrapped provider does',
        Logger.errors.NOT_IMPLEMENTED,
        { parent: this.parent }
      );
    }
    return new CCIPReadSigner(_constructorGuard, this.parent.getSigner(addressOrIndex), this);
  }

  async perform(method: string, params: any): Promise<any> {
    switch (method) {
      case 'call':
        const { result } = await handleCall(this, params);
        return result;
      default:
        return this.parent.perform(method, params);
    }
  }

  detectNetwork(): Promise<Network> {
    return this.parent.detectNetwork();
  }
}
Example #23
Source File: avatar.ts    From ens-metadata-service with MIT License 5 votes vote down vote up
export async function getAvatarMeta(
  provider: BaseProvider,
  name: string,
  networkName: string
): Promise<any> {
  const avatar = new AvatarMetadata(provider, name);
  return await avatar.getMeta(networkName);
}
Example #24
Source File: ether-js-fetcher.test.tsx    From ether-swr with MIT License 5 votes vote down vote up
ProviderMock = BaseProvider as jest.Mocked<typeof BaseProvider>
Example #25
Source File: kyberDMM.ts    From index-rebalance-utils with Apache License 2.0 5 votes vote down vote up
export async function getKyberDMMQuote(
  provider: BaseProvider,
  tokenAddress: Address,
  targetPriceImpact: BigNumber
): Promise<ExchangeQuote> {
  const token: kyberToken = await kyberFetcher.fetchTokenData(ChainId.MAINNET, tokenAddress, provider);
  const weth: kyberToken = await kyberFetcher.fetchTokenData(ChainId.MAINNET, ETH_ADDRESS, provider);
  const wbtc: kyberToken = await kyberFetcher.fetchTokenData(ChainId.MAINNET, BTC_ADDRESS, provider);
  const usdc: kyberToken = await kyberFetcher.fetchTokenData(ChainId.MAINNET, USDC_ADDRESS, provider);

  const trades = await kyberTrade.bestTradeExactIn(
    await getKyberDMMPairs(provider, [token, weth, wbtc, usdc]),
    new kyberTokenAmount(weth, ether(1).toString()),
    token,
    {maxNumResults: 3, maxHops: 1},
  );

  if (trades.length != 0) {
    // Use linear approximation of price impact to find out how many 1 ETH trades add to 50 bps price
    // impact (net of fees)
    const fee: BigNumber = BigNumber.from(trades[0].route.pairs[0].fee.toString());
    const priceImpactRatio = preciseDiv(
      targetPriceImpact,
      // Price impact measured in percent so fee must be as well
      ether((parseFloat(trades[0].priceImpact.toSignificant(18)) - fee.toNumber() / 10 ** 16).toFixed(18))
    );

    return {
      exchange: exchanges.KYBER,
      size: preciseMul(
        ether(parseFloat(trades[0].outputAmount.toExact())).div(BigNumber.from(10).pow(18 - token.decimals)),
        priceImpactRatio).toString(),
      data: trades[0].route.pairs[0].address,
    } as ExchangeQuote;
  }

  return {
    exchange: exchanges.KYBER,
    size: ZERO.toString(),
    data: "0x",
  } as ExchangeQuote;
}
Example #26
Source File: Web3ReactProvider.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
export function Web3ReactProvider<T extends BaseProvider = Web3Provider>(
  props: Web3ReactProviderProps,
) {
  const { children } = props;

  const [connectionType, setConnectionType] = useLocalStorage<ConnectType>(
    '__anchor_evm_wallet_connect_type__',
    ConnectType.None,
  );

  const {
    useSelectedChainId,
    useSelectedAccounts,
    useSelectedIsActivating,
    useSelectedError,
    useSelectedAccount,
    useSelectedIsActive,
    useSelectedProvider,
  } = getSelectedConnector(...connectors);

  const [connector, , store] = getWeb3Connector(connectionType);

  const chainId = useSelectedChainId(connector);
  const accounts = useSelectedAccounts(connector);
  const isActivating = useSelectedIsActivating(connector);
  const error = useSelectedError(connector);
  const account = useSelectedAccount(connector);
  const isActive = useSelectedIsActive(connector);
  const provider = useSelectedProvider<T>(connector, 'any');

  const connect = useCallback(
    (connectionType: ConnectType) => {
      setConnectionType(connectionType);
      return getWeb3Connector(connectionType)[0];
    },
    [setConnectionType],
  );

  const disconnect = useCallback(() => {
    setConnectionType(ConnectType.None);
  }, [setConnectionType]);

  const value = useMemo(() => {
    return {
      chainId,
      accounts,
      isActivating,
      error,
      account,
      isActive,
      provider,
      connector,
      connectionType: connectionType ?? ConnectType.None,
      store,
      connect,
      disconnect,
    };
  }, [
    chainId,
    accounts,
    isActivating,
    error,
    account,
    isActive,
    provider,
    connector,
    connectionType,
    store,
    connect,
    disconnect,
  ]);

  return <Web3Context.Provider value={value}>{children}</Web3Context.Provider>;
}
Example #27
Source File: provider.test.ts    From ethcall with MIT License 5 votes vote down vote up
class FakeProvider extends BaseProvider {
  async getNetwork(): Promise<Network> {
    return {
      name: 'FakeNetwork',
      chainId: -1,
    };
  }
}
Example #28
Source File: provider.ts    From ethcall with MIT License 5 votes vote down vote up
provider?: BaseProvider;
Example #29
Source File: bridgeAssetsQuery.ts    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
fetchEvmAddr = async (
  lcd: LCDClient,
  wormholeChainId: ChainId,
  provider: BaseProvider,
  network: NetworkInfo,
  tokenAddr: string,
) => {
  const ETH_ADDR_ZERO = '0x0000000000000000000000000000000000000000';

  const wormhole = await getOriginalAssetTerra(lcd as any, tokenAddr);
  if (wormhole.isWrapped) {
    // the token is wrapped on terra which means this
    // the information we get back is the original
    if (wormhole.chainId === wormholeChainId) {
      return [
        tokenAddr,
        uint8ArrayToNative(
          wormhole.assetAddress,
          wormhole.chainId,
        ) as ERC20Addr,
      ];
    }
    return undefined;
  }

  // the token is on Terra so need to check if
  // it is wrapped onto our selected chain
  const foreignAsset = await getForeignAssetEth(
    // TODO: need a better way to handle this
    network.chainID === 'bombay-12'
      ? '0x61E44E506Ca5659E6c0bba9b678586fA2d729756'
      : '0x0e082F06FF657D94310cB8cE8B0D9a04541d8052',
    provider,
    CHAIN_ID_TERRA,
    hexToUint8Array(await getEmitterAddressTerra(tokenAddr)),
  );
  if (foreignAsset && foreignAsset !== ETH_ADDR_ZERO) {
    return [tokenAddr, foreignAsset as ERC20Addr];
  }

  return undefined;
}