js解析智能合约Solidity返回的struct

前言

Solidity是以太坊智能合约的编程语言,我们可以通过web3.js来与合约进行通信,并接收Solidity函数的返回值。不少人在接收struct类型的返回值时不知道怎么处理,本文展示一种解析方法,以供各位学习交流,如有更好的方法,欢迎讨论。
#Solidity返回的struct
首先看solidity代码,截取了关键部分,定义了一个结构体以及一个id到结构体的映射,该映射为public,意味着会自动生成getter函数。

    struct Status{
        string studentId; // 学籍号
        string schoolId;// 学校
        string majorId;// 专业
        uint8 length;// 学制
        uint8 eduType;// 学历类别
        uint8 eduForm;// 学习形式
        uint8 level;// 层次(专/本/硕/博)
        uint8 state;// 学籍状态
        uint16 class;// 班级
        uint32 admissionDate;// 入学日期
        uint32 departureDate;// 离校日期
    }
	mapping (uint32=>Status) public idToUndergraduate;// id到本科学籍的映射

js调用合约

this.StudentFactory = TruffleContract(StudentFactoryABI);
if (typeof web3 !== 'undefined') {
        console.warn('Using web3 detected from external source.');
        window.web3 = new Web3(window.web3.currentProvider)
} else {
        $('body').html('<h1>没有检测到MetaMask插件,请安装MetaMask后刷新页面重试</h1>');
}
this.StudentFactory.setProvider(window.web3.currentProvider);
        
let studentFactory;
StudentFactory.at(address).then((instance) => {
	studentFactory = instance;
	return studentFactory.idToUndergraduate.call(id);
}).then((result) => {
	console.log(result);// 打印结果
}).catch((e) => {
	console.warn(e);
})

通过promise获取到result,将result输出到控制台显示。结果如下:

这里写图片描述
可以看到,整体上struct变成了一个数组,但是只有struct摆在前面的string类型数据是正常显示,而后面的uint都变成了形如**r {s: 1, e: 0, c: Array(1)}**的东西。

解析方法

具体代码如下,通过map()和回调函数解析数据:

let studentFactory;
StudentFactory.at(address).then((instance) => {
	studentFactory = instance;
	return studentFactory.idToUndergraduate.call(id);
}).then((result) => {
	result.map((v, i) => { // 遍历
        console.log(v.valueOf()); // 打印结果
    });
}).catch((e) => {
	console.warn(e);
})

打印效果:
这里写图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄嘉成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值