Search code examples
solidityethers.jsdecentralized-applications

Ethers.js, send money to a smart contract (receive function)


I have a smart contract with a receive function :

receive() external payable {
    Wallets[msg.sender] += msg.value;
}

I have a front end and I want to send Ethers to this smart contract using the receive() function.

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, there is no "send" function, what is the function I need to use there ? Thx a lot !


Solution

  • When you want to invoke the receive() function, you need to send a transaction to the contract address with empty data field. The same way as if you were sending ETH to a non-contract address.

    // not defining `data` field will use the default value - empty data
    const transaction = signer.sendTransaction({
        from: accounts[0],
        to: WalletAddress,
        value: amount
    });