Replies: 1 comment
Web3.py Uniswap 見積もりコードfrom web3 import Web3
# Ethereumノードへの接続設定(InfuraプロジェクトIDを入力)
provider_url = "https://mainnet.zkevm.cronos.org/"
w3 = Web3(Web3.HTTPProvider(provider_url))
# コネクション確認
if not w3.is_connected():
raise ConnectionError("Ethereumノードへの接続に失敗しました")
# トークンとルーターのアドレス設定
WETH_ADDRESS = Web3.to_checksum_address("0xBCaA34FF9D5BFD0d948b18Cf6Bf39a882F4a1cBD")
USDC_ADDRESS = Web3.to_checksum_address("0xC1bF55EE54E16229d9b369a5502Bfe5fC9F20b6d")
UNISWAP_V2_ROUTER = Web3.to_checksum_address(
"0x39aD8C3067281e60045DF041846EE01c1Dd3a853"
)
# Uniswap V2ルーターABI(getAmountsOut用)
router_abi = [
{
"inputs": [
{"internalType": "uint256", "name": "amountIn", "type": "uint256"},
{"internalType": "address[]", "name": "path", "type": "address[]"},
],
"name": "getAmountsOut",
"outputs": [
{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}
],
"stateMutability": "view",
"type": "function",
}
]
# コントラクトインスタンス作成
router_contract = w3.eth.contract(address=UNISWAP_V2_ROUTER, abi=router_abi)
# スワップパス設定(ETH→WETH→USDC)
swap_path = [WETH_ADDRESS, USDC_ADDRESS]
# スワップするETHの量(1 ETH = 10^18 wei)
amount_eth = 10 * 10**8
try:
# スワップ結果を取得
amounts_out = router_contract.functions.getAmountsOut(amount_eth, swap_path).call()
if len(amounts_out) >= 2:
usdc_amount = amounts_out[-1] / 10**18 # USDCの小数桁数(6桁)で割る
print(f"1 ETH = {usdc_amount:,} USDC")
print(amounts_out[0] / 10**8)
else:
print("想定外のデータ形式です。パスを確認してください")
except Exception as e:
print(f"エラーが発生しました: {e}") |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Today I Learned ...
All reactions