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

如何在Foundry测试中向Solidity payable函数发送msg.value?

问题内容

合约代码(OrderManager.sol)

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {CarNFT} from "./CarNFT.sol";
// OrderManager contract

contract OrderManager {
    ... code

    function deposit() external payable onlyBuyer {
        // Buyer deposits funds
        require(msg.value == price, "Incorrect deposit amount");
    }

}

测试代码(OrderManager.t.sol)

function testDeposit() public {
        // Assuming startPrank, deal, and stopPrank functions work as expected
        vm.startPrank(buyer);
        vm.deal(buyer, 10 ether);

        // Ensure the buyer has the expected balance
        uint256 buyerBalanceBefore = address(buyer).balance;
        assertEq(buyerBalanceBefore, 10 ether);

        // Deposit into OrderManager contract
        orderM.deposit();

        // Ensure the balance of the OrderManager contract is updated
        uint256 contractBalance = orderM.getBalance();
        emit log_named_uint("Contract's balance is", contractBalance);
        assertEq(price, contractBalance);

        // Ensure the buyer's balance has been reduced by the deposited amount
        uint256 buyerBalanceAfter = address(buyer).balance;
        emit log_named_uint("Buyer's balance after deposit is", buyerBalanceAfter);
        assertEq(buyerBalanceBefore - price, buyerBalanceAfter);

        vm.stopPrank();
    }

疑问

我想在调用deposit()时通过msg.value发送ETH,应该使用什么语法?我使用Foundry作为开发工具,是否需要使用Foundry cheatcodes来实现此需求?


解决方案
  • 不需要额外的Foundry cheatcode,直接用Solidity的内置函数调用语法就能指定msg.value,这是调用payable函数发送ETH的标准方式。
  • 修改测试代码中调用deposit的语句,添加{value: price}参数,让ETH随调用一起发送:
    // 替换原来的orderM.deposit();
    orderM.deposit{value: price}();
    
  • 你当前使用的vm.deal(buyer, 10 ether)是正确的,它负责给测试账户充值ETH,确保账户有足够余额完成交易,这个步骤无需改动。
  • 修改后,deposit函数中的require(msg.value == price)会被满足,原有的余额校验断言也会正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 07:02:23