如何调用通过new实例化的_Elector合约中的getInformation()函数?
主合约与dApp(ethers.js)调用_Elector合约getInformation()方法的实现方案
一、主合约内调用实现
你的主合约已经通过new _Elector(...)实例化并存储了合约实例,只需新增代理调用函数即可获取选举者信息:
1. 直接通过存储的_Elector实例调用
如果主合约中_pollingByCandidate的electors是_Elector[]类型数组(当前代码已满足),可以新增以下函数:
// 主合约中新增函数,根据候选ID和选举者索引获取信息 function getElectorInfo(uint candidateId, uint electorIndex) external view returns (address, VoteType) { // 检查索引合法性 require(electorIndex < _pollingByCandidate[candidateId].electors.length, "Elector index out of bounds"); // 取出目标_Elector实例 _Elector targetElector = _pollingByCandidate[candidateId].electors[electorIndex]; // 调用其getInformation方法 return targetElector.getInformation(); }
2. 通过合约地址直接调用(适用于已知_Elector地址的场景)
如果仅知道_Elector合约地址,可通过接口实例化后调用:
// 先定义_Elector合约的接口 interface IElector { function getInformation() external view returns (address, VoteType); } // 主合约新增函数 function getElectorInfoByAddress(address electorAddr) external view returns (address, VoteType) { IElector targetElector = IElector(electorAddr); return targetElector.getInformation(); }
二、dApp端用ethers.js调用实现
1. 准备_Elector合约ABI
只需包含getInformation函数的ABI片段即可:
const electorABI = [ { "inputs": [], "name": "getInformation", "outputs": [ { "internalType": "address", "name": "", "type": "address" }, { "internalType": "enum VoteType", "name": "", "type": "uint8" } // 枚举类型在ABI中以uint8形式存在 ], "stateMutability": "view", "type": "function" } ];
2. 获取_Elector合约地址
可通过主合约读取存储的选举者地址,例如:
// 先实例化主合约(需准备主合约ABI和地址) const mainContract = new ethers.Contract(mainContractAddress, mainABI, provider); // 获取指定候选ID下的第一个选举者地址 const candidateElectors = await mainContract._pollingByCandidate(targetCandidateId); const targetElectorAddr = candidateElectors.electors[0];
3. 实例化_Elector合约并调用方法
// 实例化_Elector合约(只读调用仅需provider,写操作需signer) const electorContract = new ethers.Contract(targetElectorAddr, electorABI, provider); // 调用getInformation方法 const [electorWallet, voteType] = await electorContract.getInformation(); // 打印结果 console.log("选举者钱包地址:", electorWallet); console.log("投票类型(枚举对应uint8值):", voteType.toString());
内容的提问来源于stack exchange,提问作者THIAGO DE BONIS
相关产品推荐
相关产品推荐

