Struct web30::client::Web3

source ·
pub struct Web3 { /* private fields */ }
Expand description

An instance of Web3Client.

Implementations§

Queries the Uniswap V2 Router02 to get the amount of token_out obtainable for amount of token_in This method will not swap any funds

Arguments
  • caller_address - The ethereum address simulating the swap
  • token_in - The address of an ERC20 token to offer up
  • token_out - The address of an ERC20 token to receive
  • amount - the amount of token_in to swap for some amount of token_out
  • uniswap_router - Optional address of the Uniswap v2 Router02 to contact, default is 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
Examples
use std::time::Duration;
use std::str::FromStr;
use clarity::Address;
use clarity::Uint256;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("https://eth.althea.net", Duration::from_secs(5));
let result = web3.get_uniswap_v2_price(
    Address::parse_and_validate("0x1111111111111111111111111111111111111111").unwrap(),
    *WETH_CONTRACT_ADDRESS,
    *DAI_CONTRACT_ADDRESS,
    Uint256::from_str("1000000000000000000"), // 1 WETH in
    Some(*UNISWAP_V3_ROUTER_ADDRESS),
);

Checks all the standard Uniswap v3 fee pools to get the amount of token_out obtainable for amount of token_in, accounting for slippage A pool with low liquidity will have its price rejected This method is particularly useful for newer tokens which may not have a 0.3% fee pool in Uniswap v3 The queried fee levels are 0.3%, 0.05%, 1%, and 0.01% This method repeatedly simulates transactions using the Uniswap Quoter, it does not swap any funds

Arguments
  • caller_address - The ethereum address simulating the swap
  • token_in - The address of an ERC20 token to offer up
  • token_out - The address of an ERC20 token to receive
  • amount - the amount of token_in to swap for some amount of token_out
  • max_slippage - The maximum acceptable slippage, defaults to 0.005 (0.5%)
  • uniswap_quoter - Optional Uniswap v3 Quoter contract to use, default is 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6
Examples
use std::time::Duration;
use std::str::FromStr;
use clarity::Address;
use clarity::Uint256;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("https://eth.althea.net", Duration::from_secs(5));
let result = web3.get_uniswap_price_with_retries(
    Address::parse_and_validate("0x1111111111111111111111111111111111111111").unwrap(),
    *WETH_CONTRACT_ADDRESS,
    *DAI_CONTRACT_ADDRESS,
    Uint256::from_str("1000000000000000000"), // 1 WETH in
    Some(0.05f64), // 5% max slippage
    Some(*UNISWAP_V3_QUOTER_ADDRESS),
);

An easy to use price checker simulating a Uniswap v3 swap for amount of token_in to get token_out, accounting for slippage A sensible fee level of the pool and slippage amount will be calculated if None are provided This method simulates a transaction using the Uniswap Quoter, it does not swap any funds

Arguments
  • caller_address - The ethereum address simulating the swap
  • token_in - The address of an ERC20 token to offer up
  • token_out - The address of an ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • amount - the amount of token_in to swap for some amount of token_out
  • max_slippage - The maximum acceptable slippage, defaults to 0.005 (0.5%)
  • uniswap_quoter - Optional address of the Uniswap v3 quoter to contact, default is 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6
Examples
use std::time::Duration;
use std::str::FromStr;
use clarity::Address;
use clarity::Uint256;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("https://eth.althea.net", Duration::from_secs(5));
let result = web3.get_uniswap_price_with_slippage(
    Address::parse_and_validate("0x1111111111111111111111111111111111111111").unwrap(),
    *WETH_CONTRACT_ADDRESS,
    *DAI_CONTRACT_ADDRESS,
    Some(500u16.into()), // the 0.05% fee pool
    Uint256::from_str("1000000000000000000"), // 1 WETH in
    Some(0.05f64), // 5% max slippage
    Some(*UNISWAP_V3_QUOTER_ADDRESS),
);

