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

运行brownie test报错:如何在Python中正确比较合约返回值与浮点数?

解决Brownie测试中TransactionReceipt与浮点数比较的TypeError错误

问题重现

运行brownie test时触发TypeError,提示**'<' 不支持在TransactionReceipt实例与浮点数之间进行比较**。部署脚本运行正常,但测试脚本调用Solidity合约的getConversionRate函数后,直接将返回结果与浮点数比较导致报错。

错误根源

在Brownie中,直接调用合约函数(如donation.getConversionRate(...))默认会发送一笔交易,并返回TransactionReceipt对象,而非合约函数的实际返回值。测试代码中误将交易收据当成数值与浮点数比较,触发类型错误。

解决方案

1. 获取合约函数返回值而非交易收据

调用合约函数时,使用.call()方法直接读取返回值,该方法不会发送交易,仅模拟调用获取结果。

2. 单位转换适配

合约返回的是带18位小数的wei单位数值,需转换为以太币单位后再与浮点数比较。

修改后的测试代码

from scripts.helpful_scripts import get_account
from scripts.deploy import deploy_donation
from web3 import Web3


def test_can_get_conversion_rate():
    account = get_account()
    donation = deploy_donation()

    # 使用call()获取函数返回的wei数值,而非交易收据
    eth_amount_wei = donation.getConversionRate.call(100, {"from": account})
    # 将wei转换为以太币单位
    eth_amount = Web3.fromWei(eth_amount_wei, "ether")
    
    assert eth_amount < 0.075
    assert eth_amount > 0.06
    print(f"The ethAmount is {eth_amount}")


def main():
    test_can_get_conversion_rate()

额外优化:修复合约精度问题

原合约getConversionRate函数的整数除法会导致精度丢失,建议调整计算顺序(先乘后除):

function getConversionRate(uint256 rawUSD) public returns (uint256) {
    // 先乘10**18再除以价格,避免整数除法截断小数
    uint256 ethUSD = (rawUSD * 10**18) / getPrice();
    return ethUSD;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:15:33