Solidity合约问题:无法获取phone:balance数组仅得最新值如何修复?
修复Solidity合约details函数的返回格式问题
问题根源
你的details函数有两个核心问题:
- 循环里每次直接覆盖
var1和var2,没有累积拼接所有条目,最终只会返回最后一条数据 - 错误地把
var1赋值为余额的字符串(userBalances就是balance的引用,完全多余),导致返回balance:balance的重复值,而非期望的phone:balance格式
修复方案
修改details函数,初始化一个结果字符串容器,循环遍历所有手机号,逐个拼接phone:balance格式的条目,同时处理好条目间的分隔符:
import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract GoTekERC721 is ERC721, Ownable { constructor() ERC721("Go NFT", "GoN") {} // Owner to Phone mapping(address => uint256[]) public phones; // Phone to Balance mapping(uint256 => uint256) public balance; function register(uint256 phone, uint256 Balance) public { _mint(msg.sender, phone); phones[msg.sender].push(phone); balance[phone] = Balance; } function details(address owner) public view returns(string memory) { uint256[] memory ownerPhones = phones[owner]; string memory result = ""; for (uint256 i = 0; i < ownerPhones.length; i++) { uint256 phone = ownerPhones[i]; uint256 bal = balance[phone]; // 拼接当前条目的phone:balance格式 string memory currentEntry = string( bytes.concat( bytes(Strings.toString(phone)), bytes(":"), bytes(Strings.toString(bal)) ) ); // 非第一个条目时,先加逗号分隔符 if (i > 0) { result = string(bytes.concat(bytes(result), bytes(", "))); } // 将当前条目追加到结果中 result = string(bytes.concat(bytes(result), bytes(currentEntry))); } return result; } }
关键修改说明
- 移除了多余的
userBalances映射引用,直接通过balance[phone]获取余额 - 新增
result变量用于累积所有条目,避免每次覆盖数据 - 循环内先处理单条
phone:balance格式,再根据位置添加分隔符,保证输出符合9658965896:199, 8569856985:49的要求 - 删除无意义的
var1、var2变量,简化逻辑
内容的提问来源于stack exchange,提问作者monish nagre
相关产品推荐
相关产品推荐