A highly-flexible price checker simulating a Uniswap v3 swap amount of token_out obtainable for amount of token_in Returns an error if the pool’s liquidity is too low, resulting in a swap returning less than what the sqrt_price_limit_x96_uint160 implies should be traded This method simulates a transaction using the Uniswap Quoter, it does not swap any funds

Arguments
  • caller_address - The ethereum address simulating the swap
  • token_in - The address of an ERC20 token to offer up
  • token_out - The address of an ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • sqrt_price_limit_x96_uint160 - Optional square root price limit, see methods below for more information
  • uniswap_quoter - Optional address of the Uniswap v3 quoter to contact, default is 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6
Examples
use std::time::Duration;
use std::str::FromStr;
use clarity::Address;
use clarity::Uint256;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("https://eth.althea.net", Duration::from_secs(5));
let result = web3.get_uniswap_price(
    Address::parse_and_validate("0x1111111111111111111111111111111111111111").unwrap(),
    *WETH_CONTRACT_ADDRESS,
    *DAI_CONTRACT_ADDRESS,
    Some(500u16.into()),
    Uint256::from_str("1000000000000000000"), // 1 WETH
    Some(uniswap_sqrt_price(2023u16.into(), 1u8.into())), // Sample 1 Eth ->  2k Dai swap rate,
    Some(*UNISWAP_V3_QUOTER_ADDRESS),
);

An easy to use swap method for Uniswap v3, exchanging amount of token_in for token_out, accounting for slippage If max_slippage is None, the default of 0.5% will be used This method calls exactInputSingle on the Uniswap v3 Router

Arguments
  • eth_private_key - The private key of the holder of token_in who will receive token_out
  • token_in - The address of the ERC20 token to exchange for token_out
  • token_out - The address of the ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the medium pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • amount - The amount of token_in to exchange for as much token_out as possible
  • deadline - Optional deadline to the swap before it is cancelled, 10 minutes if None
  • max_slippage - Optional maximum slippage amount for the swap, defaults to 0.005 (0.5%) if None
  • uniswap_router - Optional address of the Uniswap v3 SwapRouter to contact, default is 0xE592427A0AEce92De3Edee1F18E0157C05861564
  • options - Optional arguments for the Transaction, see send_transaction()
  • wait_timeout - Set to Some(TIMEOUT) if you wish to wait for this tx to enter the chain before returning

A highly-flexible swap method for Uniswap v3, exchanging, exchanging amount of token_in for token_out This method calls exactInputSingle on the Uniswap v3 Router

Arguments
  • eth_private_key - The private key of the holder of token_in who will receive token_out
  • token_in - The address of the ERC20 token to exchange for token_out
  • token_out - The address of the ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the medium pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • amount - The amount of token_in to exchange for as much token_out as possible
  • deadline - Optional deadline to the swap before it is cancelled, 10 minutes if None
  • amount_out_min - Optional minimum amount of token_out to receive or the swap is cancelled, ignored if None
  • sqrt_price_limit_x96_64 - Optional square root price limit, ignored if None or 0. See the methods below for more information
  • uniswap_router - Optional address of the Uniswap v3 SwapRouter to contact, default is 0xE592427A0AEce92De3Edee1F18E0157C05861564
  • options - Optional arguments for the Transaction, see send_transaction()
  • wait_timeout - Set to Some(TIMEOUT) if you wish to wait for this tx to enter the chain before returning
Examples
use std::time::Duration;
use clarity::PrivateKey;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("http://localhost:8545", Duration::from_secs(5));
let result = web3.swap_uniswap_v3(
    "0x1111111111111111111111111111111111111111111111111111111111111111".parse().unwrap(),
    *WETH_CONTRACT_ADDRESS,
    *DAI_CONTRACT_ADDRESS,
    Some(500u16.into()),
    1000000000000000000u128.into(), // 1 WETH
    Some(60u8.into()), // Wait 1 minute
    Some(2020000000000000000000u128.into()), // Expect >= 2020 DAI
    Some(uniswap_v3_sqrt_price_from_amounts(1u8.into(), 2000u16.into())), // Sample 1 Eth ->  2k Dai swap rate
    Some(*UNISWAP_V3_ROUTER_ADDRESS),
    None,
    None,
);

