签署
TON 数据签名常用于链下验证、登录证明和合约相关授权。签名前请确保数据结构、schema 和挑战值由应用后端生成并可验证。
签名任意数据
使用 signData 可以请求用户签名 Base64 编码的 cell:
const callResult = await provider.send({
method: "signData",
id: Date.now().toString(),
requestParams: [
JSON.stringify({
schema_crc: 0, // 自定义 schema ID
cell: cellBoc.toString("base64"), // Base64 编码的待签名 cell 数据
}),
],
});
if ("callResult" in callResult) {
console.log("生成的签名:", callResult.callResult.signature); // Base64 格式签名
console.log("记录时间戳:", callResult.callResult.timestamp); // UNIX 时间戳
}
签名证明(身份验证)
登录类场景建议在连接时请求 ton_proof,并把服务端生成的 challenge 放入 payload:
const connectEvent = await provider.connect(2, {
manifestUrl: "https://sampleapp.example/tonconnect-manifest.json",
items: [
{ name: "ton_addr" },
{
name: "ton_proof",
payload: "server-issued-demo-challenge", // 用于防重放的 Nonce
},
],
});
if (connectEvent.event === "connect") {
const proofItem = connectEvent.payload.items.find(
(i) => i.name === "ton_proof",
);
if (proofItem) {
// 把 proof 发送到后端校验
const proof = proofItem.proof;
console.log({
signature: proof.signature,
timestamp: proof.timestamp,
domain: proof.domain,
payload: proof.payload,
});
}
}
处理异常
const callResult = await provider.send({
method: "sendTransaction",
id: Date.now().toString(),
requestParams: [
/* remaining fields omitted */
],
});
if ("error" in callResult) {
switch (callResult.error.code) {
case 300:
console.log("用户拒绝了这笔交易");
break;
case 1:
console.log("请求出错,请检查参数");
break;
case 400:
console.log("当前方法不受支持");
break;
default:
console.error("执行报错:", callResult.error.message);
}
} else {
console.log("成功结果:", callResult.callResult);
}
错误码
| 错误码 | 说明 |
|---|---|
| 0 | 未归类错误 |
| 1 | 请求内容有误 |
| 100 | 应用来源未知 |
| 300 | 用户取消了本次请求 |
| 400 | 当前方法不可用 |