在 Solidity 中测试应付函数

Testing a Payable Function in Solidity

所以我尝试使用 truffle 框架在以下智能合约上测试支付功能:

contract FundMe {
    using SafeMathChainlink for uint256;

    mapping(address => uint256) public addressToAmountFunded;
    address[] public funders;
    address public owner;
    AggregatorV3Interface public priceFeed;

    constructor(address _priceFeed) public {
        priceFeed = AggregatorV3Interface(_priceFeed);
        owner = msg.sender;
    }

    function fund() public payable {
        uint256 mimimumUSD = 50 * 10**18;
        require(
            getConversionRate(msg.value) >= mimimumUSD,
            "You need to spend more ETH!"
        );
        addressToAmountFunded[msg.sender] += msg.value;
        funders.push(msg.sender);
    }

我特别想测试 payable 函数,我在互联网上看到了一些事情,人们创建其他具有初始余额的合约,然后向他们的测试合约发送一些 eth。但是我只想拿一个本地的 ganache 钱包并向合约发送一些 eth 然后进行测试,如果有人可以向我展示一些测试 javascript 代码来解决这个问题,我将不胜感激!

对于能够接收 ETH(或任何原生代币 - Binance Smart Chain 上的 BNB,Tron 网络上的 TRX,......)的合约 无需调用任何功能,您需要至少定义其中一个函数 receive() (docs) or fallback() (docs).

contract FundMe {

    // intentionally missing the `function` keyword
    receive() external payable {
        // can be empty
    }

    // ... rest of your code
}

然后你可以发送一个普通的交易到truffle中的合约地址(docs):

const instance = await MyContract.at(contractAddress);
await instance.send(web3.toWei(1, "ether"));

请注意,因为 receive()fallback() 不是常规函数,您 不能 使用 truffle 自动生成的方法调用它们:myContract.functionName()


如果你想执行支付功能发送ETH,你可以使用transaction paramsdocs)。它始终是最后一个参数,在所有常规函数参数之后。

const instance = await MyContract.at(contractAddress);
await instance.fund({
    value: web3.toWei(1, "ether")
});

注意:如果 fund() 函数有 1 个参数(比如 bool),transaction params 将是第二个:

await instance.fund(true, {
    value: web3.toWei(1, "ether")
});