Skip to content

How to Send ETH to a Solidity Payable Function Using Ether.js?

How to Send ETH to a Solidity Payable Function Using Ether.js

What is the Solidity payable function?

A Solidity payable function is a type of function that allows you to receive ether (ETH – Ethereum token) as an input parameter. When a contract calls the payable function, this feature allows the caller to input ether. After the transaction is complete, the ether becomes a part of the contract’s balance. Exciting, right?

So, how do you send ether to your Solidity payable function? We can use the ether.js to perform this task with ease. Here’s the coding example for you.

🔥 Check this out: Build in Public

Send ETH to Solidity payable function coding example

This code snippet demonstrates how to send ether to a payable function in a smart contract using ethers.js. It covers the initialization of a provider, creating a contract instance, specifying the amount of ether to send, and executing a transaction.

//Initial Setup

const amountToSend = ethers.utils.parseUnits("0.1", 18); // 0.1 ETH in wei
const options = { value: amountToSend };

const transaction = await contractInstance.myPayableFunction(options);
await transaction.wait();

console.log("Transaction complete:", transaction.hash);

Explanation

  1. The amount of ether to send (0.1 ETH) is converted to Wei (Wei is a smaller unit of ETH, which is equivalent to 10^-18 ETH.) using ethers.utils.parseUnits.
  2. We create an options object specifying the ether value to send.
  3. The payable function (myPayableFunction) is called with the specified options, initiating the transaction.
  4. We wait for the transaction to be processed and confirmed on the blockchain using the await keyword.
  5. We log the transaction hash once the transaction is complete.

🔥 Check this course out: Write an Elon Musk NFT Smart Contract on OpenSea

Conclusion

This code provides a practical example of interacting with a payable function in a smart contract, demonstrating the essential steps using ethers.js.

Try it out, ask us questions, and let us know how it went by tagging Metaschool on Social Media.

Follow us on –

🔮Twitter – https://twitter.com/0xmetaschool

🔗LinkedIn – https://www.linkedin.com/company/0xmetaschool/