无法将令牌交换为令牌 Web3Py

问题描述 投票:0回答:1

我正在尝试使用带有 Polygon 的 SushiSwap 路由器将 WETH 换成 USDC。 这是我当前的代码:

import web3
from web3.middleware import geth_poa_middleware
import time

def swap(node, account_address, pvt_key, contract_address, contract_abi, action_type):
    #imagine we are trade on weth-usdc
    weth_addr = '0x7ceb23fd6bc0add59e62ac25578270cff1b9f619'
    usdc_addr = '0x2791bca1f2de4661ed88a30c99a7a9449aa84174'
    
    #connect to polygon node
    w3 = web3.Web3(web3.Web3.HTTPProvider(node))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    
    contract_addr = web3.Web3.toChecksumAddress(contract_address.lower())
    contract = w3.eth.contract(contract_addr, abi=contract_abi)

    gasPrice = w3.toWei(30, 'gwei')

    amount_in = 0.001
    amount_out_min = 0.00001
    path = [weth_addr, usdc_addr]
    deadline = int(time.time()+1000)
    
    build_txn = contract.functions.swapExactTokensForTokens(amount_in, amount_out_min, [weth_addr, usdc_addr], account_address, deadline).buildTransaction({'chainId': 137,'gas': int(300000),'gasPrice': gasPrice,'nonce': w3.eth.get_transaction_count(account_address),"value": 0,})

#we are acting on polygon blockchain
node = 'https://polygon-rpc.com'

account_from = {
    'private_key': 'XXX',
    'address': 'XXX'
    }

contract_address = '0x1b02da8cb0d097eb8d57a175b88c7d8b47997506'
contract_abi = ''''''

#actions available are two: buy or swap. buy=1, sell=0.
action = 0

#call function
swap(node, account_from['address'], account_from['private_key'], contract_address, contract_abi, action)

我认为一切都很好,但是在尝试构建 tnx 时我得到了这个错误:

Found 1 function(s) with the name `swapExactTokensForTokens`: ['swapExactTokensForTokens(uint256,uint256,address[],address,uint256)']
Function invocation failed due to no matching argument types.

有人知道为什么吗?谢谢

polygon smartcontracts web3py uniswap
1个回答
1
投票

函数

swapExactTokensForTokens
(和类似函数)期望所有参数都以整数形式传递。原因之一是 Solidity 没有浮点数。此外,金额应从人类可读格式转换为内部表示形式(ETH 为 wei,其他代币为十进制单位)。

一种方法是在

swapExactTokensForTokens
调用之前添加这些行:

amount_in = int(amount_in * (10**token_in_decimals))
amount_out_min = int(amount_out_min * (10**token_out_decimals)) 

在示例中,

token_in_decimals
应设置为 18(对于 WETH),
token_out_decimals
应设置为 6(对于 USDC)。

© www.soinside.com 2019 - 2024. All rights reserved.