An easy to use swap method for Uniswap v3, exchanging amount of eth for token_out, accounting for slippage If max_slippage is None, the default of 0.5% will be used This method calls exactInputSingle on the Uniswap v3 Router

IMPORTANT: normally Uniswap v3 only works with ERC20 tokens, but in the case of transfers involving wETH, they will wrap the ETH for you before the swap. Using this method you will be charged the additional gas required to wrap the input amount of ETH. If you will be calling this method multiple times, it is likely cheaper to wrap a lot of ETH and calling swap_uniswap_with_slippage() instead.

Arguments
  • eth_private_key - The private key of the holder of token_in who will receive token_out
  • token_out - The address of the ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the medium pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • amount - The amount of token_in to exchange for as much token_out as possible
  • deadline - Optional deadline to the swap before it is cancelled, 10 minutes if None
  • max_slippage - Optional maximum slippage amount for the swap, defaults to 0.005 (0.5%) if None
  • uniswap_router - Optional address of the Uniswap v3 SwapRouter to contact, default is 0xE592427A0AEce92De3Edee1F18E0157C05861564
  • options - Optional arguments for the Transaction, see send_transaction()
  • wait_timeout - Set to Some(TIMEOUT) if you wish to wait for this tx to enter the chain before returning

A highly-flexible swap method for Uniswap v3, exchanging, exchanging amount of eth directly for token_out This method calls exactInputSingle on the Uniswap v3 Router

IMPORTANT: normally Uniswap v3 only works with ERC20 tokens, but in the case of transfers involving wETH, they will wrap the ETH for you before the swap. Using this method you will be charged the additional gas required to wrap the input amount of ETH. If you will be calling this method multiple times, it is likely cheaper to wrap a lot of ETH and calling swap_uniswap() instead.

Arguments
  • eth_private_key - The private key of the holder of token_in who will receive token_out
  • token_out - The address of the ERC20 token to receive
  • fee_uint24 - Optional fee level of the token_in<->token_out pool to query - limited to uint24 in size. Defaults to the medium pool fee of 0.3% The suggested pools are 0.3% (3000), 0.05% (500), 1% (10000), and 0.01% (100) but more may be added permissionlessly
  • amount - The amount of token_in to exchange for as much token_out as possible
  • deadline - Optional deadline to the swap before it is cancelled, 10 minutes if None
  • amount_out_min - Optional minimum amount of token_out to receive or the swap is cancelled, if None and sqrt_price_limit_x96_64 is Some(_) then a sensible value will be computed
  • sqrt_price_limit_x96_64 - Optional square root price limit, ignored if None or 0. See methods below for how to work with this value
  • uniswap_router - Optional address of the Uniswap v3 SwapRouter to contact, default is 0xE592427A0AEce92De3Edee1F18E0157C05861564
  • options - Optional arguments for the Transaction, see send_transaction()
  • wait_timeout - Set to Some(TIMEOUT) if you wish to wait for this tx to enter the chain before returning
Examples
use std::time::Duration;
use clarity::PrivateKey;
use web30::amm::*;
use web30::client::Web3;
let web3 = Web3::new("http://localhost:8545", Duration::from_secs(5));
let result = web3.swap_uniswap_v3_eth_in(
    "0x1111111111111111111111111111111111111111111111111111111111111111".parse().unwrap(),
    *DAI_CONTRACT_ADDRESS,
    Some(500u16.into()),
    1000000000000000000u128.into(), // 1 ETH
    Some(60u8.into()), // Wait 1 minute
    Some(2020000000000000000000u128.into()), // Expect >= 2020 DAI
    Some(uniswap_v3_sqrt_price_from_amounts(1u8.into(), 2000u16.into())), // Sample 1 Eth ->  2k Dai swap rate
    Some(*UNISWAP_V3_ROUTER_ADDRESS),
    None,
    None,
);

