使用Web3Py在Polygon通过SushiSwap Router代币兑换报错求助
问题原因与解决方案
错误核心原因
调用swapExactTokensForTokens时触发的参数类型不匹配,根源是:
- Solidity合约要求该函数的前两个参数是**
uint256类型的整数**(对应代币的最小单位数量,比如WETH的wei),但你直接传入了人类可读的浮点数金额(0.001、0.00001)。 - 不同代币的小数位不同,WETH是18位,USDC是6位,必须将金额转换为对应小数位的整数才能被合约识别。
具体修正步骤
转换金额为代币最小单位整数
把浮点数金额按代币小数位转为整数:- WETH(18位小数):
amount_in = int(0.001 * 10**18) - USDC(6位小数):
amount_out_min = int(0.00001 * 10**6)
- WETH(18位小数):
统一地址为Checksum格式
合约要求地址是Checksum格式,需对path里的代币地址做转换:weth_addr = web3.Web3.toChecksumAddress('0x7ceb23fd6bc0add59e62ac25578270cff1b9f619') usdc_addr = web3.Web3.toChecksumAddress('0x2791bca1f2de4661ed88a30c99a7a9449aa84174')(可选)优化Gas参数
硬编码gas价格可能不适应网络波动,建议动态获取当前gas价格:gasPrice = w3.eth.gas_price
修改后的核心代码片段
def swap(node, account_address, pvt_key, contract_address, contract_abi, action_type): weth_addr = web3.Web3.toChecksumAddress('0x7ceb23fd6bc0add59e62ac25578270cff1b9f619') usdc_addr = web3.Web3.toChecksumAddress('0x2791bca1f2de4661ed88a30c99a7a9449aa84174') 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) # 动态获取gas价格 gasPrice = w3.eth.gas_price # 转换为代币最小单位的整数 amount_in = int(0.001 * 10**18) # WETH 18位小数 amount_out_min = int(0.00001 * 10**6) # USDC 6位小数 path = [weth_addr, usdc_addr] deadline = int(time.time() + 1000) build_txn = contract.functions.swapExactTokensForTokens( amount_in, amount_out_min, path, account_address, deadline ).buildTransaction({ 'chainId': 137, 'gas': int(300000), 'gasPrice': gasPrice, 'nonce': w3.eth.get_transaction_count(account_address), "value": 0, }) # 补充签名和发送交易的代码(原代码缺失这部分) signed_txn = w3.eth.account.sign_transaction(build_txn, private_key=pvt_key) tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction) print(f"交易哈希: {w3.toHex(tx_hash)}")
注意:原代码仅构建了交易,未包含签名和发送逻辑,补充上述代码才能完成完整的兑换流程。
内容的提问来源于stack exchange,提问作者giacomomaraglino
相关产品推荐
相关产品推荐

