Truffle
如何在松露測試中將乙太幣發送到合約?
出於某種原因,我無法弄清楚在 truffle 中進行測試時如何將乙太幣發送到合約中。這是我的嘗試:
await myContract.send(10, {from: accounts[0]});
錯誤資訊是:
Error: VM Exception while processing transaction: revert
如果我嘗試,我會收到相同的錯誤消息:
let txHash = await web3.eth.sendTransaction({from: accounts[0], to: myContract.address, value: 10 });
知道如何讓它工作嗎?
謝謝!
備份功能
要創建可以通過該
.send()
方法接收 eth 的合約,您需要在合約中聲明一個備用函式。只需在契約中創建一個沒有名稱的應付函式,就可以很容易地做到這一點,如下所示:
// @notice Will receive any eth sent to the contract function () external payable { }
如果您想對應付函式中的資金做任何事情,您可以使用
msg.sender
和msg.value
變數來計算發送了誰以及發送了多少。完整範例:
pragma solidity ^0.4.19; /// @title An example contract that demonstrates making a payment via the send function contract Test { /// @notice Logs the address of the sender and amounts paid to the contract event Paid(address indexed _from, uint _value); /// @notice Any funds sent to this function will be unrecoverable /// @dev This function receives funds, there is currently no way to send funds back function () external payable { Paid(msg.sender, msg.value); } }
輸出:
當上述合約被編譯、創建和發送資金時,你會得到以下輸出:
truffle(develop)> Test.new().then(c => c.send(10, {from: '0x627306090abab3a6e1400e9345bc60c78a8bef57'}).then(tx => {console.log(tx.tx); tx.logs.length && console.log(tx.logs[0].event, tx.logs[0].args)})) 0x911ceb59724001b3cb99a035281745b4af5b02a10a1c79906b4c527f8c462db8 Paid { _from: '0x627306090abab3a6e1400e9345bc60c78a8bef57', _value: BigNumber { s: 1, e: 1, c: [ 10 ] } }