Requests the contract address for the Uniswap v3 pool determined by token_a, token_b, and fee_uint24 from the default or given Uniswap Factory contract

Identifies token0 and token1 in a Uniswap v3 pool, which all stored data is based off of

Returns either token0 or token1 from a Uniswap v3 pool, depending on input

Fetches the “slot0” data from a Uniswap pool, which contains the following binary encoded data: uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked

Fetches the current sqrtPriceX96 value from the given pool sqrtPriceX96 is returned as the first value from a call to pool.slot0()

Note that this value will differ slightly from the swap price due to the pool fee

Generates a Uniswap v3 sqrtPriceX96 to allow a maximum amount of slippage on a trade by querying the specified pool If fee is None then the 0.3% fee pool will be used

Returns a sensible swap amount_out for any input sqrt_price_limit, defined as the minimum swap the sqrt_price_limit would allow in an on-chain swap (sqrt_price_limit * amount)

Handles the directional nature of swaps by querying the Uniswap v3 pool for its token order Returns an error if the pool given by token_in, token_out, and fee does not exist

Returns the EIP155 chain ID used for transaction signing at the current best block. Null is returned if not available.

Get the median gas price over the last 10 blocks. This function does not simply wrap eth_gasPrice, in post London chains it also requests the base gas from the previous block and prevents the use of a lower value

Returns a bool indicating whether our eth node is currently syncing or not

Retrieves the latest synced block number regardless of state of eth node

Sends a transaction which changes blockchain state. options takes a vector of SendTxOption for configuration unlike the lower level eth_send_transaction() this call builds the transaction abstracting away details like chain id, gas, and network id. WARNING: you must specify networkID in situations where a single node is operating no more than one chain. Otherwise it is possible for the full node to trick the client into signing transactions on unintended chains potentially to their benefit

Simulates an Ethereum contract call by making a fake transaction and sending it to a special endpoint this code is executed exactly as if it where an actual transaction executing. This can be used to execute both getter endpoints on Solidity contracts and to test actual executions. User beware, this function requires ETH in the caller address to run. Even if you’re just trying to call a getter function and never need to actually run code this faithful simulation will fail if you have no ETH to pay for gas.

In an attempt to maximize the amount of info you can get with this function gas is computed for you as the maximum possible value, if you need to get gas estimation you should use web3.eth_estimate_gas instead.

optionally this data can come from some historic block

Waits for a transaction with the given hash to be included in a block it will wait for at most timeout time and optionally can wait for n blocks to have passed

Waits for the next Ethereum block to be produced

Checks if any given contract is approved to spend money from any given erc20 contract using any given address. What exactly this does can be hard to grok, essentially when you want contract A to be able to spend your erc20 contract funds you need to call ‘approve’ on the ERC20 contract with your own address and A’s address so that in the future when you call contract A it can manipulate your ERC20 balances. This function checks if that has already been done.

Approves a given contract to spend erc20 funds from the given address from the erc20 contract provided. What exactly this does can be hard to grok, essentially when you want contract A to be able to spend your erc20 contract funds you need to call ‘approve’ on the ERC20 contract with your own address and A’s address so that in the future when you call contract A it can manipulate your ERC20 balances. This function performs that action and waits for it to complete for up to Timeout duration options takes a vector of SendTxOption for configuration unlike the lower level eth_send_transaction() this call builds the transaction abstracting away details like chain id, gas, and network id.

Send an erc20 token to the target address, optionally wait until it enters the blockchain options takes a vector of SendTxOption for configuration unlike the lower level eth_send_transaction() this call builds the transaction abstracting away details like chain id, gas, and network id. WARNING: you must specify networkID in situations where a single node is operating no more than one chain. Otherwise it is possible for the full node to trick the client into signing transactions on unintended chains potentially to their benefit

