Search code examples
ethereumblockchainsoliditysmartcontracts

Can someone explain the syntax of this line of Solidity code?


There's so much I don't understand about this line of code, is anyone able to break it down for me?

(bool success, ) = msg.sender.call{value: balance}("");

What I don't grasp:

  • The commas around the bool declaration
  • The comma after success
  • Curly braces before the parentheses after msg.sender.call
  • The reasoning behind passing an empty string (is it being passed to msg.send.call?)

I find documentation for Solidity very hard to grasp, are there any resources concerning just the syntax of the language?


Solution

    • The commas around the bool declaration
    • The comma after success

    msg.sender.call returns two values

    (bool success, bytes memory data) = msg.sender.call{value: balance}("");
    

    if you do not need the data, you dont specify the name. that is why

    (bool success, )
    
    • Curly braces before the parentheses after msg.sender.call

    it is syntax to specify the amount of ether to send. before it was like this

    contract.call.value(...)(...)
    

    you could also pass gas parameter here

    {value: balance, gas: 1000000}
    
    • The reasoning behind passing an empty string (is it being passed to msg.send.call?)

    call defined on address type. address can be contract or externally owned accounts (accounts that users hold their balance)

    If you are calling contract.call, "" calls the fallback function on msg.sender contract address. remember, contract can call other contracts, so msg.sender can be a contract address. if you want to call the specific function on msg.sender, you have to pass the function signature. For example, if you want to call test() with its parameter types

    // 1 for uint value, msg.sender for address value
    msg.sender.call{value: balance}(abi.encodeWithSignature("test(uint,address)", 1, msg.sender))
    

    call is also used to transfer fund to an externally owned account. in this case there is not a function to call, in this case we have "". Imagine you have a contract for an ecommerce contract, a user buys the product and user sends the price to the owner

    (bool success, ) = owner.call{value: item.price}("");
    require(success, "Transfer failed");