python collects on-chain data based on Web3.py and Infura gateway

  • Web3.py is a Python library for interacting with Ethereum. Functionality includes connecting to Ethereum network nodes, retrieving data, and broadcasting data to the Ethereum network.
pip install web3

At present, the data volume of Ethereum full nodes reaches several terabytes, and it is not practical to build a local full node by yourself. Therefore, data query is generally implemented through a gateway such as Infura. Create a new project in Infura to obtain the API KEY

from web3 import Web3
chainApi = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/6efdb....(替换为你的API KEY)'))
# 获取最新区块数据
block = chainApi.eth.getBlock("latest")
print(block)
# 获取某地址的余额
balance = chainApi.eth.getBalance("0x7A6381...(替换为你要查询的地址)")
print(balance)

Interacting with ERC-20 contracts

Requirement: Identify the USD price of token assets held by the current user address, and calculate the total net asset value


Implementation ideas: 1. First scan the wallet address to see which tokens are held (needs to interact with each ERC20 contract). 2. Calculate the USD value of the token to calculate the total net worth.

first step

All contracts that comply with ERC-20 specifications have the following functions:

function name() public view returns (string)
function symbol() public view returns (string)
function decimals() public view returns (uint8)
function totalSupply() public view returns (uint256)
function balanceOf(address _owner) public view returns (uint256 balance)
function transfer(address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
function allowance(address _owner, address _spender) public view returns (uint256 remaining)
  • ​​balanceOf​ ​is a function used to query how many tokens a wallet address holds.

Interacting with the contract requires passing the ABI: application binary interface. ABI is used to define how data should be encoded/decoded in EVM.

Here we take the Synthetix (SNX) contract as an example. The sample code is as follows:

import json
ABI = json.loads('[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]')

wallet_address = '0x7A638...(换成你的地址)'
wallet_address = Web3.toChecksumAddress(wallet_address)

token_contract_address = '0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f' # SNX合约地址
token_contract_address = Web3.toChecksumAddress(token_contract_address)

# define contract
contract = chainApi.eth.contract(token_contract_address, abi=ABI)

# call contract and get data from balanceOf for argument wallet_address
raw_balance = contract.functions.balanceOf(wallet_address).call()

# convert the value from Wei to Ether
synthetix_value = Web3.fromWei(raw_balance, 'ether')

print(synthetix_value)
  • ​​toChecksumAddress()​​to ensure that our address is in checksum format
  • fromWei() converts our Wei price to ether 1ETH is 1 0 18 10^{18}1018 Wei

Iterating through all token assets can be done by building a master list of ERC-20 contract addresses and iterating to find the tokens held by a specific wallet.

Step 2
: Use The Graph to obtain market data (USD price)

from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

sample_transport = RequestsHTTPTransport(
   url='https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
   verify=True,
   retries=5,
)
client = Client(transport=sample_transport)

# Get the value of SNX/ETH
query = gql('''
    query {
        pair(id: "0x43ae24960e5534731fc831386c07755a2dc33d47"){
            reserve0
            reserve1
        }
    }
''')
response = client.execute(query)
snx_eth_pair = response['pair']
eth_value = float(snx_eth_pair['reserve1']) / float(snx_eth_pair['reserve0'])

# Get the value of ETH/DAI
query = gql('''
query {
    pair(id: "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11"){
        reserve0
        reserve1
    }
}
''')
response = client.execute(query)
eth_dai_pair = response['pair']
dai_value = float(eth_dai_pair['reserve0']) / float(eth_dai_pair['reserve1'])

snx_dai_value = eth_value * dai_value
print(snx_dai_value)

The exchange rate between SNX and the stable currency anchored to the US dollar is calculated using DEX data. Here, two calculations are made with ETH as the intermediate currency (DAI stable currency is anchored to the US dollar).
Query The Graph to get the DAI value of SNX. We first get the ETH value of each SNX, and then multiply it by the amount of DAI equivalent to one ETH to get the DAI value of one SNX. Multiply the final DAI value by the amount of SNX held in our wallet to find the total USD value of the position.

Reference

[1] Query Ethereum data using Web3.py, Infura and Graph

Guess you like

Origin blog.csdn.net/qq_33583069/article/details/126146725