第126篇 合约间调用方法

114 篇文章 713 订阅 ¥39.90 ¥99.00

本文介绍三种类型的合约间调用;

1.一般调用

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

contract Receiver {
    event Received(address caller, uint256 amount, string message);

    receive() external payable {}

    fallback()  external payable {
        emit Received(msg.sender, msg.value, "Fallback was called");
    }

    function foo(string memory _message, uint256 _x)
        public
        payable
        returns (uint256)
    {
        emit Received(msg.sender, msg.value, _message);

        return _x + 1;
    }
}

contract Caller {
    event Response(bool success, bytes data);

    // Let's imagine that contract B does not have the source code for
    // contract A, but we do know the address of A and the function to call.
    function testCallFoo(address payable _addr) public payable {
        // You can send ether and specify a custom gas amount
        (bool success, bytes memory data) = _addr.call{
            value: msg.value
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Solidity 合约调用可以通过合约地址进行实现合约调用的语法如下: ``` contract ContractA { function foo(uint256 x) public returns (uint256) { // do something } } contract ContractB { ContractA contractA = ContractA(0x1234567890123456789012345678901234567890); function bar() public { uint256 result = contractA.foo(123); // do something with result } } ``` 在上面的示例合约 B 调用合约 A 的函数 `foo`,并将值 `123` 作为参数传递给了该函数。需要注意的是,调用 `foo` 函数会消耗 Gas,因此需要确保调用合约有足够的 Gas 储备。 在合约调用时,还需要注意传递参数的类型和顺序。Solidity 支持多种数据类型,包括整数、布尔值、字符串、地址等等。在传递参数时,需要确保参数类型和数量与被调用函数的参数类型和数量相匹配,否则会导致编译错误。 另外,如果被调用的函数是视图函数(即不修改状态的函数),则可以使用 `call` 方法进行调用。例如: ``` contract ContractA { function foo(uint256 x) public view returns (uint256) { // do something } } contract ContractB { ContractA contractA = ContractA(0x1234567890123456789012345678901234567890); function bar() public { (bool success, uint256 result) = contractA.call(abi.encodeWithSignature("foo(uint256)", 123)); require(success, "failed to call ContractA.foo"); // do something with result } } ``` 在上面的示例,`ContractB` 调用了 `ContractA` 的函数 `foo`,并使用 `call` 方法进行调用。需要注意的是,使用 `call` 方法时需要手动编码参数,因此需要使用 `abi.encodeWithSignature` 函数将参数编码为字节数组。另外,如果调用失败,需要使用 `require` 断言确保调用成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wonderBlock

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

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

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

打赏作者

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

抵扣说明:

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

余额充值