React中从TON交易BOC获取状态及信息?解析遇Invalid data报错
TON区块链交易BOC解析及交易状态验证问题
问题描述
已成功用React在TON区块链发起交易,但提取交易返回的BOC(Bag of Cells)有效信息时遇到困难,无法判断交易是否成功完成。发送交易后收到BOC字符串,尝试用loadTransaction方法解析时抛出“Invalid data”错误,相关代码片段如下:
const tx = await tonConnectUI.sendTransaction(myTransaction); const boc = tx.boc; const code_cell = Cell.fromBoc(Buffer.from(boc, 'base64'))?.[0] const txI = loadTransaction(code_cell.beginParse());
正确处理方式
1. 明确BOC类型
TON Connect返回的tx.boc是交易消息的BOC,并非链上完成的交易本身的BOC。交易消息是发起交易的封装结构,和链上交易对象结构完全不同,直接用loadTransaction解析必然报错。
2. 通过交易哈希查询链上状态(推荐方案)
验证交易是否成功最可靠的方式,是利用TON Connect返回的交易哈希,调用TON节点API查询链上交易详情:
const tx = await tonConnectUI.sendTransaction(myTransaction); // 提取交易哈希 const txHash = tx.transactionHash; // 调用TON节点API查询交易 const apiResponse = await fetch(`https://toncenter.com/api/v2/getTransactions?address=${你的钱包地址}&limit=1&hash=${txHash}`); const result = await apiResponse.json(); if (result.ok && result.result.length > 0) { const targetTx = result.result[0]; // transaction.status为"ok"代表交易成功 const isSuccess = targetTx.status === 'ok'; console.log('交易状态:', isSuccess ? '成功' : '失败'); // 还可获取区块高度、转账金额等其他信息 } else { console.log('交易未确认或查询失败'); }
3. 解析返回的消息BOC(若需)
如果确实需要解析TON Connect返回的BOC,因为它是外部消息结构,要使用loadMessage而非loadTransaction:
import { Cell, loadMessage } from '@ton/core'; const tx = await tonConnectUI.sendTransaction(myTransaction); const boc = tx.boc; try { const cell = Cell.fromBoc(Buffer.from(boc, 'base64'))[0]; const message = loadMessage(cell.beginParse()); // 获取消息相关信息 console.log('消息接收地址:', message.info.dest.toString()); console.log('转账金额:', message.body.coins.toString()); } catch (error) { console.error('BOC解析失败:', error); }
核心注意事项
- 无法从TON Connect返回的BOC中直接获取交易成功状态,因为它只是发送的消息,不是链上确认后的交易。
- 交易成功的唯一有效验证是链上确认,通过交易哈希查询节点API是标准流程。
- 解析时要区分消息和交易结构,对应使用
loadMessage和loadTransaction方法。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

