Wallet synchronization, payments and recovery
WalletSession manages inventory, input selection, change, reservations and durable operations. It does not replace account unlocking, key management or application decryption.
Open a session
This function takes application-configured Invisi, Protocol, public Wallet and Store capabilities. It does not choose a database or encryption key.
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",
});
}
For IndexedDB or SQLite persistence, provide the database and a separate storage key for EncryptedWalletCodec. Recovery must reuse the account, deployment, namespace, database and key. MemoryWalletStore cannot recover after restart.
Synchronization has two steps
session.refresh() authenticates public history and returns a pending scan. pending.decrypt(decryptor) uses application viewing capabilities to authenticate deliveries and commit private inventory.
Implement DeliveryDecryptor.decryptNote / decryptCredit to return authenticated plaintext bytes. Return null only for a known nonrecipient. An ambiguous AEAD failure returns authentication-failed; locked accounts, cancellation and wrong-account errors must reject the batch.
Unresolved candidates can leave completeness and available balance unknown. Do not swallow every decryption error as zero balance. Display coverage with getScanStatus() and retry using retryUnresolved(decryptor).
Pay from Notes
This integration function requires a connected persistent session, an ethers Signer matching its owner, an authenticated decryptor, and a persist callback that durably saves operation IDs and hashes in the host database. Calling it signs, proves and submits; invoke it through your application’s user confirmation flow. Amounts are base units.
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 });
}
}
Persist the transaction hash immediately after sending, even if association, waiting or reconciliation subsequently fails. Production hosts should wrap sending and hash persistence in their durable application flow. Do not simply rerun this entire function after catching an error.
If using session.sendTransaction(ready, options) instead, inject a session signer and provide an explicit positive gasLimit. The local estimateGas() is a benchmark preview, not simulation of this call.
Recover an existing operation
- Reopen the original Store and retain the operation ID.
- Use
await session.resume(id), not another payment preparation. - If the host submitted an unassociated transaction, call
trackTransaction(hash)and keep its returned handle. - Use
reconcile()to verify canonical receipts and actual effects before updating inventory and reservations. - Observe native confirmation using
getConfirmation(); it does not reconcile or release reservations.
Retain reservations while input consumption is uncertain. Reorganizations require rebuilding affected state. Offline scans recover retained history but cannot prove current spendability.