[英]How to call the function of another smart contract in Solidity? With an example of OpenZeppelin transferOwnership function
我在學習OpenZeppelin的時候,發現它的Ownable庫有一個function transferOwnership,可以給當前合約的所有者一個地址。 我可以理解將所有者更改為某人的帳戶地址,但是,它也可以將所有者更改為合同地址。 我的問題是:如果我將當前合約的所有者更改為另一個合約地址,我如何使用另一個合約來處理我原始合約的所有者? 我用 super 關鍵字嘗試了 inheritance,它不起作用。
失敗代碼如下。
順便說一句,將當前合約的所有者更改為另一個合約地址是否有用? 有沒有使用這種情況的示例項目?
// 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);
}
}
我使用界面並成功。 代碼如下:
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。第二,將合約A地址復制到合約B。第三,部署B。第四,以合約B的地址作為參數調用合約A的transferOwnership function。 5、調用B合約的changeAOwner function處理合約A的所有權。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.