user1506104
user1506104

Reputation: 7106

Transfer eth with hex data via smart contract

I am trying to transfer a certain number of eth from my contract to another contract. However, aside from eth, I also need to transfer hexdata. Just like how it is done in metamask:

enter image description here

How do I do this with solidity? I could not find anything from the docs.

Upvotes: 1

Views: 1208

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43591

You can use the low-level call member of address type (docs).

It takes the value as a property of the options object, and the argument represents the data field of the transaction.

pragma solidity ^0.8;

contract Sender {
    Receiver receiver;

    constructor(address payable _receiver) {
        receiver = Receiver(_receiver);
    }

    function sendWithData() external payable {
        bytes memory sendData = abi.encode("hello");
        (bool success,) = address(receiver).call{value: msg.value}(sendData);
        require(success);
    }
}

contract Receiver {
    event Received(bytes, uint256);

    fallback(bytes calldata receivedData) external payable returns (bytes memory) {
        emit Received(receivedData, msg.value);
        return "";
    }
}

Upvotes: 1

Related Questions