使用eth.rb调用合约mint函数遇transaction underpriced错误求助
解决「transaction underpriced」错误(Ruby eth gem + Polygon网络)
问题分析
出现该错误的核心原因通常有两点:
- 浮点数格式的gas price会导致客户端/合约处理时出现精度问题,实际发送的费用低于网络要求
- Polygon已全面支持EIP-1559交易机制,传统
gas_price参数的兼容性远不如max_fee_per_gas+max_priority_fee_per_gas的组合
具体修复步骤
1. 替换浮点数gas price为整数运算
你的代码中170 * 1e9生成的是浮点数(170000000000.0),以太坊系网络要求gas费用必须是整数,浮点数可能被截断或转换,导致实际gas价格不符合预期。
修改为整数计算:
# 用整数运算避免浮点数精度问题,170 Gwei = 170 * 10^9 Wei gas_price = 170 * 10**9
2. 适配Polygon的EIP-1559交易机制
Polygon现在优先处理EIP-1559类型交易,建议改用max_priority_fee_per_gas(矿工优先费用)和max_fee_per_gas(最大总费用)替代传统gas_price:
# 示例值,可根据当前Polygon网络拥堵情况调整 max_priority_fee = 30 * 10**9 # 30 Gwei max_fee_per_gas = 170 * 10**9 # 170 Gwei # 给合约配置EIP-1559参数 wow_contract.max_priority_fee_per_gas = max_priority_fee wow_contract.max_fee_per_gas = max_fee_per_gas
3. 确保transact_and_wait参数生效
显式在transact_and_wait中传递gas参数,避免合约设置被方法默认值覆盖:
tx_hash = client.transact_and_wait( wow_contract, "mint", mint_address, mint_amount_in_smallest_unit, sender_key: signer, max_priority_fee_per_gas: max_priority_fee, max_fee_per_gas: max_fee_per_gas, gas_limit: 200000 )
完整修复后的代码
def self.mint(mint_address, mint_amount) signer = Eth::Key.new(priv: @@private_key) client = Eth::Client.create "https://polygon-mainnet.g.alchemy.com/v2/API" contract_name = "WOW" wow_contract = Eth::Contract.from_abi(abi: @@abiWOW.to_json, address: @@master_contract_address, name: contract_name) wow_contract.key = signer # 用整数运算设置EIP-1559参数 max_priority_fee = 30 * 10**9 # 30 Gwei max_fee_per_gas = 170 * 10**9 # 170 Gwei gas_limit = 200000 # 配置合约参数 wow_contract.max_priority_fee_per_gas = max_priority_fee wow_contract.max_fee_per_gas = max_fee_per_gas wow_contract.gas_limit = gas_limit puts "max_fee_per_gas: #{wow_contract.max_fee_per_gas}" puts "max_priority_fee_per_gas: #{wow_contract.max_priority_fee_per_gas}" mint_amount_in_smallest_unit = (mint_amount.to_f * (10**18)).to_i tx_hash = client.transact_and_wait( wow_contract, "mint", mint_address, mint_amount_in_smallest_unit, sender_key: signer, max_priority_fee_per_gas: max_priority_fee, max_fee_per_gas: max_fee_per_gas, gas_limit: gas_limit ) if client.tx_mined?(tx_hash) puts "Transaction was successful!" else puts "Transaction failed!" end end
额外建议
- 可根据Polygon实时gas行情调整
max_priority_fee和max_fee_per_gas的值,确保费用符合网络要求 - 确认账户余额足够支付总费用(
gas_limit * max_fee_per_gas+ mint金额)
内容的提问来源于stack exchange,提问作者javanoob2pro
相关产品推荐
相关产品推荐

