@lethenymous/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lethenymous
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ # @lethenymous/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript protocol client for the frozen Lethenymous / zkCPMM program.
4
+
5
+ ## Status
6
+
7
+ This package provides source-derived codecs for the fixed deployment, PDA
8
+ derivation, account decoding, public and private instructions, exact CPMM
9
+ integer math, shielded primitives, and finalized Merkle verification. It does
10
+ not provide browser/WASM proving support.
11
+
12
+ Private operations require an authenticated local `ProductionProver`, the
13
+ production proving keys, a validated v0 address lookup table, and an encrypted
14
+ persistent `NoteStore`. The package does not bundle the prover, PKs, VKs, or
15
+ frozen SBF.
16
+
17
+ ## Install and build
18
+
19
+ ```bash
20
+ npm install @lethenymous/sdk
21
+ npm run build
22
+ ```
23
+
24
+ The package is Node.js-first and requires Node.js 20 or newer.
25
+
26
+ ## Public client
27
+
28
+ ```ts
29
+ import { Connection, Keypair, PublicKey } from "@solana/web3.js";
30
+ import { Lethenymous } from "@lethenymous/sdk";
31
+
32
+ const secretKey = Uint8Array.from(JSON.parse(process.env.KEYPAIR_JSON!));
33
+ const keypair = Keypair.fromSecretKey(secretKey);
34
+ const connection = new Connection(process.env.RPC_URL!, "finalized");
35
+ const wallet = {
36
+ publicKey: keypair.publicKey,
37
+ signTransaction: async tx => { tx.partialSign(keypair); return tx; },
38
+ signVersionedTransaction: async tx => { tx.sign([keypair]); return tx; },
39
+ };
40
+ const sdk = new Lethenymous({ connection, wallet });
41
+ const poolAddress = new PublicKey(process.env.POOL_ADDRESS!);
42
+ const quote = await sdk.quote(poolAddress, "AToB", 1_000_000n);
43
+ ```
44
+
45
+ All protocol amounts and indices are `bigint`. Quotes include the frozen
46
+ `MINIMUM_LIQUIDITY` LP-claim reserve floor. Quotes are advisory; callers must
47
+ choose their own slippage limits.
48
+
49
+ ## Private operations
50
+
51
+ The prover binary must match the authenticated release identity in
52
+ `release/production-prover-manifest.json`. The SDK verifies the executable
53
+ digest and exact `production-prover 0.2.0 ipc-v1` version before every proof.
54
+ The child receives only a minimal environment and receives witness tokens over
55
+ bounded private stdin IPC; it does not receive the parent environment, wallet
56
+ seed, or RPC credentials.
57
+
58
+ The PK paths must refer to the exact production artifacts. PK identity is
59
+ verified both by the SDK and inside the Rust prover. Do not pass caller-chosen
60
+ PK hashes as production configuration.
61
+
62
+ ```ts
63
+ import {
64
+ EncryptedFileNoteStore,
65
+ Lethenymous,
66
+ ProductionProver,
67
+ keyHierarchy,
68
+ ownerCommitment,
69
+ } from "@lethenymous/sdk";
70
+
71
+ const seed = Uint8Array.from(Buffer.from(process.env.WALLET_SEED_HEX!, "hex"));
72
+ const owner = ownerCommitment(keyHierarchy(seed).spendSecret);
73
+ const store = EncryptedFileNoteStore.fromSeed("/secure/path/notes.lnsj", seed, owner);
74
+ const prover = new ProductionProver({
75
+ executablePath: "/trusted/release/production-prover",
76
+ privateSwapPkPath: "/trusted/artifacts/private_swap_pk.production.bin",
77
+ unshieldPkPath: "/trusted/artifacts/unshield_pk.production.bin",
78
+ });
79
+ const shielded = sdk.shieldedWallet(seed, prover, { noteStore: store });
80
+ ```
81
+
82
+ `EncryptedFileNoteStore` uses an encrypted, authenticated append-only journal
83
+ with atomic reservation and operation transitions. The file contains note
84
+ randomness and pending operation preimages, so it must be protected like the
85
+ seed. Losing both the seed and the journal/backup loses recovery material.
86
+
87
+ For persistent finalized Merkle reconstruction, pass the same store to
88
+ `RpcMerkleWitnessProvider` as its checkpoint store. Checkpoints are encrypted
89
+ and authenticated sidecars keyed by genesis identity, program, pool, tree, and
90
+ generation. The provider still refreshes finalized tree state and verifies the
91
+ reconstructed root before returning a witness. A custom checkpoint store must
92
+ provide equivalent authenticated, crash-safe replacement semantics.
93
+
94
+ ```ts
95
+ let sdk: Lethenymous;
96
+ const witnessProvider = new RpcMerkleWitnessProvider(
97
+ connection,
98
+ programId,
99
+ pool => sdk.getTree(pool),
100
+ store,
101
+ );
102
+ sdk = new Lethenymous({ connection, wallet, programId, witnessProvider });
103
+ const shielded = sdk.shieldedWallet(seed, prover, { noteStore: store });
104
+ ```
105
+
106
+ The default `Lethenymous.shieldedWallet` path refuses to create a volatile
107
+ store. `InMemoryNoteStore` remains available only when explicitly supplied for
108
+ tests, demos, or ephemeral development.
109
+
110
+ After a process restart, call `reconcilePending()` before selecting notes for
111
+ new private operations. The method checks finalized transaction status and the
112
+ authenticated zkCPMM event before applying pending local state. A wallet can
113
+ also call `recoverShieldedNotes(pool)` with `RpcMerkleWitnessProvider` to scan
114
+ finalized shield events and decrypt the frozen outer-version-1 note envelope.
115
+ Recovery also verifies finalized spent-nullifier PDAs before marking a note
116
+ spent, rather than relying only on event history.
117
+ In a shared pool, envelopes that fail this wallet's view-key authentication are
118
+ foreign-wallet ciphertexts and are ignored; decryptable notes still require
119
+ commitment, owner, and spent-nullifier validation.
120
+
121
+ Use `exportBackup()` and `importBackup()` for encrypted journal backup and
122
+ restore. Backups contain note randomness and pending operation material and
123
+ must be kept under the same custody policy as the seed.
124
+
125
+ Private-swap outputs created with the current random-output design require the
126
+ durable journal or an encrypted backup for recovery. The frozen event does not
127
+ contain output randomness, so chain-only recovery of an output whose local
128
+ journal and backups are both lost is not possible without changing the wallet
129
+ protocol convention.
130
+
131
+ ## Lookup tables and transaction outcomes
132
+
133
+ Unshield and private swap require a validated v0 address lookup table and a
134
+ wallet adapter implementing `signVersionedTransaction`. If the requirement is
135
+ not met, the SDK throws `LookupTableRequiredError` before proving or signing.
136
+
137
+ For the audited Devnet fixture, configure
138
+ `FMVUyVx6byt3dVV7nmkbXbsu5fLQPM8gTdJwN5YYL9HC` with its frozen address list
139
+ and authority, as `e2e/fixture.mjs` does. That table places the stable
140
+ shielded-state, tree, custody, mint, token-program, and system accounts in the
141
+ LUT while recipient and recipient-ATA accounts remain dynamic. The arbitrary
142
+ recipient Private Send transaction measures 1078 bytes with this table; the
143
+ older partial table `2LDxX9aeVaQhTjcDtwBqCGzA8Nm9MGGCShwnGSKzDYwy` measures
144
+ 1233 bytes and must not be used for this flow.
145
+
146
+ Transactions are confirmed at finalized commitment. A confirmation response
147
+ with a non-null `value.err` is a finalized failure. Timeouts and incomplete
148
+ status are represented as an unknown/ambiguous outcome and must be reconciled;
149
+ a signature alone is not success.
150
+
151
+ ## Repository and license
152
+
153
+ The public source repository is
154
+ [`lethenymous/lethenymous-sdk`](https://github.com/lethenymous/lethenymous-sdk).
155
+ `@lethenymous/sdk` is distributed under the MIT License; see `LICENSE`. The
156
+ underlying zkCPMM repository is a separate project with its own license.
157
+
158
+ The repository's extracted development-history provenance is documented in
159
+ `MIGRATION.md`.
160
+
161
+ ## Security model
162
+
163
+ Spend secrets, view keys, note randomness, commitments, and proving witnesses
164
+ are sensitive. Do not log or upload them. RPC is transport/state access, not a
165
+ trusted prover. The witness provider accepts only finalized successful events
166
+ invoked by the configured zkCPMM program and fails closed on contradictory or
167
+ incomplete history.
168
+
169
+ Private Send is an SDK-level use of the existing arbitrary-recipient unshield
170
+ instruction. It does not hide the recipient, amount, asset, payer, timing, or
171
+ fact of withdrawal. Public recipient and transaction metadata remain visible
172
+ on chain.
@@ -0,0 +1,6 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import type { PoolState, ProtocolConfig, ShieldedState, TreeState } from "./types.js";
3
+ export declare function decodePool(data: Uint8Array, address?: PublicKey): PoolState;
4
+ export declare function decodeShieldedState(data: Uint8Array): ShieldedState;
5
+ export declare function decodeProtocolConfig(data: Uint8Array): ProtocolConfig;
6
+ export declare function decodeTreeState(data: Uint8Array): TreeState;
@@ -0,0 +1,75 @@
1
+ import { Reader } from "./encoding.js";
2
+ import { PublicKey } from "@solana/web3.js";
3
+ export function decodePool(data, address) {
4
+ if (data.length !== 364)
5
+ throw new Error("Invalid Pool account length");
6
+ const r = new Reader(data);
7
+ return {
8
+ address: address ?? PublicKey.default,
9
+ authority: r.pubkey(),
10
+ tokenAMint: r.pubkey(),
11
+ tokenBMint: r.pubkey(),
12
+ tokenAVault: r.pubkey(),
13
+ tokenBVault: r.pubkey(),
14
+ protocolFeeVaultA: r.pubkey(),
15
+ protocolFeeVaultB: r.pubkey(),
16
+ creatorFeeVaultA: r.pubkey(),
17
+ creatorFeeVaultB: r.pubkey(),
18
+ creatorFeeRecipient: r.pubkey(),
19
+ lpMint: r.pubkey(),
20
+ feeBps: r.u16(),
21
+ bump: r.u8(),
22
+ version: r.u8(),
23
+ swapNonce: r.u64(),
24
+ };
25
+ }
26
+ export function decodeShieldedState(data) {
27
+ if (data.length !== 194)
28
+ throw new Error("Invalid ShieldedState account length");
29
+ const r = new Reader(data);
30
+ return {
31
+ pool: r.pubkey(),
32
+ tokenAMint: r.pubkey(),
33
+ tokenBMint: r.pubkey(),
34
+ custodyA: r.pubkey(),
35
+ custodyB: r.pubkey(),
36
+ tree: r.pubkey(),
37
+ bump: r.u8(),
38
+ version: r.u8(),
39
+ };
40
+ }
41
+ export function decodeProtocolConfig(data) {
42
+ if (data.length !== 66)
43
+ throw new Error("Invalid ProtocolConfig account length");
44
+ const r = new Reader(data);
45
+ return {
46
+ authority: r.pubkey(),
47
+ feeRecipient: r.pubkey(),
48
+ bump: r.u8(),
49
+ version: r.u8(),
50
+ };
51
+ }
52
+ export function decodeTreeState(data) {
53
+ if (data.length !== 2664)
54
+ throw new Error("Invalid TreeState account length");
55
+ const r = new Reader(data);
56
+ const pool = r.pubkey(), generation = r.u64(), nextIndex = r.u64(), sequence = r.u64();
57
+ const frontier = Array.from({ length: 16 }, () => r.bytes(32));
58
+ const frontierPresent = Array.from({ length: 16 }, () => r.u8());
59
+ const emptySubtrees = Array.from({ length: 17 }, () => r.bytes(32));
60
+ const roots = Array.from({ length: 32 }, () => r.bytes(32));
61
+ const rootSequences = Array.from({ length: 32 }, () => r.u64());
62
+ const rootGenerations = Array.from({ length: 32 }, () => r.u64());
63
+ return {
64
+ pool,
65
+ generation,
66
+ nextIndex,
67
+ sequence,
68
+ frontier,
69
+ frontierPresent,
70
+ emptySubtrees,
71
+ roots,
72
+ rootSequences,
73
+ rootGenerations,
74
+ };
75
+ }
@@ -0,0 +1,73 @@
1
+ import { Connection, PublicKey, TransactionInstruction } from "@solana/web3.js";
2
+ import type { ClientConfig, MerkleWitnessProvider, NoteStore, PoolState, ProtocolConfig, ShieldedState, TransactionOutcome, TreeState, WalletAdapter, Prover, Direction } from "./types.js";
3
+ import { ShieldedWallet } from "./wallet.js";
4
+ export declare function transactionSignatureFromBytes(serialized: Uint8Array): string | undefined;
5
+ export declare class LookupTableRequiredError extends Error {
6
+ constructor();
7
+ }
8
+ export declare class TransactionFailedError extends Error {
9
+ readonly outcome: Extract<TransactionOutcome, {
10
+ status: "finalized-failed";
11
+ }>;
12
+ constructor(outcome: Extract<TransactionOutcome, {
13
+ status: "finalized-failed";
14
+ }>);
15
+ }
16
+ export declare class TransactionUnknownError extends Error {
17
+ readonly outcome: Extract<TransactionOutcome, {
18
+ status: "unknown";
19
+ }>;
20
+ constructor(outcome: Extract<TransactionOutcome, {
21
+ status: "unknown";
22
+ }>);
23
+ }
24
+ export interface SendOptions {
25
+ requireVersioned?: boolean;
26
+ onPrepared?: (signedTransaction: Uint8Array, lastValidBlockHeight: bigint) => Promise<void>;
27
+ onSubmitted?: (signature: string) => Promise<void>;
28
+ }
29
+ export interface ShieldedWalletOptions {
30
+ noteStore?: NoteStore;
31
+ storagePath?: string;
32
+ }
33
+ export declare class Lethenymous {
34
+ readonly connection: Connection;
35
+ readonly wallet: WalletAdapter;
36
+ readonly programId: PublicKey;
37
+ readonly witnessProvider?: MerkleWitnessProvider;
38
+ private readonly lookupTables;
39
+ private readonly lookupTableCache;
40
+ private readonly lookupTableLoads;
41
+ constructor(config: ClientConfig);
42
+ private account;
43
+ getPool(address: PublicKey): Promise<PoolState>;
44
+ getShieldedState(pool: PublicKey): Promise<ShieldedState>;
45
+ getTree(pool: PublicKey): Promise<TreeState>;
46
+ getProtocolConfig(): Promise<ProtocolConfig>;
47
+ getReserves(pool: PoolState): Promise<{
48
+ a: bigint;
49
+ b: bigint;
50
+ }>;
51
+ getLpSupply(pool: PoolState): Promise<bigint>;
52
+ private validatedTables;
53
+ buildAndSendOutcome(instructions: TransactionInstruction[], options?: SendOptions): Promise<TransactionOutcome>;
54
+ reconcileTransaction(signature: string, lastValidBlockHeight?: number, reason?: string): Promise<TransactionOutcome>;
55
+ hasFinalizedProgramEvent(signature: string, name: string, needles?: Uint8Array[]): Promise<boolean>;
56
+ buildAndSend(instructions: TransactionInstruction[], options?: SendOptions): Promise<string>;
57
+ initializePool(a: PublicKey, b: PublicKey, feeBps: number, creator?: PublicKey): Promise<string>;
58
+ initializeShieldedState(pool: PublicKey): Promise<string>;
59
+ private ata;
60
+ addLiquidity(poolAddress: PublicKey, amountA: bigint, amountB: bigint, minLp?: bigint): Promise<string>;
61
+ removeLiquidity(poolAddress: PublicKey, lpAmount: bigint, minA?: bigint, minB?: bigint): Promise<string>;
62
+ quote(poolAddress: PublicKey, direction: Direction, amountIn: bigint): Promise<bigint>;
63
+ swap(poolAddress: PublicKey, direction: Direction, amountIn: bigint, minAmountOut: bigint): Promise<string>;
64
+ ensureAta(mint: PublicKey, owner?: PublicKey, allowOwnerOffCurve?: boolean): Promise<PublicKey>;
65
+ ensureAtas(mintOwnerPairs: Array<{
66
+ mint: PublicKey;
67
+ owner: PublicKey;
68
+ allowOwnerOffCurve?: boolean;
69
+ }>): Promise<PublicKey[]>;
70
+ assertPrivateTransactionReady(): void;
71
+ validatePrivateTransactionReady(instructions: TransactionInstruction[]): Promise<void>;
72
+ shieldedWallet(seed: Uint8Array, prover?: Prover, options?: ShieldedWalletOptions): ShieldedWallet;
73
+ }