Queries the target_address’s current balance of erc20

See get_erc20_balance_at_height and get_erc20_balance_as_address if you need more flexibility including historical balances and balances of targets which hold very little ETH

Queries the target_address’s balance of erc20 at an optional ethereum height

The latest balance from the current block will be queried if height is None

Queries the target_address’s balance of erc20 using requester_address as the transaction’s from field

The target_address will be used as from if requester_address is None

This is particularly useful if the ERC20 holder has too little ETH for gas fees, e.g. Gravity.sol

Queries the target_address’s balance of erc20 at an optional ethereum height, using requester_address as the transaction’s from field

The target_address will be used as from if requester_address is None The latest balance from the current block will be queried if height is None

This is particularly useful if the ERC20 holder had too little ETH for gas fees, e.g. Gravity.sol

Executes EIP-721 getApproved(uint256 _tokenId) external view returns (address) Checks if any given contract is approved to spend money from any given erc721 contract using any given address. What exactly this does can be hard to grok, essentially when you want contract A to be able to spend your erc721 contract funds you need to call ‘approve’ on the ERC721 contract with your own address and A’s address so that in the future when you call contract A it can move the ERC721 token. This function checks if that has already been done.

Executes EIP-721 approve(address,uint256) Approves a given contract to transfer ERC721 tokens from the given address from the erc721 contract provided. What exactly this does can be hard to grok, essentially when you want contract A to be able to spend your erc721 contract tokens you need to call ‘approve’ on the ERC721 contract with your own address and A’s address so that in the future when you call contract A it can manipulate your ERC721 ownership. This function performs that action and waits for it to complete for up to Timeout duration options takes a vector of SendTxOption for configuration unlike the lower level eth_send_transaction() this call builds the transaction abstracting away details like chain id, gas, and network id.

Executes EIP-721 transferFrom(address _from, address _to, uint256 _tokenId) Send an erc721 token to the target address, optionally wait until it enters the blockchain options takes a vector of SendTxOption for configuration unlike the lower level eth_send_transaction() this call builds the transaction abstracting away details like chain id, gas, and network id. WARNING: you must specify networkID in situations where a single node is operating no more than one chain. Otherwise it is possible for the full node to trick the client into signing transactions on unintended chains potentially to their benefit

Executes EIP-721 name() external view returns (string _name) Here we make a call using the EIP-721 standard, it will return a string representing ERC721 name or Web3Error::ContractCallError

Executes EIP-721 symbol() external view returns (string _symbol) Here we make a call using the EIP-721 standard, it will return a string representing ERC721 symbol or Web3Error::ContractCallError

Executes EIP-721 totalSupply() external view returns (uint256) Here we make a call using the EIP-721 standard, it will return a Uint256 representing ERC721 supply or Web3Error::ContractCallError

Executes EIP-721 tokenURI(uint256 _tokenId) external view returns (string); Here we make a call using the EIP-721 standard, it will return a string representing ERC721 URI or Web3Error::ContractCallError

Executes EIP-721 ownerOf(uint256 _tokenId) external view returns (address) Here we make a call using the EIP-721 standard, it will return a string representing ERC721 owner or Web3Error::ContractCallError

Waits for a single event but instead of creating a filter and checking for changes this function waits for the provided wait time before checking if the event has occurred. This function will wait for at

Sets up an event filter, waits for a single event to happen, then removes the filter. Includes a local filter. If a captured event does not pass this filter, it is ignored. This differs from wait_for_event_alt in that it will check for filter changes every second and potentially exit earlier than the wait_for time provided by the user.

Checks for multiple events as defined by their signature strings over a block range. If no ending block is provided the latest will be used. This function will not wait for events to occur.

Checks for multiple events as defined by arbitrary user input over a block range. If no ending block is provided the latest will be used. This function will not wait for events to occur

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more