You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Solidity中返回手机号与余额的映射格式数据?

问题:如何让Solidity合约返回手机号与对应余额的映射格式数据

现有Solidity代码如下:

//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(uint256[] memory){
    return (phones[owner]);
}

当前调用details函数仅返回已铸造的手机号数组,希望返回类似{"9222111888":"150","9093164641":"550"}这样的手机号与对应余额的映射格式数据,请问该如何实现?


解决方案

Solidity本身不支持直接返回JSON格式的数据,因为EVM(以太坊虚拟机)的返回值只能是基础类型、数组或自定义结构体。我们可以通过以下两种方式实现需求:

方式1:返回自定义结构体数组

定义一个包含手机号和余额的结构体,让details函数返回该结构体的数组,前端拿到数据后可轻松组装成所需的JSON格式。

修改后的代码如下:

//Owner to Phone
mapping(address => uint256[]) public phones;
// Phone to Balance
mapping(uint256 => uint256) public balance;

// 定义存储手机号与余额的结构体
struct PhoneBalance {
    uint256 phone;
    uint256 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(PhoneBalance[] memory) {
    uint256[] memory userPhones = phones[owner];
    PhoneBalance[] memory result = new PhoneBalance[](userPhones.length);
    
    for (uint256 i = 0; i < userPhones.length; i++) {
        uint256 phone = userPhones[i];
        result[i] = PhoneBalance(phone, balance[phone]);
    }
    
    return result;
}

方式2:返回两个平行数组

如果不想定义结构体,也可以同时返回手机号数组和对应的余额数组,前端再将两个数组按索引对应组装成映射:

//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(uint256[] memory, uint256[] memory) {
    uint256[] memory userPhones = phones[owner];
    uint256[] memory userBalances = new uint256[](userPhones.length);
    
    for (uint256 i = 0; i < userPhones.length; i++) {
        userBalances[i] = balance[userPhones[i]];
    }
    
    return (userPhones, userBalances);
}

说明

两种方式的返回结果都需要前端做简单处理:

  • 对于结构体数组,遍历数组将每个元素的phone作为键、balance作为值,构建成目标JSON对象。
  • 对于平行数组,按索引一一对应,将userPhones[i]作为键、userBalances[i]作为值来组装。

内容的提问来源于stack exchange,提问作者monish nagre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:35:42