For example, I have a contract address for a pair of WETH/USDC: 0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640 how can i get the price of this pair using web3.py?
2 Answers
from web3 import Web3
Connect to a local or remote Ethereum node
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
The address of the WETH/USDC contract
contract_address = '0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640'
The ABI (Application Binary Interface) of the contract
contract_abi = [abi_json_string]
Instantiate the contract object
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
Call the 'price0CumulativeLast' function to get the price of WETH in wei
price_weth = contract.functions.price0CumulativeLast().call()
Convert the price from wei to ether
price_weth_ether = w3.fromWei(price_weth, 'ether')
Call the 'price1CumulativeLast' function to get the price of USDC in wei
price_usdc = contract.functions.price1CumulativeLast().call()
Convert the price from wei to ether
price_usdc_ether = w3.fromWei(price_usdc, 'ether')
Calculate the price of WETH/USDC
price_pair = price_weth_ether / price_usdc_ether
print('WETH/USDC price:', price_pair)
note that the ABI is not provided in this example, you need to get the ABI from the contract developer or by using a tool like remix to get the ABI.
Also, this is just an example, the actual price calculation will depend on the design of the smart contract.
You could just use an API from like binance or something to get the prices. If you were doing it onchain then Chainlink Price Feeds