【问题标题】:How to call the function of another smart contract in Solidity? With an example of OpenZeppelin transferOwnership functionSolidity中如何调用另一个智能合约的函数?以 OpenZeppelin transferOwnership 函数为例
【发布时间】:2023-01-29 16:55:39
【问题描述】:

我在学习OpenZeppelin的时候,发现它的Ownable库有一个函数transferOwnership,可以给当前合约的所有者一个地址。 我可以理解将所有者更改为某人的帐户地址,但是,它也可以将所有者更改为合同地址。 我的问题是:如果我将当前合约的所有者更改为另一个合约地址,我如何使用另一个合约来处理我原始合约的所有者?我尝试使用 super 关键字进行继承,但它不起作用。

失败代码如下。

顺便说一句,将当前合约的所有者更改为另一个合约地址是否有用?有没有使用这种情况的示例项目?

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

import "@openzeppelin/contracts/access/Ownable.sol";

contract MyContract is Ownable {
    function getCurrentBalance() public view onlyOwner returns (uint) {
        return address(this).balance;
    }
    receive() external payable {}
}

contract ManageOwner is MyContract {
    function changeOwner(address newOwner) public  {
        super.transferOwnership(newOwner);
    }
}

【问题讨论】:

  • 澄清一下:1) MyContractManageOwner 都部署在两个不同的地址上(例如地址 A 上的 MyContract 和地址 B 上的 ManageOwner)? 2)你的目标是启用MyContract部署者(即当前的owner)并且没有其他人调用changeOwner()并有效地改变MyContract(在地址A上)所有者?
  • 是的!绝对正确。
  • 我使用界面并成功。代码如下:

标签: ethereum solidity smartcontracts ownership openzeppelin


【解决方案1】:

我使用界面并成功。代码如下:

import "@openzeppelin/contracts/access/Ownable.sol";

contract A is Ownable {

    receive() external payable {}

    function getCurrentBalance() public view onlyOwner returns (uint) {
        return address(this).balance;
    }
}

interface I {
    function getCurrentBalance() external view returns (uint) ;
    function transferOwnership(address newOwner) external;
}


contract B is Ownable {

    I public itf = I(contract_A_address_); 

    receive() external payable {}

    function getBalanceOfA() public view onlyOwner returns (uint) {
        return itf.getCurrentBalance();
    }

    function changeAOwner(address newOwner) public onlyOwner{
        itf.transferOwnership(newOwner);
    }
}

首先,部署合约A。 2、复制合约A地址到合约B。 3、部署B。 4、以合约B的地址为参数调用合约A的transferOwnership函数。 5、调用合约B的changeAOwner函数处理合约A的所有权。

【讨论】:

    猜你喜欢
    • 2021-03-06
    • 2021-09-02
    • 2017-08-19
    • 1970-01-01
    • 2021-08-25
    • 2022-10-25
    • 2021-09-11
    • 2022-11-22
    • 2017-08-07
    相关资源
    最近更新 更多