跳到主要内容

钱包同步、支付与恢复

WalletSession 管理凭证库存、输入选择、找零、在途预留和持久化操作。它不代替账户解锁、密钥管理或应用自己的解密能力。

创建会话​

以下函数接收应用配置好的 Invisi、Protocol、公开 Wallet 与 Store,不隐式创建数据库或选择加密密钥。

import { Invisi, Protocol, Wallet } from "@invisi-labs/sdk";
import { WalletSession, type WalletStore } from "@invisi-labs/session";

export function openSession(
invisi: Invisi, protocol: Protocol, wallet: Wallet, store: WalletStore,
) {
return WalletSession.connect({
invisi, protocol, wallet, store, namespace: "wallet-payments",
});
}

选择 IndexedDB 或 SQLite 持久化适配器时,由应用提供数据库和 EncryptedWalletCodec 的独立存储密钥。恢复时保持同一账户、部署、namespace、数据库及密钥。MemoryWalletStore 仅保留内存状态,不能用于重启恢复。

同步分为两个步骤​

session.refresh() 获取并认证公共历史,返回待扫描批次;pending.decrypt(decryptor) 使用应用提供的查看能力认证解密并提交私密库存。

应用实现 DeliveryDecryptor.decryptNote / decryptCredit:返回认证后的明文字节;只有已知不属于本账户时才返回 null。无法区分错误密钥与损坏密文的 AEAD 失败应返回 authentication-failed,而锁定、取消或错误账户等操作错误应抛出。

存在未解决候选时,扫描完整性与可用余额可能为未知。不能将所有解密异常吞掉并记成“余额为零”。用 getScanStatus() 展示覆盖与未解决情况,用 retryUnresolved(decryptor) 重试。

从 Note 支付​

下例是集成函数,依赖已连接且持久化的会话、匹配 owner 的 ethers Signer、认证解密器,以及将操作 ID / 哈希可靠保存到宿主数据库的 persist 回调。调用会签名、证明并提交交易,应由应用的用户确认流程触发。amount 为最小单位。

import type { Signer } from "ethers";
import { NoteOutput, type DeliveryDecryptor } from "@invisi-labs/sdk";
import { WalletSession } from "@invisi-labs/session";

export async function payFromNotes(
session: WalletSession, signer: Signer, decryptor: DeliveryDecryptor,
tokenAddress: `0x${string}`, recipientAddress: `0i${string}`, amount: bigint,
persist: (record: { operationId: string; transactionHash?: string }) => Promise<void>,
) {
if (amount <= 0n) throw new Error("Amount must be positive base units");
const chainId = session.protocol.context.chainId;
if (!signer.provider || (await signer.provider.getNetwork()).chainId !== chainId) {
throw new Error("Signer is connected to the wrong network");
}
const pending = await session.refresh();
await pending.decrypt(decryptor);
const balance = await session.balance(tokenAddress);
if (balance.availableKnown === null || balance.availableKnown < amount) {
throw new Error("Insufficient verified available balance");
}
const output = await NoteOutput.create({
...session.protocol.context, tokenAddress, amount,
recipient: { type: "invisi", address: recipientAddress },
});
const operation = await session.prepareTransfer({ tokenAddress, outputs: [output] });
const authorization = await operation.exportWalletAuthorization();
const signature = await signer.signTypedData(
authorization.domain, authorization.types, authorization.message,
);
const ready = await (await operation.withWalletSignature(signature)).prove();
await ready.validateSubmission();
await persist({ operationId: ready.id });
const tx = await signer.sendTransaction({ ...await ready.exportTransaction(), chainId });
try {
await persist({ operationId: ready.id, transactionHash: tx.hash });
const tracked = await ready.trackTransaction(tx.hash);
await tx.wait();
await tracked.reconcile();
return { operationId: tracked.id, transactionHash: tx.hash };
} catch (cause) {
throw new Error(`Recover operation ${ready.id} with transaction ${tx.hash}`, { cause });
}
}

应用需要在提交后立即可靠保存返回哈希,即使后续关联、等待或对账失败也保留它。生产集成可把发送与保存哈希包装在宿主持久化流程中;不能在捕获异常后直接重新调用整个支付函数。

若改用 session.sendTransaction(ready, options),会话需注入 signer,且必须显式传入正 gasLimit;本地 estimateGas() 是基准估算,不是本次链上模拟结果。

恢复已有操作​

  1. 用原 Store 恢复会话,读取保存的 operation ID。
  2. await session.resume(id) 打开原操作,而非创建新支付。
  3. 如果交易由宿主提交但尚未关联,调用 trackTransaction(hash),保留返回的新句柄。
  4. 用 reconcile() 核对规范回执及实际状态,再更新预留与库存。
  5. 用 getConfirmation() 观察原生确认等级;它不会替代对账或自动释放预留。

不确定交易是否已消费输入时保留预留。重组需要重建受影响状态;离线扫描只能恢复已留存历史,不能证明当前尚未花费。