@ethersproject/providers#Web3Provider TypeScript Examples
The following examples show how to use
@ethersproject/providers#Web3Provider.
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 apeswap-swap-core with GNU General Public License v3.0 | 7 votes |
export async function mineBlock(provider: Web3Provider | MockProvider, timestamp: number): Promise<void> {
await new Promise(async (resolve, reject) => {
;(provider.provider.sendAsync as any)(
{ jsonrpc: '2.0', method: 'evm_mine', params: [timestamp] },
(error: any, result: any): void => {
if (error) {
reject(error)
} else {
resolve(result)
}
}
)
})
}
Example #2
Source File: utilities.ts From vvs-swap-core with GNU General Public License v3.0 | 7 votes |
export async function mineBlock(provider: Web3Provider, timestamp: number): Promise<void> {
await new Promise(async (resolve, reject) => {
;(provider.provider.sendAsync as any)(
{ jsonrpc: '2.0', method: 'evm_mine', params: [timestamp] },
(error: any, result: any): void => {
if (error) {
reject(error)
} else {
resolve(result)
}
}
)
})
}
Example #3
Source File: fixtures.ts From apeswap-swap-core with GNU General Public License v3.0 | 6 votes |
export async function pairFixture([wallet]: Wallet[], provider: Web3Provider): Promise<PairFixture> {
const { factory } = await factoryFixture([wallet], provider)
const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
await factory.createPair(tokenA.address, tokenB.address, overrides)
const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
const pair = new Contract(pairAddress, JSON.stringify(ApePair.abi), provider).connect(wallet)
const token0Address = (await pair.token0()).address
const token0 = tokenA.address === token0Address ? tokenA : tokenB
const token1 = tokenA.address === token0Address ? tokenB : tokenA
return { factory, token0, token1, pair }
}
Example #4
Source File: uniswapV3Fixture.ts From index-coop-smart-contracts with Apache License 2.0 | 6 votes |
/**
* 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 #5
Source File: WalletConnect.tsx From hypertext with GNU General Public License v3.0 | 6 votes |
export default function WalletConnect(): JSX.Element | null {
const { active, error, activate, setError } = useWeb3React<Web3Provider>()
const [connecting, setConnecting] = useState(false)
useEffect(() => {
if (active || error) {
setConnecting(false)
}
}, [active, error])
if (error) {
return null
}
return (
<Button
isLoading={connecting}
leftIcon={'walletconnect' as 'edit'}
onClick={(): void => {
setConnecting(true)
// reset the connector if it was tried already
if (walletconnect?.walletConnectProvider?.wc?.uri) {
walletconnect.walletConnectProvider = undefined
}
activate(walletconnect, undefined, true).catch((error) => {
if (error instanceof UserRejectedRequestError) {
setConnecting(false)
} else {
setError(error)
}
})
}}
>
WalletConnect
</Button>
)
}
Example #6
Source File: index.ts From interface-v2 with GNU General Public License v3.0 | 6 votes |
export function useActiveWeb3React(): Web3ReactContextInterface<
Web3Provider
> & {
chainId?: ChainId;
} {
const context = useWeb3ReactCore<Web3Provider>();
const contextNetwork = useWeb3ReactCore<Web3Provider>(
GlobalConst.utils.NetworkContextName,
);
return context.active ? context : contextNetwork;
}
Example #7
Source File: governance.ts From sybil-interface with GNU General Public License v3.0 | 6 votes |
export async function fetchTopDelegates(
client: any,
library: Web3Provider,
allIdentities: Identities
): Promise<DelegateData[] | null> {
return fetchDelegatesFromClient(client, library, allIdentities, {
query: TOP_DELEGATES,
fetchPolicy: 'cache-first',
})
}
Example #8
Source File: App.tsx From ether-swr with MIT License | 6 votes |
EthBalance = () => {
const { account } = useWeb3React<Web3Provider>()
const { data: balance, mutate } = useEtherSWR(
['getBalance', account, 'latest'],
{
subscribe: [
{
name: 'block',
on: (event: any) => {
console.log('block', { event })
// on every block we check if Ether balance has changed by re-fetching
mutate(undefined, true)
}
}
]
}
)
if (!balance) {
return <div>...</div>
}
return <div>{parseFloat(formatEther(balance)).toPrecision(4)} Ξ</div>
}
Example #9
Source File: ethers.ts From react-celo with MIT License | 6 votes |
useProvider = (): Web3Provider => {
const { kit, network } = useCelo();
const provider = kit.connection.web3
.currentProvider as unknown as ExternalProvider;
const { chainId, name } = network;
return useMemo(() => {
return new Web3Provider(provider, { chainId, name });
}, [provider, chainId, name]);
}
Example #10
Source File: web3.ts From dope-monorepo with GNU General Public License v3.0 | 6 votes |
useWAGMI = () => {
const { connector } = useWeb3React<Web3Provider>();
const [activatingConnector, setActivatingConnector] = useState<any>();
useEffect(() => {
if (activatingConnector && activatingConnector === connector) {
setActivatingConnector(undefined);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activatingConnector, connector]);
const triedEager = useEagerConnect();
useInactiveListener(!triedEager || !!activatingConnector);
}
Example #11
Source File: index.ts From limit-orders-lib with GNU General Public License v3.0 | 6 votes |
// account is optional
// account is optional
export function getContract(
address: string,
ABI: any,
library: Web3Provider,
account?: string
): Contract {
if (!isAddress(address) || address === AddressZero) {
throw Error(`Invalid 'address' parameter '${address}'.`);
}
return new Contract(
address,
ABI,
getProviderOrSigner(library, account) as any
);
}
Example #12
Source File: useActiveWeb3React.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: api.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
constructor(
_factory: any,
contractAddress: string,
web3Provider: ExternalProvider
) {
this.contractAddress = contractAddress;
this.Provider = new Web3Provider(web3Provider);
// 12s minute polling interval (default is 4s)
this.Provider.pollingInterval = 12000;
}
Example #14
Source File: index.tsx From nouns-monorepo with GNU General Public License v3.0 | 6 votes |
ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <ChainSubscriber /> <React.StrictMode> <Web3ReactProvider getLibrary={ provider => new Web3Provider(provider) // this will vary according to whether you use e.g. ethers or web3.js } > <ApolloProvider client={client}> <PastAuctions /> <DAppProvider config={useDappConfig}> <LanguageProvider> <App /> </LanguageProvider> <Updaters /> </DAppProvider> </ApolloProvider> </Web3ReactProvider> </React.StrictMode> </ConnectedRouter> </Provider>, document.getElementById('root'), );
Example #15
Source File: ConnectWallet.tsx From lp-inspector with MIT License | 6 votes |
function ConnectWallet({ children, callback }: ConnectWalletProps) {
const { activate, active, account, error } = useWeb3React<Web3Provider>();
const [btnText, setBtnText] = useState(children);
const [btnClass, setBtnClass] = useState("connect-wallet-btn");
useEffect(() => {
if (error && error instanceof UnsupportedChainIdError) {
setBtnText("Supported only BSC chain (56).");
setBtnClass("connect-wallet-btn connect-wallet-btn-error");
} else if (account) {
setBtnClass("connect-wallet-btn");
const ellisizeText =
account.substring(0, 6) +
"..." +
account.substring(account.length - 4, account.length);
setBtnText(ellisizeText);
callback(account);
} else {
setBtnClass("connect-wallet-btn");
setBtnText(children);
}
}, [account, activate, active, callback, children, error]);
function handleClick(e: React.MouseEvent<HTMLDivElement>) {
activate(injectedConnector);
}
return (
<div className="connect-wallet-container" onClick={handleClick}>
{!active ? (
<button className={btnClass} disabled={active}>
{btnText}
</button>
) : (
<p>{btnText}</p>
)}
</div>
);
}
Example #16
Source File: index.ts From snapshot-strategies with MIT License | 6 votes |
export async function strategy(
...args: [string, string, Web3Provider, string[], { coeff?: number }, number]
) {
const [space, network, provider, addresses, options, snapshot] = args;
const { coeff = 100 } = options;
return ethReceivedStrategy(
space,
network,
provider,
addresses,
{
receivingAddresses: ethCharities.map(([, address]) => address),
coeff
},
snapshot
);
}
Example #17
Source File: client.ts From snapshot.js with MIT License | 6 votes |
async broadcast(
web3: Web3Provider,
account: string,
space: string,
type: string,
payload: any
) {
const msg: any = {
address: account,
msg: JSON.stringify({
version,
timestamp: (Date.now() / 1e3).toFixed(),
space,
type,
payload
})
};
msg.sig = await signMessage(web3, msg.msg, account);
return await this.send(msg);
}
Example #18
Source File: useSwapper.ts From forward.swaps with GNU General Public License v3.0 | 6 votes |
// For demo
function useSwapCallArguments(): SwapCall[] {
const { account, chainId, library } = useActiveWeb3React()
return useMemo(() => {
if (!library || !account || !chainId) return []
const _contract: Contract | null = getBiconomySwappperContract(
BICONOMY_CONTRACT,
BICONOMYSWAPPER_ABI,
library,
account
)
const _ethersProvider: Web3Provider | null = getEthersProvider()
if (!_contract) {
return []
}
const swapMethods = []
const _parameters = { pid: '0', amount: '0' }
const pass = {
account: account,
contract: _contract,
ethersProvider: _ethersProvider,
// permitClient: _permitClient,
// ercForwarderClient: _ercForwarderClient,
parameters: _parameters
}
swapMethods.push(pass)
return swapMethods
// return swapMethods.map(parameters => ({ parameters, contract }))
}, [account, chainId, library])
}
Example #19
Source File: rpcconnector.ts From sdk with ISC License | 6 votes |
/**
* @internal
*/
setProviderConfig(
chainId: number,
endpoint: string,
batchInterval: number = 50,
) {
const provider = this._newProvider(chainId, endpoint, batchInterval);
delete this._chainEndpoints[chainId];
delete this._providers[chainId];
delete this._web3Providers[chainId];
this._chainEndpoints[chainId] = endpoint;
this._providers[chainId] = provider
this._web3Providers[chainId] = new Web3Provider(provider);
}
Example #20
Source File: index.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
// account is optional
export function getRouterContract(_: number, library: Web3Provider, account?: string): Contract {
return getContract(
_ === 89 || _ === 88 || _ === 99 ? TOMO_ROUTER_ADDRESS : ROUTER_ADDRESS,
IUniswapV2Router02ABI,
library,
account
)
}
Example #21
Source File: fixtures.ts From vvs-swap-core with GNU General Public License v3.0 | 6 votes |
export async function pairFixture([wallet]: Wallet[], provider: Web3Provider): Promise<PairFixture> {
const { factory } = await factoryFixture([wallet], provider)
const tokenA = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
const tokenB = await deployContract(wallet, ERC20, [expandTo18Decimals(10000)], overrides)
await factory.createPair(tokenA.address, tokenB.address, overrides)
const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
const pair = new Contract(pairAddress, JSON.stringify(VVSPair.abi), provider).connect(wallet)
const token0Address = (await pair.token0()).address
const token0 = tokenA.address === token0Address ? tokenA : tokenB
const token1 = tokenA.address === token0Address ? tokenB : tokenA
return { factory, token0, token1, pair }
}
Example #22
Source File: EvmWalletProvider.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
function WalletProvider({ children }: UIElementProps) {
const {
connector,
store,
chainId,
isActive,
isActivating,
account,
error,
provider,
connectionType,
} = useWeb3React();
const evmWallet = useMemo<EvmWallet>(() => {
const status: WalletStatus = isActivating
? WalletStatus.Initializing
: isActive
? WalletStatus.Connected
: WalletStatus.Disconnected;
const activate = async (chainId?: number): Promise<Error | undefined> => {
await connector.activate(chainId);
// the activate method doesnt fail as it reports any
// errors to its local zustand store so we need
// to access that to determine if it failed
const { error } = store.getState();
return error;
};
const watchAsset = async (token: ERC20Token) => {
if (connector instanceof MetaMask && connector.provider) {
await connector.provider?.request({
method: 'wallet_watchAsset',
params: {
// @ts-ignore ethers has wrong params type (Array<any>)
type: 'ERC20',
options: token,
},
});
}
};
const connection =
account === undefined
? null
: AvailableConnections.filter((c) => c.type === connectionType)[0];
return {
activate,
watchAsset,
connectionType,
availableConnectTypes: [ConnectType.MetaMask, ConnectType.WalletConnect],
availableConnections: AvailableConnections,
connection,
address: account,
chainId,
status,
error,
provider: provider as Web3Provider,
};
}, [
connectionType,
connector,
store,
account,
isActivating,
isActive,
chainId,
error,
provider,
]);
return (
<EvmWalletContext.Provider value={evmWallet}>
{children}
</EvmWalletContext.Provider>
);
}
Example #23
Source File: eth.ts From pawnft with GNU General Public License v3.0 | 5 votes |
/**
* Provides functionality for Eth account/state management
*/
function useEth() {
const [address, setAddress] = useState<string | null>(null); // User address
const [onboard, setOnboard] = useState<API | null>(null); // Onboard provider
const [provider, setProvider] = useState<Web3Provider | null>(null); // Ethers provider
/**
* Unlock wallet, store ethers provider and address
*/
const unlock = async () => {
// Enables wallet selection via BNC onboard
await onboard.walletSelect();
await onboard.walletCheck();
};
// --> Lifecycle: on mount
useEffect(() => {
// Onboard provider
const onboard = Onboard({
// Rinkeby testnet
networkId: 4,
// Hide Blocknative branding
hideBranding: true,
// Setup custom wallets for selection
walletSelect: {
heading: "Connect to PawnLoan",
description: "Please select a wallet to authenticate with PawnLoan.",
wallets: wallets,
},
// Track subscriptions
subscriptions: {
// On wallet update
wallet: async (wallet) => {
// If wallet provider exists
if (wallet.provider) {
// Collect ethers provider
const provider = new ethers.providers.Web3Provider(wallet.provider);
// Collect address
const signer = await provider.getSigner();
const address: string = await signer.getAddress();
// Update provider, address, and raw address
setProvider(provider);
setAddress(address);
} else {
// Nullify data
setProvider(null);
setAddress(null);
}
},
},
// Force connect on walletCheck for WalletConnect
walletCheck: [{ checkName: "network" }, { checkName: "connect" }],
});
// Update onboard
setOnboard(onboard);
}, []);
return { address, provider, unlock };
}
Example #24
Source File: fixtures.ts From apeswap-swap-core with GNU General Public License v3.0 | 5 votes |
export async function factoryFixture([wallet]: Wallet[], _: Web3Provider): Promise<FactoryFixture> {
const factory = await deployContract(wallet, ApeFactory, [wallet.address], overrides)
return { factory }
}
Example #25
Source File: index.ts From cuiswap with GNU General Public License v3.0 | 5 votes |
export function useActiveWeb3React(): Web3ReactContextInterface<Web3Provider> & { chainId?: ChainId } {
const context = useWeb3ReactCore<Web3Provider>()
const contextNetwork = useWeb3ReactCore<Web3Provider>(NetworkContextName)
return context.active ? context : contextNetwork
}
Example #26
Source File: blockchainUtils.ts From index-coop-smart-contracts with Apache License 2.0 | 5 votes |
constructor(_provider: Web3Provider | JsonRpcProvider) {
this._provider = _provider;
this._snapshotId = 0;
}
Example #27
Source File: data.ts From hypertext with GNU General Public License v3.0 | 5 votes |
function getBlockNumber(library: Web3Provider): () => Promise<number> {
return async (): Promise<number> => {
return library.getBlockNumber()
}
}
Example #28
Source File: index.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
export function getNetworkLibrary(): Web3Provider {
return (networkLibrary =
networkLibrary ?? new Web3Provider(network.provider as any));
}
Example #29
Source File: index.ts From sybil-interface with GNU General Public License v3.0 | 5 votes |
export function getNetworkLibrary(): Web3Provider {
return (networkLibrary = networkLibrary ?? new Web3Provider(network.provider as any))
}