How to use call.value

Recently someone asked me about the difference between transfer() and call.value. Why people were talking about it now? Well, it happened because of Istanbul hard fork in 2019. Gas cost of the SLOAD operation increased, causing a contract’s fallback function to cost more than 2300 gas. So everybody should stop using .transfer() and .send() and instead use .call(). More information you can have at this very good repo, Secure Development Recommendations, maintained by ConsenSys Diligence: https://consensys.github.io/smart-contract-best-practices/recommendations/#dont-use-transfer-or-send.

Solidity

You can easily find a bunch of examples of how to use this new standard, ig, here and here.

But let's talk about one specific topic: the payload. All examples have just a simple ether transfer, msg.sender.call{value: amount}("") . What is calling some attention is the 2nd parameter, the empty string "". I am going to explain how to use it.

First, let's check how a very simple withdraw() function works:

But what happens if you would like to send ether to another smart contract? It is almost the same. In my simple example, Bank is a smart contract that has a payable fallback function.

So far so good. Now you would like to send ether to a function called deposit() from Bank smart contract. How to do it? It is also pretty simple. But because of the lack of information, I decided to explain it with more details.

  • functionHash is going to be equal to 0xd0e30db03f2e24c6531d8ae2f6c09d8e7a6ad7f7e87a81cb75dfda61c9d83286 . The part that is in bold is just to highlight the next step.
  • We just need the first 4 bytes from the function hash, so function4bytes is equal to 0xd0e30db0.
  • payload is the result that we want to be used inside call.value. And it is equal to 0xd0e30db000000000000000000000000000000000000000000000000000000000

I hope that writing in 3 steps you can better understand what is needed to be able to send ether to another smart contract.

Here is a working example so you can try and test using Remix. You can use the github version or the code pasted here. Have fun.

--

--

I enjoy life. I read. I eat. I sleep. I dream. I work. I wake up in the morning.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luiz Soares

I enjoy life. I read. I eat. I sleep. I dream. I work. I wake up in the morning.