如何解码near-api-js txStatus返回的NEAR函数调用参数为JSON?
NEAR交易FunctionCall参数解码方法
你拿到的args字段是NEAR交易中对函数调用参数做Base64编码后的结果,要得到明文JSON只需做两次逆向转换即可,步骤如下:
- 第一步:从返回结果中提取
FunctionCall.args的Base64编码字符串 - 第二步:将Base64字符串解码为UTF-8格式的普通字符串
- 第三步:将解码后的字符串反序列化为JSON对象
Node.js环境实现
// 假设你调用txStatus拿到的交易结果存在txRes变量中 const funcCall = txRes.transaction.actions[0].FunctionCall // 解码逻辑 const decodedArgsStr = Buffer.from(funcCall.args, 'base64').toString('utf-8') const decodedArgsJson = JSON.parse(decodedArgsStr) // decodedArgsJson就是和NEAR explorer展示一致的明文参数 console.log(decodedArgsJson)
浏览器环境实现
浏览器环境没有内置Buffer模块,可以用原生atob方法处理:
const funcCall = txRes.transaction.actions[0].FunctionCall const decodedArgsStr = decodeURIComponent(escape(atob(funcCall.args))) const decodedArgsJson = JSON.parse(decodedArgsStr)
如果你的参数不是JSON格式的二进制,才需要用到near-api-js的序列化工具做针对性解码,绝大多数常规合约调用的参数都是JSON编码,用上面的方法即可直接得到预期结果。
内容的提问来源于stack exchange,提问作者Tien Do
相关产品推荐
相关产品推荐

