solidity call使用

solidity call使用

<address>.call(bytes memory payload) returns (bool, bytes memory)

call 仅发送ETH,不传入data

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

contract SendEther {
    // 构造函数,payable使得部署的时候可以转eth进去
    constructor() payable {}

    function callEther(address payable recipient, uint256 amount)
        public
        returns (bool)
    {
        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Transfer failed.");
        return success;
    }
}

1、部署合约时附带 value

2、调用合约,给接收地址recipient转账

call 传入data,附带发送ETH

在合约中调用其他的合约的方法

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Callee {
    uint256 value;

    function getValue() public view returns (uint256) {
        return value;
    }

    function setValue(uint256 value_) public payable {
        require(msg.value > 0, "msg.value must > 0");
        value = value_;
    }
    // 获取合约地址的eth余额
    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }

}

contract Caller006 {

    // 构造函数,payable使得部署的时候可以转eth进去
    constructor() payable {}

    function callSetValue(address callee, uint256 value)
        public
        returns (bool)
    {
        Callee meta = Callee(callee);

        // 对函数签名和参数进行编码
        bytes memory methodop = abi.encodeWithSignature(
            "setValue(uint256)",
            value
        );
        (bool flg, ) = address(meta).call{value: 1 ether}(methodop);

        if (!flg) {
            revert("call function failed");
        }

        return flg;
    }

    // 获取合约地址的eth余额
    function getBalance() public view returns (uint256) {
        return address(this).balance;
    }

}

staticcall调用其他合约的方法

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Callee {
    function getData() public pure returns (uint256) {
        return 42;
    }
}

contract Caller {
    function callGetData(address callee) public view returns (uint256 data) {
        // call by staticcall
        // 对函数签名和参数进行编码
        bytes memory methodop = abi.encodeWithSignature("getData()");
        (bool flg, bytes memory result) = callee.staticcall(methodop);

        if(!flg){
            revert("staticcall function failed");
        }
        data = bytesToUint(result);

        return data;
    }

    function bytesToUint(bytes memory b) public pure returns (uint256) {
        uint256 number;
        for (uint256 i = 0; i < b.length; i++) {
            number = number + uint8(b[i]) * (2**(8 * (b.length - (i + 1))));
        }
        return number;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半山猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值