[Ethereum] Solidity to inline assembly

assemblysolidity

Taken a smart contract like the following:

contract A {
    address public beneficiary;

    function A(address _beneficiary) public {
         beneficiary = _beneficiary;
    }

    function () public payable {
         beneficiary.transfer(msg.value);
    }
}

How would you write it in inline assembly? No problem for me with the constructor, but got stuck with the fallback function, since I don't know how to translate the transfer()

Best Answer

I'd do something like this, using call() to do an external function call, passing the msg.value inside it.

function () payable {
    bytes4 sig = bytes4(keccak256("()")); // function signature

    assembly {
        let x := mload(0x40) // get empty storage location
        mstore ( x, sig ) // 4 bytes - place signature in empty storage

        let ret := call (gas, 
            beneficiary,
            msg.value, 
            x, // input
            0x04, // input size = 4 bytes
            x, // output stored at input location, save space
            0x0 // output size = 0 bytes
        )

        mstore(0x40, add(x,0x20)) // update free memory pointer
    }
}
Related Topic