Ethers.js,向智能合约汇款(接收功能)
Ethers.js, send money to a smart contract (receive function)
我有一个带有接收函数的智能合约:
receive() external payable {
Wallets[msg.sender] += msg.value;
}
我有一个前端,我想使用 receive() 函数将以太币发送到这个智能合约。
async function transfer() {
if(typeof window.ethereum !== 'undefined') {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(WalletAddress, Wallet.abi, signer);
const transaction = await contract.send({
from: accounts[0],
value: amount
})
await transaction.wait();
alert('ok');
setAmount('');
getBalance();
}
}
Saldy,没有“发送”功能,我需要在那里使用什么功能?
非常感谢!
当您想要调用receive()
功能时,您需要向data
字段为空的合约地址发送交易。就像您将 ETH 发送到非合约地址一样。
// not defining `data` field will use the default value - empty data
const transaction = signer.sendTransaction({
from: accounts[0],
to: WalletAddress,
value: amount
});
我有一个带有接收函数的智能合约:
receive() external payable {
Wallets[msg.sender] += msg.value;
}
我有一个前端,我想使用 receive() 函数将以太币发送到这个智能合约。
async function transfer() {
if(typeof window.ethereum !== 'undefined') {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(WalletAddress, Wallet.abi, signer);
const transaction = await contract.send({
from: accounts[0],
value: amount
})
await transaction.wait();
alert('ok');
setAmount('');
getBalance();
}
}
Saldy,没有“发送”功能,我需要在那里使用什么功能? 非常感谢!
当您想要调用receive()
功能时,您需要向data
字段为空的合约地址发送交易。就像您将 ETH 发送到非合约地址一样。
// not defining `data` field will use the default value - empty data
const transaction = signer.sendTransaction({
from: accounts[0],
to: WalletAddress,
value: amount
});