工厂合约的地址如果经常变化,就必须追踪这些合约。在这种情况下,就可以使用名字登录模式,存储合约名到合约地址的映射mapping,同时提供根据合约名来查找合约地址的功能,甚至还可以追踪版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| pragma solidity ^0.6.12;
contract NameRegistry { struct ContractDetails { address owner; address contractAddress; uint16 version; } mapping(string => ContractDetails) registry; function registerName(string memory name, address addr, uint16 ver) public returns (bool) { require(ver >= 1); ContractDetails memory info = registry[name]; require(info.owner == msg.sender); if(info.contractAddress == address(0)) { info = ContractDetails({ owner:msg.sender, contractAddress:addr, version:ver }); } else { info.version = ver; info.contractAddress = addr; } registry[name] = info; return true; } function getContractDetails(string memory name) public view returns (address, uint16) { return(registry[name].contractAddress, registry[name].version); } }
|
通过 getContractDetails(name)
获得合约地址和指定版本的合约。
关联文档:
- 智能合约-CURD的详细分析
- 智能合约-自毁模式
- 智能合约-工厂合约模式
- 智能合约-名字登录模式
- 智能合约-退款方式