Solidity – Comprehensive Guide on .call{}() in Solidity

payableremixsolidity

This is a Smart Contract written in solidity, compiled and deployed in remix

// SPDX-License-Identifier: MIT OR Apache 2.0

pragma solidity ^0.8.8;

contract Payable{

    // payable address can send and receive ethers
    address payable public owner;

    // payable constructor can receive ethers
    constructor() payable{
        owner = payable(msg.sender);
    }

    // this function can receive ethers
    function deposit() public payable{}

    // this cannot accept ethers
    function nonPayable() public{}

    function withdraw() public {
        uint amount = address(this).balance;

        (bool success,) = owner.call{value:amount}("Amount Withdrawn from smart contract");

        require(success,"Failed to receive ether");
    }

    function transfer(address payable _to, uint _amount) public{
        (bool success,) = _to.call{value:_amount}("ether trransferred");
        require(success,"Failed to send ether to address");
    }
}

It is recommended to use .call{}() instead of .transfer() or .send()

I think .call{}() returns a tuple, containing status of transaction and a string memory which stores the string(Amount Withdrawn from smart contract).

If the transaction is successful this string is treated as a data parameter sent as a part of the low-level message call.

What is this low-level message call?

Where could I see this message getting passed in the console?

Is there any other use of this string?

Also I'm bit confused it is string or some function.

Best Answer

call allows to send ether with a selected amount of gas to an Externally Owned Account or to another contract which implements the receive() or fallback() functions.

Additionally, a function in the target contract can be called with the parameter call function has. In this example, we will be calling the myFunction function, with arguments 7 and true:

(bool success, ) = to.call{value: 1 ether, gas: 100000}(abi.encodeWithSignature("myFunction(uint,bool)", 7, true));

If the called function does not match with any function in the target contract, fallback() function will be called. If fallback() does not exist, the success variable returned will be false.

Related Topic