In the previous lecture, we read data from our Smart Contract. In this lecture, we are going to write data in our Smart Contract. To perform this operation, we will be using the second API, called eth_sendTransaction.
Reminder: if we send transactions to a Smart Contract, we actually change the blockchain. If changes occur, it must be mined, thus it will cost some gas fees.
Let's reuse our previous index.js initial code:
In this case, we will be using the other method called 'methods.myMethod.send'. Unlike the call method, we cannot leave parameters blank here. Since the execution will cost some gas, we have to define what address we will pay with.
- From: the address from which we will send the transaction. In this case, we will use one among the 10 automatically generated addresses from Ganache. In production, we would have use Metamask for instance. This part will be covered in next parts of this tutorial.
It’s important to use an async function. Since we are using a local development environment, the mining will be executed immediately. But, on the Mainnet or any other Public Test environment, a transaction mining could take up to 15sec. Thus, it’s important to wait for the results.
Here is the code. Comments are following.
- First, we collect the generated accounts by Ganache, and store it in the array accounts. In this case, we will be using the first account, thus accounts.
- Next, we use our previous method, to check the value of data, with the get function. We will see that its value is 0 (cf. previous part).
- Then, we use the 'send' method, and we set the value to 100.
- Finally, we reuse the 'call' method to check if the data was properly updated to 100.
Here is our results:
First, we see 0. Which is what we expected.
Then, we get the receipt of the transaction, which corresponds to the Transaction Hash:
- transactionHash: hexadecimal string that uniquely identifies the transaction on the blockchain. In prod, you could use that transactionHash in Etherscan to see your transaction details.
- blockHash: the hash of the block in which the transaction was mined,
- From: the address that sends the transaction. As you can see, we recognize our previously stated address there.
- To: is the recipient address of the transaction, which is our Smart Contract address,
- gasUsed: how much gas were used to mine the transaction
Finally, we get the updated value of 100.
As you can see in Ganache, our first account has less than 100 ETH now, since it paid the transaction.
🎉 🥳 👯♂️ 🎈 Congratulations! We successfully send our first transaction using the set() method from our Smart Contract. In the next lecture, we will send Ether to the Smart Contract !