准备消息
在使用TON Connect时,您应该为在各种交易中使用的Payload构造消息体。在此页面上,您可以找到与TON Connect SDK一起使用的payload的最相关示例。
信息
期望您学习了创建TON Connect连接的基础知识。了解更多请参阅集成手册。
TON Connect JS SDK 示例
在深入研究构建消息之前,我们先来介绍一下 cell 的概念,消息体就是由 cell 组成的。
什么是 cell ?
cell 是 TON 区块链中的基本数据结构。它可以存储多达 1023
位的数据,并持有多达 4
个指向其他 cell 的引用,从而允许您存储更复杂的数据结构。
像 @ton/core
和 @ton-community/assets-sdk
这样的库提供了处理 cell 的有效方法。
您可以在 此处 了解有关 cell 的更多信息。
创建 cell
要创建 cell ,需要使用 beginCell()
函数。当 cell "打开" 时,您可以使用 store...()
函数存储各种数据类型。
完成后,使用 endCell()
函数关闭 cell 。
import { Address, beginCell } from "@ton/ton";
const cell = beginCell()
.storeUint(99, 64) // Stores uint 99 in 64 bits
.storeAddress(Address.parse('[SOME_ADDR]')) // Stores an address
.storeCoins(123) // Stores 123 as coins
.endCell() // Closes the cell
解析 cell
要从 cell 中读取或解析数据,需要调用 beginParse()
函数。使用类似的load...()
函数,读取数据的顺序与存储数据的顺序相同:
const slice = cell.beginParse();
const uint = slice.loadUint(64);
const address = slice.loadAddress();
const coins = slice.loadCoins();
数据量更大
每个 cell 都有 1023 位的限制。如果超过上限,就会发生错误:
// This will fail due to overflow
const cell = beginCell()
.storeUint(1, 256)
.storeUint(2, 256)
.storeUint(3, 256)
.storeUint(4, 256) // Exceeds 1023-bit limit (256 + 256 + 256 + 256 = 1024)
.endCell()
使用TON Connect JS SDK执行常规TON转账如下所示:
const cell = beginCell()
.storeUint(1, 256)
.storeUint(2, 256)
.storeRef(beginCell()
.storeUint(3, 256)
.storeUint(4, 256)
.endCell())
.endCell()
要加载引用(嵌套) cell ,请使用 loadRef()
:
const slice = cell.beginParse();
const uint1 = slice.loadUint(256);
const uint2 = slice.loadUint(256);
const innerSlice = slice.loadRef().beginParse(); // Load and parse nested cell
const uint3 = innerSlice.loadUint(256);
const uint4 = innerSlice.loadUint(256);