🧰 Web3 [Serie Part 6/10] - Send Ether to a Smart Contract
Sometimes it's necessary to load the Smart Contract with Ethers. Thus, we need to be able to send some token to our Smart Contract.
Since we are modifying the Blockchain, it will have to be mined, and by consequence it will cost some gas fees.
Actually, there are two ways to send Ether to a Smart Contract.
Method #1: Execute a Function
We will be using a different Smart Contract code for this new part. Thus, let's create a new file 'MyContract2.sol' in our contracts directory, and copy the code below. Comments are following.
We define a new contract MyContract2 including 2 functions.
We declare a public variable called message as a string type.
Function sendEther() is simulating a payment, while the second function is a fallback function. It will be detailed in section.
Don't forget to adapt the migration file (2_contract_deploy.js) accordingly.
We simply added the MyContract2 to be deployed. If you want things cleaner, you can drop the MyContract since we won't use it anymore. It's up to you.
Now, we can migrate our new MyContract2.sol by running the following command in our terminal:
truffle migrate --reset
Among the results, you should see our MyContract2 deployment feedback:
Now, let's change this index2.js script to send 1 ETH to our Smart Contract MyContract2.sol.
Here we call our sendEther() methods, using 'send API'. The send method requires several parameters. We will be using the 2 following parameters (more details here in the doc):
From: The address the transaction should be sent from.
Value: The value transferred for the transaction in wei.
Note: 1 WEI = 10^(-18) ETH.
🚨 WARNING, there is a caveat here 🚨
As you can see, the value we are transferring is written as a String type with quite a lot of 0.
If you have to perform math operations on this number, I recommend using the bn.js library. Here we keep it simple, and use the String version.
This being said, let's run our index2.js . We will see the following results:
Hurra ! It works. We get the receipt of our transaction, as well as the message ‘Ether sent!’. Thus, we successfully sent 1 ETH to our Smart Contract (MyContract2).
Method #2: Send Ether Directly
The second method consists in sending Ether to our Smart Contract, without calling any function.
In our Smart Contract, if you remember, we added what we call a ‘fallback’ method. This method will be fired by default, if a wrong function name is called in our JS file, or if no function name is used. It serves as a fallback…
Here is the updated index2.js. Comments are following.
Instead of calling a method from the Smart Contract, we call directly the sendTransaction method.
Thus we are not referencing a specific method from our Smart Contract. As parameters we are using: