You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发环境中交易回退时Brownie报错而非抛异常的问题排查

解决Brownie测试中int() can't convert non-string with explicit base错误

问题场景

编写Brownie测试验证合约仅所有者可提款功能时,代码如下:

def test_only_owner_can_withdraw():    
    fund_me = deploy()
    bad_actor = accounts.add()
    with pytest.raises(exceptions.VirtualMachineError):
        fund_me.withdraw({"from": bad_actor})

预期交易回退时抛出VirtualMachineError使测试通过,但实际运行触发以下错误:

>       fund_me.withdraw({"from": bad_actor})
E       TypeError: int() can't convert non-string with explicit base

追踪发现错误来自Brownie的transaction.py文件中step["pc"] = int(step["pc"], 16)行,此时step数据为:

{'depth': 1, 'error': '', 'gas': 11978936, 'gasCost': 3, 'memory': [], 'op': 'PUSH1', 'pc': 0, 'stack': [], 'storage': None}

问题根源是trace[0]["gas"]为十六进制字符串,导致fix_gas被设为True,代码强制对pc做十六进制转换,但pc实际是整数,因此触发类型错误。

解决方案

1. 临时修改Brownie源码修复转换逻辑

找到Brownie安装目录下的transaction.py文件,定位到处理pc转换的代码段,添加类型判断:

# 原代码
step["pc"] = int(step["pc"], 16)

# 修改为:
if isinstance(step["pc"], str):
    step["pc"] = int(step["pc"], 16)

该修改仅在pc为字符串时执行十六进制转换,避免整数转换报错。

2. 调整Brownie与以太坊客户端版本兼容性

这个错误通常是Brownie与本地以太坊客户端(如Ganache)版本不兼容导致的:

  • 升级Brownie到最新稳定版:
    pip install --upgrade eth-brownie
    
  • 若升级后问题仍存在,尝试降级到已知兼容版本(例如1.19.3):
    pip install eth-brownie==1.19.3
    

3. 修正以太坊客户端输出格式

如果使用Ganache,检查其配置是否输出符合Brownie预期的trace数据:

  • 确保Ganache未将gas等数值以十六进制字符串返回,调整客户端的输出格式设置,使其输出整数类型的gas值。

4. 测试代码中添加参数绕过trace解析

在提款交易中指定gas_price参数,可能跳过触发错误的trace处理流程:

def test_only_owner_can_withdraw():    
    fund_me = deploy()
    bad_actor = accounts.add()
    with pytest.raises(exceptions.VirtualMachineError):
        fund_me.withdraw({"from": bad_actor, "gas_price": 10**9})

内容的提问来源于stack exchange,提问作者gcodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:15:31