web3调用solidity合约函数时如何添加ETH作为参数
How to add ETH as parameter when calling solidity contract function on web3
我已经创建了具有以下功能的智能合约:
function putOrder() external payable {
require(msg.value == itemPrice);
(bool sent, bytes memory data) = shopManager.call{value: msg.value}("");
require(sent, "Failed to purchase");
}
这只是检查 eth/bnb 值是否正确传递给函数,然后将其发送到管理器地址。
这是我在 web3 上使用 React 的函数的样子:
const putOrder() = async () => {
...
window.contract.methods.orderStuff().send({from: accounts[0]}).on(
'receipt', function(){
processOrder();
}
);
...
}
很明显,我收到一个错误,指出不满足 itemPrice。那么如何传递 eth/bnb 值以通过 web3 发送到合约函数调用?
您可以将其作为名为 value
的 属性 传递给 send()
函数参数。它的值是要发送的wei的数量(不是ETH的数量)。
它只是对 transaction 参数(执行合约功能的交易)的覆盖。因此,如果需要,您还可以使用它来覆盖 gas
值、nonce
和其他参数。
.send({
from: accounts[0],
value: 1 // 1 wei
})
.send({
from: accounts[0],
value: web3.utils.toWei(1, 'ether') // 1 ETH == 10^18 wei
})
我已经创建了具有以下功能的智能合约:
function putOrder() external payable {
require(msg.value == itemPrice);
(bool sent, bytes memory data) = shopManager.call{value: msg.value}("");
require(sent, "Failed to purchase");
}
这只是检查 eth/bnb 值是否正确传递给函数,然后将其发送到管理器地址。
这是我在 web3 上使用 React 的函数的样子:
const putOrder() = async () => {
...
window.contract.methods.orderStuff().send({from: accounts[0]}).on(
'receipt', function(){
processOrder();
}
);
...
}
很明显,我收到一个错误,指出不满足 itemPrice。那么如何传递 eth/bnb 值以通过 web3 发送到合约函数调用?
您可以将其作为名为 value
的 属性 传递给 send()
函数参数。它的值是要发送的wei的数量(不是ETH的数量)。
它只是对 transaction 参数(执行合约功能的交易)的覆盖。因此,如果需要,您还可以使用它来覆盖 gas
值、nonce
和其他参数。
.send({
from: accounts[0],
value: 1 // 1 wei
})
.send({
from: accounts[0],
value: web3.utils.toWei(1, 'ether') // 1 ETH == 10^18 wei
})