Contract-Design
使用 Solidity 0.5 在合約之間傳遞結構
我正在嘗試將
Storage
結構的實例從 StorageController.sol 傳遞給 Publisher.sol。不管我做什麼,我都會VM Exception while processing transaction: revert
參加我的松露測試。兩個契約都
pragma experimental ABIEncoderV2;
在頂部。StorageController.sol 由 Publisher 導入。到目前為止,這是我嘗試過的: 1. 使用映射:StorageController:
mapping(uint256 => Storage) public storages;
出版商:
Storage memory _storage = _storages.storages(storage_id);
這甚至不會編譯,它說,
TypeError: Different number of components on the left hand side (1) than on the right hand side (6).
- 使用函式
儲存控制器:
function getStorage(uint256 i) external view returns(Storage memory) { return storages[i]; }
出版商
StorageController.Storage memory _storage = _storages.getStorage(storage_id);
輸出:
VM Exception while processing transaction: revert
- 傳遞一個元組
儲存控制器:
function getStorageData(uint256 i) external view returns(bytes32 name, uint256 maxLength, uint256 rank, uint256 writingFee, uint256 sellPrice, bool nonpublic) { return ("", 1,1,1,1,false); }
(我硬編碼輸出值以防萬一)
出版商:
(bytes32 name,,,,,) = _storages.getStorageData(storage_id);
輸出:同上。
很可能您會收到此錯誤,因為您的合約在部署後
Publisher
不知道合約。StorageController
我已經寫了 2 份工作契約。
儲存控制器合約
contract StorageController { struct Storage { string name; uint256 maxLength; uint256 rank; uint256 writingFee; uint256 sellPrice; bool nonpublic; } mapping(uint256 => Storage) public storages; uint storageCount = 0; constructor() public { Storage memory newStorage = Storage({ name: 'aaa', maxLength: 11, rank: 12, writingFee: 13, sellPrice: 14, nonpublic: false }); storages[storageCount++] = newStorage; } function getStorageData(uint256 i) external view returns(string memory name, uint256 maxLength, uint256 rank, uint256 writingFee, uint256 sellPrice, bool nonpublic) { return (storages[i].name, storages[i].maxLength,storages[i].rank,storages[i].writingFee,storages[i].sellPrice,storages[i].nonpublic); } }
出版商契約
contract Publisher { StorageController _storages; constructor(address storageControllerAddress) public { _storages = StorageController(storageControllerAddress); } function getStorage(uint index) public view returns(string memory, uint256, uint256, uint256, uint256, bool) { (string memory name, uint256 maxLength, uint256 rank, uint256 writingFee, uint256 sellPrice,bool nonpublic) = _storages.getStorageData(index); return (name, maxLength,rank,writingFee,sellPrice,nonpublic); } }
筆記:
- 使用了solidity 0.5.4編譯器,你不需要
pragma experimental ABIEncoderV2;
StorageController
首先部署合約。然後它的地址被用來部署Publisher
合約。