@usearete/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,913 @@
1
+ /**
2
+ * Wallet adapter interface for signing and sending transactions.
3
+ * This is framework-agnostic and can be implemented by any wallet provider.
4
+ */
5
+ interface WalletAdapter {
6
+ /** The wallet's public key as a base58-encoded string */
7
+ publicKey: string;
8
+ /**
9
+ * Sign and send a transaction.
10
+ * @param transaction - The transaction to sign and send (can be raw bytes, a Transaction object, or an array of instructions)
11
+ * @returns The transaction signature
12
+ */
13
+ signAndSend: (transaction: unknown) => Promise<string>;
14
+ }
15
+ /**
16
+ * Wallet connection state
17
+ */
18
+ type WalletState = 'disconnected' | 'connecting' | 'connected' | 'error';
19
+ /**
20
+ * Options for wallet connection
21
+ */
22
+ interface WalletConnectOptions {
23
+ /** Whether to use the default wallet selection UI if multiple wallets are available */
24
+ useDefaultSelector?: boolean;
25
+ /** Specific wallet provider to use */
26
+ provider?: string;
27
+ }
28
+
29
+ /**
30
+ * Categories of accounts in an instruction.
31
+ * - `signer`: Must sign the transaction (e.g., user wallet)
32
+ * - `known`: Program-derived addresses with fixed known addresses (e.g., System Program)
33
+ * - `pda`: Program-derived addresses computed from seeds
34
+ * - `userProvided`: Must be provided by the caller (e.g., mint, bonding curve)
35
+ */
36
+ type AccountCategory = 'signer' | 'known' | 'pda' | 'userProvided';
37
+ /**
38
+ * Metadata for a single account in an instruction.
39
+ */
40
+ interface AccountMeta {
41
+ /** Account name (e.g., "user", "mint") */
42
+ name: string;
43
+ /** Whether this account must sign the transaction */
44
+ isSigner: boolean;
45
+ /** Whether this account is writable */
46
+ isWritable: boolean;
47
+ /** Category of this account */
48
+ category: AccountCategory;
49
+ /** Fixed address for "known" accounts (e.g., "11111111111111111111111111111111") */
50
+ knownAddress?: string;
51
+ /** PDA configuration for "pda" accounts */
52
+ pdaConfig?: PdaConfig;
53
+ /** Whether this account is optional */
54
+ isOptional?: boolean;
55
+ }
56
+ /**
57
+ * Configuration for PDA (Program-Derived Address) derivation.
58
+ */
59
+ interface PdaConfig {
60
+ /** Program ID that owns this PDA (defaults to instruction's programId) */
61
+ programId?: string;
62
+ /** Seed definitions for PDA derivation */
63
+ seeds: PdaSeed[];
64
+ }
65
+ /**
66
+ * Single seed in a PDA derivation.
67
+ */
68
+ type PdaSeed = {
69
+ type: 'literal';
70
+ value: string;
71
+ } | {
72
+ type: 'argRef';
73
+ argName: string;
74
+ } | {
75
+ type: 'accountRef';
76
+ accountName: string;
77
+ };
78
+ /**
79
+ * Resolved account with its final address.
80
+ */
81
+ interface ResolvedAccount {
82
+ /** Account name */
83
+ name: string;
84
+ /** The resolved public key address */
85
+ address: string;
86
+ /** Whether this account must sign */
87
+ isSigner: boolean;
88
+ /** Whether this account is writable */
89
+ isWritable: boolean;
90
+ }
91
+ /**
92
+ * Result of account resolution.
93
+ */
94
+ interface AccountResolutionResult {
95
+ /** All resolved accounts in order */
96
+ accounts: ResolvedAccount[];
97
+ /** Accounts that need to be provided by the user */
98
+ missingUserAccounts: string[];
99
+ }
100
+ /**
101
+ * Options for account resolution.
102
+ */
103
+ interface AccountResolutionOptions {
104
+ /** User-provided account addresses */
105
+ accounts?: Record<string, string>;
106
+ /** Wallet adapter for signer accounts */
107
+ wallet?: WalletAdapter;
108
+ /** Program ID for PDA derivation (required if any PDAs exist) */
109
+ programId?: string;
110
+ }
111
+ /**
112
+ * Resolves instruction accounts by categorizing and deriving addresses.
113
+ *
114
+ * Resolution order:
115
+ * 1. Non-PDA accounts (signer, known, userProvided) are resolved first
116
+ * 2. PDA accounts are resolved in dependency order (accounts they reference come first)
117
+ *
118
+ * @param accountMetas - Account metadata from the instruction definition
119
+ * @param args - Instruction arguments (used for PDA derivation with argRef seeds)
120
+ * @param options - Resolution options including wallet, user-provided accounts, and programId
121
+ * @returns Resolved accounts and any missing required accounts
122
+ */
123
+ declare function resolveAccounts(accountMetas: AccountMeta[], args: Record<string, unknown>, options: AccountResolutionOptions): AccountResolutionResult;
124
+ /**
125
+ * Validates that all required accounts are present.
126
+ *
127
+ * @param result - Account resolution result
128
+ * @throws Error if any required accounts are missing
129
+ */
130
+ declare function validateAccountResolution(result: AccountResolutionResult): void;
131
+
132
+ /**
133
+ * PDA (Program Derived Address) derivation utilities.
134
+ *
135
+ * Implements Solana's PDA derivation algorithm without depending on @solana/web3.js.
136
+ */
137
+ /**
138
+ * Decode base58 string to Uint8Array.
139
+ */
140
+ declare function decodeBase58(str: string): Uint8Array;
141
+ /**
142
+ * Encode Uint8Array to base58 string.
143
+ */
144
+ declare function encodeBase58(bytes: Uint8Array): string;
145
+ /**
146
+ * Derives a Program-Derived Address (PDA) from seeds and program ID.
147
+ *
148
+ * Algorithm:
149
+ * 1. For bump = 255 down to 0:
150
+ * a. Concatenate: seeds + [bump] + programId + "ProgramDerivedAddress"
151
+ * b. SHA-256 hash the concatenation
152
+ * c. If result is off the ed25519 curve, return it
153
+ * 2. If no valid PDA found after 256 attempts, throw error
154
+ *
155
+ * @param seeds - Array of seed buffers (max 32 bytes each, max 16 seeds)
156
+ * @param programId - The program ID (base58 string)
157
+ * @returns Tuple of [derivedAddress (base58), bumpSeed]
158
+ */
159
+ declare function findProgramAddress(seeds: Uint8Array[], programId: string): Promise<[string, number]>;
160
+ /**
161
+ * Synchronous version of findProgramAddress.
162
+ * Uses synchronous SHA-256 (Node.js crypto module).
163
+ */
164
+ declare function findProgramAddressSync(seeds: Uint8Array[], programId: string): [string, number];
165
+ /**
166
+ * Creates a seed buffer from various input types.
167
+ *
168
+ * @param value - The value to convert to a seed
169
+ * @returns Uint8Array suitable for PDA derivation
170
+ */
171
+ declare function createSeed(value: string | Uint8Array | bigint | number): Uint8Array;
172
+ /**
173
+ * Creates a public key seed from a base58-encoded address.
174
+ *
175
+ * @param address - Base58-encoded public key
176
+ * @returns 32-byte Uint8Array
177
+ */
178
+ declare function createPublicKeySeed(address: string): Uint8Array;
179
+
180
+ /**
181
+ * Borsh-compatible instruction data serializer.
182
+ *
183
+ * This module handles serializing instruction arguments into the binary format
184
+ * expected by Solana programs using Borsh serialization.
185
+ */
186
+ /**
187
+ * Instruction argument schema for serialization.
188
+ */
189
+ interface ArgSchema {
190
+ /** Argument name */
191
+ name: string;
192
+ /** Argument type */
193
+ type: ArgType;
194
+ }
195
+ /**
196
+ * Supported argument types for Borsh serialization.
197
+ */
198
+ type ArgType = 'u8' | 'u16' | 'u32' | 'u64' | 'u128' | 'i8' | 'i16' | 'i32' | 'i64' | 'i128' | 'bool' | 'string' | 'pubkey' | {
199
+ vec: ArgType;
200
+ } | {
201
+ option: ArgType;
202
+ } | {
203
+ array: [ArgType, number];
204
+ };
205
+ /**
206
+ * Serializes instruction arguments into a Buffer using Borsh encoding.
207
+ *
208
+ * @param discriminator - The 8-byte instruction discriminator
209
+ * @param args - Arguments to serialize
210
+ * @param schema - Schema defining argument types
211
+ * @returns Serialized instruction data
212
+ */
213
+ declare function serializeInstructionData(discriminator: Uint8Array, args: Record<string, unknown>, schema: ArgSchema[]): Buffer;
214
+
215
+ /**
216
+ * Confirmation level for transaction processing.
217
+ * - `processed`: Transaction processed but not confirmed
218
+ * - `confirmed`: Transaction confirmed by cluster
219
+ * - `finalized`: Transaction finalized (recommended for production)
220
+ */
221
+ type ConfirmationLevel = 'processed' | 'confirmed' | 'finalized';
222
+ /**
223
+ * Options for executing an instruction.
224
+ */
225
+ interface ExecuteOptions {
226
+ /** Wallet adapter for signing */
227
+ wallet?: WalletAdapter;
228
+ /** User-provided account addresses */
229
+ accounts?: Record<string, string>;
230
+ /** Confirmation level to wait for */
231
+ confirmationLevel?: ConfirmationLevel;
232
+ /** Maximum time to wait for confirmation (ms) */
233
+ timeout?: number;
234
+ /** Refresh view after transaction completes */
235
+ refresh?: {
236
+ view: string;
237
+ key?: string;
238
+ }[];
239
+ }
240
+ /**
241
+ * Result of a successful instruction execution.
242
+ */
243
+ interface ExecutionResult {
244
+ /** Transaction signature */
245
+ signature: string;
246
+ /** Confirmation level achieved */
247
+ confirmationLevel: ConfirmationLevel;
248
+ /** Slot when transaction was processed */
249
+ slot: number;
250
+ /** Error code if transaction failed */
251
+ error?: string;
252
+ }
253
+ /**
254
+ * Waits for transaction confirmation.
255
+ *
256
+ * @param signature - Transaction signature
257
+ * @param level - Desired confirmation level
258
+ * @param timeout - Maximum wait time in milliseconds
259
+ * @returns Confirmation result
260
+ */
261
+ declare function waitForConfirmation(signature: string, level?: ConfirmationLevel, timeout?: number): Promise<{
262
+ level: ConfirmationLevel;
263
+ slot: number;
264
+ }>;
265
+
266
+ /**
267
+ * Parses and handles instruction errors.
268
+ */
269
+ /**
270
+ * Custom error from a Solana program.
271
+ */
272
+ interface ProgramError {
273
+ /** Error code */
274
+ code: number;
275
+ /** Error name */
276
+ name: string;
277
+ /** Error message */
278
+ message: string;
279
+ }
280
+ /**
281
+ * Error metadata from IDL.
282
+ */
283
+ interface ErrorMetadata {
284
+ code: number;
285
+ name: string;
286
+ msg: string;
287
+ }
288
+ /**
289
+ * Parses an error returned from a Solana transaction.
290
+ *
291
+ * @param error - The error from the transaction
292
+ * @param errorMetadata - Error definitions from the IDL
293
+ * @returns Parsed program error or null if not a program error
294
+ */
295
+ declare function parseInstructionError(error: unknown, errorMetadata: ErrorMetadata[]): ProgramError | null;
296
+ /**
297
+ * Formats an error for display.
298
+ *
299
+ * @param error - The program error
300
+ * @returns Human-readable error message
301
+ */
302
+ declare function formatProgramError(error: ProgramError): string;
303
+
304
+ /**
305
+ * Resolved accounts map passed to the instruction builder.
306
+ * Keys are account names, values are base58 addresses.
307
+ */
308
+ type ResolvedAccounts = Record<string, string>;
309
+ /**
310
+ * The instruction object returned by the handler's build function.
311
+ * This is a framework-agnostic representation that can be converted
312
+ * to @solana/web3.js TransactionInstruction.
313
+ */
314
+ interface BuiltInstruction {
315
+ /** Program ID (base58) */
316
+ programId: string;
317
+ /** Account keys in order */
318
+ keys: Array<{
319
+ pubkey: string;
320
+ isSigner: boolean;
321
+ isWritable: boolean;
322
+ }>;
323
+ /** Serialized instruction data */
324
+ data: Uint8Array;
325
+ }
326
+ /**
327
+ * Instruction handler from the generated stack SDK.
328
+ * The build() function is generated code that handles serialization.
329
+ */
330
+ interface InstructionHandler {
331
+ /**
332
+ * Build the instruction with resolved accounts.
333
+ * This is generated code - serialization logic lives here.
334
+ */
335
+ build(args: Record<string, unknown>, accounts: ResolvedAccounts): BuiltInstruction;
336
+ /** Account metadata - used by core SDK for resolution */
337
+ accounts: AccountMeta[];
338
+ /** Error definitions - used by core SDK for error parsing */
339
+ errors: ErrorMetadata[];
340
+ /** Program ID for this instruction (used for PDA derivation) */
341
+ programId?: string;
342
+ }
343
+ /**
344
+ * @deprecated Use InstructionHandler instead. Will be removed in next major version.
345
+ * Legacy instruction definition for backwards compatibility.
346
+ */
347
+ interface InstructionDefinition {
348
+ /** Instruction name */
349
+ name: string;
350
+ /** Program ID (base58) */
351
+ programId: string;
352
+ /** 8-byte discriminator */
353
+ discriminator: Uint8Array;
354
+ /** Account metadata */
355
+ accounts: AccountMeta[];
356
+ /** Argument schema for serialization */
357
+ argsSchema: ArgSchema[];
358
+ /** Error definitions */
359
+ errors: ErrorMetadata[];
360
+ }
361
+ /**
362
+ * Executes an instruction handler with the given arguments and options.
363
+ *
364
+ * This is the main function for executing Solana instructions. It handles:
365
+ * 1. Account resolution (signer, PDA, user-provided)
366
+ * 2. Calling the generated build() function
367
+ * 3. Transaction signing and sending
368
+ * 4. Confirmation waiting
369
+ *
370
+ * @param handler - Instruction handler from generated SDK
371
+ * @param args - Instruction arguments
372
+ * @param options - Execution options
373
+ * @returns Execution result with signature
374
+ */
375
+ declare function executeInstruction(handler: InstructionHandler, args: Record<string, unknown>, options?: ExecuteOptions): Promise<ExecutionResult>;
376
+ /**
377
+ * Creates an instruction executor bound to a specific wallet.
378
+ *
379
+ * @param wallet - Wallet adapter
380
+ * @returns Bound executor function
381
+ */
382
+ declare function createInstructionExecutor(wallet: WalletAdapter): {
383
+ execute: (handler: InstructionHandler, args: Record<string, unknown>, options?: Omit<ExecuteOptions, "wallet">) => Promise<ExecutionResult>;
384
+ };
385
+
386
+ type SeedDef = {
387
+ type: 'literal';
388
+ value: string;
389
+ } | {
390
+ type: 'bytes';
391
+ value: Uint8Array;
392
+ } | {
393
+ type: 'argRef';
394
+ argName: string;
395
+ argType?: string;
396
+ } | {
397
+ type: 'accountRef';
398
+ accountName: string;
399
+ };
400
+ interface PdaDeriveContext {
401
+ accounts?: Record<string, string>;
402
+ args?: Record<string, unknown>;
403
+ programId?: string;
404
+ }
405
+ interface PdaFactory {
406
+ readonly seeds: readonly SeedDef[];
407
+ readonly programId: string;
408
+ program(programId: string): PdaFactory;
409
+ derive(context: PdaDeriveContext): Promise<string>;
410
+ deriveSync(context: PdaDeriveContext): string;
411
+ }
412
+ declare function literal(value: string): SeedDef;
413
+ declare function account(name: string): SeedDef;
414
+ declare function arg(name: string, type?: string): SeedDef;
415
+ declare function bytes(value: Uint8Array): SeedDef;
416
+ declare function pda(programId: string, ...seeds: SeedDef[]): PdaFactory;
417
+ type ProgramPdas<T extends Record<string, PdaFactory>> = T;
418
+ declare function createProgramPdas<T extends Record<string, PdaFactory>>(pdas: T): ProgramPdas<T>;
419
+
420
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'error';
421
+ type Update<T> = {
422
+ type: 'upsert';
423
+ key: string;
424
+ data: T;
425
+ } | {
426
+ type: 'patch';
427
+ key: string;
428
+ data: Partial<T>;
429
+ } | {
430
+ type: 'delete';
431
+ key: string;
432
+ };
433
+ type RichUpdate<T> = {
434
+ type: 'created';
435
+ key: string;
436
+ data: T;
437
+ } | {
438
+ type: 'updated';
439
+ key: string;
440
+ before: T;
441
+ after: T;
442
+ patch?: unknown;
443
+ } | {
444
+ type: 'deleted';
445
+ key: string;
446
+ lastKnown?: T;
447
+ };
448
+ interface ViewDef<T, TMode extends 'state' | 'list'> {
449
+ readonly mode: TMode;
450
+ readonly view: string;
451
+ readonly _entity?: T;
452
+ }
453
+ interface StackDefinition {
454
+ readonly name: string;
455
+ readonly url: string;
456
+ readonly views: Record<string, ViewGroup>;
457
+ readonly schemas?: Record<string, Schema<unknown>>;
458
+ instructions?: Record<string, InstructionHandler>;
459
+ }
460
+ interface ViewGroup {
461
+ state?: ViewDef<unknown, 'state'>;
462
+ list?: ViewDef<unknown, 'list'>;
463
+ }
464
+ interface Subscription {
465
+ view: string;
466
+ key?: string;
467
+ partition?: string;
468
+ filters?: Record<string, string>;
469
+ take?: number;
470
+ skip?: number;
471
+ /** Whether to include initial snapshot (defaults to true for backward compatibility) */
472
+ withSnapshot?: boolean;
473
+ /** Cursor for resuming from a specific point (_seq value) */
474
+ after?: string;
475
+ /** Maximum number of entities to include in snapshot (pagination hint) */
476
+ snapshotLimit?: number;
477
+ }
478
+ type SchemaResult<T> = {
479
+ success: true;
480
+ data: T;
481
+ } | {
482
+ success: false;
483
+ error: unknown;
484
+ };
485
+ interface Schema<T> {
486
+ safeParse: (input: unknown) => SchemaResult<T>;
487
+ }
488
+ interface WatchOptions<TSchema = unknown> {
489
+ take?: number;
490
+ skip?: number;
491
+ filters?: Record<string, string>;
492
+ schema?: Schema<TSchema>;
493
+ /** Whether to include initial snapshot (defaults to true) */
494
+ withSnapshot?: boolean;
495
+ /** Cursor for resuming from a specific point (_seq value) */
496
+ after?: string;
497
+ /** Maximum number of entities to include in snapshot */
498
+ snapshotLimit?: number;
499
+ }
500
+ interface AreteOptions<TStack extends StackDefinition> {
501
+ stack: TStack;
502
+ autoReconnect?: boolean;
503
+ reconnectIntervals?: number[];
504
+ maxReconnectAttempts?: number;
505
+ validateFrames?: boolean;
506
+ }
507
+ declare const DEFAULT_MAX_ENTRIES_PER_VIEW = 10000;
508
+ interface AuthTokenResult {
509
+ token: string;
510
+ expiresAt?: number;
511
+ expires_at?: number;
512
+ }
513
+ interface WebSocketFactoryInit {
514
+ headers?: Record<string, string>;
515
+ }
516
+ /**
517
+ * Authentication configuration for Arete connections
518
+ */
519
+ interface AuthConfig {
520
+ /** Custom token provider function - called before each connection and during refresh */
521
+ getToken?: () => Promise<string | AuthTokenResult>;
522
+ /** Arete Cloud token endpoint URL */
523
+ tokenEndpoint?: string;
524
+ /** Publishable key for Arete Cloud */
525
+ publishableKey?: string;
526
+ /** Pre-minted static token (for server-side use) */
527
+ token?: string;
528
+ /** How the websocket token is sent to the server */
529
+ tokenTransport?: 'query' | 'bearer';
530
+ /** Custom websocket factory for non-browser environments */
531
+ websocketFactory?: (url: string, init?: WebSocketFactoryInit) => WebSocket;
532
+ /** Additional headers sent to the token endpoint */
533
+ tokenEndpointHeaders?: Record<string, string>;
534
+ /** Credentials mode for token endpoint fetches */
535
+ tokenEndpointCredentials?: RequestCredentials;
536
+ }
537
+ interface AreteConfig {
538
+ websocketUrl?: string;
539
+ reconnectIntervals?: number[];
540
+ maxReconnectAttempts?: number;
541
+ initialSubscriptions?: Subscription[];
542
+ maxEntriesPerView?: number | null;
543
+ /** Authentication configuration */
544
+ auth?: AuthConfig;
545
+ }
546
+ interface SocketIssue {
547
+ error: string;
548
+ message: string;
549
+ code: AuthErrorCode;
550
+ retryable: boolean;
551
+ retryAfter?: number;
552
+ suggestedAction?: string;
553
+ docsUrl?: string;
554
+ fatal: boolean;
555
+ }
556
+ declare const DEFAULT_CONFIG: Required<Pick<AreteConfig, 'reconnectIntervals' | 'maxReconnectAttempts' | 'maxEntriesPerView'>>;
557
+ /**
558
+ * Machine-readable error codes for authentication and rate limiting failures
559
+ *
560
+ * These codes match the Rust AuthErrorCode enum for cross-platform consistency.
561
+ */
562
+ type AuthErrorCode = 'TOKEN_MISSING' | 'TOKEN_EXPIRED' | 'TOKEN_INVALID_SIGNATURE' | 'TOKEN_INVALID_FORMAT' | 'TOKEN_INVALID_ISSUER' | 'TOKEN_INVALID_AUDIENCE' | 'TOKEN_MISSING_CLAIM' | 'TOKEN_KEY_NOT_FOUND' | 'ORIGIN_MISMATCH' | 'ORIGIN_REQUIRED' | 'ORIGIN_NOT_ALLOWED' | 'AUTH_REQUIRED' | 'MISSING_AUTHORIZATION_HEADER' | 'INVALID_AUTHORIZATION_FORMAT' | 'INVALID_API_KEY' | 'EXPIRED_API_KEY' | 'USER_NOT_FOUND' | 'SECRET_KEY_REQUIRED' | 'DEPLOYMENT_ACCESS_DENIED' | 'RATE_LIMIT_EXCEEDED' | 'WEBSOCKET_SESSION_RATE_LIMIT_EXCEEDED' | 'CONNECTION_LIMIT_EXCEEDED' | 'SUBSCRIPTION_LIMIT_EXCEEDED' | 'SNAPSHOT_LIMIT_EXCEEDED' | 'EGRESS_LIMIT_EXCEEDED' | 'QUOTA_EXCEEDED' | 'INVALID_STATIC_TOKEN' | 'INTERNAL_ERROR';
563
+ declare class AreteError extends Error {
564
+ code: string | AuthErrorCode;
565
+ details?: unknown | undefined;
566
+ constructor(message: string, code: string | AuthErrorCode, details?: unknown | undefined);
567
+ }
568
+ type TypedViews<TViews extends StackDefinition['views']> = {
569
+ [K in keyof TViews]: TypedViewGroup<TViews[K]>;
570
+ };
571
+ type TypedViewGroup<TGroup> = {
572
+ [K in keyof TGroup]: TGroup[K] extends ViewDef<infer T, 'state'> ? TypedStateView<T> : TGroup[K] extends ViewDef<infer T, 'list'> ? TypedListView<T> : never;
573
+ };
574
+ interface TypedStateView<T> {
575
+ use<TSchema = T>(key: string, options?: WatchOptions<TSchema>): AsyncIterable<TSchema>;
576
+ watch(key: string, options?: WatchOptions): AsyncIterable<Update<T>>;
577
+ watchRich(key: string, options?: WatchOptions): AsyncIterable<RichUpdate<T>>;
578
+ get(key: string): Promise<T | null>;
579
+ getSync(key: string): T | null | undefined;
580
+ }
581
+ interface TypedListView<T> {
582
+ use<TSchema = T>(options?: WatchOptions<TSchema>): AsyncIterable<TSchema>;
583
+ watch(options?: WatchOptions): AsyncIterable<Update<T>>;
584
+ watchRich(options?: WatchOptions): AsyncIterable<RichUpdate<T>>;
585
+ get(): Promise<T[]>;
586
+ getSync(): T[] | undefined;
587
+ }
588
+ type SubscribeCallback<T> = (update: Update<T>) => void;
589
+ type UnsubscribeFn = () => void;
590
+ type ConnectionStateCallback = (state: ConnectionState, error?: string) => void;
591
+ type SocketIssueCallback = (issue: SocketIssue) => void;
592
+
593
+ type FrameMode = 'state' | 'append' | 'list';
594
+ type FrameOp = 'create' | 'upsert' | 'patch' | 'delete' | 'snapshot' | 'subscribed';
595
+ type SortOrder = 'asc' | 'desc';
596
+ interface SortConfig {
597
+ field: string[];
598
+ order: SortOrder;
599
+ }
600
+ interface SubscribedFrame {
601
+ op: 'subscribed';
602
+ view: string;
603
+ mode: FrameMode;
604
+ sort?: SortConfig;
605
+ }
606
+ interface EntityFrame<T = unknown> {
607
+ mode: FrameMode;
608
+ entity: string;
609
+ op: FrameOp;
610
+ key: string;
611
+ data: T;
612
+ append?: string[];
613
+ /** Sequence cursor for ordering and resume capability */
614
+ seq?: string;
615
+ }
616
+ interface SnapshotEntity<T = unknown> {
617
+ key: string;
618
+ data: T;
619
+ }
620
+ interface SnapshotFrame<T = unknown> {
621
+ mode: FrameMode;
622
+ entity: string;
623
+ op: 'snapshot';
624
+ data: SnapshotEntity<T>[];
625
+ /** Indicates if this is the final snapshot batch. When false, more batches will follow. */
626
+ complete?: boolean;
627
+ }
628
+ type Frame<T = unknown> = EntityFrame<T> | SnapshotFrame<T> | SubscribedFrame;
629
+ declare function isSnapshotFrame<T>(frame: Frame<T>): frame is SnapshotFrame<T>;
630
+ declare function isSubscribedFrame(frame: Frame): frame is SubscribedFrame;
631
+ declare function isEntityFrame<T>(frame: Frame<T>): frame is EntityFrame<T>;
632
+ declare function parseFrame(data: ArrayBuffer | string): Frame;
633
+ declare function parseFrameFromBlob(blob: Blob): Promise<Frame>;
634
+ declare function isValidFrame(frame: unknown): frame is Frame;
635
+
636
+ type FrameHandler = <T>(frame: Frame<T>) => void;
637
+ declare class ConnectionManager {
638
+ private ws;
639
+ private websocketUrl;
640
+ private reconnectIntervals;
641
+ private maxReconnectAttempts;
642
+ private reconnectAttempts;
643
+ private reconnectTimeout;
644
+ private pingInterval;
645
+ private tokenRefreshTimeout;
646
+ private tokenRefreshInFlight;
647
+ private currentState;
648
+ private subscriptionQueue;
649
+ private activeSubscriptions;
650
+ private frameHandlers;
651
+ private stateHandlers;
652
+ private socketIssueHandlers;
653
+ private authConfig?;
654
+ private currentToken?;
655
+ private tokenExpiry?;
656
+ private readonly hostedAreteUrl;
657
+ private reconnectForTokenRefresh;
658
+ constructor(config: AreteConfig);
659
+ private getTokenEndpoint;
660
+ private getAuthStrategy;
661
+ private hasRefreshableAuth;
662
+ private updateTokenState;
663
+ private clearTokenState;
664
+ private getOrRefreshToken;
665
+ private createTokenEndpointRequestBody;
666
+ private fetchTokenFromEndpoint;
667
+ private isTokenExpired;
668
+ private scheduleTokenRefresh;
669
+ private clearTokenRefreshTimeout;
670
+ private refreshTokenInBackground;
671
+ private sendInBandAuthRefresh;
672
+ private handleRefreshAuthResponse;
673
+ private handleSocketIssueMessage;
674
+ private rotateConnectionForTokenRefresh;
675
+ private buildAuthUrl;
676
+ private createWebSocket;
677
+ getState(): ConnectionState;
678
+ onFrame(handler: FrameHandler): () => void;
679
+ onStateChange(handler: ConnectionStateCallback): () => void;
680
+ onSocketIssue(handler: SocketIssueCallback): () => void;
681
+ private notifySocketIssue;
682
+ connect(): Promise<void>;
683
+ disconnect(): void;
684
+ subscribe(subscription: Subscription): void;
685
+ unsubscribe(view: string, key?: string): void;
686
+ isConnected(): boolean;
687
+ private makeSubKey;
688
+ private flushSubscriptionQueue;
689
+ private resubscribeActive;
690
+ private updateState;
691
+ private notifyFrameHandlers;
692
+ private handleReconnect;
693
+ private clearReconnectTimeout;
694
+ private startPingInterval;
695
+ private stopPingInterval;
696
+ }
697
+
698
+ type UpdateCallback<T = unknown> = (viewPath: string, key: string, update: Update<T>) => void;
699
+ type RichUpdateCallback$1<T = unknown> = (viewPath: string, key: string, update: RichUpdate<T>) => void;
700
+ interface StorageAdapterConfig {
701
+ maxEntriesPerView?: number | null;
702
+ }
703
+ interface ViewSortConfig {
704
+ sort?: SortConfig;
705
+ }
706
+ /**
707
+ * Storage adapter interface for Arete entity storage.
708
+ * Implement this to integrate with Zustand, Pinia, Svelte stores, Redux, IndexedDB, etc.
709
+ */
710
+ interface StorageAdapter {
711
+ get<T>(viewPath: string, key: string): T | null;
712
+ getAll<T>(viewPath: string): T[];
713
+ getAllSync<T>(viewPath: string): T[] | undefined;
714
+ getSync<T>(viewPath: string, key: string): T | null | undefined;
715
+ has(viewPath: string, key: string): boolean;
716
+ keys(viewPath: string): string[];
717
+ size(viewPath: string): number;
718
+ set<T>(viewPath: string, key: string, data: T): void;
719
+ delete(viewPath: string, key: string): void;
720
+ clear(viewPath?: string): void;
721
+ evictOldest?(viewPath: string): string | undefined;
722
+ setViewConfig?(viewPath: string, config: ViewSortConfig): void;
723
+ getViewConfig?(viewPath: string): ViewSortConfig | undefined;
724
+ onUpdate(callback: UpdateCallback): () => void;
725
+ onRichUpdate(callback: RichUpdateCallback$1): () => void;
726
+ notifyUpdate<T>(viewPath: string, key: string, update: Update<T>): void;
727
+ notifyRichUpdate<T>(viewPath: string, key: string, update: RichUpdate<T>): void;
728
+ }
729
+
730
+ declare class SubscriptionRegistry {
731
+ private subscriptions;
732
+ private connection;
733
+ constructor(connection: ConnectionManager);
734
+ subscribe(subscription: Subscription): UnsubscribeFn;
735
+ unsubscribe(subscription: Subscription): void;
736
+ getRefCount(subscription: Subscription): number;
737
+ getActiveSubscriptions(): Subscription[];
738
+ clear(): void;
739
+ private makeSubKey;
740
+ }
741
+
742
+ interface ConnectOptions {
743
+ url?: string;
744
+ storage?: StorageAdapter;
745
+ maxEntriesPerView?: number | null;
746
+ autoReconnect?: boolean;
747
+ reconnectIntervals?: number[];
748
+ maxReconnectAttempts?: number;
749
+ flushIntervalMs?: number;
750
+ validateFrames?: boolean;
751
+ /** Authentication configuration */
752
+ auth?: AuthConfig;
753
+ }
754
+ /** @deprecated Use ConnectOptions instead */
755
+ interface AreteOptionsWithStorage<TStack extends StackDefinition> extends AreteOptions<TStack> {
756
+ storage?: StorageAdapter;
757
+ maxEntriesPerView?: number | null;
758
+ flushIntervalMs?: number;
759
+ auth?: AuthConfig;
760
+ }
761
+ interface InstructionExecutorOptions extends Omit<ExecuteOptions, 'wallet'> {
762
+ wallet: WalletAdapter;
763
+ }
764
+ type InstructionExecutor = (args: Record<string, unknown>, options: InstructionExecutorOptions) => Promise<ExecutionResult>;
765
+ type InstructionsInterface<TInstructions extends Record<string, InstructionHandler> | undefined> = TInstructions extends Record<string, InstructionHandler> ? {
766
+ [K in keyof TInstructions]: InstructionExecutor;
767
+ } : {};
768
+ declare class Arete<TStack extends StackDefinition> {
769
+ private readonly connection;
770
+ private readonly storage;
771
+ private readonly processor;
772
+ private readonly subscriptionRegistry;
773
+ private readonly _views;
774
+ private readonly stack;
775
+ private readonly _instructions;
776
+ private constructor();
777
+ private buildInstructions;
778
+ static connect<T extends StackDefinition>(stack: T, options?: ConnectOptions): Promise<Arete<T>>;
779
+ get views(): TypedViews<TStack['views']>;
780
+ get instructions(): InstructionsInterface<TStack['instructions']>;
781
+ get connectionState(): ConnectionState;
782
+ get stackName(): string;
783
+ get store(): StorageAdapter;
784
+ onConnectionStateChange(callback: ConnectionStateCallback): UnsubscribeFn;
785
+ onFrame(callback: (frame: Frame) => void): UnsubscribeFn;
786
+ onSocketIssue(callback: SocketIssueCallback): UnsubscribeFn;
787
+ connect(): Promise<void>;
788
+ disconnect(): void;
789
+ isConnected(): boolean;
790
+ clearStore(): void;
791
+ getStore(): StorageAdapter;
792
+ getConnection(): ConnectionManager;
793
+ getSubscriptionRegistry(): SubscriptionRegistry;
794
+ }
795
+
796
+ interface FrameProcessorConfig {
797
+ maxEntriesPerView?: number | null;
798
+ /**
799
+ * Interval in milliseconds to buffer frames before flushing to storage.
800
+ * Set to 0 for immediate processing (no buffering).
801
+ * Default: 0 (immediate)
802
+ *
803
+ * For React applications, 16ms (one frame at 60fps) is recommended to
804
+ * reduce unnecessary re-renders during high-frequency updates.
805
+ */
806
+ flushIntervalMs?: number;
807
+ schemas?: Record<string, Schema<unknown>>;
808
+ }
809
+ declare class FrameProcessor {
810
+ private storage;
811
+ private maxEntriesPerView;
812
+ private flushIntervalMs;
813
+ private schemas?;
814
+ private pendingUpdates;
815
+ private flushTimer;
816
+ private isProcessing;
817
+ constructor(storage: StorageAdapter, config?: FrameProcessorConfig);
818
+ private getSchema;
819
+ private validateEntity;
820
+ handleFrame<T>(frame: Frame<T>): void;
821
+ /**
822
+ * Immediately flush all pending updates.
823
+ * Useful for ensuring all updates are processed before reading state.
824
+ */
825
+ flush(): void;
826
+ /**
827
+ * Clean up any pending timers. Call when disposing the processor.
828
+ */
829
+ dispose(): void;
830
+ private scheduleFlush;
831
+ private flushPendingUpdates;
832
+ private processFrame;
833
+ private processFrameWithoutEnforce;
834
+ private handleSubscribedFrame;
835
+ private handleSnapshotFrame;
836
+ private handleSnapshotFrameWithoutEnforce;
837
+ private handleEntityFrame;
838
+ private handleEntityFrameWithoutEnforce;
839
+ private emitRichUpdate;
840
+ private enforceMaxEntries;
841
+ }
842
+
843
+ interface EntityStoreConfig {
844
+ maxEntriesPerView?: number | null;
845
+ }
846
+ interface ViewConfig {
847
+ sort?: SortConfig;
848
+ }
849
+ type EntityUpdateCallback = (viewPath: string, key: string, update: Update<unknown>) => void;
850
+ type RichUpdateCallback = (viewPath: string, key: string, update: RichUpdate<unknown>) => void;
851
+ declare class EntityStore {
852
+ private views;
853
+ private viewConfigs;
854
+ private updateCallbacks;
855
+ private richUpdateCallbacks;
856
+ private maxEntriesPerView;
857
+ constructor(config?: EntityStoreConfig);
858
+ private enforceMaxEntries;
859
+ handleFrame<T>(frame: Frame<T>): void;
860
+ private handleSubscribedFrame;
861
+ private handleSnapshotFrame;
862
+ private handleEntityFrame;
863
+ getAll<T>(viewPath: string): T[];
864
+ get<T>(viewPath: string, key: string): T | null;
865
+ getAllSync<T>(viewPath: string): T[] | undefined;
866
+ getSync<T>(viewPath: string, key: string): T | null | undefined;
867
+ keys(viewPath: string): string[];
868
+ size(viewPath: string): number;
869
+ clear(): void;
870
+ clearView(viewPath: string): void;
871
+ getViewConfig(viewPath: string): ViewConfig | undefined;
872
+ setViewConfig(viewPath: string, config: ViewConfig): void;
873
+ onUpdate(callback: EntityUpdateCallback): UnsubscribeFn;
874
+ onRichUpdate(callback: RichUpdateCallback): UnsubscribeFn;
875
+ subscribe<T>(viewPath: string, callback: SubscribeCallback<T>): UnsubscribeFn;
876
+ subscribeToKey<T>(viewPath: string, key: string, callback: SubscribeCallback<T>): UnsubscribeFn;
877
+ private notifyUpdate;
878
+ private notifyRichUpdate;
879
+ private notifyRichDelete;
880
+ }
881
+
882
+ declare class MemoryAdapter implements StorageAdapter {
883
+ private views;
884
+ private updateCallbacks;
885
+ private richUpdateCallbacks;
886
+ constructor(_config?: StorageAdapterConfig);
887
+ get<T>(viewPath: string, key: string): T | null;
888
+ getAll<T>(viewPath: string): T[];
889
+ getAllSync<T>(viewPath: string): T[] | undefined;
890
+ getSync<T>(viewPath: string, key: string): T | null | undefined;
891
+ has(viewPath: string, key: string): boolean;
892
+ keys(viewPath: string): string[];
893
+ size(viewPath: string): number;
894
+ set<T>(viewPath: string, key: string, data: T): void;
895
+ delete(viewPath: string, key: string): void;
896
+ clear(viewPath?: string): void;
897
+ evictOldest(viewPath: string): string | undefined;
898
+ onUpdate(callback: UpdateCallback): () => void;
899
+ onRichUpdate(callback: RichUpdateCallback$1): () => void;
900
+ notifyUpdate<T>(viewPath: string, key: string, update: Update<T>): void;
901
+ notifyRichUpdate<T>(viewPath: string, key: string, update: RichUpdate<T>): void;
902
+ }
903
+
904
+ declare function createUpdateStream<T>(storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry, subscription: Subscription, keyFilter?: string): AsyncIterable<Update<T>>;
905
+ declare function createEntityStream<T>(storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry, subscription: Subscription, options?: WatchOptions<any>, keyFilter?: string): AsyncIterable<T>;
906
+ declare function createRichUpdateStream<T>(storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry, subscription: Subscription, keyFilter?: string): AsyncIterable<RichUpdate<T>>;
907
+
908
+ declare function createTypedStateView<T>(viewDef: ViewDef<T, 'state'>, storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry): TypedStateView<T>;
909
+ declare function createTypedListView<T>(viewDef: ViewDef<T, 'list'>, storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry): TypedListView<T>;
910
+ declare function createTypedViews<TStack extends StackDefinition>(stack: TStack, storage: StorageAdapter, subscriptionRegistry: SubscriptionRegistry): TypedViews<TStack['views']>;
911
+
912
+ export { Arete, AreteError, ConnectionManager, DEFAULT_CONFIG, DEFAULT_MAX_ENTRIES_PER_VIEW, EntityStore, FrameProcessor, MemoryAdapter, SubscriptionRegistry, account, arg, bytes, createEntityStream, createInstructionExecutor, createProgramPdas, createPublicKeySeed, createRichUpdateStream, createSeed, createTypedListView, createTypedStateView, createTypedViews, createUpdateStream, decodeBase58, findProgramAddress as derivePda, encodeBase58, executeInstruction, findProgramAddress, findProgramAddressSync, formatProgramError, isEntityFrame, isSnapshotFrame, isSubscribedFrame, isValidFrame, literal, parseFrame, parseFrameFromBlob, parseInstructionError, pda, resolveAccounts, serializeInstructionData, validateAccountResolution, waitForConfirmation };
913
+ export type { AccountCategory, AccountMeta, AccountResolutionOptions, AccountResolutionResult, AreteConfig, AreteOptions, AreteOptionsWithStorage, ArgSchema, ArgType, AuthConfig, AuthTokenResult, BuiltInstruction, ConfirmationLevel, ConnectionState, ConnectionStateCallback, EntityFrame, EntityStoreConfig, ErrorMetadata, ExecuteOptions, ExecutionResult, Frame, FrameMode, FrameOp, FrameProcessorConfig, InstructionDefinition, InstructionExecutor, InstructionExecutorOptions, InstructionHandler, PdaConfig, PdaDeriveContext, PdaFactory, PdaSeed, ProgramError, ProgramPdas, ResolvedAccount, ResolvedAccounts, RichUpdate, RichUpdateCallback$1 as RichUpdateCallback, Schema, SchemaResult, SeedDef, SnapshotEntity, SnapshotFrame, SocketIssue, SocketIssueCallback, SortConfig, SortOrder, StackDefinition, StorageAdapter, StorageAdapterConfig, SubscribeCallback, SubscribedFrame, Subscription, TypedListView, TypedStateView, TypedViewGroup, TypedViews, UnsubscribeFn, Update, UpdateCallback, ViewConfig, ViewDef, ViewGroup, ViewSortConfig, WalletAdapter, WalletConnectOptions, WalletState, WatchOptions, WebSocketFactoryInit };