@ocash/sdk 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.
@@ -0,0 +1,1692 @@
1
+ import { Address, PublicClient } from 'viem';
2
+
3
+ type OperationStatus = 'created' | 'submitted' | 'confirmed' | 'failed';
4
+ type OperationType = 'deposit' | 'transfer' | 'withdraw' | (string & {});
5
+ type Hex$1 = `0x${string}`;
6
+ type ListOperationsQuery = {
7
+ limit?: number;
8
+ offset?: number;
9
+ chainId?: number;
10
+ tokenId?: string;
11
+ type?: OperationType | OperationType[];
12
+ status?: OperationStatus | OperationStatus[];
13
+ sort?: 'desc' | 'asc';
14
+ };
15
+ type DepositOperationDetail = {
16
+ token: string;
17
+ amount: string;
18
+ protocolFee?: string;
19
+ depositRelayerFee?: string;
20
+ inputCommitments?: Hex$1[];
21
+ outputCommitments?: Hex$1[];
22
+ };
23
+ type TransferOperationDetail = {
24
+ token: string;
25
+ amount: string;
26
+ fee?: string;
27
+ relayerFeeTotal?: string;
28
+ protocolFeeTotal?: string;
29
+ mergeCount?: number;
30
+ feeCount?: number;
31
+ to: Hex$1;
32
+ inputCommitments?: Hex$1[];
33
+ outputCommitments?: Hex$1[];
34
+ };
35
+ type WithdrawOperationDetail = {
36
+ token: string;
37
+ amount: string;
38
+ burnAmount?: string;
39
+ protocolFee?: string;
40
+ relayerFee?: string;
41
+ relayerFeeTotal?: string;
42
+ protocolFeeTotal?: string;
43
+ mergeCount?: number;
44
+ feeCount?: number;
45
+ recipient: Hex$1;
46
+ inputCommitments?: Hex$1[];
47
+ outputCommitments?: Hex$1[];
48
+ };
49
+ type BuiltinOperationDetailByType = {
50
+ deposit: DepositOperationDetail;
51
+ transfer: TransferOperationDetail;
52
+ withdraw: WithdrawOperationDetail;
53
+ };
54
+ type OperationDetailFor<TType extends OperationType> = TType extends keyof BuiltinOperationDetailByType ? BuiltinOperationDetailByType[TType] : Record<string, unknown>;
55
+ type StoredOperation<TDetail = Record<string, unknown>> = {
56
+ id: string;
57
+ type: OperationType;
58
+ createdAt: number;
59
+ chainId?: number;
60
+ tokenId?: string;
61
+ status: OperationStatus;
62
+ requestUrl?: string;
63
+ relayerTxHash?: `0x${string}`;
64
+ txHash?: `0x${string}`;
65
+ detail?: TDetail;
66
+ error?: string;
67
+ };
68
+ type OperationCreateInput<TType extends OperationType = OperationType> = Omit<StoredOperation<OperationDetailFor<TType>>, 'id' | 'createdAt' | 'status'> & Partial<Pick<StoredOperation<OperationDetailFor<TType>>, 'createdAt' | 'id' | 'status'>> & {
69
+ type: TType;
70
+ };
71
+ type DepositOperation = Omit<StoredOperation<DepositOperationDetail>, 'type'> & {
72
+ type: 'deposit';
73
+ detail?: DepositOperationDetail;
74
+ };
75
+ type TransferOperation = Omit<StoredOperation<TransferOperationDetail>, 'type'> & {
76
+ type: 'transfer';
77
+ detail?: TransferOperationDetail;
78
+ };
79
+ type WithdrawOperation = Omit<StoredOperation<WithdrawOperationDetail>, 'type'> & {
80
+ type: 'withdraw';
81
+ detail?: WithdrawOperationDetail;
82
+ };
83
+
84
+ type Hex = `0x${string}`;
85
+ type BigintLikeString = string;
86
+ type TransactionReceipt = Awaited<ReturnType<PublicClient['waitForTransactionReceipt']>>;
87
+ type SdkErrorCode = 'CONFIG' | 'ASSETS' | 'STORAGE' | 'SYNC' | 'CRYPTO' | 'MERKLE' | 'WITNESS' | 'PROOF' | 'RELAYER';
88
+ interface TokenMetadata {
89
+ id: string;
90
+ symbol: string;
91
+ decimals: number;
92
+ wrappedErc20: Address;
93
+ viewerPk: [string, string];
94
+ freezerPk: [string, string];
95
+ depositFeeBps?: number;
96
+ withdrawFeeBps?: number;
97
+ transferMaxAmount?: bigint | string;
98
+ withdrawMaxAmount?: bigint | string;
99
+ }
100
+ interface ChainConfigInput {
101
+ chainId: number;
102
+ rpcUrl?: string;
103
+ entryUrl?: string;
104
+ ocashContractAddress?: Address;
105
+ relayerUrl?: string;
106
+ merkleProofUrl?: string;
107
+ tokens?: TokenMetadata[];
108
+ /**
109
+ * Legacy fields: kept for compatibility with existing code/tests.
110
+ * Prefer `ocashContractAddress`.
111
+ */
112
+ contract?: Address;
113
+ }
114
+ interface RelayerFeeEntry {
115
+ token_address: Hex;
116
+ fee: bigint;
117
+ }
118
+ interface RelayerFeeConfigure {
119
+ valid_time: number;
120
+ transfer: Record<string, RelayerFeeEntry>;
121
+ withdraw: Record<string, RelayerFeeEntry>;
122
+ }
123
+ interface RelayerConfig {
124
+ config: {
125
+ contract_address: Address;
126
+ chain_id: number;
127
+ name: string;
128
+ relayer_address: Address;
129
+ img_url?: string;
130
+ submit_timeout?: number;
131
+ };
132
+ fee_configure: RelayerFeeConfigure;
133
+ fetched_at?: number;
134
+ }
135
+ interface MemoWorkerConfig {
136
+ workerUrl?: string;
137
+ concurrency?: number;
138
+ type?: 'classic' | 'module';
139
+ }
140
+ type AssetOverrideEntry = string | string[];
141
+ interface AssetsOverride {
142
+ [filename: string]: AssetOverrideEntry;
143
+ }
144
+ interface OCashSdkConfig {
145
+ chains: ChainConfigInput[];
146
+ assetsOverride?: AssetsOverride;
147
+ memoWorker?: MemoWorkerConfig;
148
+ cacheDir?: string;
149
+ runtime?: 'auto' | 'browser' | 'node' | 'hybrid';
150
+ storage?: StorageAdapter;
151
+ merkle?: {
152
+ /**
153
+ * `remote`: always use `chain.merkleProofUrl`.
154
+ * `local`: always use locally built merkle (requires feeding all leaves).
155
+ * `hybrid`: prefer local, fallback to remote if missing.
156
+ */
157
+ mode?: 'remote' | 'local' | 'hybrid';
158
+ /**
159
+ * Merkle depth used by the on-chain tree (defaults to 32).
160
+ */
161
+ treeDepth?: number;
162
+ };
163
+ sync?: {
164
+ pageSize?: number;
165
+ pollMs?: number;
166
+ requestTimeoutMs?: number;
167
+ /**
168
+ * Optional network retry policy for sync requests (Entry/Merkle).
169
+ * Defaults to no retries.
170
+ */
171
+ retry?: {
172
+ attempts?: number;
173
+ baseDelayMs?: number;
174
+ maxDelayMs?: number;
175
+ };
176
+ };
177
+ onEvent?: (event: SdkEvent) => void;
178
+ }
179
+ interface SdkErrorPayload {
180
+ code: SdkErrorCode;
181
+ message: string;
182
+ detail?: unknown;
183
+ cause?: unknown;
184
+ }
185
+ type SdkEvent = {
186
+ type: 'core:ready';
187
+ payload: {
188
+ assetsVersion: string;
189
+ durationMs: number;
190
+ };
191
+ } | {
192
+ type: 'core:progress';
193
+ payload: {
194
+ stage: 'fetch' | 'compile' | 'init';
195
+ loaded: number;
196
+ total?: number;
197
+ };
198
+ } | {
199
+ type: 'sync:start';
200
+ payload: {
201
+ chainId: number;
202
+ source: 'entry' | 'rpc' | 'subgraph';
203
+ };
204
+ } | {
205
+ type: 'sync:progress';
206
+ payload: {
207
+ chainId: number;
208
+ resource: 'memo' | 'nullifier' | 'merkle';
209
+ downloaded: number;
210
+ total?: number;
211
+ };
212
+ } | {
213
+ type: 'sync:done';
214
+ payload: {
215
+ chainId: number;
216
+ cursor: SyncCursor;
217
+ };
218
+ } | {
219
+ type: 'debug';
220
+ payload: {
221
+ scope: string;
222
+ message: string;
223
+ detail?: unknown;
224
+ };
225
+ } | {
226
+ type: 'operations:update';
227
+ payload: {
228
+ action: 'create' | 'update';
229
+ operationId?: string;
230
+ patch?: Partial<StoredOperation>;
231
+ operation?: StoredOperation;
232
+ };
233
+ }
234
+ /**
235
+ * UTXO state changed due to memo/nullifier sync.
236
+ *
237
+ * `added` is the number of (unique) UTXOs upserted in this batch after local validation/decryption;
238
+ * it is not guaranteed to equal "newly discovered" rows (may include updates/duplicates).
239
+ */
240
+ | {
241
+ type: 'wallet:utxo:update';
242
+ payload: {
243
+ chainId: number;
244
+ added: number;
245
+ spent: number;
246
+ frozen: number;
247
+ };
248
+ } | {
249
+ type: 'assets:update';
250
+ payload: {
251
+ chainId: number;
252
+ kind: 'token' | 'pool' | 'relayer';
253
+ };
254
+ } | {
255
+ type: 'zkp:start';
256
+ payload: {
257
+ circuit: 'transfer' | 'withdraw';
258
+ };
259
+ } | {
260
+ type: 'zkp:done';
261
+ payload: {
262
+ circuit: 'transfer' | 'withdraw';
263
+ costMs: number;
264
+ };
265
+ } | {
266
+ type: 'error';
267
+ payload: SdkErrorPayload;
268
+ };
269
+ interface CommitmentData {
270
+ asset_id: bigint;
271
+ asset_amount: bigint;
272
+ user_pk: {
273
+ user_address: [bigint, bigint];
274
+ };
275
+ blinding_factor: bigint;
276
+ is_frozen: boolean;
277
+ }
278
+ interface MemoDecryptRequest {
279
+ memo: Hex;
280
+ secretKey: bigint;
281
+ metadata?: Record<string, unknown>;
282
+ }
283
+ interface MemoDecryptResult {
284
+ memo: Hex;
285
+ record: CommitmentData | null;
286
+ metadata?: Record<string, unknown>;
287
+ error?: {
288
+ message: string;
289
+ };
290
+ }
291
+ interface AccMemberWitness {
292
+ /**
293
+ * Circuits witness format (matches `circuits/pkg/core/policies/witness_json.go`):
294
+ * - `root`: merkle root
295
+ * - `path`: merkle proof path (leaf at index 0, then sibling nodes)
296
+ * - `index`: leaf index
297
+ */
298
+ root: Hex | BigintLikeString;
299
+ path: Array<Hex | BigintLikeString>;
300
+ index: number;
301
+ }
302
+ interface InputSecret {
303
+ owner_keypair: {
304
+ user_pk: {
305
+ user_address: [bigint, bigint];
306
+ aead_encryption_key?: Hex;
307
+ };
308
+ user_sk: {
309
+ /**
310
+ * Witness payloads can be either raw bigint values (from local key derivation)
311
+ * or decimal strings (from wasm/json bridges).
312
+ */
313
+ address_sk: bigint | BigintLikeString;
314
+ aead_decryption_key?: Hex;
315
+ };
316
+ };
317
+ ro: CommitmentData;
318
+ acc_member_witness: AccMemberWitness;
319
+ }
320
+ interface FrPointJson {
321
+ X: bigint;
322
+ Y: bigint;
323
+ }
324
+ interface ViewerPkJson {
325
+ EncryptionKey: {
326
+ Key: FrPointJson;
327
+ };
328
+ }
329
+ interface FreezerPkJson {
330
+ Point: FrPointJson;
331
+ }
332
+ interface TransferWitnessInput {
333
+ asset_id: string;
334
+ asset_token_id: string;
335
+ asset_policy: {
336
+ viewer_pk: ViewerPkJson;
337
+ freezer_pk: FreezerPkJson;
338
+ };
339
+ input_secrets: InputSecret[];
340
+ array: Hex[];
341
+ fee: bigint;
342
+ max_amount: bigint;
343
+ output_record_openings: CommitmentData[];
344
+ viewing_memo_randomness?: Uint8Array | number[];
345
+ proof_binding?: string;
346
+ }
347
+ interface WithdrawWitnessInput {
348
+ asset_id: string;
349
+ asset_token_id: string;
350
+ asset_policy: {
351
+ viewer_pk: ViewerPkJson;
352
+ freezer_pk: FreezerPkJson;
353
+ };
354
+ input_secret: InputSecret;
355
+ output_record_opening: CommitmentData;
356
+ array: Hex[];
357
+ amount: bigint;
358
+ relayer_fee: bigint;
359
+ gas_drop_value: bigint;
360
+ viewing_memo_randomness?: Uint8Array | number[];
361
+ proof_binding?: string;
362
+ }
363
+ interface WitnessBuildResult {
364
+ witness: TransferWitnessInput | WithdrawWitnessInput | Record<string, any>;
365
+ array_hash_index?: number;
366
+ merkle_root_index?: number;
367
+ relayer?: string;
368
+ extra_data?: WitnessExtraData;
369
+ relayer_fee?: bigint;
370
+ gas_drop_value?: bigint;
371
+ array_hash_digest?: Hex;
372
+ witness_type?: 'transfer' | 'withdraw';
373
+ warnings?: string[];
374
+ }
375
+ interface WitnessContext {
376
+ array_hash_index?: number;
377
+ merkle_root_index?: number;
378
+ relayer?: string;
379
+ extra_data?: WitnessExtraData;
380
+ relayer_fee?: bigint;
381
+ gas_drop_value?: bigint;
382
+ array_hash_digest?: Hex;
383
+ recipient?: Address;
384
+ withdraw_amount?: bigint;
385
+ }
386
+ interface ProofResult {
387
+ proof: [string, string, string, string, string, string, string, string];
388
+ flatten_input: string[];
389
+ public_input?: Record<string, any>;
390
+ array_hash_index?: number;
391
+ merkle_root_index?: number;
392
+ relayer?: string;
393
+ recipient?: Address;
394
+ withdraw_amount?: bigint;
395
+ extra_data?: WitnessExtraData;
396
+ relayer_fee?: bigint;
397
+ gas_drop_value?: bigint;
398
+ array_hash_digest?: Hex;
399
+ gnark_output?: unknown;
400
+ witness_json?: Record<string, any>;
401
+ err?: {
402
+ message: string;
403
+ stack?: string;
404
+ } | null;
405
+ warnings?: string[];
406
+ }
407
+ type TransferExtraData = readonly [Hex, Hex, Hex];
408
+ type WithdrawExtraData = Hex;
409
+ type WitnessExtraData = TransferExtraData | WithdrawExtraData;
410
+ interface ProofBridge {
411
+ init(): Promise<void>;
412
+ initTransfer(): Promise<void>;
413
+ initWithdraw(): Promise<void>;
414
+ proveTransfer(witness: string): Promise<string>;
415
+ proveWithdraw(witness: string): Promise<string>;
416
+ createMemo(ro: CommitmentData): Hex;
417
+ decryptMemo(secretKey: bigint, memo: Hex): CommitmentData | null;
418
+ commitment(ro: CommitmentData, format?: 'hex' | 'bigint'): Hex | bigint;
419
+ nullifier(secretKey: bigint, commitment: Hex, freezerPk?: [bigint, bigint]): Hex;
420
+ createDummyRecordOpening(): Promise<CommitmentData>;
421
+ createDummyInputSecret(): Promise<InputSecret>;
422
+ }
423
+ interface CommitmentFn {
424
+ (ro: CommitmentData, format: 'hex'): Hex;
425
+ (ro: CommitmentData, format: 'bigint'): bigint;
426
+ (ro: CommitmentData, format?: undefined): Hex;
427
+ }
428
+ interface SyncCursor {
429
+ memo: number;
430
+ nullifier: number;
431
+ /**
432
+ * Merkle cursor is the merkle root index (batch cursor), derived from memo sync (total elements).
433
+ * The root index typically advances only after a full batch (e.g. 32 leaves), so it will not equal `memo`.
434
+ */
435
+ merkle: number;
436
+ }
437
+ interface SyncChainStatus {
438
+ memo: {
439
+ status: 'idle' | 'syncing' | 'synced' | 'error';
440
+ downloaded: number;
441
+ total?: number;
442
+ errorMessage?: string;
443
+ };
444
+ nullifier: {
445
+ status: 'idle' | 'syncing' | 'synced' | 'error';
446
+ downloaded: number;
447
+ total?: number;
448
+ errorMessage?: string;
449
+ };
450
+ merkle: {
451
+ status: 'idle' | 'syncing' | 'synced' | 'error';
452
+ cursor: number;
453
+ errorMessage?: string;
454
+ };
455
+ }
456
+ type ListUtxosQuery = {
457
+ /** Filter by chain id. */
458
+ chainId?: number;
459
+ /** Filter by shielded asset id (pool id). */
460
+ assetId?: string;
461
+ /** Include spent UTXOs (default: false). */
462
+ includeSpent?: boolean;
463
+ /** Include frozen UTXOs (default: false). */
464
+ includeFrozen?: boolean;
465
+ /** Filter by spent flag (overrides includeSpent when set). */
466
+ spent?: boolean;
467
+ /** Filter by frozen flag (overrides includeFrozen when set). */
468
+ frozen?: boolean;
469
+ /** Result pagination offset (default: 0). */
470
+ offset?: number;
471
+ /** Result pagination limit (default: no limit). */
472
+ limit?: number;
473
+ /** Order by field (default: mkIndex). */
474
+ orderBy?: 'mkIndex' | 'createdAt';
475
+ /** Order direction (default: asc). */
476
+ order?: 'asc' | 'desc';
477
+ };
478
+ type EntryMemoRecord = {
479
+ /** Chain id (scoped). */
480
+ chainId: number;
481
+ /** Entry cid (memo index). */
482
+ cid: number;
483
+ /** Commitment of the leaf. */
484
+ commitment: Hex;
485
+ /** Encrypted memo payload. */
486
+ memo: Hex;
487
+ /** EntryService memo transparency flag. */
488
+ isTransparent?: boolean;
489
+ /** Optional transparent asset id override (hex). */
490
+ assetId?: Hex | null;
491
+ /** Optional transparent amount override (hex). */
492
+ amount?: Hex | null;
493
+ /** Optional transparent partial hash. */
494
+ partialHash?: Hex | null;
495
+ /** Optional transaction hash. */
496
+ txHash?: Hex | null;
497
+ /** Optional created_at from EntryService. */
498
+ createdAt?: number | null;
499
+ };
500
+ type EntryNullifierRecord = {
501
+ /** Chain id (scoped). */
502
+ chainId: number;
503
+ /**
504
+ * Nullifier index in EntryService ordering (stable for pagination).
505
+ * This is derived from `list_by_block` pagination offsets.
506
+ */
507
+ nid: number;
508
+ /** Nullifier value. */
509
+ nullifier: Hex;
510
+ /** Optional created_at from EntryService. */
511
+ createdAt?: number | null;
512
+ };
513
+ type ListEntryMemosQuery = {
514
+ chainId: number;
515
+ /** Start cid (inclusive). Defaults to 0. */
516
+ offset?: number;
517
+ /** Max rows to return. */
518
+ limit?: number;
519
+ /** Order by field (default: cid). */
520
+ orderBy?: 'cid' | 'createdAt';
521
+ /** Order direction (default: asc). */
522
+ order?: 'asc' | 'desc';
523
+ /** Filter by cid range (inclusive). */
524
+ cidFrom?: number;
525
+ /** Filter by cid range (inclusive). */
526
+ cidTo?: number;
527
+ /** Filter by createdAt range (inclusive, epoch). */
528
+ createdAtFrom?: number;
529
+ /** Filter by createdAt range (inclusive, epoch). */
530
+ createdAtTo?: number;
531
+ };
532
+ type ListEntryNullifiersQuery = {
533
+ chainId: number;
534
+ /** nid offset (defaults to 0). */
535
+ offset?: number;
536
+ /** Max rows to return. */
537
+ limit?: number;
538
+ /** Order by field (default: nid). */
539
+ orderBy?: 'nid' | 'createdAt';
540
+ /** Order direction (default: asc). */
541
+ order?: 'asc' | 'desc';
542
+ /** Filter by nid range (inclusive). */
543
+ nidFrom?: number;
544
+ /** Filter by nid range (inclusive). */
545
+ nidTo?: number;
546
+ /** Filter by createdAt range (inclusive, epoch). */
547
+ createdAtFrom?: number;
548
+ /** Filter by createdAt range (inclusive, epoch). */
549
+ createdAtTo?: number;
550
+ };
551
+ type ListEntryMemosResult = {
552
+ total: number;
553
+ rows: EntryMemoRecord[];
554
+ };
555
+ type ListEntryNullifiersResult = {
556
+ total: number;
557
+ rows: EntryNullifierRecord[];
558
+ };
559
+ type ListUtxosResult = {
560
+ total: number;
561
+ rows: UtxoRecord[];
562
+ };
563
+ type MerkleTreeState = {
564
+ /** Chain id (scoped). */
565
+ chainId: number;
566
+ /** Current tree root (for the merged/main tree). */
567
+ root: Hex;
568
+ /**
569
+ * Total elements that have been merged into the main tree.
570
+ * This matches `totalElementsInTree(contract.totalElements, tempArraySize)`.
571
+ */
572
+ totalElements: number;
573
+ /** Last updated timestamp (ms). */
574
+ lastUpdated: number;
575
+ };
576
+ type MerkleLeafRecord = {
577
+ chainId: number;
578
+ cid: number;
579
+ commitment: Hex;
580
+ };
581
+ type MerkleNodeRecord = {
582
+ chainId: number;
583
+ /**
584
+ * Node id.
585
+ * - Normal node: `${level}-${position}`
586
+ * - Frontier node: `frontier-${level}`
587
+ */
588
+ id: string;
589
+ level: number;
590
+ position: number;
591
+ hash: Hex;
592
+ };
593
+ interface StorageAdapter {
594
+ /**
595
+ * Initialize adapter state, optionally scoping storage by wallet id.
596
+ * Implementations should clear any cached state when `walletId` changes.
597
+ */
598
+ init?(options?: {
599
+ walletId?: string;
600
+ }): Promise<void> | void;
601
+ /** Close connections / flush pending writes. */
602
+ close?(): Promise<void> | void;
603
+ /** Read the last synced cursor for a chain. */
604
+ getSyncCursor(chainId: number): Promise<SyncCursor | undefined>;
605
+ /** Persist the current sync cursor for a chain. */
606
+ setSyncCursor(chainId: number, cursor: SyncCursor): Promise<void>;
607
+ /**
608
+ * Insert or update UTXO records by `(chainId, commitment)`.
609
+ * Implementations should preserve `isSpent` when upserting the same UTXO.
610
+ */
611
+ upsertUtxos(utxos: UtxoRecord[]): Promise<void>;
612
+ /**
613
+ * List UTXOs with optional filters and pagination.
614
+ * Pagination is applied after filtering.
615
+ */
616
+ listUtxos(query?: ListUtxosQuery): Promise<ListUtxosResult>;
617
+ /**
618
+ * Mark matching UTXOs as spent by nullifier.
619
+ * @returns number of updated records.
620
+ */
621
+ markSpent(input: {
622
+ chainId: number;
623
+ nullifiers: Hex[];
624
+ }): Promise<number>;
625
+ /**
626
+ * Create a local operation record (e.g. deposit/transfer/withdraw).
627
+ * Implementations should generate `id`, `createdAt`, and default `status` if missing.
628
+ */
629
+ createOperation<TType extends OperationType>(input: OperationCreateInput<TType>): StoredOperation<OperationDetailFor<TType>> & {
630
+ type: TType;
631
+ };
632
+ /** Update an existing operation record by id (best-effort). */
633
+ updateOperation(id: string, patch: Partial<StoredOperation>): void;
634
+ /** List operations with optional query (`limit`/`offset`/filters). */
635
+ listOperations(input?: number | ListOperationsQuery): StoredOperation[];
636
+ /**
637
+ * Optional governance helpers for long-lived apps.
638
+ * Implementations may persist changes best-effort.
639
+ */
640
+ deleteOperation?(id: string): Promise<boolean> | boolean;
641
+ clearOperations?(): Promise<void> | void;
642
+ pruneOperations?(options?: {
643
+ max?: number;
644
+ }): Promise<number> | number;
645
+ /**
646
+ * Optional merkle leaf persistence for `MerkleEngine` local/hybrid modes.
647
+ * Leaves are expected to be contiguous and cid-ordered (starting at 0).
648
+ * Implementations may store them best-effort.
649
+ */
650
+ getMerkleLeaves?(chainId: number): Promise<Array<{
651
+ cid: number;
652
+ commitment: Hex;
653
+ }> | undefined>;
654
+ appendMerkleLeaves?(chainId: number, leaves: Array<{
655
+ cid: number;
656
+ commitment: Hex;
657
+ }>): Promise<void>;
658
+ clearMerkleLeaves?(chainId: number): Promise<void>;
659
+ /**
660
+ * Optional Merkle DB: leaf lookup by cid (fast path for proof generation).
661
+ */
662
+ getMerkleLeaf?(chainId: number, cid: number): Promise<MerkleLeafRecord | undefined>;
663
+ /**
664
+ * Optional Merkle DB: node lookup by id (fast path for proof generation and incremental updates).
665
+ */
666
+ getMerkleNode?(chainId: number, id: string): Promise<MerkleNodeRecord | undefined>;
667
+ upsertMerkleNodes?(chainId: number, nodes: MerkleNodeRecord[]): Promise<void>;
668
+ clearMerkleNodes?(chainId: number): Promise<void>;
669
+ /**
670
+ * Optional entry memo persistence (raw EntryService payloads).
671
+ * Useful for debugging, rebuilds, and app-like local caches.
672
+ */
673
+ upsertEntryMemos?(memos: EntryMemoRecord[]): Promise<number> | number;
674
+ listEntryMemos?(query: ListEntryMemosQuery): Promise<ListEntryMemosResult>;
675
+ clearEntryMemos?(chainId: number): Promise<void> | void;
676
+ /**
677
+ * Optional entry nullifier persistence (raw EntryService payloads).
678
+ * Useful for debugging and app-like local caches.
679
+ */
680
+ upsertEntryNullifiers?(nullifiers: EntryNullifierRecord[]): Promise<number> | number;
681
+ listEntryNullifiers?(query: ListEntryNullifiersQuery): Promise<ListEntryNullifiersResult>;
682
+ clearEntryNullifiers?(chainId: number): Promise<void> | void;
683
+ /**
684
+ * Optional merkle tree state persistence (merged/main-tree only).
685
+ * This mirrors the client/app `MerkleDexie.trees` metadata.
686
+ */
687
+ getMerkleTree?(chainId: number): Promise<MerkleTreeState | undefined>;
688
+ setMerkleTree?(chainId: number, tree: MerkleTreeState): Promise<void>;
689
+ clearMerkleTree?(chainId: number): Promise<void>;
690
+ }
691
+ interface CoreApi {
692
+ ready: (onProgress?: (value: number) => void) => Promise<void>;
693
+ reset: () => void;
694
+ on: (type: SdkEvent['type'], handler: (event: SdkEvent) => void) => void;
695
+ off: (type: SdkEvent['type'], handler: (event: SdkEvent) => void) => void;
696
+ }
697
+ interface CryptoApi {
698
+ commitment: CommitmentFn;
699
+ nullifier: (secretKey: bigint, commitment: Hex, freezerPk?: [bigint, bigint]) => Hex;
700
+ createRecordOpening: (input: {
701
+ asset_id: bigint | number | string;
702
+ asset_amount: bigint | number | string;
703
+ user_pk: {
704
+ user_address: [bigint | number | string, bigint | number | string];
705
+ };
706
+ blinding_factor?: bigint | number | string;
707
+ is_frozen?: boolean;
708
+ }) => CommitmentData;
709
+ poolId: (tokenAddress: Hex | bigint | number | string, viewerPk: [bigint, bigint], freezerPk: [bigint, bigint]) => bigint;
710
+ viewingRandomness: () => Uint8Array;
711
+ memo: {
712
+ createMemo: (ro: CommitmentData) => Hex;
713
+ memoNonce: (ephemeralPublicKey: [bigint, bigint], userPublicKey: [bigint, bigint]) => Uint8Array;
714
+ decryptMemo: (secretKey: bigint, memo: Hex) => CommitmentData | null;
715
+ decryptBatch: (requests: MemoDecryptRequest[]) => Promise<MemoDecryptResult[]>;
716
+ };
717
+ dummy: {
718
+ createRecordOpening: () => Promise<CommitmentData>;
719
+ createInputSecret: () => Promise<InputSecret>;
720
+ };
721
+ utils: {
722
+ calcDepositFee: (amount: bigint, feeBps?: number) => bigint;
723
+ randomBytes32: () => Uint8Array;
724
+ randomBytes32Bigint: (isScalar?: boolean) => bigint;
725
+ serializeBigInt: <T>(value: T) => string;
726
+ };
727
+ }
728
+ interface KeysApi {
729
+ deriveKeyPair: (seed: string, nonce?: string) => UserKeyPair;
730
+ getSecretKeyBySeed: (seed: string, nonce?: string) => UserSecretKey;
731
+ getPublicKeyBySeed: (seed: string, nonce?: string) => UserPublicKey;
732
+ userPkToAddress: (userPk: {
733
+ user_address: [bigint | string, bigint | string];
734
+ }) => Hex;
735
+ addressToUserPk: (address: Hex) => {
736
+ user_address: [bigint, bigint];
737
+ };
738
+ }
739
+ interface AssetsApi {
740
+ getChains: () => ChainConfigInput[];
741
+ getChain: (chainId: number) => ChainConfigInput;
742
+ getTokens: (chainId: number) => TokenMetadata[];
743
+ getPoolInfo: (chainId: number, tokenId: string) => TokenMetadata | undefined;
744
+ getAllowanceTarget: (chainId: number) => Address;
745
+ appendTokens: (chainId: number, tokens: TokenMetadata[]) => void;
746
+ loadFromUrl: (url: string) => Promise<void>;
747
+ getRelayerConfig: (chainId: number) => RelayerConfig | undefined;
748
+ syncRelayerConfig: (chainId: number) => Promise<RelayerConfig>;
749
+ syncAllRelayerConfigs: () => Promise<void>;
750
+ }
751
+ interface StorageApi {
752
+ getAdapter: () => StorageAdapter;
753
+ }
754
+ interface SyncApi {
755
+ start(options?: {
756
+ chainIds?: number[];
757
+ pollMs?: number;
758
+ }): Promise<void>;
759
+ stop(): void;
760
+ syncOnce(options?: {
761
+ chainIds?: number[];
762
+ resources?: Array<'memo' | 'nullifier' | 'merkle'>;
763
+ signal?: AbortSignal;
764
+ requestTimeoutMs?: number;
765
+ pageSize?: number;
766
+ continueOnError?: boolean;
767
+ }): Promise<void>;
768
+ getStatus(): Record<number, SyncChainStatus>;
769
+ }
770
+ interface RemoteMerkleProofResponse {
771
+ proof: Array<{
772
+ path: Array<Hex | BigintLikeString>;
773
+ leaf_index: string | number;
774
+ }>;
775
+ merkle_root: Hex | BigintLikeString;
776
+ latest_cid: number;
777
+ }
778
+ interface MerkleApi {
779
+ currentMerkleRootIndex: (totalElements: number, tempArraySize?: number) => number;
780
+ /**
781
+ * Get Merkle proofs by cid with local-first fallback behavior.
782
+ *
783
+ * Notes (mirrors client/app behavior):
784
+ * - First try to build proofs locally (if enabled and available).
785
+ * - If local proof is missing for some cids, check whether those cids are still in the on-chain buffer
786
+ * (i.e. not yet merged into the main tree); such cids do not require remote proof fetching.
787
+ * - Otherwise, fetch missing proofs from the remote proof service.
788
+ */
789
+ getProofByCids: (input: {
790
+ chainId: number;
791
+ cids: number[];
792
+ totalElements: bigint;
793
+ }) => Promise<RemoteMerkleProofResponse>;
794
+ /** Convenience wrapper for single cid. */
795
+ getProofByCid: (input: {
796
+ chainId: number;
797
+ cid: number;
798
+ totalElements: bigint;
799
+ }) => Promise<RemoteMerkleProofResponse>;
800
+ /**
801
+ * Optional helper for building a local Merkle tree from contiguous Entry memo pages.
802
+ * When supported by the implementation, callers may feed memo batches to enable local proof generation.
803
+ */
804
+ ingestEntryMemos?: (chainId: number, memos: Array<{
805
+ cid: number | null;
806
+ commitment: Hex | string | bigint;
807
+ }>) => Promise<void> | void;
808
+ buildAccMemberWitnesses: (input: {
809
+ remote: RemoteMerkleProofResponse;
810
+ utxos: Array<{
811
+ commitment: Hex;
812
+ mkIndex: number;
813
+ }>;
814
+ arrayHash: bigint;
815
+ totalElements: bigint;
816
+ }) => AccMemberWitness[];
817
+ buildInputSecretsFromUtxos: (input: {
818
+ remote: RemoteMerkleProofResponse;
819
+ utxos: Array<{
820
+ commitment: Hex;
821
+ memo?: Hex;
822
+ mkIndex: number;
823
+ }>;
824
+ ownerKeyPair: UserKeyPair;
825
+ arrayHash: bigint;
826
+ totalElements: bigint;
827
+ /**
828
+ * Transfer circuit uses fixed `maxInputs=3`. When provided, the implementation pads the returned
829
+ * list with dummy input secrets to reach this length (and errors if utxos exceed it).
830
+ */
831
+ maxInputs?: number;
832
+ }) => Promise<InputSecret[]>;
833
+ }
834
+ interface WalletSessionInput {
835
+ seed: string | Uint8Array;
836
+ accountNonce?: number;
837
+ }
838
+ interface UtxoRecord {
839
+ chainId: number;
840
+ assetId: string;
841
+ amount: bigint;
842
+ commitment: Hex;
843
+ nullifier: Hex;
844
+ mkIndex: number;
845
+ isFrozen: boolean;
846
+ isSpent: boolean;
847
+ memo?: Hex;
848
+ createdAt?: number;
849
+ }
850
+ interface WalletApi {
851
+ open(session: WalletSessionInput): Promise<void>;
852
+ close(): Promise<void>;
853
+ getUtxos(query?: ListUtxosQuery): Promise<ListUtxosResult>;
854
+ getBalance(query?: {
855
+ chainId?: number;
856
+ assetId?: string;
857
+ }): Promise<bigint>;
858
+ markSpent(input: {
859
+ chainId: number;
860
+ nullifiers: Hex[];
861
+ }): Promise<void>;
862
+ }
863
+ type PlannerEstimateTransferResult = {
864
+ action: 'transfer';
865
+ chainId: number;
866
+ assetId: string;
867
+ sendAmount: bigint;
868
+ relayerFee: bigint;
869
+ required: bigint;
870
+ selectedInputs: UtxoRecord[];
871
+ selectedSum: bigint;
872
+ ok: boolean;
873
+ okWithMerge: boolean;
874
+ feeSummary: PlannerFeeSummary;
875
+ maxSummary: PlannerFeeSummary;
876
+ constraints: {
877
+ maxInputs: number;
878
+ };
879
+ };
880
+ type PlannerEstimateWithdrawResult = {
881
+ action: 'withdraw';
882
+ chainId: number;
883
+ assetId: string;
884
+ requestedAmount: bigint;
885
+ relayerFee: bigint;
886
+ protocolFee: bigint;
887
+ burnAmount: bigint;
888
+ selectedInput: UtxoRecord | null;
889
+ ok: boolean;
890
+ okWithMerge: boolean;
891
+ feeSummary: PlannerFeeSummary;
892
+ maxSummary: PlannerFeeSummary;
893
+ constraints: {
894
+ requiresSingleInput: true;
895
+ };
896
+ };
897
+ type PlannerEstimateResult = PlannerEstimateTransferResult | PlannerEstimateWithdrawResult;
898
+ type PlannerFeeSummary = {
899
+ mergeCount: number;
900
+ feeCount: number;
901
+ relayerFeeTotal: bigint;
902
+ protocolFeeTotal: bigint;
903
+ totalInput: bigint;
904
+ outputAmount: bigint;
905
+ cost: bigint;
906
+ inputCount: number;
907
+ };
908
+ type PlannerMaxEstimateResult = {
909
+ action: 'transfer' | 'withdraw';
910
+ chainId: number;
911
+ assetId: string;
912
+ ok: boolean;
913
+ maxSummary: PlannerFeeSummary;
914
+ };
915
+ type TransferPlan = {
916
+ action: 'transfer';
917
+ chainId: number;
918
+ assetId: string;
919
+ token: TokenMetadata;
920
+ requestedAmount: bigint;
921
+ sendAmount: bigint;
922
+ to: Hex;
923
+ relayer: Address;
924
+ relayerUrl?: string;
925
+ relayerFee: bigint;
926
+ required: bigint;
927
+ okWithMerge: boolean;
928
+ feeSummary: PlannerFeeSummary;
929
+ maxSummary: PlannerFeeSummary;
930
+ selectedInputs: UtxoRecord[];
931
+ selectedSum: bigint;
932
+ outputs: readonly [CommitmentData, CommitmentData, CommitmentData];
933
+ extraData: readonly [Hex, Hex, Hex];
934
+ proofBinding: string;
935
+ };
936
+ type TransferMergePlan = {
937
+ action: 'transfer-merge';
938
+ chainId: number;
939
+ assetId: string;
940
+ requestedAmount: bigint;
941
+ sendAmount: bigint;
942
+ to: Hex;
943
+ relayer: Address;
944
+ relayerUrl?: string;
945
+ relayerFee: bigint;
946
+ required: bigint;
947
+ okWithMerge: boolean;
948
+ feeSummary: PlannerFeeSummary;
949
+ maxSummary: PlannerFeeSummary;
950
+ mergePlan: TransferPlan;
951
+ };
952
+ type WithdrawPlan = {
953
+ action: 'withdraw';
954
+ chainId: number;
955
+ assetId: string;
956
+ token: TokenMetadata;
957
+ requestedAmount: bigint;
958
+ relayer: Address;
959
+ relayerUrl?: string;
960
+ relayerFee: bigint;
961
+ protocolFee: bigint;
962
+ burnAmount: bigint;
963
+ gasDropValue: bigint;
964
+ okWithMerge: boolean;
965
+ feeSummary: PlannerFeeSummary;
966
+ maxSummary: PlannerFeeSummary;
967
+ selectedInput: UtxoRecord;
968
+ outputRecordOpening: CommitmentData;
969
+ extraData: Hex;
970
+ proofBinding: string;
971
+ recipient: Hex;
972
+ };
973
+ type PlannerPlanResult = TransferPlan | TransferMergePlan | WithdrawPlan;
974
+ interface PlannerApi {
975
+ estimate(input: {
976
+ chainId: number;
977
+ assetId: string;
978
+ action: 'transfer' | 'withdraw';
979
+ amount: bigint;
980
+ payIncludesFee?: boolean;
981
+ }): Promise<PlannerEstimateResult>;
982
+ estimateMax(input: {
983
+ chainId: number;
984
+ assetId: string;
985
+ action: 'transfer' | 'withdraw';
986
+ payIncludesFee?: boolean;
987
+ }): Promise<PlannerMaxEstimateResult>;
988
+ plan(input: Record<string, unknown>): Promise<PlannerPlanResult>;
989
+ }
990
+ interface ZkpApi {
991
+ createWitnessTransfer: (input: TransferWitnessInput, context?: WitnessContext) => Promise<WitnessBuildResult>;
992
+ createWitnessWithdraw: (input: WithdrawWitnessInput, context?: WitnessContext) => Promise<WitnessBuildResult>;
993
+ proveTransfer: (witness: TransferWitnessInput | string, context?: WitnessContext) => Promise<ProofResult>;
994
+ proveWithdraw: (witness: WithdrawWitnessInput | string, context?: WitnessContext) => Promise<ProofResult>;
995
+ }
996
+ interface RelayerRequest {
997
+ kind: 'relayer';
998
+ method: 'POST';
999
+ path: string;
1000
+ body: Record<string, unknown>;
1001
+ }
1002
+ interface TxBuilderApi {
1003
+ buildTransferCalldata: (input: {
1004
+ chainId: number;
1005
+ proof: ProofResult;
1006
+ }) => Promise<RelayerRequest>;
1007
+ buildWithdrawCalldata: (input: {
1008
+ chainId: number;
1009
+ proof: ProofResult;
1010
+ }) => Promise<RelayerRequest>;
1011
+ }
1012
+ interface OpsApi {
1013
+ prepareTransfer(input: {
1014
+ chainId: number;
1015
+ assetId: string;
1016
+ amount: bigint;
1017
+ to: Hex;
1018
+ ownerKeyPair: UserKeyPair;
1019
+ publicClient: PublicClient;
1020
+ relayerUrl?: string;
1021
+ autoMerge?: boolean;
1022
+ }): Promise<{
1023
+ kind: 'transfer';
1024
+ plan: TransferPlan;
1025
+ witness: TransferWitnessInput;
1026
+ proof: ProofResult;
1027
+ request: RelayerRequest;
1028
+ meta: {
1029
+ arrayHashIndex: number;
1030
+ merkleRootIndex: number;
1031
+ relayer: Address;
1032
+ };
1033
+ } | {
1034
+ kind: 'merge';
1035
+ plan: TransferMergePlan;
1036
+ merge: {
1037
+ plan: TransferPlan;
1038
+ witness: TransferWitnessInput;
1039
+ proof: ProofResult;
1040
+ request: RelayerRequest;
1041
+ meta: {
1042
+ arrayHashIndex: number;
1043
+ merkleRootIndex: number;
1044
+ relayer: Address;
1045
+ };
1046
+ };
1047
+ nextInput: {
1048
+ chainId: number;
1049
+ assetId: string;
1050
+ amount: bigint;
1051
+ to: Hex;
1052
+ relayerUrl?: string;
1053
+ autoMerge?: boolean;
1054
+ };
1055
+ }>;
1056
+ prepareWithdraw(input: {
1057
+ chainId: number;
1058
+ assetId: string;
1059
+ amount: bigint;
1060
+ recipient: Address;
1061
+ ownerKeyPair: UserKeyPair;
1062
+ publicClient: PublicClient;
1063
+ gasDropValue?: bigint;
1064
+ relayerUrl?: string;
1065
+ }): Promise<{
1066
+ plan: WithdrawPlan;
1067
+ witness: WithdrawWitnessInput;
1068
+ proof: ProofResult;
1069
+ request: RelayerRequest;
1070
+ meta: {
1071
+ arrayHashIndex: number;
1072
+ merkleRootIndex: number;
1073
+ relayer: Address;
1074
+ };
1075
+ }>;
1076
+ prepareDeposit(input: {
1077
+ chainId: number;
1078
+ assetId: string;
1079
+ amount: bigint;
1080
+ ownerPublicKey: UserPublicKey;
1081
+ account: Address;
1082
+ publicClient: PublicClient;
1083
+ }): Promise<{
1084
+ chainId: number;
1085
+ assetId: string;
1086
+ amount: bigint;
1087
+ token: TokenMetadata;
1088
+ recordOpening: CommitmentData;
1089
+ memo: Hex;
1090
+ protocolFee: bigint;
1091
+ payAmount: bigint;
1092
+ depositRelayerFee: bigint;
1093
+ value: bigint;
1094
+ approveNeeded: boolean;
1095
+ approveRequest?: {
1096
+ chainId: number;
1097
+ address: Address;
1098
+ abi: any;
1099
+ functionName: 'approve';
1100
+ args: [Address, bigint];
1101
+ };
1102
+ depositRequest: {
1103
+ chainId: number;
1104
+ address: Address;
1105
+ abi: any;
1106
+ functionName: 'deposit';
1107
+ args: [bigint, bigint, [bigint, bigint], bigint, Hex];
1108
+ value: bigint;
1109
+ };
1110
+ }>;
1111
+ submitDeposit(input: {
1112
+ prepared: Awaited<ReturnType<OpsApi['prepareDeposit']>>;
1113
+ walletClient: {
1114
+ writeContract: (request: {
1115
+ address: Address;
1116
+ abi: any;
1117
+ functionName: string;
1118
+ args: any;
1119
+ value?: bigint;
1120
+ chainId?: number;
1121
+ }) => Promise<Hex>;
1122
+ };
1123
+ publicClient: PublicClient;
1124
+ autoApprove?: boolean;
1125
+ confirmations?: number;
1126
+ operationId?: string;
1127
+ }): Promise<{
1128
+ txHash: Hex;
1129
+ approveTxHash?: Hex;
1130
+ receipt?: TransactionReceipt;
1131
+ operationId?: string;
1132
+ }>;
1133
+ waitRelayerTxHash(input: {
1134
+ relayerUrl: string;
1135
+ relayerTxHash: Hex;
1136
+ timeoutMs?: number;
1137
+ intervalMs?: number;
1138
+ signal?: AbortSignal;
1139
+ operationId?: string;
1140
+ requestUrl?: string;
1141
+ }): Promise<Hex>;
1142
+ waitForTransactionReceipt(input: {
1143
+ publicClient: PublicClient;
1144
+ txHash: Hex;
1145
+ timeoutMs?: number;
1146
+ pollIntervalMs?: number;
1147
+ confirmations?: number;
1148
+ operationId?: string;
1149
+ }): Promise<TransactionReceipt>;
1150
+ submitRelayerRequest<T = unknown>(input: {
1151
+ prepared: {
1152
+ plan: TransferPlan | WithdrawPlan;
1153
+ request: RelayerRequest;
1154
+ kind?: 'transfer' | 'merge';
1155
+ };
1156
+ relayerUrl?: string;
1157
+ signal?: AbortSignal;
1158
+ operationId?: string;
1159
+ operation?: OperationCreateInput;
1160
+ publicClient?: PublicClient;
1161
+ relayerTimeoutMs?: number;
1162
+ relayerIntervalMs?: number;
1163
+ receiptTimeoutMs?: number;
1164
+ receiptPollIntervalMs?: number;
1165
+ confirmations?: number;
1166
+ }): Promise<{
1167
+ result: T;
1168
+ operationId?: string;
1169
+ updateOperation: (patch: Partial<StoredOperation>) => void;
1170
+ waitRelayerTxHash: Promise<Hex>;
1171
+ transactionReceipt?: Promise<TransactionReceipt>;
1172
+ }>;
1173
+ }
1174
+ interface OCashSdk {
1175
+ core: CoreApi;
1176
+ crypto: CryptoApi;
1177
+ keys: KeysApi;
1178
+ assets: AssetsApi;
1179
+ storage: StorageApi;
1180
+ sync: SyncApi;
1181
+ merkle: MerkleApi;
1182
+ wallet: WalletApi;
1183
+ planner: PlannerApi;
1184
+ zkp: ZkpApi;
1185
+ tx: TxBuilderApi;
1186
+ ops: OpsApi;
1187
+ }
1188
+ interface UserPublicKey {
1189
+ user_pk: {
1190
+ user_address: [bigint, bigint];
1191
+ };
1192
+ }
1193
+ interface UserSecretKey extends UserPublicKey {
1194
+ user_sk: {
1195
+ address_sk: bigint;
1196
+ };
1197
+ }
1198
+ interface UserKeyPair extends UserSecretKey {
1199
+ }
1200
+
1201
+ declare const defaultAssetsOverride: AssetsOverride;
1202
+
1203
+ declare class MemoKit {
1204
+ static createMemo(ro: CommitmentData): `0x${string}`;
1205
+ static decryptMemo(secretKey: bigint, encoded: `0x${string}`): CommitmentData | null;
1206
+ static decodeMemoForOwner(input: {
1207
+ secretKey: bigint;
1208
+ memo: Hex;
1209
+ expectedAddress?: Hex | null;
1210
+ isTransparent?: boolean;
1211
+ }): CommitmentData | null;
1212
+ static memoNonce(ephemeralPublicKey: [bigint, bigint], userPublicKey: [bigint, bigint]): Uint8Array;
1213
+ }
1214
+
1215
+ declare class CryptoToolkit {
1216
+ static commitment(record: CommitmentData, format: 'hex'): Hex;
1217
+ static commitment(record: CommitmentData, format: 'bigint'): bigint;
1218
+ static nullifier(secretKey: bigint, commitment: `0x${string}`, freezerPk?: [bigint, bigint]): `0x${string}`;
1219
+ static createRecordOpening(input: {
1220
+ asset_id: bigint | number | string;
1221
+ asset_amount: bigint | number | string;
1222
+ user_pk: {
1223
+ user_address: [bigint | number | string, bigint | number | string];
1224
+ };
1225
+ blinding_factor?: bigint | number | string;
1226
+ is_frozen?: boolean;
1227
+ }): CommitmentData;
1228
+ static viewingRandomness(): Uint8Array;
1229
+ static poolId(tokenAddress: Hex | bigint | number | string, viewerPk: [bigint, bigint], freezerPk: [bigint, bigint]): bigint;
1230
+ }
1231
+
1232
+ declare class KeyManager {
1233
+ static deriveKeyPair(seed: string, nonce?: string): UserKeyPair;
1234
+ static getPublicKeyBySeed(seed: string, nonce?: string): UserPublicKey;
1235
+ static getSecretKeyBySeed(seed: string, nonce?: string): UserSecretKey;
1236
+ static userPkToAddress(userPk: {
1237
+ user_address: [bigint | string, bigint | string];
1238
+ }): Hex;
1239
+ static addressToUserPk(address: Hex): {
1240
+ user_address: [bigint, bigint];
1241
+ };
1242
+ }
1243
+
1244
+ declare class LedgerInfo {
1245
+ private readonly chains;
1246
+ private readonly relayerManager;
1247
+ constructor(initialChains?: ChainConfigInput[]);
1248
+ private upsertChain;
1249
+ getChains(): ChainConfigInput[];
1250
+ getChain(chainId: number): ChainConfigInput;
1251
+ getTokens(chainId: number): TokenMetadata[];
1252
+ getPoolInfo(chainId: number, tokenId: string): TokenMetadata | undefined;
1253
+ getAllowanceTarget(chainId: number): Address;
1254
+ appendTokens(chainId: number, tokens: TokenMetadata[]): void;
1255
+ loadFromUrl(url: string): Promise<void>;
1256
+ getRelayerConfig(chainId: number): RelayerConfig | undefined;
1257
+ syncRelayerConfig(chainId: number): Promise<RelayerConfig>;
1258
+ syncAllRelayerConfigs(): Promise<void>;
1259
+ }
1260
+
1261
+ /**
1262
+ * Normalize token metadata from app-style or sdk-style shapes.
1263
+ *
1264
+ * Supported legacy fields (app):
1265
+ * - `wrapped_erc20` (instead of `wrappedErc20`)
1266
+ * - `viewerPK` / `freezerPK` (instead of `viewerPk` / `freezerPk`)
1267
+ * - `depositFeeBPS` / `withdrawFeeBPS` (instead of `depositFeeBps` / `withdrawFeeBps`)
1268
+ */
1269
+ declare const normalizeTokenMetadata: (input: unknown) => TokenMetadata;
1270
+
1271
+ declare function assertTokenMetadata(value: unknown, name?: string): asserts value is TokenMetadata;
1272
+ declare function assertTokenList(value: unknown, name?: string): asserts value is TokenMetadata[];
1273
+ declare function assertChainConfigInput(value: unknown, name?: string): asserts value is ChainConfigInput;
1274
+
1275
+ declare function fetchPoolTokensFromContract(input: {
1276
+ publicClient: PublicClient;
1277
+ chainId: number;
1278
+ contractAddress: Address;
1279
+ maxPools?: number;
1280
+ includeErc20Metadata?: boolean;
1281
+ }): Promise<TokenMetadata[]>;
1282
+
1283
+ declare class DummyFactory {
1284
+ private readonly bridge;
1285
+ constructor(bridge: ProofBridge);
1286
+ createRecordOpening(): Promise<CommitmentData>;
1287
+ createInputSecret(): Promise<InputSecret>;
1288
+ }
1289
+
1290
+ declare const Utils: {
1291
+ calcDepositFee: (amount: bigint, feeBps?: number) => bigint;
1292
+ randomBytes32: () => Uint8Array<ArrayBufferLike>;
1293
+ randomBytes32Bigint: (isBabyJubScalar?: boolean) => bigint;
1294
+ serializeBigInt: <T>(value: T) => string;
1295
+ };
1296
+
1297
+ declare const BABYJUBJUB_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
1298
+
1299
+ declare function calcTransferProofBinding(input: {
1300
+ relayer: string;
1301
+ extraData: TransferExtraData;
1302
+ }): bigint;
1303
+ declare function calcWithdrawProofBinding(input: {
1304
+ recipient: string;
1305
+ amount: bigint;
1306
+ relayer: string;
1307
+ relayerFee: bigint;
1308
+ gasDropValue: bigint;
1309
+ extraData: Hex;
1310
+ }): bigint;
1311
+
1312
+ declare const App_ABI: readonly [{
1313
+ readonly type: "function";
1314
+ readonly name: "depositRelayerFee";
1315
+ readonly inputs: readonly [];
1316
+ readonly outputs: readonly [{
1317
+ readonly name: "";
1318
+ readonly type: "uint128";
1319
+ }];
1320
+ readonly stateMutability: "view";
1321
+ }, {
1322
+ readonly type: "function";
1323
+ readonly name: "poolIds";
1324
+ readonly inputs: readonly [{
1325
+ readonly name: "";
1326
+ readonly type: "uint256";
1327
+ }];
1328
+ readonly outputs: readonly [{
1329
+ readonly name: "";
1330
+ readonly type: "uint256";
1331
+ }];
1332
+ readonly stateMutability: "view";
1333
+ }, {
1334
+ readonly type: "function";
1335
+ readonly name: "getPoolInfo";
1336
+ readonly inputs: readonly [{
1337
+ readonly name: "poolId";
1338
+ readonly type: "uint256";
1339
+ }];
1340
+ readonly outputs: readonly [{
1341
+ readonly name: "";
1342
+ readonly type: "tuple";
1343
+ readonly components: readonly [{
1344
+ readonly name: "token";
1345
+ readonly type: "address";
1346
+ }, {
1347
+ readonly name: "depositFeeBPS";
1348
+ readonly type: "uint16";
1349
+ }, {
1350
+ readonly name: "withdrawFeeBPS";
1351
+ readonly type: "uint16";
1352
+ }, {
1353
+ readonly name: "accumulatedFee";
1354
+ readonly type: "uint128";
1355
+ }, {
1356
+ readonly name: "viewerPK";
1357
+ readonly type: "uint256[2]";
1358
+ }, {
1359
+ readonly name: "freezerPK";
1360
+ readonly type: "uint256[2]";
1361
+ }, {
1362
+ readonly name: "transferMaxAmount";
1363
+ readonly type: "uint128";
1364
+ }, {
1365
+ readonly name: "withdrawMaxAmount";
1366
+ readonly type: "uint128";
1367
+ }];
1368
+ }];
1369
+ readonly stateMutability: "view";
1370
+ }, {
1371
+ readonly type: "function";
1372
+ readonly name: "deposit";
1373
+ readonly inputs: readonly [{
1374
+ readonly name: "poolId";
1375
+ readonly type: "uint256";
1376
+ }, {
1377
+ readonly name: "amount";
1378
+ readonly type: "uint128";
1379
+ }, {
1380
+ readonly name: "userPK";
1381
+ readonly type: "uint256[2]";
1382
+ }, {
1383
+ readonly name: "nonce";
1384
+ readonly type: "uint256";
1385
+ }, {
1386
+ readonly name: "";
1387
+ readonly type: "bytes";
1388
+ }];
1389
+ readonly outputs: readonly [];
1390
+ readonly stateMutability: "payable";
1391
+ }, {
1392
+ readonly type: "function";
1393
+ readonly name: "getArray";
1394
+ readonly inputs: readonly [];
1395
+ readonly outputs: readonly [{
1396
+ readonly name: "";
1397
+ readonly type: "uint256[]";
1398
+ }];
1399
+ readonly stateMutability: "view";
1400
+ }, {
1401
+ readonly type: "function";
1402
+ readonly name: "digest";
1403
+ readonly inputs: readonly [];
1404
+ readonly outputs: readonly [{
1405
+ readonly name: "merkleTreeRoot";
1406
+ readonly type: "uint256";
1407
+ }, {
1408
+ readonly name: "currentArrayHash";
1409
+ readonly type: "uint256";
1410
+ }];
1411
+ readonly stateMutability: "view";
1412
+ }, {
1413
+ readonly type: "function";
1414
+ readonly name: "totalElements";
1415
+ readonly inputs: readonly [];
1416
+ readonly outputs: readonly [{
1417
+ readonly name: "";
1418
+ readonly type: "uint256";
1419
+ }];
1420
+ readonly stateMutability: "view";
1421
+ }, {
1422
+ readonly type: "function";
1423
+ readonly name: "merkleRoots";
1424
+ readonly inputs: readonly [{
1425
+ readonly name: "";
1426
+ readonly type: "uint256";
1427
+ }];
1428
+ readonly outputs: readonly [{
1429
+ readonly name: "";
1430
+ readonly type: "uint256";
1431
+ }];
1432
+ readonly stateMutability: "view";
1433
+ }, {
1434
+ readonly type: "event";
1435
+ readonly name: "ArrayMergedToTree";
1436
+ readonly inputs: readonly [{
1437
+ readonly name: "batchIndex";
1438
+ readonly type: "uint256";
1439
+ readonly indexed: true;
1440
+ }, {
1441
+ readonly name: "newRoot";
1442
+ readonly type: "uint256";
1443
+ readonly indexed: true;
1444
+ }];
1445
+ readonly anonymous: false;
1446
+ }];
1447
+
1448
+ declare const ERC20_ABI: readonly [{
1449
+ readonly type: "function";
1450
+ readonly name: "name";
1451
+ readonly inputs: readonly [];
1452
+ readonly outputs: readonly [{
1453
+ readonly name: "";
1454
+ readonly type: "string";
1455
+ }];
1456
+ readonly stateMutability: "view";
1457
+ }, {
1458
+ readonly type: "function";
1459
+ readonly name: "symbol";
1460
+ readonly inputs: readonly [];
1461
+ readonly outputs: readonly [{
1462
+ readonly name: "";
1463
+ readonly type: "string";
1464
+ }];
1465
+ readonly stateMutability: "view";
1466
+ }, {
1467
+ readonly type: "function";
1468
+ readonly name: "decimals";
1469
+ readonly inputs: readonly [];
1470
+ readonly outputs: readonly [{
1471
+ readonly name: "";
1472
+ readonly type: "uint8";
1473
+ }];
1474
+ readonly stateMutability: "view";
1475
+ }, {
1476
+ readonly type: "function";
1477
+ readonly name: "allowance";
1478
+ readonly inputs: readonly [{
1479
+ readonly name: "owner";
1480
+ readonly type: "address";
1481
+ }, {
1482
+ readonly name: "spender";
1483
+ readonly type: "address";
1484
+ }];
1485
+ readonly outputs: readonly [{
1486
+ readonly name: "";
1487
+ readonly type: "uint256";
1488
+ }];
1489
+ readonly stateMutability: "view";
1490
+ }, {
1491
+ readonly type: "function";
1492
+ readonly name: "approve";
1493
+ readonly inputs: readonly [{
1494
+ readonly name: "spender";
1495
+ readonly type: "address";
1496
+ }, {
1497
+ readonly name: "amount";
1498
+ readonly type: "uint256";
1499
+ }];
1500
+ readonly outputs: readonly [{
1501
+ readonly name: "";
1502
+ readonly type: "bool";
1503
+ }];
1504
+ readonly stateMutability: "nonpayable";
1505
+ }];
1506
+
1507
+ declare class MemoryStore implements StorageAdapter {
1508
+ private walletId;
1509
+ private readonly cursors;
1510
+ private readonly utxos;
1511
+ private operations;
1512
+ private readonly merkleLeavesByChain;
1513
+ private readonly merkleTreesByChain;
1514
+ private readonly merkleNodesByChain;
1515
+ private readonly entryMemosByChain;
1516
+ private readonly entryNullifiersByChain;
1517
+ private readonly maxOperations;
1518
+ constructor(options?: {
1519
+ maxOperations?: number;
1520
+ });
1521
+ init(options?: {
1522
+ walletId?: string;
1523
+ }): void;
1524
+ close(): void;
1525
+ private enforceMaxOperations;
1526
+ getSyncCursor(chainId: number): Promise<SyncCursor | undefined>;
1527
+ setSyncCursor(chainId: number, cursor: SyncCursor): Promise<void>;
1528
+ upsertUtxos(utxos: UtxoRecord[]): Promise<void>;
1529
+ listUtxos(query?: ListUtxosQuery): Promise<{
1530
+ total: number;
1531
+ rows: UtxoRecord[];
1532
+ }>;
1533
+ markSpent(input: {
1534
+ chainId: number;
1535
+ nullifiers: Hex[];
1536
+ }): Promise<number>;
1537
+ getMerkleLeaves(chainId: number): Promise<Array<{
1538
+ cid: number;
1539
+ commitment: Hex;
1540
+ }> | undefined>;
1541
+ appendMerkleLeaves(chainId: number, leaves: Array<{
1542
+ cid: number;
1543
+ commitment: Hex;
1544
+ }>): Promise<void>;
1545
+ clearMerkleLeaves(chainId: number): Promise<void>;
1546
+ getMerkleLeaf(chainId: number, cid: number): Promise<MerkleLeafRecord | undefined>;
1547
+ getMerkleNode(chainId: number, id: string): Promise<MerkleNodeRecord | undefined>;
1548
+ upsertMerkleNodes(chainId: number, nodes: MerkleNodeRecord[]): Promise<void>;
1549
+ clearMerkleNodes(chainId: number): Promise<void>;
1550
+ getMerkleTree(chainId: number): Promise<MerkleTreeState | undefined>;
1551
+ setMerkleTree(chainId: number, tree: MerkleTreeState): Promise<void>;
1552
+ clearMerkleTree(chainId: number): Promise<void>;
1553
+ upsertEntryMemos(memos: EntryMemoRecord[]): Promise<number>;
1554
+ listEntryMemos(query: ListEntryMemosQuery): Promise<{
1555
+ total: number;
1556
+ rows: EntryMemoRecord[];
1557
+ }>;
1558
+ clearEntryMemos(chainId: number): Promise<void>;
1559
+ upsertEntryNullifiers(nullifiers: EntryNullifierRecord[]): Promise<number>;
1560
+ listEntryNullifiers(query: ListEntryNullifiersQuery): Promise<{
1561
+ total: number;
1562
+ rows: EntryNullifierRecord[];
1563
+ }>;
1564
+ clearEntryNullifiers(chainId: number): Promise<void>;
1565
+ createOperation<TType extends OperationType>(input: Omit<StoredOperation<OperationDetailFor<TType>>, 'id' | 'createdAt' | 'status'> & Partial<Pick<StoredOperation<OperationDetailFor<TType>>, 'createdAt' | 'id' | 'status'>> & {
1566
+ type: TType;
1567
+ }): StoredOperation<OperationDetailFor<TType>> & {
1568
+ type: TType;
1569
+ };
1570
+ updateOperation(id: string, patch: Partial<StoredOperation>): void;
1571
+ deleteOperation(id: string): boolean;
1572
+ clearOperations(): void;
1573
+ pruneOperations(options?: {
1574
+ max?: number;
1575
+ }): number;
1576
+ listOperations(input?: number | ListOperationsQuery): StoredOperation[];
1577
+ }
1578
+
1579
+ type KeyValueStoreOptions = {
1580
+ client: KeyValueClient;
1581
+ keyPrefix?: string;
1582
+ maxOperations?: number;
1583
+ };
1584
+ declare class KeyValueStore implements StorageAdapter {
1585
+ private readonly options;
1586
+ private walletId;
1587
+ private readonly cursors;
1588
+ private readonly utxos;
1589
+ private operations;
1590
+ private merkleLeaves;
1591
+ private merkleTrees;
1592
+ private merkleNodes;
1593
+ private entryMemos;
1594
+ private entryNullifiers;
1595
+ private saveChain;
1596
+ private readonly maxOperations;
1597
+ constructor(options: KeyValueStoreOptions);
1598
+ init(options?: {
1599
+ walletId?: string;
1600
+ }): Promise<void>;
1601
+ close(): Promise<void>;
1602
+ private stateKey;
1603
+ private load;
1604
+ private save;
1605
+ getMerkleNode(chainId: number, id: string): Promise<MerkleNodeRecord | undefined>;
1606
+ upsertMerkleNodes(chainId: number, nodes: MerkleNodeRecord[]): Promise<void>;
1607
+ clearMerkleNodes(chainId: number): Promise<void>;
1608
+ getMerkleTree(chainId: number): Promise<MerkleTreeState | undefined>;
1609
+ setMerkleTree(chainId: number, tree: MerkleTreeState): Promise<void>;
1610
+ clearMerkleTree(chainId: number): Promise<void>;
1611
+ upsertEntryMemos(memos: EntryMemoRecord[]): Promise<number>;
1612
+ listEntryMemos(query: ListEntryMemosQuery): Promise<{
1613
+ total: number;
1614
+ rows: EntryMemoRecord[];
1615
+ }>;
1616
+ clearEntryMemos(chainId: number): Promise<void>;
1617
+ upsertEntryNullifiers(nullifiers: EntryNullifierRecord[]): Promise<number>;
1618
+ listEntryNullifiers(query: ListEntryNullifiersQuery): Promise<{
1619
+ total: number;
1620
+ rows: EntryNullifierRecord[];
1621
+ }>;
1622
+ clearEntryNullifiers(chainId: number): Promise<void>;
1623
+ getMerkleLeaves(chainId: number): Promise<Array<{
1624
+ cid: number;
1625
+ commitment: Hex;
1626
+ }> | undefined>;
1627
+ getMerkleLeaf(chainId: number, cid: number): Promise<{
1628
+ chainId: number;
1629
+ cid: number;
1630
+ commitment: `0x${string}`;
1631
+ } | undefined>;
1632
+ appendMerkleLeaves(chainId: number, leaves: Array<{
1633
+ cid: number;
1634
+ commitment: Hex;
1635
+ }>): Promise<void>;
1636
+ clearMerkleLeaves(chainId: number): Promise<void>;
1637
+ getSyncCursor(chainId: number): Promise<SyncCursor | undefined>;
1638
+ setSyncCursor(chainId: number, cursor: SyncCursor): Promise<void>;
1639
+ upsertUtxos(utxos: UtxoRecord[]): Promise<void>;
1640
+ listUtxos(query?: ListUtxosQuery): Promise<{
1641
+ total: number;
1642
+ rows: UtxoRecord[];
1643
+ }>;
1644
+ markSpent(input: {
1645
+ chainId: number;
1646
+ nullifiers: Hex[];
1647
+ }): Promise<number>;
1648
+ createOperation<TType extends OperationType>(input: Omit<StoredOperation<OperationDetailFor<TType>>, 'id' | 'createdAt' | 'status'> & Partial<Pick<StoredOperation<OperationDetailFor<TType>>, 'createdAt' | 'id' | 'status'>> & {
1649
+ type: TType;
1650
+ }): StoredOperation<OperationDetailFor<TType>> & {
1651
+ type: TType;
1652
+ };
1653
+ updateOperation(id: string, patch: Partial<StoredOperation>): void;
1654
+ deleteOperation(id: string): boolean;
1655
+ clearOperations(): void;
1656
+ pruneOperations(options?: {
1657
+ max?: number;
1658
+ }): number;
1659
+ listOperations(input?: number | ListOperationsQuery): StoredOperation[];
1660
+ }
1661
+ type RedisStoreOptions = KeyValueStoreOptions;
1662
+ declare class RedisStore extends KeyValueStore {
1663
+ constructor(options: RedisStoreOptions);
1664
+ }
1665
+ type SqliteStoreOptions = KeyValueStoreOptions;
1666
+ declare class SqliteStore extends KeyValueStore {
1667
+ constructor(options: SqliteStoreOptions);
1668
+ }
1669
+ interface KeyValueClient {
1670
+ get(key: string): Promise<string | null>;
1671
+ set(key: string, value: string): Promise<void>;
1672
+ del?(key: string): Promise<void>;
1673
+ }
1674
+
1675
+ declare const createSdk: (config: OCashSdkConfig) => OCashSdk;
1676
+ declare const OcashSdk: {
1677
+ readonly createSdk: (config: OCashSdkConfig) => OCashSdk;
1678
+ readonly MemoKit: typeof MemoKit;
1679
+ readonly CryptoToolkit: typeof CryptoToolkit;
1680
+ readonly KeyManager: typeof KeyManager;
1681
+ readonly LedgerInfo: typeof LedgerInfo;
1682
+ readonly DummyFactory: typeof DummyFactory;
1683
+ readonly Utils: {
1684
+ calcDepositFee: (amount: bigint, feeBps?: number) => bigint;
1685
+ randomBytes32: () => Uint8Array<ArrayBufferLike>;
1686
+ randomBytes32Bigint: (isBabyJubScalar?: boolean) => bigint;
1687
+ serializeBigInt: <T>(value: T) => string;
1688
+ };
1689
+ readonly MemoryStore: typeof MemoryStore;
1690
+ };
1691
+
1692
+ export { type TransferWitnessInput as $, App_ABI as A, BABYJUBJUB_SCALAR_FIELD as B, type ChainConfigInput as C, type DepositOperation as D, type EntryMemoRecord as E, type OpsApi as F, type PlannerEstimateWithdrawResult as G, type Hex as H, type ProofResult as I, type RedisStoreOptions as J, KeyManager as K, type ListEntryMemosQuery as L, type MerkleNodeRecord as M, type RelayerRequest as N, type OperationType as O, type PlannerEstimateTransferResult as P, type SdkEvent as Q, RedisStore as R, type StorageAdapter as S, SqliteStore as T, type UtxoRecord as U, type SqliteStoreOptions as V, type SyncChainStatus as W, type TokenMetadata as X, type TransactionReceipt as Y, type TransferOperation as Z, type TransferOperationDetail as _, type MerkleTreeState as a, Utils as a0, type WalletSessionInput as a1, type WithdrawOperation as a2, type WithdrawOperationDetail as a3, type WithdrawWitnessInput as a4, type WitnessBuildResult as a5, type WitnessContext as a6, assertChainConfigInput as a7, assertTokenList as a8, assertTokenMetadata as a9, calcTransferProofBinding as aa, calcWithdrawProofBinding as ab, createSdk as ac, OcashSdk as ad, defaultAssetsOverride as ae, fetchPoolTokensFromContract as af, normalizeTokenMetadata as ag, type EntryNullifierRecord as b, type ListEntryNullifiersQuery as c, type SyncCursor as d, type ListUtxosQuery as e, type StoredOperation as f, type OperationDetailFor as g, type ListOperationsQuery as h, type AssetOverrideEntry as i, type AssetsOverride as j, type CommitmentData as k, CryptoToolkit as l, type DepositOperationDetail as m, DummyFactory as n, ERC20_ABI as o, type KeyValueClient as p, KeyValueStore as q, type KeyValueStoreOptions as r, LedgerInfo as s, MemoKit as t, MemoryStore as u, type MerkleLeafRecord as v, type OCashSdk as w, type OCashSdkConfig as x, type OperationCreateInput as y, type OperationStatus as z };