@rialo/ts-cdk 0.2.0-alpha.1 → 0.2.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,3287 +0,0 @@
1
- export { field, fixedArray, option, vec } from '@dao-xyz/borsh';
2
-
3
- interface HttpTransportConfig {
4
- /** Request timeout in milliseconds */
5
- timeout?: number;
6
- /** Maximum number of retry attempts */
7
- maxRetries?: number;
8
- /** Base delay for exponential backoff (ms) */
9
- retryBaseDelay?: number;
10
- /** Maximum retry delay (ms) */
11
- retryMaxDelay?: number;
12
- /** Custom headers to include in requests */
13
- headers?: Record<string, string>;
14
- }
15
- /**
16
- * HTTP transport with built-in retry logic and timeout handling.
17
- *
18
- * Features:
19
- * - Automatic retries with exponential backoff
20
- * - Request timeouts using AbortController
21
- * - Network error recovery
22
- * - Rate limit handling
23
- * - Proper HTTP status code handling
24
- */
25
- declare class HttpTransport {
26
- private readonly url;
27
- private readonly config;
28
- constructor(url: string, config?: HttpTransportConfig);
29
- /**
30
- * Makes an HTTP request with automatic retry logic.
31
- *
32
- * Retries are attempted for network errors and server errors (5xx).
33
- * Uses exponential backoff between retry attempts.
34
- */
35
- request(body: string, requestDetails?: Record<string, unknown>): Promise<unknown>;
36
- /**
37
- * Make a single HTTP request with timeout
38
- */
39
- private makeRequest;
40
- /**
41
- * Handle HTTP error responses.
42
- *
43
- * Parses the response body to extract JSON-RPC error details when available,
44
- * regardless of HTTP status code. Falls back to HTTP status-based error handling.
45
- */
46
- private handleHttpError;
47
- /**
48
- * Parse error response body to extract message and RPC error code.
49
- *
50
- * Handles multiple formats:
51
- * - JSON-RPC error: { error: { code, message, data? } }
52
- * - Simple JSON: { message: "..." }
53
- * - Non-JSON responses
54
- */
55
- private parseErrorResponse;
56
- /**
57
- * Returns the configured RPC endpoint URL.
58
- */
59
- getUrl(): string;
60
- }
61
-
62
- type IdentifierString = `${string}:${string}`;
63
- type RialoNetwork = "mainnet" | "devnet" | "testnet" | "localnet";
64
- interface ChainDefinition {
65
- /** * The Wallet Standard Chain Identifier.
66
- * e.g., 'rialo:mainnet', 'rialo:devnet'
67
- */
68
- id: IdentifierString;
69
- /** Human-readable name for UI */
70
- name: string;
71
- /** The default RPC URL for this chain */
72
- rpcUrl: string;
73
- }
74
- /**
75
- * Configuration for the Rialo Client.
76
- */
77
- interface RialoClientConfig {
78
- /**
79
- * The Chain Definition.
80
- * Can be a preset (RIALO_MAINNET) or a custom object.
81
- */
82
- chain: ChainDefinition;
83
- transport?: HttpTransportConfig;
84
- }
85
-
86
- /** Default number of accounts to derive in HD wallets */
87
- declare const DEFAULT_NUM_ACCOUNTS: number;
88
- /** Rialo mainnet RPC URL */
89
- declare const URL_MAINNET: string;
90
- /** Rialo testnet RPC URL */
91
- declare const URL_TESTNET: string;
92
- /** Rialo devnet RPC URL */
93
- declare const URL_DEVNET: string;
94
- /** Rialo localnet RPC URL */
95
- declare const URL_LOCALNET: string;
96
- /** Rialo shitnet RPC URL */
97
- declare const URL_SHITNET: string;
98
- declare const RIALO_MAINNET_CHAIN: ChainDefinition;
99
- declare const RIALO_TESTNET_CHAIN: ChainDefinition;
100
- declare const RIALO_DEVNET_CHAIN: ChainDefinition;
101
- declare const RIALO_LOCALNET_CHAIN: ChainDefinition;
102
- declare const RIALO_SHITNET_CHAIN: ChainDefinition;
103
- /** System program ID */
104
- declare const SYSTEM_PROGRAM_ID: string;
105
- /** Base derivation path for Rialo wallets (BIP44 coin type 756) */
106
- /** Coin type 756 follows the telephone keypad convention: R=7, L=5, O=6 */
107
- declare const BASE_DERIVATION_PATH: string;
108
- declare const KELVIN_PER_RLO: number;
109
- declare const PUBLIC_KEY_LENGTH: number;
110
- declare const SECRET_KEY_LENGTH: number;
111
- declare const SIGNATURE_LENGTH: number;
112
-
113
- /**
114
- * Error codes for cryptographic operations.
115
- */
116
- declare enum CryptoErrorCode {
117
- INVALID_KEY_LENGTH = "INVALID_KEY_LENGTH",
118
- INVALID_SIGNATURE = "INVALID_SIGNATURE",
119
- INVALID_PUBLIC_KEY = "INVALID_PUBLIC_KEY",
120
- INVALID_BLOCKHASH = "INVALID_BLOCKHASH",
121
- INVALID_MNEMONIC = "INVALID_MNEMONIC",
122
- KEY_DERIVATION_FAILED = "KEY_DERIVATION_FAILED",
123
- KEYPAIR_DISPOSED = "KEYPAIR_DISPOSED",
124
- MAX_SEED_LENGTH_EXCEEDED = "MAX_SEED_LENGTH_EXCEEDED",
125
- MAX_SEEDS_EXCEEDED = "MAX_SEEDS_EXCEEDED",
126
- INVALID_SEEDS_ON_CURVE = "INVALID_SEEDS_ON_CURVE",
127
- NO_VIABLE_BUMP_SEED = "NO_VIABLE_BUMP_SEED",
128
- INVALID_SEED = "INVALID_SEED"
129
- }
130
- /**
131
- * Error class for cryptographic operations.
132
- *
133
- * Provides structured error information with error codes and contextual details
134
- * for better debugging and error handling.
135
- */
136
- declare class CryptoError extends Error {
137
- readonly code: CryptoErrorCode;
138
- readonly details?: Record<string, unknown>;
139
- constructor(code: CryptoErrorCode, message: string, details?: Record<string, unknown>);
140
- static invalidKeyLength(expected: number, actual: number): CryptoError;
141
- static invalidMnemonic(reason?: string): CryptoError;
142
- static keyDerivationFailed(path: string, cause?: Error): CryptoError;
143
- static keypairDisposed(): CryptoError;
144
- }
145
-
146
- /**
147
- * Represents a 64-byte Ed25519 signature.
148
- *
149
- * @example
150
- * ```typescript
151
- * // From bytes
152
- * const sig = Signature.fromBytes(signatureBytes);
153
- *
154
- * // From base58 string
155
- * const sig = Signature.fromString("3Bxs4h...");
156
- *
157
- * // Serialize
158
- * const base58 = sig.toString();
159
- * ```
160
- */
161
- declare class Signature {
162
- private readonly bytes;
163
- private constructor();
164
- /**
165
- * Creates a Signature from raw bytes.
166
- *
167
- * @param bytes - 64-byte Ed25519 signature
168
- * @throws {CryptoError} If bytes length is not 64
169
- */
170
- static fromBytes(bytes: Uint8Array): Signature;
171
- /**
172
- * Creates a Signature from a base58-encoded string.
173
- *
174
- * @param str - Base58-encoded signature
175
- * @throws {CryptoError} If string is invalid or decodes to wrong length
176
- */
177
- static fromString(str: string): Signature;
178
- /**
179
- * Returns a copy of the raw bytes.
180
- */
181
- toBytes(): Uint8Array;
182
- /**
183
- * Returns the base58-encoded string representation.
184
- */
185
- toString(): string;
186
- /**
187
- * JSON serialization (returns base58 string).
188
- */
189
- toJSON(): string;
190
- }
191
-
192
- /**
193
- * A seed for PDA derivation - string (UTF-8) or raw bytes.
194
- */
195
- type Seed = string | Uint8Array;
196
- /**
197
- * Bump seed (0-255) that pushes derived address off the Ed25519 curve.
198
- */
199
- type Bump = number;
200
- /**
201
- * Result of PDA derivation: [address, bump].
202
- */
203
- type PDA = readonly [PublicKey, Bump];
204
- /**
205
- * Represents a 32-byte Ed25519 public key.
206
- *
207
- * @example
208
- * ```typescript
209
- * // From base58 string
210
- * const pubkey = PublicKey.fromString("5ZqB9U...");
211
- *
212
- * // From bytes
213
- * const pubkey = PublicKey.fromBytes(new Uint8Array(32));
214
- *
215
- * // Comparison
216
- * if (pubkey1.equals(pubkey2)) {
217
- * console.log("Keys match");
218
- * }
219
- * ```
220
- */
221
- declare class PublicKey {
222
- private readonly bytes;
223
- private constructor();
224
- /**
225
- * Creates a PublicKey from raw bytes.
226
- *
227
- * @param bytes - 32-byte Ed25519 public key
228
- * @throws {CryptoError} If bytes length is not 32
229
- */
230
- static fromBytes(bytes: Uint8Array): PublicKey;
231
- /**
232
- * Creates a PublicKey from a base58-encoded string.
233
- *
234
- * @param str - Base58-encoded public key
235
- * @throws {CryptoError} If string is invalid or decodes to wrong length
236
- */
237
- static fromString(str: string): PublicKey;
238
- /**
239
- * Derives a program address from seeds and a program ID.
240
- *
241
- * @remarks
242
- * This is the low-level derivation function. It will throw if the resulting
243
- * address falls on the Ed25519 curve. For most use cases, prefer
244
- * {@link findProgramAddress} which automatically finds a valid bump seed.
245
- *
246
- * Use this method when you already know the bump seed (e.g., stored on-chain
247
- * or passed from a previous computation) for better performance.
248
- *
249
- * @param seeds - Array of seeds (strings or byte arrays, max 16 seeds, each max 32 bytes)
250
- * @param programId - The program that will own this PDA
251
- * @returns The derived public key
252
- * @throws {CryptoError} If seeds exceed limits or result is on curve
253
- *
254
- * @example
255
- * ```typescript
256
- * // With known bump seed (most efficient for verification)
257
- * const pda = PublicKey.createProgramAddress(
258
- * ["metadata", mintPubkey.toBytes(), new Uint8Array([254])],
259
- * metadataProgramId
260
- * );
261
- * ```
262
- */
263
- static createProgramAddress(seeds: Seed[], programId: PublicKey): PublicKey;
264
- /**
265
- * Finds a valid program derived address by searching for a bump seed.
266
- *
267
- * @remarks
268
- * Iterates from bump 255 down to 0, returning the first combination that
269
- * produces an address off the Ed25519 curve. The bump seed should be stored
270
- * or passed to programs to allow efficient verification via {@link createProgramAddress}.
271
- *
272
- * @param seeds - Array of seeds (max 16 seeds, each max 32 bytes)
273
- * @param programId - The program that will own this PDA
274
- * @returns Tuple of [PublicKey, Bump] where bump is 0-255
275
- * @throws {CryptoError} If no valid bump found (extremely rare) or seeds invalid
276
- *
277
- * @example
278
- * ```typescript
279
- * const [vaultPda, vaultBump] = PublicKey.findProgramAddress(
280
- * ["vault", userPubkey.toBytes()],
281
- * programId
282
- * );
283
- *
284
- * // Store bump for later use
285
- * console.log(`Vault: ${vaultPda}, Bump: ${vaultBump}`);
286
- * ```
287
- */
288
- static findProgramAddress(seeds: Seed[], programId: PublicKey): PDA;
289
- /**
290
- * Creates a derived address from a base address, seed string, and program ID.
291
- *
292
- * @remarks
293
- * Unlike PDAs, this derivation CAN produce addresses on the curve.
294
- * This is useful for creating deterministic addresses that a user can sign for,
295
- * where the base address's private key holder can sign transactions.
296
- *
297
- * @param baseAddress - The base public key (signer)
298
- * @param seed - A seed string (max 32 bytes when UTF-8 encoded)
299
- * @param programId - The program that will own the derived account
300
- * @returns The derived address
301
- *
302
- * @example
303
- * ```typescript
304
- * const derivedAddress = PublicKey.createWithSeed(
305
- * userPubkey,
306
- * "savings-account",
307
- * systemProgramId
308
- * );
309
- * ```
310
- */
311
- static createWithSeed(baseAddress: PublicKey, seed: string, programId: PublicKey): PublicKey;
312
- /**
313
- * Returns a copy of the raw bytes.
314
- */
315
- toBytes(): Uint8Array;
316
- /**
317
- * Returns the base58-encoded string representation.
318
- */
319
- toString(): string;
320
- /**
321
- * Checks equality with another public key using constant-time comparison.
322
- */
323
- equals(other: PublicKey): boolean;
324
- /**
325
- * Verifies an Ed25519 signature over a message.
326
- *
327
- * @param message - Message bytes that were signed
328
- * @param signature - Signature to verify
329
- * @returns True if signature is valid, false otherwise
330
- *
331
- * @example
332
- * ```typescript
333
- * const message = new Uint8Array([1, 2, 3]);
334
- * const signature = keypair.sign(message);
335
- * const isValid = keypair.publicKey.verify(message, signature);
336
- * ```
337
- */
338
- verify(message: Uint8Array, signature: Signature): boolean;
339
- /**
340
- * Checks if the public key is on the Ed25519 curve.
341
- *
342
- * @returns True if the public key is on the curve, false otherwise
343
- */
344
- isOnCurve(): boolean;
345
- /**
346
- * JSON serialization (returns base58 string).
347
- */
348
- toJSON(): string;
349
- }
350
-
351
- /**
352
- * Represents an Ed25519 keypair for signing transactions.
353
- *
354
- * Provides secure key generation, signing, and disposal capabilities.
355
- * Call {@link dispose} when finished to securely erase the private key from memory.
356
- *
357
- * @example
358
- * ```typescript
359
- * // Generate random keypair
360
- * const keypair = Keypair.generate();
361
- *
362
- * // Sign a message
363
- * const message = new TextEncoder().encode("Hello");
364
- * const signature = keypair.sign(message);
365
- *
366
- * // Verify signature
367
- * const isValid = keypair.verify(message, signature);
368
- *
369
- * // Secure cleanup
370
- * keypair.dispose();
371
- * ```
372
- */
373
- declare class Keypair {
374
- readonly publicKey: PublicKey;
375
- private secretKey;
376
- private disposed;
377
- private constructor();
378
- /**
379
- * Generates a random keypair using cryptographically secure randomness.
380
- */
381
- static generate(): Keypair;
382
- /**
383
- * Creates a keypair from a 32-byte secret key.
384
- * The public key will be derived from the secret key.
385
- *
386
- * @param secretKey - 32-byte Ed25519 secret key
387
- */
388
- static fromSecretKey(secretKey: Uint8Array): Keypair;
389
- /**
390
- * Creates a keypair from a secret key and pre-computed public key.
391
- *
392
- * Use this for SLIP-0010/BIP32 derived keys where the public key
393
- * should NOT be re-derived (compatibility with hierarchical derivation).
394
- *
395
- * @param secretKey - 32-byte Ed25519 secret key
396
- * @param publicKey - 32-byte Ed25519 public key (pre-computed)
397
- */
398
- static fromKeyPair(secretKey: Uint8Array, publicKey: Uint8Array): Keypair;
399
- /**
400
- * Signs a message with this keypair.
401
- *
402
- * @param message - Message bytes to sign
403
- * @returns Ed25519 signature
404
- * @throws {CryptoError} If keypair has been disposed
405
- */
406
- sign(message: Uint8Array): Signature;
407
- /**
408
- * Verifies a signature against a message using this keypair's public key.
409
- *
410
- * @param message - Original message that was signed
411
- * @param signature - Signature to verify
412
- * @returns true if signature is valid
413
- */
414
- verify(message: Uint8Array, signature: Signature): boolean;
415
- /**
416
- * Exports the secret key for storage.
417
- *
418
- * **WARNING**: Keep this secret! Never expose it in logs, APIs, or client-side code.
419
- *
420
- * @returns Copy of the 32-byte secret key
421
- * @throws {CryptoError} If keypair has been disposed
422
- */
423
- secretKeyBytes(): Uint8Array;
424
- /**
425
- * Checks if this keypair has been disposed.
426
- */
427
- isDisposed(): boolean;
428
- /**
429
- * Securely erases the secret key from memory.
430
- *
431
- * After calling this method, the keypair can no longer be used for signing.
432
- * This is important for security when the keypair is no longer needed.
433
- */
434
- dispose(): void;
435
- private ensureNotDisposed;
436
- }
437
-
438
- type MnemonicStrength = 128 | 256;
439
- /**
440
- * Represents a validated BIP39 mnemonic phrase with SLIP-0010 Ed25519 hierarchical key derivation.
441
- *
442
- * Implements the SLIP-0010 standard for Ed25519 key derivation, ensuring compatibility
443
- * with other implementations (e.g., Rust CDK). The default derivation path uses coin type
444
- * 756 (R=7, L=5, O=6 on telephone keypad).
445
- *
446
- * @example
447
- * ```typescript
448
- * // Generate new mnemonic (12 or 24 words)
449
- * const mnemonic = Mnemonic.generate(128); // 12 words
450
- *
451
- * // Restore from existing phrase
452
- * const restored = Mnemonic.fromPhrase("word1 word2 ...");
453
- *
454
- * // Derive keypairs at specific account indices
455
- * const keypair0 = await mnemonic.toKeypair(0); // m/44'/756'/0'/0'
456
- * const keypair1 = await mnemonic.toKeypair(1); // m/44'/756'/1'/0'
457
- *
458
- * // With custom passphrase (BIP39 extension)
459
- * const secure = await mnemonic.toKeypair(0, {
460
- * passphrase: "my-secret"
461
- * });
462
- * ```
463
- *
464
- * @see {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md SLIP-0010 Specification}
465
- */
466
- declare class Mnemonic {
467
- private readonly phrase;
468
- private constructor();
469
- /**
470
- * Generates a new random BIP39 mnemonic phrase.
471
- *
472
- * @param strength - Entropy strength (128 = 12 words, 256 = 24 words). Default: 128
473
- * @returns Validated Mnemonic instance
474
- */
475
- static generate(strength?: MnemonicStrength): Mnemonic;
476
- /**
477
- * Creates a Mnemonic from an existing phrase.
478
- *
479
- * @param phrase - BIP39 mnemonic phrase (12 or 24 space-separated words)
480
- * @returns Validated Mnemonic instance
481
- * @throws {CryptoError} If phrase is invalid (wrong words or checksum)
482
- */
483
- static fromPhrase(phrase: string): Mnemonic;
484
- /**
485
- * Validates a phrase without creating an instance.
486
- *
487
- * Checks both word validity and BIP39 checksum.
488
- *
489
- * @param phrase - Mnemonic phrase to validate
490
- * @returns true if phrase is valid
491
- */
492
- static isValid(phrase: string): boolean;
493
- private getMasterKeyFromSeed;
494
- private deriveChildKey;
495
- private derivePath;
496
- /**
497
- * Derives a keypair at a specific account index.
498
- *
499
- * Uses SLIP-0010 Ed25519 derivation with the default path:
500
- * `m/44'/756'/{accountIndex}'/0'`
501
- *
502
- * Coin type 756 follows the telephone keypad convention (R=7, L=5, O=6).
503
- *
504
- * @param accountIndex - Account index to derive (default: 0)
505
- * @param options - Derivation options
506
- * @param options.passphrase - Optional BIP39 passphrase for additional security
507
- * @param options.baseDerivationPath - Base path (default: "m/44'/756'")
508
- * @returns Keypair for the derived account
509
- */
510
- toKeypair(accountIndex?: number, options?: {
511
- passphrase?: string;
512
- baseDerivationPath?: string;
513
- }): Promise<Keypair>;
514
- /**
515
- * Derives a keypair using an explicit full derivation path.
516
- *
517
- * @param fullPath - Complete derivation path (e.g., "m/44'/756'/0'/0'")
518
- * @param passphrase - Optional BIP39 passphrase
519
- */
520
- toKeypairWithPath(fullPath: string, passphrase?: string): Promise<Keypair>;
521
- /**
522
- * Derives multiple keypairs sequentially from this mnemonic.
523
- *
524
- * @param count - Number of keypairs to derive
525
- * @param startIndex - Starting account index (default: 0)
526
- * @param options - Derivation options (passphrase and path)
527
- */
528
- deriveKeypairs(count: number, startIndex?: number, options?: {
529
- passphrase?: string;
530
- baseDerivationPath?: string;
531
- }): Promise<Keypair[]>;
532
- /**
533
- * Converts the mnemonic to a BIP39 seed.
534
- *
535
- * @param passphrase - Optional BIP39 passphrase for additional security
536
- * @returns 64-byte seed
537
- */
538
- toSeed(passphrase?: string): Promise<Uint8Array>;
539
- /**
540
- * Returns the mnemonic phrase as a string.
541
- */
542
- toString(): string;
543
- /**
544
- * Returns the individual words of the mnemonic.
545
- */
546
- getWords(): string[];
547
- /**
548
- * Returns the word count (12 or 24).
549
- */
550
- getWordCount(): 12 | 24;
551
- /**
552
- * Returns the entropy strength (128 or 256 bits).
553
- */
554
- getStrength(): MnemonicStrength;
555
- /**
556
- * Checks equality with another mnemonic using constant-time comparison.
557
- */
558
- equals(other: Mnemonic): boolean;
559
- /**
560
- * JSON serialization (returns the mnemonic phrase).
561
- */
562
- toJSON(): string;
563
- private buildFullPath;
564
- }
565
-
566
- /**
567
- * Checks if a 32-byte array represents a valid point on the Ed25519 curve.
568
- *
569
- * This is used for PDA (Program Derived Address) derivation, where valid PDAs
570
- * must NOT be on the curve to ensure they can only be signed by the program.
571
- *
572
- * @param bytes - 32-byte public key or hash to check
573
- * @returns true if the bytes represent a valid Ed25519 point, false otherwise
574
- *
575
- * @example
576
- * ```typescript
577
- * const hash = sha256(data);
578
- * if (!isOnCurve(hash)) {
579
- * // Valid PDA - not on curve
580
- * }
581
- * ```
582
- */
583
- declare function isOnCurve(bytes: Uint8Array): boolean;
584
- /**
585
- * Converts a seed to a 32-byte array.
586
- *
587
- * @param seed - Seed to convert
588
- * @returns 32-byte array
589
- */
590
- declare function seedToBytes(seed: Seed): Uint8Array;
591
- /**
592
- * Concatenates multiple byte arrays into a single byte array.
593
- *
594
- * @param arrays - Byte arrays to concatenate
595
- * @returns Concatenated byte array
596
- */
597
- declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
598
-
599
- /**
600
- * Error handling for the Rialo CDK.
601
- *
602
- * This module defines the common error types used throughout the Rialo CDK.
603
- * It provides a centralized error handling mechanism for all operations.
604
- */
605
- /**
606
- * Structured RPC error information parsed from JSON-RPC error responses.
607
- */
608
- interface RpcErrorDetails$1 {
609
- /** HTTP status code (e.g., 200, 422, 500) */
610
- status?: number;
611
- /** JSON-RPC error code (e.g., -32002) */
612
- code: number;
613
- /** Human-readable error message */
614
- message: string;
615
- }
616
- /**
617
- * Error types for different subsystems in the Rialo CDK.
618
- */
619
- declare enum RialoErrorType {
620
- /** Errors related to file or system I/O operations */
621
- IO = "IO",
622
- /** Errors occurring during RPC communication with blockchain nodes */
623
- RPC = "RPC",
624
- /** Errors related to public key parsing or validation */
625
- PARSE_PUBKEY = "PARSE_PUBKEY",
626
- /** Errors related to blockhash parsing or validation */
627
- INVALID_BLOCKHASH_FORMAT = "INVALID_BLOCKHASH_FORMAT",
628
- /** Errors related to wallet operations such as creation, loading, or signing */
629
- WALLET = "WALLET",
630
- /** Errors related to configuration loading, parsing, or validation */
631
- CONFIG = "CONFIG",
632
- /** Errors occurring during transaction building, signing, or submission */
633
- TRANSACTION = "TRANSACTION",
634
- /** Network-related errors, including HTTP client errors */
635
- NETWORK = "NETWORK",
636
- /** Errors related to password handling, validation, or verification */
637
- PASSWORD = "PASSWORD",
638
- /** Errors related to encryption or decryption operations */
639
- ENCRYPTION = "ENCRYPTION",
640
- /** Errors occurring during JSON parsing, serialization, or deserialization */
641
- JSON = "JSON",
642
- /** Errors related to BIP32 key derivation */
643
- BIP32 = "BIP32",
644
- /** Errors related to invalid input parameters or data */
645
- INVALID_INPUT = "INVALID_INPUT",
646
- /** Errors related to serialization/deserialization */
647
- SERIALIZATION = "SERIALIZATION"
648
- }
649
- /**
650
- * Base error class for all Rialo CDK errors.
651
- *
652
- * Provides structured error handling with type categorization and optional
653
- * cause tracking for error chains. Use the static factory methods for
654
- * consistent error creation across the SDK.
655
- *
656
- * @example
657
- * ```typescript
658
- * // Create typed errors using factory methods
659
- * throw RialoError.invalidInput("Amount must be positive");
660
- * throw RialoError.network("Connection failed", originalError);
661
- * throw RialoError.rpc({ code: -32002, message: "Invalid params" });
662
- *
663
- * // Handle errors with type information
664
- * try {
665
- * await client.sendTransaction(tx);
666
- * } catch (error) {
667
- * if (error instanceof RialoError && error.type === RialoErrorType.NETWORK) {
668
- * console.log("Network error, retrying...");
669
- * }
670
- * }
671
- * ```
672
- */
673
- declare class RialoError extends Error {
674
- readonly type: RialoErrorType;
675
- readonly cause?: Error;
676
- readonly details?: RpcErrorDetails$1;
677
- constructor(type: RialoErrorType, message: string, cause?: Error, details?: RpcErrorDetails$1);
678
- /**
679
- * Creates an IO error.
680
- */
681
- static io(message: string, cause?: Error): RialoError;
682
- /**
683
- * Creates an RPC error.
684
- */
685
- static rpc(details: RpcErrorDetails$1): RialoError;
686
- /**
687
- * Creates a public key parsing error.
688
- */
689
- static parsePubkey(message: string): RialoError;
690
- /**
691
- * Creates a blockhash format error.
692
- */
693
- static invalidBlockhash(message: string): RialoError;
694
- /**
695
- * Creates a wallet error.
696
- */
697
- static wallet(message: string): RialoError;
698
- /**
699
- * Creates a configuration error.
700
- */
701
- static config(message: string): RialoError;
702
- /**
703
- * Creates a transaction error.
704
- */
705
- static transaction(message: string): RialoError;
706
- /**
707
- * Creates a network error.
708
- */
709
- static network(message: string, cause?: Error): RialoError;
710
- /**
711
- * Creates a password error.
712
- */
713
- static password(message: string): RialoError;
714
- /**
715
- * Creates an encryption error.
716
- */
717
- static encryption(message: string): RialoError;
718
- /**
719
- * Creates a JSON error.
720
- */
721
- static json(message: string, cause?: Error): RialoError;
722
- /**
723
- * Creates a BIP32 error.
724
- */
725
- static bip32(message: string): RialoError;
726
- /**
727
- * Creates an invalid input error.
728
- */
729
- static invalidInput(message: string): RialoError;
730
- /**
731
- * Creates a serialization error.
732
- */
733
- static serialization(message: string): RialoError;
734
- }
735
-
736
- /**
737
- * Error codes for HPKE encryption operations.
738
- */
739
- declare enum HpkeErrorCode {
740
- /** Key length does not match expected size */
741
- INVALID_KEY_LENGTH = "INVALID_KEY_LENGTH",
742
- /** Ciphertext is shorter than minimum required length */
743
- CIPHERTEXT_TOO_SHORT = "CIPHERTEXT_TOO_SHORT",
744
- /** HPKE encryption operation failed */
745
- ENCRYPTION_FAILED = "ENCRYPTION_FAILED",
746
- /** Failed to deserialize Borsh data */
747
- BORSH_DESERIALIZE_FAILED = "BORSH_DESERIALIZE_FAILED",
748
- /** RexValue has invalid variant byte */
749
- INVALID_ORACLE_VALUE = "INVALID_ORACLE_VALUE"
750
- }
751
- /**
752
- * Error class for HPKE encryption operations.
753
- *
754
- * Provides detailed error information for encryption failures,
755
- * including error codes and contextual details.
756
- */
757
- declare class HpkeError extends Error {
758
- readonly code: HpkeErrorCode;
759
- readonly cause?: Error;
760
- constructor(code: HpkeErrorCode, message: string, cause?: Error);
761
- /**
762
- * Create an error for invalid key length.
763
- *
764
- * @param expected - Expected key length in bytes
765
- * @param actual - Actual key length in bytes
766
- * @param keyType - Description of the key type (e.g., "REX public key")
767
- */
768
- static invalidKeyLength(expected: number, actual: number, keyType: string): HpkeError;
769
- /**
770
- * Create an error for ciphertext that is too short.
771
- *
772
- * @param minLength - Minimum required length
773
- * @param actual - Actual length
774
- */
775
- static ciphertextTooShort(minLength: number, actual: number): HpkeError;
776
- /**
777
- * Create an error for encryption failure.
778
- *
779
- * @param cause - The underlying error
780
- */
781
- static encryptionFailed(cause: Error): HpkeError;
782
- /**
783
- * Create an error for Borsh deserialization failure.
784
- *
785
- * @param cause - The underlying error
786
- */
787
- static borshDeserializeFailed(cause: Error): HpkeError;
788
- /**
789
- * Create an error for invalid RexValue variant.
790
- *
791
- * @param variant - The invalid variant byte
792
- */
793
- static invalidRexValue(variant: number): HpkeError;
794
- }
795
-
796
- /**
797
- * Constants for REX HPKE encryption.
798
- *
799
- * These constants MUST match the Rust implementation exactly:
800
- * - `crates/tee/secret-sharing/src/constants.rs`
801
- *
802
- * @module
803
- */
804
- /**
805
- * Additional Authenticated Data (AAD) prefix for user secrets.
806
- *
807
- * This 13-byte string is prepended to the sender's public key to form
808
- * the complete AAD for HPKE encryption. It provides domain separation
809
- * to prevent cross-protocol attacks.
810
- *
811
- * Format: `USER_SECRET_AAD || senderPubkey` = 45 bytes total AAD
812
- *
813
- * @remarks
814
- * Must match Rust: `pub const USER_SECRET_AAD: &[u8] = b"rex-secret-v1";`
815
- */
816
- declare const USER_SECRET_AAD: Uint8Array<ArrayBuffer>;
817
- /**
818
- * HPKE info string for secret sharing context.
819
- *
820
- * This 32-byte string is used as the `info` parameter in HPKE encryption,
821
- * providing domain separation for secret sharing operations.
822
- *
823
- * @remarks
824
- * Must match Rust: `pub const SECRET_SHARING_HPKE_INFO: &[u8; 32] = b"rialo/tee/secret-sharing-hpke/v1";`
825
- */
826
- declare const SECRET_SHARING_HPKE_INFO: Uint8Array<ArrayBuffer>;
827
- /**
828
- * Length of an X25519 public key in bytes.
829
- *
830
- * Used for the REX encryption public key (secret sharing key).
831
- */
832
- declare const X25519_PUBLIC_KEY_LENGTH = 32;
833
- /**
834
- * Length of an Ed25519 public key in bytes.
835
- *
836
- * Used for sender identity binding in AAD construction.
837
- */
838
- declare const ED25519_PUBLIC_KEY_LENGTH = 32;
839
- /**
840
- * Length of the HPKE encapsulated key (enc) in bytes.
841
- *
842
- * For X25519, this is always 32 bytes.
843
- */
844
- declare const HPKE_ENC_LENGTH = 32;
845
- /**
846
- * Length of the ChaCha20-Poly1305 authentication tag in bytes.
847
- */
848
- declare const CHACHA20_POLY1305_TAG_LENGTH = 16;
849
- /**
850
- * Total overhead added by HPKE encryption.
851
- *
852
- * This is the additional bytes beyond the plaintext:
853
- * - enc (32 bytes): Encapsulated ephemeral public key
854
- * - tag (16 bytes): ChaCha20-Poly1305 authentication tag
855
- *
856
- * Ciphertext length = plaintext length + 48 bytes
857
- */
858
- declare const HPKE_OVERHEAD_LENGTH: number;
859
-
860
- /**
861
- * Variant discriminator for RexValue Borsh serialization.
862
- */
863
- declare enum RexValueVariant {
864
- /** Plain (unencrypted) data variant */
865
- Plain = 0,
866
- /** Encrypted data variant */
867
- Encrypted = 1
868
- }
869
- /**
870
- * Represents an rex value that can be plain or encrypted.
871
- *
872
- * This class provides Borsh-compatible serialization that matches
873
- * the Rust `RexValue` enum:
874
- *
875
- * ```rust
876
- * pub enum RexValue {
877
- * Plain(Vec<u8>),
878
- * Encrypted(Vec<u8>),
879
- * }
880
- * ```
881
- *
882
- * ## Borsh Format
883
- *
884
- * - Plain: `[0x00] [length: u32 LE] [data bytes]`
885
- * - Encrypted: `[0x01] [length: u32 LE] [ciphertext bytes]`
886
- *
887
- * @example
888
- * ```typescript
889
- * // Plain value (unencrypted)
890
- * const plain = RexValue.plain(new TextEncoder().encode("hello"));
891
- *
892
- * // Encrypted value (via HPKE)
893
- * const encrypted = RexValue.encrypted(ciphertextBytes);
894
- *
895
- * // Serialize to Borsh
896
- * const borsh = plain.toBorsh();
897
- *
898
- * // Deserialize from Borsh
899
- * const restored = RexValue.fromBorsh(borsh);
900
- * ```
901
- */
902
- declare class RexValue {
903
- private readonly variant;
904
- private readonly data;
905
- private constructor();
906
- /**
907
- * Create a plain (unencrypted) RexValue from raw bytes.
908
- *
909
- * @param data - The raw byte data
910
- * @returns A new RexValue with Plain variant
911
- */
912
- static plain(data: Uint8Array): RexValue;
913
- /**
914
- * Create a plain (unencrypted) RexValue from a UTF-8 string.
915
- *
916
- * @param s - The string to encode
917
- * @returns A new RexValue with Plain variant
918
- */
919
- static plainString(s: string): RexValue;
920
- /**
921
- * Create an encrypted RexValue from HPKE ciphertext.
922
- *
923
- * @param ciphertext - The HPKE-encrypted ciphertext (enc || ct || tag)
924
- * @returns A new RexValue with Encrypted variant
925
- */
926
- static encrypted(ciphertext: Uint8Array): RexValue;
927
- /**
928
- * Check if this is a plain (unencrypted) value.
929
- */
930
- isPlain(): boolean;
931
- /**
932
- * Check if this is an encrypted value.
933
- */
934
- isEncrypted(): boolean;
935
- /**
936
- * Get the variant type.
937
- */
938
- getVariant(): RexValueVariant;
939
- /**
940
- * Get the raw bytes (plaintext or ciphertext).
941
- *
942
- * For Plain values, returns the plaintext.
943
- * For Encrypted values, returns the ciphertext.
944
- */
945
- asBytes(): Uint8Array;
946
- /**
947
- * Try to decode the plain value as a UTF-8 string.
948
- *
949
- * @returns The decoded string, or null if encrypted or not valid UTF-8
950
- */
951
- asString(): string | null;
952
- /**
953
- * Serialize to Borsh format.
954
- *
955
- * Format: `[variant: u8] [length: u32 LE] [data bytes]`
956
- *
957
- * @returns The Borsh-serialized bytes
958
- */
959
- toBorsh(): Uint8Array;
960
- /**
961
- * Deserialize from Borsh format.
962
- *
963
- * @param data - The Borsh-serialized bytes
964
- * @returns A new RexValue
965
- * @throws {HpkeError} If deserialization fails
966
- */
967
- static fromBorsh(data: Uint8Array): RexValue;
968
- }
969
-
970
- /**
971
- * Encrypt data using HPKE for REX secret sharing.
972
- *
973
- * This function performs HPKE encryption using the Base mode with:
974
- * - X25519 for key encapsulation
975
- * - HKDF-SHA256 for key derivation
976
- * - ChaCha20-Poly1305 for authenticated encryption
977
- *
978
- * The output format is: `enc (32 bytes) || ciphertext || tag (16 bytes)`
979
- *
980
- * @param rexPubkey - The REX X25519 public key (32 bytes)
981
- * @param data - The plaintext data to encrypt
982
- * @param senderPubkey - The sender's Ed25519 public key (32 bytes) for AAD construction
983
- * @returns The encrypted ciphertext including enc and tag
984
- * @throws {HpkeError} If key lengths are invalid or encryption fails
985
- *
986
- * @example
987
- * ```typescript
988
- * const rexPubkey = await client.getSecretSharingPubkey();
989
- * const ciphertext = await hpkeEncrypt(
990
- * rexPubkey,
991
- * new TextEncoder().encode("secret data"),
992
- * keypair.publicKey.toBytes()
993
- * );
994
- * ```
995
- */
996
- declare function hpkeEncrypt(rexPubkey: Uint8Array, data: Uint8Array, senderPubkey: Uint8Array): Promise<Uint8Array>;
997
- /**
998
- * Encrypt data for REX and wrap it in an RexValue.
999
- *
1000
- * This is a convenience function that combines:
1001
- * 1. HPKE encryption using `hpkeEncrypt`
1002
- * 2. Wrapping the ciphertext in an `RexValue.encrypted`
1003
- *
1004
- * The resulting RexValue can be serialized to Borsh and sent to the network.
1005
- *
1006
- * @param rexPubkey - The REX X25519 public key (32 bytes)
1007
- * @param data - The plaintext data to encrypt
1008
- * @param senderPubkey - The sender's Ed25519 public key (32 bytes)
1009
- * @returns An RexValue containing the encrypted ciphertext
1010
- * @throws {HpkeError} If key lengths are invalid or encryption fails
1011
- *
1012
- * @example
1013
- * ```typescript
1014
- * import { RpcClient, Keypair } from "@rialo/ts-cdk";
1015
- * import { encryptForRex, RexValue } from "@rialo/ts-cdk/rex";
1016
- *
1017
- * // Get REX public key from the network
1018
- * const client = new RpcClient("https://rpc.rialo.xyz");
1019
- * const rexPubkey = await client.getSecretSharingPubkey();
1020
- *
1021
- * // Create keypair for signing
1022
- * const keypair = Keypair.generate();
1023
- *
1024
- * // Encrypt secret data
1025
- * const oracleValue = await encryptForRex(
1026
- * rexPubkey,
1027
- * new TextEncoder().encode("my secret API key"),
1028
- * keypair.publicKey.toBytes()
1029
- * );
1030
- *
1031
- * // The RexValue can now be serialized and used in transactions
1032
- * const borshBytes = oracleValue.toBorsh();
1033
- * ```
1034
- */
1035
- declare function encryptForRex(rexPubkey: Uint8Array, data: Uint8Array, senderPubkey: Uint8Array): Promise<RexValue>;
1036
- /**
1037
- * Calculate the expected ciphertext length for a given plaintext length.
1038
- *
1039
- * The ciphertext consists of:
1040
- * - enc (32 bytes): Encapsulated ephemeral public key
1041
- * - ciphertext (plaintext.length bytes): Encrypted data
1042
- * - tag (16 bytes): ChaCha20-Poly1305 authentication tag
1043
- *
1044
- * @param plaintextLength - Length of the plaintext in bytes
1045
- * @returns Expected ciphertext length
1046
- *
1047
- * @example
1048
- * ```typescript
1049
- * const ciphertextLen = getCiphertextLength(100);
1050
- * console.log(ciphertextLen); // 148 (32 + 100 + 16)
1051
- * ```
1052
- */
1053
- declare function getCiphertextLength(plaintextLength: number): number;
1054
- /**
1055
- * Validate that a ciphertext has a valid length.
1056
- *
1057
- * A valid HPKE ciphertext must be at least 48 bytes (32 enc + 16 tag).
1058
- *
1059
- * @param ciphertext - The ciphertext to validate
1060
- * @returns true if the ciphertext length is valid
1061
- *
1062
- * @example
1063
- * ```typescript
1064
- * if (!isValidCiphertextLength(ciphertext)) {
1065
- * throw new Error("Ciphertext too short");
1066
- * }
1067
- * ```
1068
- */
1069
- declare function isValidCiphertextLength(ciphertext: Uint8Array): boolean;
1070
-
1071
- /**
1072
- * Base client with JSON-RPC protocol handling.
1073
- *
1074
- * All specific clients (QueryClient, TransactionClient) extend this.
1075
- */
1076
- declare class BaseRpcClient {
1077
- protected readonly transport: HttpTransport;
1078
- private requestId;
1079
- constructor(transport: HttpTransport);
1080
- /**
1081
- * Makes a JSON-RPC 2.0 method call with type safety.
1082
- *
1083
- * Handles request serialization, response validation, and error mapping.
1084
- */
1085
- protected call<T>(method: string, params?: unknown[]): Promise<T>;
1086
- /**
1087
- * Validate JSON-RPC response structure
1088
- */
1089
- private isValidJsonRpcResponse;
1090
- /**
1091
- * Generates the next request ID with Overflow Protection.
1092
- * @returns The next request ID.
1093
- */
1094
- private nextRequestId;
1095
- /**
1096
- * Returns the configured RPC endpoint URL.
1097
- */
1098
- getUrl(): string;
1099
- }
1100
-
1101
- /**
1102
- * RPC type definitions for the Rialo blockchain.
1103
- */
1104
-
1105
- /**
1106
- * Account information response.
1107
- */
1108
- interface AccountInfo {
1109
- /** Account balance in smallest denomination */
1110
- balance: bigint;
1111
- /** Owner program public key */
1112
- owner: PublicKey;
1113
- /** Account data */
1114
- data: Uint8Array;
1115
- /** Whether the account is executable */
1116
- executable: boolean;
1117
- /** Rent epoch */
1118
- rentEpoch: bigint;
1119
- }
1120
- /**
1121
- * Transaction response.
1122
- */
1123
- interface TransactionResponse {
1124
- /** Transaction signature */
1125
- signature: string;
1126
- /** Block height */
1127
- blockHeight?: bigint;
1128
- /** Error message if transaction failed */
1129
- err?: string;
1130
- }
1131
- /**
1132
- * Options for sending a transaction.
1133
- */
1134
- interface SendTransactionOptions {
1135
- /** Skip preflight transaction checks */
1136
- skipPreflight?: boolean;
1137
- /** Maximum number of times to retry */
1138
- maxRetries?: number;
1139
- }
1140
- /**
1141
- * Epoch information response.
1142
- */
1143
- interface EpochInfoResponse {
1144
- /** Current epoch */
1145
- epoch: bigint;
1146
- /** Current slot in the epoch */
1147
- slotIndex: bigint;
1148
- /** Total slots in the epoch */
1149
- slotsInEpoch: bigint;
1150
- /** Absolute slot number */
1151
- absoluteSlot: bigint;
1152
- /** Block height */
1153
- blockHeight: bigint;
1154
- /** Transaction count */
1155
- transactionCount?: bigint;
1156
- }
1157
- /**
1158
- * Subscription kind.
1159
- */
1160
- type SubscriptionKind = "Persistent" | "OneShot";
1161
- /**
1162
- * Subscription data.
1163
- */
1164
- interface Subscription {
1165
- /** Type of subscription */
1166
- kind: SubscriptionKind;
1167
- /** Topic for the subscription */
1168
- topic: string;
1169
- /** Instructions to execute when triggered */
1170
- instructions: unknown[];
1171
- /** Subscriber public key (base58) */
1172
- subscriber: string;
1173
- /** Event account public key (base58) */
1174
- eventAccount?: string;
1175
- /** Timestamp range [start, end] */
1176
- timestampRange?: [bigint, bigint];
1177
- }
1178
- /**
1179
- * Triggered transaction data.
1180
- */
1181
- interface TriggeredTransaction {
1182
- /** Transaction signature (base58) */
1183
- signature: string;
1184
- /** Block number where the transaction was executed */
1185
- blockNumber: bigint;
1186
- }
1187
- /**
1188
- * Get workflow lineage request.
1189
- */
1190
- interface GetWorkflowLineageRequest {
1191
- /** Root transaction signature (base58) */
1192
- signature: string;
1193
- /** Maximum depth to traverse (1-100, default 3) */
1194
- maxDepth?: number;
1195
- /** Whether to include event details */
1196
- includeEvents?: boolean;
1197
- }
1198
- /**
1199
- * Event data from a workflow trigger.
1200
- */
1201
- interface EventData {
1202
- /** Event topic */
1203
- topic: string;
1204
- /** Event attributes */
1205
- attributes: Record<string, unknown>;
1206
- }
1207
- /**
1208
- * Timestamp range.
1209
- */
1210
- interface TimestampRange {
1211
- /** Start timestamp (unix) */
1212
- from: bigint;
1213
- /** End timestamp (unix) */
1214
- to: bigint;
1215
- }
1216
- /**
1217
- * Information about what triggered a workflow transaction.
1218
- */
1219
- interface TriggerInfo {
1220
- /** Event that triggered the transaction */
1221
- event: EventData;
1222
- /** Subscription public key (base58) */
1223
- subscriptionPubkey: string;
1224
- /** Timestamp range for the trigger */
1225
- timestampRange?: TimestampRange;
1226
- /** Event account public key (base58) */
1227
- eventAccount?: string;
1228
- }
1229
- /**
1230
- * Transaction node data within a workflow.
1231
- */
1232
- interface TransactionNodeData {
1233
- /** Block height */
1234
- blockHeight: bigint;
1235
- /** Timestamp (unix) */
1236
- timestamp: bigint;
1237
- /** Whether the transaction succeeded */
1238
- success: boolean;
1239
- /** Number of instructions */
1240
- instructionCount: number;
1241
- /** Program IDs of instructions (base58) */
1242
- instructionProgramIds: string[];
1243
- }
1244
- /**
1245
- * A node in the workflow lineage tree.
1246
- */
1247
- interface WorkflowNode {
1248
- /** Transaction signature (base58) */
1249
- id: string;
1250
- /** Distance from root transaction */
1251
- depth: number;
1252
- /** Transaction data */
1253
- data: TransactionNodeData;
1254
- /** Subscriptions on this transaction */
1255
- subscriptions: Subscription[];
1256
- /** What triggered this transaction */
1257
- triggeredBy?: TriggerInfo;
1258
- /** Child transaction signatures (base58) */
1259
- workflowChildren: string[];
1260
- /** Whether there are more children not shown */
1261
- hasMoreChildren: boolean;
1262
- }
1263
- /**
1264
- * Workflow lineage tree.
1265
- */
1266
- interface WorkflowLineage {
1267
- /** Nodes in the workflow tree */
1268
- workflowNodes: WorkflowNode[];
1269
- }
1270
- /**
1271
- * Reason for truncating workflow lineage traversal.
1272
- */
1273
- type TruncationReason = "MaxDepth" | "MaxNodes" | "None";
1274
- /**
1275
- * Get workflow lineage response.
1276
- */
1277
- interface GetWorkflowLineageResponse {
1278
- /** Workflow lineage tree */
1279
- lineage: WorkflowLineage;
1280
- /** Leaf transaction signatures (base58) */
1281
- leaves: string[];
1282
- /** Whether traversal was truncated */
1283
- truncated: boolean;
1284
- /** Reason for truncation */
1285
- truncationReason: TruncationReason;
1286
- /** Hints for continuing traversal (base58 signatures) */
1287
- continuationHints: string[];
1288
- }
1289
- /**
1290
- * Get signatures for address configuration.
1291
- */
1292
- interface GetSignaturesForAddressConfig {
1293
- /** Maximum number of signatures to return */
1294
- limit?: number;
1295
- /** Start searching backwards from this signature */
1296
- before?: string;
1297
- /** Start searching forwards from this signature */
1298
- until?: string;
1299
- }
1300
- /**
1301
- * Signature information.
1302
- */
1303
- interface SignatureInfo {
1304
- signature: string;
1305
- blockHeight: bigint;
1306
- blockTime: bigint;
1307
- err?: string;
1308
- }
1309
- /**
1310
- * Get health response.
1311
- */
1312
- type GetHealthResponse = "ok" | string;
1313
- /**
1314
- * Get transactions response.
1315
- */
1316
- interface GetTransactionsResponse {
1317
- /** Array of transaction data */
1318
- transactions: Array<Record<string, unknown>>;
1319
- }
1320
- /**
1321
- * Signature status from the RPC.
1322
- */
1323
- interface SignatureStatus {
1324
- /** Slot in which the transaction was processed */
1325
- slot: bigint;
1326
- /** Whether the transaction has been executed */
1327
- executed: boolean;
1328
- /** Error message if transaction failed */
1329
- err?: string;
1330
- }
1331
- /**
1332
- * Options for confirming a transaction.
1333
- */
1334
- interface ConfirmTransactionOptions {
1335
- /** Maximum number of retry attempts (default: 30) */
1336
- maxRetries?: number;
1337
- /** Delay between retries in milliseconds (default: 1000) */
1338
- retryDelay?: number;
1339
- }
1340
- /**
1341
- * Options for sending and confirming a transaction.
1342
- */
1343
- interface SendAndConfirmOptions extends SendTransactionOptions, ConfirmTransactionOptions {
1344
- }
1345
- /**
1346
- * Result of a confirmed transaction.
1347
- */
1348
- interface ConfirmedTransaction {
1349
- /** Transaction signature */
1350
- signature: string;
1351
- /** Whether the transaction was executed */
1352
- executed: boolean;
1353
- /** Error message if transaction failed */
1354
- err?: string;
1355
- }
1356
- /**
1357
- * Configuration for getAccountsByOwner.
1358
- */
1359
- interface GetAccountsByOwnerConfig {
1360
- /** Maximum number of accounts to return */
1361
- limit?: number;
1362
- /** Cursor for pagination (base58 pubkey) */
1363
- after?: string;
1364
- }
1365
- /**
1366
- * Filter for getAccountsByOwner.
1367
- * Matches Rust serde serialization format.
1368
- */
1369
- type AccountFilter = {
1370
- type: "programAccounts";
1371
- } | {
1372
- type: "tokenAccounts";
1373
- mint?: string;
1374
- };
1375
- /**
1376
- * An account owned by a program or address.
1377
- */
1378
- interface OwnerAccount {
1379
- /** Account public key */
1380
- pubkey: PublicKey;
1381
- /** Account information */
1382
- account: AccountInfo;
1383
- }
1384
- /**
1385
- * Pagination information.
1386
- */
1387
- interface PaginationInfo {
1388
- /** Whether there are more results */
1389
- hasMore: boolean;
1390
- /** Cursor for next page (base58 pubkey) */
1391
- nextCursor?: string;
1392
- }
1393
- /**
1394
- * Get accounts by owner response.
1395
- */
1396
- interface GetAccountsByOwnerResponse {
1397
- /** Array of owned accounts */
1398
- value: OwnerAccount[];
1399
- /** Pagination information */
1400
- pagination?: PaginationInfo;
1401
- }
1402
- /**
1403
- * Get secret sharing public key response.
1404
- *
1405
- * Contains the TEE's X25519 public key for HPKE encryption.
1406
- */
1407
- interface GetSecretSharingPubkeyResponse {
1408
- /** The TEE's X25519 public key as a hex-encoded string */
1409
- public_key: string;
1410
- }
1411
-
1412
- /**
1413
- * Main Rialo RPC client for blockchain interactions.
1414
- */
1415
-
1416
- /**
1417
- * High-level Rialo RPC client for blockchain interactions.
1418
- *
1419
- * Provides a unified interface for querying blockchain state and
1420
- * sending transactions. Internally delegates to specialized clients
1421
- * (QueryRpcClient, TransactionRpcClient) for modular organization.
1422
- *
1423
- * @example
1424
- * ```typescript
1425
- * import { createRialoClient, RIALO_DEVNET_CHAIN } from '@rialo/ts-cdk';
1426
- *
1427
- * const client = createRialoClient({ chain: RIALO_DEVNET_CHAIN });
1428
- *
1429
- * // Query operations
1430
- * const balance = await client.getBalance(publicKey);
1431
- * const chainId = client.getChainIdentifier();
1432
- *
1433
- * // Transaction operations
1434
- * const signature = await client.sendTransaction(signedTx);
1435
- * ```
1436
- */
1437
- declare class RialoClient {
1438
- private readonly queryClient;
1439
- private readonly transactionClient;
1440
- private readonly transport;
1441
- private readonly chain;
1442
- constructor(transport: HttpTransport, chain: ChainDefinition);
1443
- /**
1444
- * Returns the configured RPC endpoint URL.
1445
- */
1446
- getUrl(): string;
1447
- /**
1448
- * Returns the chain identifier.
1449
- */
1450
- getChainIdentifier(): IdentifierString;
1451
- /**
1452
- * Returns the chain configuration.
1453
- */
1454
- getChainConfig(): ChainDefinition;
1455
- /**
1456
- * Retrieves the balance of an account in kelvins (smallest unit).
1457
- */
1458
- getBalance(pubkey: PublicKey): Promise<bigint>;
1459
- /**
1460
- * Retrieves detailed information about an account.
1461
- *
1462
- * @returns Account info or null if account doesn't exist
1463
- */
1464
- getAccountInfo(pubkey: PublicKey): Promise<AccountInfo | null>;
1465
- /**
1466
- * Retrieves the current block height.
1467
- */
1468
- getBlockHeight(): Promise<bigint>;
1469
- /**
1470
- * Retrieves the signatures for an address.
1471
- */
1472
- getSignaturesForAddress(address: PublicKey, config?: GetSignaturesForAddressConfig): Promise<SignatureInfo[]>;
1473
- /**
1474
- * Retrieves detailed information about a transaction.
1475
- *
1476
- * @returns Transaction info or null if transaction not found
1477
- */
1478
- getTransaction(signature: string): Promise<TransactionResponse | null>;
1479
- /**
1480
- * Retrieves the total number of transactions processed since genesis.
1481
- */
1482
- getTransactionCount(): Promise<bigint>;
1483
- /**
1484
- * Retrieves the status of multiple transaction signatures.
1485
- */
1486
- getSignatureStatuses(signatures: string[]): Promise<(SignatureStatus | null)[]>;
1487
- /**
1488
- * Retrieves current epoch information.
1489
- */
1490
- getEpochInfo(): Promise<EpochInfoResponse>;
1491
- /**
1492
- * Checks the health status of the RPC node.
1493
- *
1494
- * @returns "ok" if healthy, error message otherwise
1495
- */
1496
- getHealth(): Promise<"ok" | string>;
1497
- /**
1498
- * Submits a signed transaction to the blockchain.
1499
- *
1500
- * @param transaction - Serialized signed transaction bytes
1501
- * @param options - Transaction submission options
1502
- * @returns Transaction signature
1503
- */
1504
- sendTransaction(transaction: Uint8Array, options?: SendTransactionOptions): Promise<string>;
1505
- /**
1506
- * Requests an airdrop of tokens to an account.
1507
- *
1508
- * **Note**: Only available on devnet and testnet.
1509
- *
1510
- * @param pubkey - Account to receive the airdrop
1511
- * @param amount - Amount in kelvins (smallest unit)
1512
- * @returns Transaction signature
1513
- */
1514
- requestAirdrop(pubkey: PublicKey, amount: bigint): Promise<string>;
1515
- /**
1516
- * Submits a signed transaction and waits for confirmation.
1517
- *
1518
- * @param transaction - Serialized signed transaction bytes
1519
- * @param options - Transaction submission and confirmation options
1520
- * @returns Confirmed transaction details
1521
- * @throws {TransactionFailedError} If the transaction fails on-chain
1522
- * @throws {TransactionConfirmationTimeoutError} If confirmation times out
1523
- *
1524
- * @example
1525
- * ```typescript
1526
- * const result = await client.sendAndConfirmTransaction(signedTx);
1527
- * console.log(`Confirmed in slot ${result.slot}`);
1528
- * ```
1529
- */
1530
- sendAndConfirmTransaction(transaction: Uint8Array, options?: SendAndConfirmOptions): Promise<ConfirmedTransaction>;
1531
- /**
1532
- * Waits for a transaction to be confirmed.
1533
- *
1534
- * @param signature - Transaction signature to monitor
1535
- * @param options - Confirmation options
1536
- * @returns Confirmed transaction details
1537
- */
1538
- confirmTransaction(signature: string, options?: ConfirmTransactionOptions): Promise<ConfirmedTransaction>;
1539
- /**
1540
- * Requests an airdrop and waits for confirmation.
1541
- *
1542
- * **Note**: Only available on devnet and testnet.
1543
- */
1544
- requestAirdropAndConfirm(pubkey: PublicKey, amount: bigint, options?: ConfirmTransactionOptions): Promise<ConfirmedTransaction>;
1545
- /**
1546
- * Calculate the minimum balance required for an account to be rent-exempt.
1547
- *
1548
- * @param accountDataSize - The size of the account data in bytes
1549
- * @returns The minimum balance in kelvins required for rent exemption
1550
- */
1551
- getMinimumBalanceForRentExemption(accountDataSize: number): Promise<bigint>;
1552
- /**
1553
- * Get the fee required to process a specific message.
1554
- *
1555
- * @param message - Base64-encoded serialized versioned message
1556
- * @returns Fee in kelvins, or null if message is invalid
1557
- */
1558
- getFeeForMessage(message: string): Promise<bigint | null>;
1559
- /**
1560
- * Get information for multiple accounts in a single request.
1561
- *
1562
- * @param pubkeys - Array of public keys to query (1-100)
1563
- * @returns Account information for each address
1564
- */
1565
- getMultipleAccounts(pubkeys: PublicKey[]): Promise<Array<AccountInfo | null>>;
1566
- /**
1567
- * Get all accounts owned by a specific program or address.
1568
- *
1569
- * @param owner - Program ID or owner public key
1570
- * @param filter - Filter type (ProgramAccounts or TokenAccounts)
1571
- * @param config - Optional configuration for pagination and encoding
1572
- * @returns Accounts owned by the specified owner
1573
- */
1574
- getAccountsByOwner(owner: PublicKey, filter?: AccountFilter, config?: GetAccountsByOwnerConfig): Promise<GetAccountsByOwnerResponse>;
1575
- /**
1576
- * Get workflow lineage information for tracking execution history.
1577
- *
1578
- * @param request - Workflow lineage request with signature and options
1579
- * @returns Workflow lineage tree with nodes and metadata
1580
- */
1581
- getWorkflowLineage(request: GetWorkflowLineageRequest): Promise<GetWorkflowLineageResponse>;
1582
- /**
1583
- * Get subscription for a given subscriber address and nonce.
1584
- *
1585
- * @param subscriber - The subscriber's public key
1586
- * @param nonce - The nonce identifying the subscription
1587
- * @returns The subscription for the subscriber and nonce
1588
- */
1589
- getSubscription(subscriber: PublicKey, nonce: string): Promise<Subscription>;
1590
- /**
1591
- * Get transactions triggered by a subscription account.
1592
- *
1593
- * @param subscriptionAccount - The subscription account public key
1594
- * @param limit - Optional limit on transactions returned
1595
- * @returns Triggered transactions for the subscription
1596
- */
1597
- getTriggeredTransactions(subscriptionAccount: PublicKey, limit?: number): Promise<TriggeredTransaction[]>;
1598
- }
1599
-
1600
- /**
1601
- * Query client for read-only RPC operations.
1602
- */
1603
-
1604
- /**
1605
- * Client for querying blockchain state.
1606
- *
1607
- * Handles all read-only operations like getting balances, account info, etc.
1608
- */
1609
- declare class QueryRpcClient extends BaseRpcClient {
1610
- /**
1611
- * Retrieve the balance of an account in kelvins (smallest unit).
1612
- *
1613
- * @param pubkey - The public key of the account to query
1614
- * @returns The account balance in kelvins
1615
- *
1616
- * @example
1617
- * ```typescript
1618
- * const balance = await client.getBalance(publicKey);
1619
- * console.log(`Balance: ${balance} kelvins`);
1620
- * ```
1621
- */
1622
- getBalance(pubkey: PublicKey): Promise<bigint>;
1623
- /**
1624
- * Retrieve detailed information about an account.
1625
- *
1626
- * Returns account data including balance, owner program, stored data,
1627
- * executable status, and rent epoch.
1628
- *
1629
- * @param pubkey - The public key of the account to query
1630
- * @returns Account information, or null if the account does not exist
1631
- *
1632
- * @example
1633
- * ```typescript
1634
- * const info = await client.getAccountInfo(publicKey);
1635
- * if (info) {
1636
- * console.log(`Owner: ${info.owner}`);
1637
- * console.log(`Balance: ${info.balance} kelvins`);
1638
- * console.log(`Data length: ${info.data.length} bytes`);
1639
- * }
1640
- * ```
1641
- */
1642
- getAccountInfo(pubkey: PublicKey): Promise<AccountInfo | null>;
1643
- /**
1644
- * Retrieve the current block height of the blockchain.
1645
- *
1646
- * The block height represents the number of blocks that have been
1647
- * confirmed on the chain since genesis.
1648
- *
1649
- * @returns The current block height
1650
- *
1651
- * @example
1652
- * ```typescript
1653
- * const height = await client.getBlockHeight();
1654
- * console.log(`Current block height: ${height}`);
1655
- * ```
1656
- */
1657
- getBlockHeight(): Promise<bigint>;
1658
- /**
1659
- * Retrieve transaction signatures for a given address.
1660
- *
1661
- * Returns transaction signatures with metadata associated with the specified
1662
- * address, ordered by slot height (most recent first).
1663
- *
1664
- * @param address - The public key of the address to query
1665
- * @param config - Optional configuration options for the query (limit, before, until)
1666
- * @returns Response containing context and array of signature info with blockHeight and blockTime
1667
- *
1668
- * @example
1669
- * ```typescript
1670
- * const result = await client.getSignaturesForAddress(publicKey, { limit: 10 });
1671
- * console.log(`Query slot: ${result.context.slot}`);
1672
- * result.value.forEach(sig => {
1673
- * console.log(`Transaction: ${sig.signature}, block: ${sig.blockHeight}`);
1674
- * });
1675
- * ```
1676
- */
1677
- getSignaturesForAddress(address: PublicKey, config?: GetSignaturesForAddressConfig): Promise<SignatureInfo[]>;
1678
- /**
1679
- * Retrieve detailed information about a confirmed transaction.
1680
- *
1681
- * Returns transaction metadata including the block height it was
1682
- * confirmed in and any execution errors.
1683
- *
1684
- * @param signature - The transaction signature to query
1685
- * @returns Transaction information, or null if the transaction is not found
1686
- *
1687
- * @example
1688
- * ```typescript
1689
- * const tx = await client.getTransaction(signature);
1690
- * if (tx) {
1691
- * console.log(`Confirmed in block: ${tx.blockHeight}`);
1692
- * if (tx.err) {
1693
- * console.log(`Transaction failed: ${tx.err}`);
1694
- * }
1695
- * }
1696
- * ```
1697
- */
1698
- getTransaction(signature: string): Promise<TransactionResponse | null>;
1699
- /**
1700
- * Retrieve the total number of transactions processed since genesis.
1701
- *
1702
- * @returns The total transaction count
1703
- *
1704
- * @example
1705
- * ```typescript
1706
- * const count = await client.getTransactionCount();
1707
- * console.log(`Total transactions: ${count}`);
1708
- * ```
1709
- */
1710
- getTransactionCount(): Promise<bigint>;
1711
- /**
1712
- * Retrieve the status of multiple transaction signatures in a single request.
1713
- *
1714
- * Useful for batch-checking transaction confirmations. Returns null for
1715
- * signatures that are not found or have expired from the status cache.
1716
- *
1717
- * @param signatures - Array of transaction signatures to query
1718
- * @returns Array of signature statuses (null if signature not found)
1719
- *
1720
- * @example
1721
- * ```typescript
1722
- * const statuses = await client.getSignatureStatuses([sig1, sig2, sig3]);
1723
- * statuses.forEach((status, i) => {
1724
- * if (status) {
1725
- * console.log(`${signatures[i]}: slot ${status.slot}, executed: ${status.executed}`);
1726
- * } else {
1727
- * console.log(`${signatures[i]}: not found`);
1728
- * }
1729
- * });
1730
- * ```
1731
- */
1732
- getSignatureStatuses(signatures: string[]): Promise<(SignatureStatus | null)[]>;
1733
- /**
1734
- * Retrieve information about the current epoch.
1735
- *
1736
- * Returns epoch metadata including the current epoch number, slot position
1737
- * within the epoch, total slots per epoch, and current block height.
1738
- *
1739
- * @returns Current epoch information
1740
- *
1741
- * @example
1742
- * ```typescript
1743
- * const info = await client.getEpochInfo();
1744
- * console.log(`Epoch: ${info.epoch}`);
1745
- * console.log(`Slot ${info.slotIndex} of ${info.slotsInEpoch}`);
1746
- * console.log(`Block height: ${info.blockHeight}`);
1747
- * ```
1748
- */
1749
- getEpochInfo(): Promise<EpochInfoResponse>;
1750
- /**
1751
- * Check the health status of the RPC node.
1752
- *
1753
- * Returns "ok" if the node is healthy. If the node is unhealthy,
1754
- * returns an error message describing the issue.
1755
- *
1756
- * @returns "ok" if healthy, otherwise an error message
1757
- *
1758
- * @example
1759
- * ```typescript
1760
- * const health = await client.getHealth();
1761
- * if (health === "ok") {
1762
- * console.log("Node is healthy");
1763
- * } else {
1764
- * console.log(`Node unhealthy: ${health}`);
1765
- * }
1766
- * ```
1767
- */
1768
- getHealth(): Promise<"ok" | string>;
1769
- /**
1770
- * Calculate the minimum balance required for an account to be rent-exempt.
1771
- *
1772
- * Accounts with at least this balance are exempt from paying rent.
1773
- *
1774
- * @param accountDataSize - The size of the account data in bytes
1775
- * @returns The minimum balance in kelvins required for rent exemption
1776
- *
1777
- * @example
1778
- * ```typescript
1779
- * const minBalance = await client.getMinimumBalanceForRentExemption(128);
1780
- * console.log(`Need at least ${minBalance} kelvins for 128 bytes`);
1781
- * ```
1782
- */
1783
- getMinimumBalanceForRentExemption(accountDataSize: number): Promise<bigint>;
1784
- /**
1785
- * Get the fee required to process a specific message.
1786
- *
1787
- * @param message - Base64-encoded serialized versioned message
1788
- * @returns Fee in kelvins, or null if message is invalid
1789
- *
1790
- * @example
1791
- * ```typescript
1792
- * const fee = await client.getFeeForMessage(base64Message);
1793
- * if (fee !== null) {
1794
- * console.log(`Fee: ${fee} kelvins`);
1795
- * }
1796
- * ```
1797
- */
1798
- getFeeForMessage(message: string): Promise<bigint | null>;
1799
- /**
1800
- * Get information for multiple accounts in a single request.
1801
- *
1802
- * Useful for batch operations and reducing RPC calls.
1803
- *
1804
- * @param pubkeys - Array of public keys to query (1-100)
1805
- * @returns Account information for each address (null for non-existent accounts)
1806
- *
1807
- * @example
1808
- * ```typescript
1809
- * const accounts = await client.getMultipleAccounts([pubkey1, pubkey2]);
1810
- * accounts.value.forEach((account, i) => {
1811
- * if (account) {
1812
- * console.log(`Account ${i}: ${account.balance} kelvins`);
1813
- * }
1814
- * });
1815
- * ```
1816
- */
1817
- getMultipleAccounts(pubkeys: PublicKey[]): Promise<Array<AccountInfo | null>>;
1818
- /**
1819
- * Get all accounts owned by a specific program or address.
1820
- *
1821
- * Essential for querying token accounts, program data, and more.
1822
- *
1823
- * @param owner - Program ID or owner public key
1824
- * @param filter - Filter type (ProgramAccounts or TokenAccounts)
1825
- * @param config - Optional configuration for pagination and encoding
1826
- * @returns Accounts owned by the specified owner with pagination info
1827
- *
1828
- * @example
1829
- * ```typescript
1830
- * const result = await client.getAccountsByOwner(programId);
1831
- * console.log(`Found ${result.value.length} accounts`);
1832
- * result.value.forEach(({ pubkey, account }) => {
1833
- * console.log(`${pubkey}: ${account.balance} kelvins`);
1834
- * });
1835
- * ```
1836
- */
1837
- getAccountsByOwner(owner: PublicKey, filter?: AccountFilter, config?: GetAccountsByOwnerConfig): Promise<GetAccountsByOwnerResponse>;
1838
- /**
1839
- * Get workflow lineage information for tracking execution history.
1840
- *
1841
- * Returns the tree of transactions spawned from a root transaction
1842
- * through subscriptions and triggers.
1843
- *
1844
- * @param request - Workflow lineage request with signature and options
1845
- * @returns Workflow lineage tree with nodes and metadata
1846
- *
1847
- * @example
1848
- * ```typescript
1849
- * const lineage = await client.getWorkflowLineage({
1850
- * signature: rootTxSignature,
1851
- * maxDepth: 5,
1852
- * });
1853
- * console.log(`Found ${lineage.lineage.workflowNodes.length} nodes`);
1854
- * ```
1855
- */
1856
- getWorkflowLineage(request: GetWorkflowLineageRequest): Promise<GetWorkflowLineageResponse>;
1857
- /**
1858
- * Get subscriptions for a given subscriber address.
1859
- *
1860
- * Returns subscriptions that will trigger transactions when matching events occur.
1861
- *
1862
- * @param subscriber - The subscriber's public key
1863
- * @param nonce - The nonce identifying the subscription
1864
- * @returns The subscription for the subscriber and nonce
1865
- *
1866
- * @example
1867
- * ```typescript
1868
- * const subscription = await client.getSubscription(subscriberPubkey, "my-nonce");
1869
- * console.log(`Topic: ${subscription.topic}, Kind: ${subscription.kind}`);
1870
- * ```
1871
- */
1872
- getSubscription(subscriber: PublicKey, nonce: string): Promise<Subscription>;
1873
- /**
1874
- * Get transactions triggered by a subscription account.
1875
- *
1876
- * Returns the history of transactions that were automatically executed
1877
- * in response to subscription matches.
1878
- *
1879
- * @param subscriptionAccount - The subscription account public key
1880
- * @param limit - Optional limit on transactions returned
1881
- * @returns Triggered transactions for the subscription
1882
- *
1883
- * @example
1884
- * ```typescript
1885
- * const result = await client.getTriggeredTransactions(subscriptionPubkey, 10);
1886
- * result.transactions.forEach(tx => {
1887
- * console.log(`Signature: ${tx.signature}, Block: ${tx.blockNumber}`);
1888
- * });
1889
- * ```
1890
- */
1891
- getTriggeredTransactions(subscriptionAccount: PublicKey, limit?: number): Promise<TriggeredTransaction[]>;
1892
- /**
1893
- * Retrieve the REX X25519 public key for secret sharing encryption.
1894
- *
1895
- * This key is used for HPKE encryption when sending encrypted data
1896
- * that should only be decryptable within the REX execution environment.
1897
- *
1898
- * @returns The REX X25519 public key as a 32-byte Uint8Array
1899
- *
1900
- * @example
1901
- * ```typescript
1902
- * import { encryptForRex } from "@rialo/ts-cdk";
1903
- *
1904
- * // Get the REX public key
1905
- * const rexPubkey = await client.getSecretSharingPubkey();
1906
- *
1907
- * // Use it for HPKE encryption
1908
- * const encrypted = await encryptForRex(
1909
- * rexPubkey,
1910
- * new TextEncoder().encode("secret data"),
1911
- * keypair.publicKey.toBytes()
1912
- * );
1913
- * ```
1914
- */
1915
- getSecretSharingPubkey(): Promise<Uint8Array>;
1916
- /**
1917
- * Get the config hash prefix for replay protection.
1918
- *
1919
- * Returns the first 64 bits of the config hash, which is used
1920
- * for transaction replay protection across chains.
1921
- *
1922
- * @returns The config hash prefix as a bigint
1923
- *
1924
- * @example
1925
- * ```typescript
1926
- * const configHashPrefix = await client.getConfigHashPrefix();
1927
- * const tx = TransactionBuilder.create()
1928
- * .setPayer(payer)
1929
- * .setValidFrom(validFrom)
1930
- * .setConfigHashPrefix(configHashPrefix)
1931
- * .addInstruction(instruction)
1932
- * .build();
1933
- * ```
1934
- */
1935
- getConfigHashPrefix(): Promise<bigint>;
1936
- }
1937
-
1938
- /**
1939
- * Query client for read-only RPC operations.
1940
- */
1941
-
1942
- /**
1943
- * Client for sending/simulating transactions and requesting airdrops.
1944
- *
1945
- * Handles all transaction operations like sending transactions, requesting airdrops, etc.
1946
- */
1947
- declare class TransactionRpcClient extends BaseRpcClient {
1948
- /**
1949
- * Submit a signed transaction to the blockchain.
1950
- *
1951
- * Sends the transaction to the network for processing. The transaction
1952
- * must be fully signed before submission. Returns immediately with the
1953
- * transaction signature - use {@link confirmTransaction} or
1954
- * {@link sendAndConfirmTransaction} to wait for confirmation.
1955
- *
1956
- * @param transaction - Serialized signed transaction bytes
1957
- * @param options - Transaction submission options
1958
- * @returns Transaction signature (base58 encoded)
1959
- *
1960
- * @example
1961
- * ```typescript
1962
- * const signature = await client.sendTransaction(signedTx);
1963
- * console.log(`Submitted: ${signature}`);
1964
- *
1965
- * // With options
1966
- * const signature = await client.sendTransaction(signedTx, {
1967
- * skipPreflight: true,
1968
- * maxRetries: 3,
1969
- * });
1970
- * ```
1971
- */
1972
- sendTransaction(transaction: Uint8Array, options?: SendTransactionOptions): Promise<string>;
1973
- /**
1974
- * Wait for a transaction to be confirmed.
1975
- *
1976
- * A transaction is considered confirmed when:
1977
- * - It has been processed in a block (`blockHeight > 0`)
1978
- *
1979
- * @param signature - Transaction signature to monitor
1980
- * @param options - Confirmation options
1981
- * @returns Confirmed transaction details
1982
- * @throws {TransactionFailedError} If the transaction fails on-chain
1983
- * @throws {TransactionConfirmationTimeoutError} If confirmation times out
1984
- */
1985
- confirmTransaction(signature: string, options?: ConfirmTransactionOptions): Promise<ConfirmedTransaction>;
1986
- /**
1987
- * Submit a signed transaction and wait for confirmation.
1988
- *
1989
- * Polls the transaction status until it is confirmed (blockHeight > 0),
1990
- * or until the maximum number of retries is reached.
1991
- *
1992
- * @param transaction - Serialized signed transaction bytes
1993
- * @param options - Transaction submission and confirmation options
1994
- * @returns Confirmed transaction details
1995
- * @throws {TransactionFailedError} If the transaction fails on-chain
1996
- * @throws {TransactionConfirmationTimeoutError} If confirmation times out
1997
- *
1998
- * @example
1999
- * ```typescript
2000
- * const result = await client.sendAndConfirmTransaction(signedTx);
2001
- * console.log(`Confirmed in block ${result.blockHeight}, executed: ${result.executed}`);
2002
- *
2003
- * // With custom retry settings
2004
- * const result = await client.sendAndConfirmTransaction(signedTx, {
2005
- * maxRetries: 3,
2006
- * retryDelay: 500,
2007
- * });
2008
- * ```
2009
- */
2010
- sendAndConfirmTransaction(transaction: Uint8Array, options?: SendAndConfirmOptions): Promise<ConfirmedTransaction>;
2011
- /**
2012
- * Request an airdrop of tokens to an account.
2013
- *
2014
- * **Note**: Only available on devnet and testnet networks.
2015
- *
2016
- * Returns immediately with the airdrop transaction signature.
2017
- * Use {@link requestAirdropAndConfirm} to wait for the airdrop to complete.
2018
- *
2019
- * @param pubkey - The public key of the account to receive tokens
2020
- * @param amount - Amount to airdrop in kelvins (smallest unit)
2021
- * @returns Airdrop transaction signature
2022
- *
2023
- * @example
2024
- * ```typescript
2025
- * const signature = await client.requestAirdrop(publicKey, 1_000_000_000n);
2026
- * console.log(`Airdrop requested: ${signature}`);
2027
- * ```
2028
- */
2029
- requestAirdrop(pubkey: PublicKey, amount: bigint): Promise<string>;
2030
- /**
2031
- * Request an airdrop of tokens and wait for confirmation.
2032
- *
2033
- * **Note**: Only available on devnet and testnet networks.
2034
- *
2035
- * Combines {@link requestAirdrop} and {@link confirmTransaction} into
2036
- * a single call for convenience.
2037
- *
2038
- * @param pubkey - The public key of the account to receive tokens
2039
- * @param amount - Amount to airdrop in kelvins (smallest unit)
2040
- * @param options - Confirmation options (max retries, retry delay)
2041
- * @returns Confirmed transaction details
2042
- * @throws {RpcError} If the airdrop transaction fails or confirmation times out
2043
- *
2044
- * @example
2045
- * ```typescript
2046
- * const result = await client.requestAirdropAndConfirm(publicKey, 1_000_000_000n);
2047
- * if (result.executed) {
2048
- * console.log("Airdrop confirmed!");
2049
- * }
2050
- * ```
2051
- */
2052
- requestAirdropAndConfirm(pubkey: PublicKey, amount: bigint, options?: ConfirmTransactionOptions): Promise<ConfirmedTransaction>;
2053
- private getTransaction;
2054
- /**
2055
- * Sleeps for a given number of milliseconds.
2056
- * @param ms - The number of milliseconds to sleep.
2057
- * @returns A promise that resolves when the sleep is complete.
2058
- */
2059
- private sleep;
2060
- }
2061
-
2062
- /**
2063
- * Error codes for RPC operations, categorized by type.
2064
- */
2065
- declare enum RpcErrorCode {
2066
- REQUEST_TIMEOUT = "REQUEST_TIMEOUT",
2067
- NETWORK_ERROR = "NETWORK_ERROR",
2068
- CONNECTION_REFUSED = "CONNECTION_REFUSED",
2069
- INVALID_NETWORK = "INVALID_NETWORK",
2070
- INVALID_RESPONSE = "INVALID_RESPONSE",
2071
- PARSE_ERROR = "PARSE_ERROR",
2072
- INVALID_REQUEST = "INVALID_REQUEST",
2073
- METHOD_NOT_FOUND = "METHOD_NOT_FOUND",
2074
- INVALID_PARAMS = "INVALID_PARAMS",
2075
- INTERNAL_ERROR = "INTERNAL_ERROR",
2076
- TRANSACTION_REJECTED = "TRANSACTION_REJECTED",
2077
- INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
2078
- TRANSACTION_CONFIRMATION_TIMEOUT = "TRANSACTION_CONFIRMATION_TIMEOUT",
2079
- ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND",
2080
- RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED",
2081
- NODE_UNHEALTHY = "NODE_UNHEALTHY"
2082
- }
2083
- /**
2084
- * Detailed error context for debugging and error handling.
2085
- */
2086
- interface RpcErrorDetails {
2087
- method?: string;
2088
- params?: unknown;
2089
- requestId?: number;
2090
- url?: string;
2091
- httpStatus?: number;
2092
- rpcCode?: number;
2093
- timeout?: number;
2094
- attempts?: number;
2095
- [key: string]: unknown;
2096
- }
2097
- /**
2098
- * Error class for RPC operations with structured error information.
2099
- *
2100
- * Provides actionable error messages and indicates whether errors are retryable.
2101
- */
2102
- declare class RpcError extends Error {
2103
- readonly code: RpcErrorCode;
2104
- readonly details: RpcErrorDetails;
2105
- readonly retryable: boolean;
2106
- constructor(code: RpcErrorCode, message: string, details?: RpcErrorDetails, retryable?: boolean);
2107
- static requestTimeout(timeoutMs: number, details: RpcErrorDetails): RpcError;
2108
- static networkError(message: string, details: RpcErrorDetails): RpcError;
2109
- static invalidResponse(details: RpcErrorDetails): RpcError;
2110
- static accountNotFound(pubkey: string): RpcError;
2111
- static rateLimitExceeded(details: RpcErrorDetails): RpcError;
2112
- static fromRpcCode(rpcCode: number, message: string, details: RpcErrorDetails): RpcError;
2113
- toJSON(): {
2114
- code: RpcErrorCode;
2115
- message: string;
2116
- details?: Record<string, unknown>;
2117
- retryable: boolean;
2118
- };
2119
- }
2120
-
2121
- /**
2122
- * Creates an RPC client with automatic retry and timeout handling.
2123
- *
2124
- * @param config - Client configuration with chain definition and optional transport settings
2125
- * @param config.chain - Chain definition (e.g., RIALO_DEVNET_CHAIN, RIALO_MAINNET_CHAIN) or a custom chain with your own rpcUrl
2126
- * @param config.transport - Optional transport configuration (timeout, retries, headers)
2127
- * @returns Configured RialoClient instance
2128
- *
2129
- * @example
2130
- * ```typescript
2131
- * // Basic usage with preset chain
2132
- * const client = createRialoClient({ chain: RIALO_DEVNET_CHAIN });
2133
- *
2134
- * // With custom transport config
2135
- * const client = createRialoClient({
2136
- * chain: RIALO_MAINNET_CHAIN,
2137
- * transport: { timeout: 30000, maxRetries: 5 }
2138
- * });
2139
- *
2140
- * // With custom RPC URL
2141
- * const client = createRialoClient({
2142
- * chain: {
2143
- * id: 'rialo:mainnet',
2144
- * name: 'Mainnet',
2145
- * rpcUrl: 'https://mainnet.custom-rpc.com:4101'
2146
- * },
2147
- * });
2148
- * ```
2149
- */
2150
- declare function createRialoClient(config: RialoClientConfig): RialoClient;
2151
- /**
2152
- * Returns a default RialoClientConfig for a given network.
2153
- *
2154
- * Provides preset chain configurations for standard Rialo networks, making it easy
2155
- * to connect to mainnet, devnet, testnet, or localnet without manual configuration.
2156
- *
2157
- * @param network - Network identifier: "mainnet", "devnet", "testnet", or "localnet"
2158
- * @returns Default RialoClientConfig for the specified network
2159
- * @throws {RpcError} With code INVALID_NETWORK if an unknown network is provided
2160
- *
2161
- * @example
2162
- * ```typescript
2163
- * // Get devnet config and create client
2164
- * const config = getDefaultRialoClientConfig('devnet');
2165
- * const client = createRialoClient(config);
2166
- *
2167
- * // Customize the config with transport options
2168
- * const config = getDefaultRialoClientConfig('mainnet');
2169
- * const client = createRialoClient({
2170
- * ...config,
2171
- * transport: { timeout: 60000, maxRetries: 5 }
2172
- * });
2173
- *
2174
- * // Use custom RPC URL while preserving network identity
2175
- * const config = getDefaultRialoClientConfig('mainnet');
2176
- * const client = createRialoClient({
2177
- * ...config,
2178
- * chain: {
2179
- * ...config.chain,
2180
- * rpcUrl: 'https://mainnet.custom-rpc.com:4101'
2181
- * },
2182
- * });
2183
- * ```
2184
- */
2185
- declare function getDefaultRialoClientConfig(network: RialoNetwork): RialoClientConfig;
2186
-
2187
- /**
2188
- * Bincode deserialization reader
2189
- *
2190
- * Matches Rust's bincode crate with default configuration:
2191
- * - Little-endian byte order
2192
- * - Fixed-size integer encoding (no varint)
2193
- * - u64 length prefixes for dynamic collections
2194
- * - u32 enum variant indices
2195
- */
2196
- declare class BincodeReader {
2197
- private view;
2198
- private offset;
2199
- private bytes;
2200
- constructor(data: Uint8Array);
2201
- getOffset(): number;
2202
- remaining(): number;
2203
- isExhausted(): boolean;
2204
- skip(bytes: number): this;
2205
- /**
2206
- * Peek at bytes without advancing the offset
2207
- */
2208
- peek(length: number): Uint8Array;
2209
- /**
2210
- * Reset reader to beginning
2211
- */
2212
- reset(): this;
2213
- /**
2214
- * Seek to specific offset
2215
- */
2216
- seek(offset: number): this;
2217
- readU8(): number;
2218
- readU16(): number;
2219
- readU32(): number;
2220
- readU64(): bigint;
2221
- readU128(): bigint;
2222
- readI8(): number;
2223
- readI16(): number;
2224
- readI32(): number;
2225
- readI64(): bigint;
2226
- readI128(): bigint;
2227
- readF32(): number;
2228
- readF64(): number;
2229
- readBool(): boolean;
2230
- readBytes(length: number): Uint8Array;
2231
- readFixedArray(length: number): Uint8Array;
2232
- readVecBytes(): Uint8Array;
2233
- readString(): string;
2234
- readVariant(): number;
2235
- readOption<T>(readValue: () => T): T | null;
2236
- readVec<T>(readElement: () => T): T[];
2237
- /**
2238
- * Read a tuple of fixed size with heterogeneous types
2239
- */
2240
- readTuple<T extends unknown[]>(readers: {
2241
- [K in keyof T]: () => T[K];
2242
- }): T;
2243
- readMap<K, V>(readKey: () => K, readValue: () => V): Map<K, V>;
2244
- /**
2245
- * Read length as u64 but validate it's within safe integer range
2246
- */
2247
- private readLength;
2248
- private ensureAvailable;
2249
- }
2250
-
2251
- /**
2252
- * Type definitions for bincode schemas
2253
- *
2254
- * IMPORTANT: For structs and enums, field/variant order MUST match Rust definition order.
2255
- * Use arrays of tuples instead of objects to guarantee order preservation.
2256
- */
2257
- type BincodeSchema = {
2258
- type: "u8";
2259
- } | {
2260
- type: "u16";
2261
- } | {
2262
- type: "u32";
2263
- } | {
2264
- type: "u64";
2265
- } | {
2266
- type: "u128";
2267
- } | {
2268
- type: "i8";
2269
- } | {
2270
- type: "i16";
2271
- } | {
2272
- type: "i32";
2273
- } | {
2274
- type: "i64";
2275
- } | {
2276
- type: "i128";
2277
- } | {
2278
- type: "f32";
2279
- } | {
2280
- type: "f64";
2281
- } | {
2282
- type: "bool";
2283
- } | {
2284
- type: "string";
2285
- } | {
2286
- type: "bytes";
2287
- } | {
2288
- type: "unit";
2289
- } | {
2290
- type: "fixedArray";
2291
- length: number;
2292
- } | {
2293
- type: "vec";
2294
- element: BincodeSchema;
2295
- } | {
2296
- type: "option";
2297
- inner: BincodeSchema;
2298
- } | {
2299
- type: "tuple";
2300
- elements: BincodeSchema[];
2301
- } | {
2302
- type: "struct";
2303
- fields: StructField[];
2304
- } | {
2305
- type: "enum";
2306
- variants: EnumVariant[];
2307
- } | {
2308
- type: "map";
2309
- key: BincodeSchema;
2310
- value: BincodeSchema;
2311
- } | {
2312
- type: "pubkey";
2313
- };
2314
- /**
2315
- * Struct field definition - order matters!
2316
- */
2317
- interface StructField {
2318
- name: string;
2319
- schema: BincodeSchema;
2320
- }
2321
- /**
2322
- * Enum variant definition - order matters!
2323
- */
2324
- interface EnumVariant {
2325
- name: string;
2326
- schema: BincodeSchema | null;
2327
- }
2328
- declare const Schema: {
2329
- readonly u8: () => BincodeSchema;
2330
- readonly u16: () => BincodeSchema;
2331
- readonly u32: () => BincodeSchema;
2332
- readonly u64: () => BincodeSchema;
2333
- readonly u128: () => BincodeSchema;
2334
- readonly i8: () => BincodeSchema;
2335
- readonly i16: () => BincodeSchema;
2336
- readonly i32: () => BincodeSchema;
2337
- readonly i64: () => BincodeSchema;
2338
- readonly i128: () => BincodeSchema;
2339
- readonly f32: () => BincodeSchema;
2340
- readonly f64: () => BincodeSchema;
2341
- readonly bool: () => BincodeSchema;
2342
- readonly string: () => BincodeSchema;
2343
- readonly bytes: () => BincodeSchema;
2344
- readonly unit: () => BincodeSchema;
2345
- readonly fixedArray: (length: number) => BincodeSchema;
2346
- readonly vec: (element: BincodeSchema) => BincodeSchema;
2347
- readonly option: (inner: BincodeSchema) => BincodeSchema;
2348
- readonly tuple: (...elements: BincodeSchema[]) => BincodeSchema;
2349
- /**
2350
- * Define a struct with ordered fields
2351
- * @example
2352
- * Schema.struct([
2353
- * ["id", Schema.u64()],
2354
- * ["name", Schema.string()],
2355
- * ["active", Schema.bool()],
2356
- * ])
2357
- */
2358
- readonly struct: (fields: [string, BincodeSchema][]) => BincodeSchema;
2359
- /**
2360
- * Define an enum with ordered variants
2361
- * @example
2362
- * Schema.enum([
2363
- * ["None", null],
2364
- * ["Some", Schema.u64()],
2365
- * ["Error", Schema.string()],
2366
- * ])
2367
- */
2368
- readonly enum: (variants: [string, BincodeSchema | null][]) => BincodeSchema;
2369
- readonly map: (key: BincodeSchema, value: BincodeSchema) => BincodeSchema;
2370
- readonly pubkey: () => BincodeSchema;
2371
- };
2372
- /**
2373
- * Serialize a value according to a schema
2374
- */
2375
- declare function serialize(schema: BincodeSchema, value: unknown): Uint8Array;
2376
- /**
2377
- * Deserialize bytes according to a schema
2378
- */
2379
- declare function deserialize<T>(schema: BincodeSchema, data: Uint8Array): T;
2380
- /**
2381
- * Deserialize bytes with strict validation
2382
- */
2383
- declare function deserializeStrict<T>(schema: BincodeSchema, data: Uint8Array): T;
2384
- /**
2385
- * Infer TypeScript type from schema (for documentation purposes)
2386
- *
2387
- * Usage:
2388
- * const mySchema = Schema.struct([...]);
2389
- * type MyType = InferSchema<typeof mySchema>;
2390
- */
2391
- type InferSchema<S extends BincodeSchema> = S extends {
2392
- type: "u8";
2393
- } ? number : S extends {
2394
- type: "u16";
2395
- } ? number : S extends {
2396
- type: "u32";
2397
- } ? number : S extends {
2398
- type: "u64";
2399
- } ? bigint : S extends {
2400
- type: "u128";
2401
- } ? bigint : S extends {
2402
- type: "i8";
2403
- } ? number : S extends {
2404
- type: "i16";
2405
- } ? number : S extends {
2406
- type: "i32";
2407
- } ? number : S extends {
2408
- type: "i64";
2409
- } ? bigint : S extends {
2410
- type: "i128";
2411
- } ? bigint : S extends {
2412
- type: "f32";
2413
- } ? number : S extends {
2414
- type: "f64";
2415
- } ? number : S extends {
2416
- type: "bool";
2417
- } ? boolean : S extends {
2418
- type: "string";
2419
- } ? string : S extends {
2420
- type: "bytes";
2421
- } ? Uint8Array : S extends {
2422
- type: "unit";
2423
- } ? undefined : S extends {
2424
- type: "fixedArray";
2425
- } ? Uint8Array : S extends {
2426
- type: "pubkey";
2427
- } ? Uint8Array : S extends {
2428
- type: "vec";
2429
- element: infer E;
2430
- } ? E extends BincodeSchema ? InferSchema<E>[] : never : S extends {
2431
- type: "option";
2432
- inner: infer I;
2433
- } ? I extends BincodeSchema ? InferSchema<I> | null : never : unknown;
2434
-
2435
- /**
2436
- * Bincode serialization writer
2437
- *
2438
- * Matches Rust's bincode crate with default configuration:
2439
- * - Little-endian byte order
2440
- * - Fixed-size integer encoding (no varint)
2441
- * - u64 length prefixes for dynamic collections
2442
- * - u32 enum variant indices
2443
- */
2444
- declare class BincodeWriter {
2445
- private buffer;
2446
- private offset;
2447
- private view;
2448
- constructor(initialCapacity?: number);
2449
- writeU8(value: number): this;
2450
- writeU16(value: number): this;
2451
- writeU32(value: number): this;
2452
- writeU64(value: bigint | number): this;
2453
- writeU128(value: bigint): this;
2454
- writeI8(value: number): this;
2455
- writeI16(value: number): this;
2456
- writeI32(value: number): this;
2457
- writeI64(value: bigint): this;
2458
- writeI128(value: bigint): this;
2459
- writeF32(value: number): this;
2460
- writeF64(value: number): this;
2461
- writeBool(value: boolean): this;
2462
- writeBytes(bytes: Uint8Array): this;
2463
- writeFixedArray(bytes: Uint8Array, expectedLength?: number): this;
2464
- writeVecBytes(bytes: Uint8Array): this;
2465
- writeString(str: string): this;
2466
- writeVariant(index: number): this;
2467
- writeOption<T>(value: T | null | undefined, writeValue: (writer: BincodeWriter, val: T) => void): this;
2468
- writeVec<T>(items: T[], writeItem: (writer: BincodeWriter, item: T) => void): this;
2469
- /**
2470
- * Write a tuple (fixed-size heterogeneous collection)
2471
- */
2472
- writeTuple<T extends unknown[]>(items: T, writers: {
2473
- [K in keyof T]: (writer: BincodeWriter, val: T[K]) => void;
2474
- }): this;
2475
- writeMap<K, V>(map: Map<K, V>, writeKey: (writer: BincodeWriter, key: K) => void, writeValue: (writer: BincodeWriter, value: V) => void): this;
2476
- toBytes(): Uint8Array;
2477
- /**
2478
- * Get a view of the written bytes WITHOUT copying.
2479
- *
2480
- * ⚠️ WARNING: This returns a view into the internal buffer.
2481
- * The view becomes INVALID if:
2482
- * - The writer continues writing (may trigger resize)
2483
- * - The writer is cleared via clear()
2484
- *
2485
- * Use toBytes() for a safe copy, or use this only for immediate
2486
- * read-only access when performance is critical.
2487
- */
2488
- toView(): Uint8Array;
2489
- length(): number;
2490
- clear(): this;
2491
- /**
2492
- * Reserve additional capacity
2493
- */
2494
- reserve(additionalBytes: number): this;
2495
- private ensureCapacity;
2496
- }
2497
-
2498
- /**
2499
- * Serializes data using Borsh (Binary Object Representation Serializer for Hashing) encoding.
2500
- *
2501
- * Borsh is efficient for complex types like enums, Options, vectors, and nested structs.
2502
- * Use the exported decorators (@field, @option, @vec) to define your data structures.
2503
- *
2504
- * @param data - Data object to serialize
2505
- * @returns Serialized bytes
2506
- *
2507
- * @example
2508
- * ```typescript
2509
- * import { serializeBorsh, field, option } from '@rialo/ts-cdk';
2510
- *
2511
- * class SwapInstruction {
2512
- * @field({ type: 'u8' })
2513
- * instruction: number;
2514
- *
2515
- * @field({ type: 'u64' })
2516
- * amountIn: bigint;
2517
- *
2518
- * @field({ type: option('u64') })
2519
- * minAmountOut?: bigint;
2520
- * }
2521
- *
2522
- * const data = serializeBorsh(new SwapInstruction({
2523
- * instruction: 1,
2524
- * amountIn: 1000n,
2525
- * minAmountOut: 900n,
2526
- * }));
2527
- * ```
2528
- */
2529
- declare function serializeBorsh<T>(data: T): Uint8Array;
2530
- /**
2531
- * Deserializes Borsh-encoded data into a typed object.
2532
- *
2533
- * @param data - Borsh-encoded bytes
2534
- * @param type - Class constructor for the target type
2535
- * @returns Deserialized object instance
2536
- */
2537
- declare function deserializeBorsh<T>(data: Uint8Array, type: new () => T): T;
2538
-
2539
- /**
2540
- * Serializes a u16 value into compact encoding.
2541
- *
2542
- * @param buffer - Output buffer to append bytes to
2543
- * @param value - Value to encode (0-65535)
2544
- * @throws {TransactionError} If value is out of range
2545
- */
2546
- declare function serializeCompactU16(buffer: number[], value: number): void;
2547
- /**
2548
- * Deserializes a compact-u16 value from bytes.
2549
- *
2550
- * @param data - Input byte array
2551
- * @param currentCursor - Starting position in the array
2552
- * @returns Tuple of [decoded value, new cursor position]
2553
- * @throws {TransactionError} If data is insufficient or malformed
2554
- */
2555
- declare function deserializeCompactU16(data: Uint8Array, currentCursor: number): [number, number];
2556
- /**
2557
- * Writes a compact-u16 value directly to a buffer (zero-copy).
2558
- *
2559
- * Optimized version for in-place writing without intermediate allocations.
2560
- *
2561
- * @param buffer - Target buffer
2562
- * @param offset - Starting position to write at
2563
- * @param value - Value to encode (0-127 only, uses 1-2 bytes)
2564
- * @returns New offset after writing
2565
- */
2566
- declare function writeCompactU16(buffer: Uint8Array, offset: number, value: number): number;
2567
-
2568
- /**
2569
- * Interface for signing messages and transactions.
2570
- *
2571
- * Enables multiple signing strategies:
2572
- * - **KeypairSigner**: Local keypair signing
2573
- * - **Browser Wallet**: Browser extension integration
2574
- * - **Hardware Wallet**: Ledger, Trezor, etc.
2575
- * - **Remote Signer**: API-based signing services
2576
- *
2577
- * @example
2578
- * ```typescript
2579
- * // Browser wallet implementation
2580
- * class BrowserWalletSigner implements Signer {
2581
- * async getPublicKey(): Promise<PublicKey> {
2582
- * const pubkey = await window.rialoWallet.getPublicKey();
2583
- * return PublicKey.fromString(pubkey);
2584
- * }
2585
- *
2586
- * async signMessage(message: Uint8Array): Promise<Signature> {
2587
- * const sig = await window.rialoWallet.signMessage(message);
2588
- * return Signature.fromBytes(sig);
2589
- * }
2590
- * }
2591
- *
2592
- * // Usage
2593
- * const signer = new BrowserWalletSigner();
2594
- * const publicKey = await signer.getPublicKey();
2595
- * const signature = await signer.signMessage(message);
2596
- * ```
2597
- */
2598
- interface Signer {
2599
- /**
2600
- * Retrieves the signer's public key.
2601
- *
2602
- * **Note**: May trigger wallet connection prompts for browser wallets.
2603
- */
2604
- getPublicKey(): Promise<PublicKey>;
2605
- /**
2606
- * Signs arbitrary message bytes.
2607
- *
2608
- * @param message - Message bytes to sign
2609
- * @returns Ed25519 signature over the message
2610
- */
2611
- signMessage(message: Uint8Array): Promise<Signature>;
2612
- }
2613
-
2614
- /**
2615
- * Signer implementation using a local Ed25519 keypair.
2616
- *
2617
- * Provides synchronous signing without external dependencies.
2618
- * Suitable for server-side applications, CLIs, and testing.
2619
- *
2620
- * @example
2621
- * ```typescript
2622
- * import { Keypair, KeypairSigner } from '@rialo/ts-cdk';
2623
- *
2624
- * // Generate new keypair
2625
- * const keypair = Keypair.generate();
2626
- * const signer = new KeypairSigner(keypair);
2627
- *
2628
- * // Or from mnemonic
2629
- * const mnemonic = Mnemonic.generate();
2630
- * const keypair = await mnemonic.toKeypair(0);
2631
- * const signer = new KeypairSigner(keypair);
2632
- *
2633
- * // Sign messages
2634
- * const publicKey = await signer.getPublicKey();
2635
- * const signature = await signer.signMessage(message);
2636
- * ```
2637
- */
2638
- declare class KeypairSigner implements Signer {
2639
- private readonly keypair;
2640
- constructor(keypair: Keypair);
2641
- /**
2642
- * Returns the keypair's public key.
2643
- */
2644
- getPublicKey(): Promise<PublicKey>;
2645
- /**
2646
- * Signs a message using the keypair's private key.
2647
- */
2648
- signMessage(message: Uint8Array): Promise<Signature>;
2649
- }
2650
-
2651
- /**
2652
- * Metadata about an account in a transaction.
2653
- */
2654
- interface AccountMeta {
2655
- /** Account public key */
2656
- readonly pubkey: PublicKey;
2657
- /** Whether this account must sign the transaction */
2658
- readonly isSigner: boolean;
2659
- /** Whether this account's data will be modified */
2660
- readonly isWritable: boolean;
2661
- }
2662
- /**
2663
- * An instruction to execute on-chain.
2664
- */
2665
- interface Instruction {
2666
- /** Program that will execute this instruction */
2667
- readonly programId: PublicKey;
2668
- /** Accounts used by this instruction */
2669
- readonly accounts: readonly AccountMeta[];
2670
- /** Instruction-specific data */
2671
- readonly data: Uint8Array;
2672
- }
2673
- /**
2674
- * Message header containing signature requirements.
2675
- */
2676
- interface MessageHeader {
2677
- /** Number of signatures required */
2678
- readonly numRequiredSignatures: number;
2679
- /** Number of read-only signed accounts */
2680
- readonly numReadonlySignedAccounts: number;
2681
- /** Number of read-only unsigned accounts */
2682
- readonly numReadonlyUnsignedAccounts: number;
2683
- }
2684
- /**
2685
- * Compiled instruction with account indices.
2686
- */
2687
- interface CompiledInstruction {
2688
- /** Index of program in account keys array */
2689
- readonly programIdIndex: number;
2690
- /** Indices of accounts in account keys array */
2691
- readonly accountKeyIndexes: readonly number[];
2692
- /** Instruction data */
2693
- readonly data: Uint8Array;
2694
- }
2695
-
2696
- /**
2697
- * Account metadata table for deduplication and sorting.
2698
- * Avoids: Complex account sorting logic scattered throughout builder
2699
- */
2700
-
2701
- /**
2702
- * Internal account entry with aggregated metadata.
2703
- */
2704
- interface AccountEntry {
2705
- pubkey: PublicKey;
2706
- isSigner: boolean;
2707
- isWritable: boolean;
2708
- }
2709
- /**
2710
- * Manages account deduplication and sorting for transaction messages.
2711
- *
2712
- * Accounts are sorted according to these rules:
2713
- * 1. Signer + writable accounts first
2714
- * 2. Then signer + readonly accounts
2715
- * 3. Then non-signer + writable accounts
2716
- * 4. Finally non-signer + readonly accounts
2717
- * 5. Within each group, sort by public key bytes
2718
- *
2719
- * This matches Solana's account sorting rules for compatibility.
2720
- */
2721
- declare class AccountMetaTable {
2722
- private readonly accounts;
2723
- private readonly accountOrder;
2724
- /**
2725
- * Add or update an account in the table.
2726
- * If account already exists, merges signer/writable flags (OR operation).
2727
- */
2728
- add(meta: AccountMeta): void;
2729
- /**
2730
- * Add multiple accounts at once.
2731
- */
2732
- addAll(metas: readonly AccountMeta[]): void;
2733
- /**
2734
- * Get the index of an account in the sorted order.
2735
- * Returns -1 if account not found.
2736
- */
2737
- getIndex(pubkey: PublicKey): number;
2738
- /**
2739
- * Get sorted accounts according to transaction rules.
2740
- */
2741
- getSortedAccounts(): readonly AccountEntry[];
2742
- /**
2743
- * Get the message header based on sorted accounts.
2744
- */
2745
- getHeader(): MessageHeader;
2746
- /**
2747
- * Get sorted public keys.
2748
- */
2749
- getPublicKeys(): readonly PublicKey[];
2750
- /**
2751
- * Get number of accounts in table.
2752
- */
2753
- size(): number;
2754
- }
2755
-
2756
- /**
2757
- * Error codes for transaction operations.
2758
- */
2759
- declare enum TransactionErrorCode {
2760
- INVALID_INSTRUCTION = "INVALID_INSTRUCTION",
2761
- INVALID_ACCOUNT_META = "INVALID_ACCOUNT_META",
2762
- NO_INSTRUCTIONS = "NO_INSTRUCTIONS",
2763
- DUPLICATE_ACCOUNT = "DUPLICATE_ACCOUNT",
2764
- MISSING_SIGNATURE = "MISSING_SIGNATURE",
2765
- INVALID_SIGNATURE = "INVALID_SIGNATURE",
2766
- SIGNATURE_OUT_OF_BOUNDS = "SIGNATURE_OUT_OF_BOUNDS",
2767
- SIGNER_NOT_FOUND = "SIGNER_NOT_FOUND",
2768
- ALREADY_SIGNED = "ALREADY_SIGNED",
2769
- INVALID_MESSAGE_FORMAT = "INVALID_MESSAGE_FORMAT",
2770
- INSUFFICIENT_DATA = "INSUFFICIENT_DATA",
2771
- SERIALIZATION_FAILED = "SERIALIZATION_FAILED",
2772
- SIMULATION_FAILED = "SIMULATION_FAILED",
2773
- INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
2774
- BLOCKHASH_EXPIRED = "BLOCKHASH_EXPIRED"
2775
- }
2776
- /**
2777
- * Error class for transaction operations with structured error information.
2778
- */
2779
- declare class TransactionError extends Error {
2780
- readonly code: TransactionErrorCode;
2781
- readonly details?: Record<string, unknown> | undefined;
2782
- constructor(code: TransactionErrorCode, message: string, details?: Record<string, unknown> | undefined);
2783
- static noInstructions(): TransactionError;
2784
- static signerNotFound(pubkey: string): TransactionError;
2785
- static missingSignature(index: number, pubkey: string): TransactionError;
2786
- static simulationFailed(logs: string[], error: string): TransactionError;
2787
- static insufficientFunds(required: bigint, available: bigint): TransactionError;
2788
- toJSON(): {
2789
- code: TransactionErrorCode;
2790
- message: string;
2791
- details?: Record<string, unknown>;
2792
- };
2793
- }
2794
-
2795
- /**
2796
- * Create an instruction with Borsh-encoded data.
2797
- *
2798
- * @example
2799
- * ```typescript
2800
- * // Define your instruction data class
2801
- * class MyInstructionData {
2802
- * @field({ type: 'u8' })
2803
- * instruction: number;
2804
- *
2805
- * @field({ type: 'u64' })
2806
- * amount: bigint;
2807
- *
2808
- * @field({ type: option('string') })
2809
- * memo?: string;
2810
- * }
2811
- *
2812
- * // Create instruction
2813
- * const instruction = createBorshInstruction({
2814
- * programId: myProgramId,
2815
- * accounts: [
2816
- * { pubkey: account1, isSigner: true, isWritable: true },
2817
- * { pubkey: account2, isSigner: false, isWritable: false },
2818
- * ],
2819
- * data: new MyInstructionData({
2820
- * instruction: 5,
2821
- * amount: 1000n,
2822
- * memo: "Hello, Rialo!",
2823
- * }),
2824
- * });
2825
- * ```
2826
- */
2827
- declare function createBorshInstruction<T>(params: {
2828
- programId: PublicKey;
2829
- accounts: AccountMeta[];
2830
- data: T;
2831
- }): Instruction;
2832
- /**
2833
- * Helper for creating Borsh-serialized instruction data from a plain object.
2834
- *
2835
- * This is useful when you don't want to define a class with decorators.
2836
- *
2837
- * @example
2838
- * ```typescript
2839
- * const data = encodeBorshData({
2840
- * instruction: { type: 'u8', value: 1 },
2841
- * amount: { type: 'u64', value: 1000n },
2842
- * recipient: { type: fixedArray('u8', 32), value: recipientBytes },
2843
- * });
2844
- * ```
2845
- */
2846
- declare function encodeBorshData(_schema: Record<string, {
2847
- type: unknown;
2848
- value: unknown;
2849
- }>): Uint8Array;
2850
-
2851
- /**
2852
- * System program instruction types.
2853
- */
2854
- declare enum SystemInstruction {
2855
- CreateAccount = 0,
2856
- Assign = 1,
2857
- Transfer = 2,
2858
- CreateAccountWithSeed = 3,
2859
- AdvanceNonceAccount = 4,
2860
- WithdrawNonceAccount = 5,
2861
- InitializeNonceAccount = 6,
2862
- AuthorizeNonceAccount = 7,
2863
- Allocate = 8,
2864
- AllocateWithSeed = 9,
2865
- AssignWithSeed = 10,
2866
- TransferWithSeed = 11
2867
- }
2868
- /**
2869
- * Create a transfer instruction.
2870
- *
2871
- * Transfers native tokens from one account to another.
2872
- *
2873
- * @param from - Source account (must be signer)
2874
- * @param to - Destination account
2875
- * @param amount - Amount to transfer in smallest denomination (kelvins)
2876
- *
2877
- * @example
2878
- * ```typescript
2879
- * const instruction = transferInstruction(fromPubkey, toPubkey, 1_000_000n);
2880
- *
2881
- * const tx = TransactionBuilder.create()
2882
- * .setPayer(fromPubkey)
2883
- * .addInstruction(instruction)
2884
- * .build();
2885
- * ```
2886
- */
2887
- declare function transferInstruction(from: PublicKey, to: PublicKey, amount: bigint): Instruction;
2888
- /**
2889
- * Create an account creation instruction.
2890
- *
2891
- * @param from - Funding account (must be signer)
2892
- * @param newAccount - New account to create (must be signer)
2893
- * @param kelvins - Initial balance for new account
2894
- * @param space - Number of bytes to allocate for account data
2895
- * @param owner - Program that will own the new account
2896
- */
2897
- declare function createAccount(from: PublicKey, newAccount: PublicKey, kelvins: bigint, space: bigint, owner: PublicKey): Instruction;
2898
- /**
2899
- * Create an allocate instruction.
2900
- *
2901
- * Allocates space for an account's data. The account must be owned by
2902
- * the system program and must sign the transaction.
2903
- *
2904
- * @param account - Account to allocate space for (must be signer)
2905
- * @param space - Number of bytes to allocate
2906
- */
2907
- declare function allocateInstruction(account: PublicKey, space: bigint): Instruction;
2908
- /**
2909
- * Create an assign instruction.
2910
- *
2911
- * Changes the owner of an account. The account must currently be owned
2912
- * by the system program and must sign the transaction.
2913
- *
2914
- * @param account - Account to reassign (must be signer)
2915
- * @param owner - New owner program
2916
- */
2917
- declare function assignInstruction(account: PublicKey, owner: PublicKey): Instruction;
2918
-
2919
- /**
2920
- * An unsigned transaction message ready to be signed.
2921
- *
2922
- * This is the data that gets signed by transaction signers.
2923
- * It's immutable to prevent accidental modification after creation.
2924
- *
2925
- * @example
2926
- * ```typescript
2927
- * const message = MessageBuilder.create()
2928
- * .setPayer(payer)
2929
- * .setValidFrom(validFrom)
2930
- * .addInstruction(transferInstruction)
2931
- * .build();
2932
- *
2933
- * // Serialize for signing
2934
- * const messageBytes = message.serialize();
2935
- * ```
2936
- */
2937
- declare class Message {
2938
- /** Message header with signature requirements */
2939
- readonly header: MessageHeader;
2940
- /** All account public keys referenced in the transaction */
2941
- readonly accountKeys: readonly PublicKey[];
2942
- /** Transaction valid from (milliseconds since Unix epoch) */
2943
- validFrom?: bigint;
2944
- /** Config hash prefix for replay protection across chains */
2945
- readonly configHashPrefix: bigint;
2946
- /** Compiled instructions with account indices */
2947
- readonly instructions: readonly CompiledInstruction[];
2948
- /** Cached serialized bytes */
2949
- private serializedCache?;
2950
- constructor(header: MessageHeader, accountKeys: readonly PublicKey[], validFrom: bigint, configHashPrefix: bigint, instructions: readonly CompiledInstruction[]);
2951
- /**
2952
- * Serialize message to bytes for signing.
2953
- * Result is cached for performance.
2954
- */
2955
- serialize(): Uint8Array;
2956
- /**
2957
- * Deserialize a message from wire format.
2958
- *
2959
- * @param data - Serialized message bytes
2960
- * @returns Deserialized Message
2961
- */
2962
- static deserialize(data: Uint8Array): Message;
2963
- private serializeInternal;
2964
- private serializeCompactArray;
2965
- private serializeCompactU16;
2966
- /**
2967
- * Get all signers required for this message.
2968
- */
2969
- getSigners(): readonly PublicKey[];
2970
- /**
2971
- * Check if a public key is a required signer.
2972
- */
2973
- isSignerRequired(pubkey: PublicKey): boolean;
2974
- /**
2975
- * Get the index of a signer in the signers array.
2976
- * Returns -1 if not a signer.
2977
- */
2978
- getSignerIndex(pubkey: PublicKey): number;
2979
- }
2980
-
2981
- /**
2982
- * A transaction with zero or more signatures.
2983
- *
2984
- * Transactions are immutable - signing methods return new instances.
2985
- * This prevents accidental modification and signature tampering.
2986
- *
2987
- * @example
2988
- * ```typescript
2989
- * // Simple signing
2990
- * const tx = builder.build();
2991
- * const signed = tx.sign(keypair);
2992
- *
2993
- * // Method chaining
2994
- * const signed = tx
2995
- * .sign(keypair1)
2996
- * .sign(keypair2)
2997
- * .sign(keypair3);
2998
- *
2999
- * // Multi-sig convenience
3000
- * const signed = tx.signAll([keypair1, keypair2, keypair3]);
3001
- * ```
3002
- */
3003
- declare class Transaction {
3004
- /** The unsigned message */
3005
- private readonly message;
3006
- /** Signatures (64 bytes each), aligned with message.header.numRequiredSignatures */
3007
- private readonly signatures;
3008
- private constructor();
3009
- /**
3010
- * Create an unsigned transaction from a message.
3011
- * All signature slots are initialized to zero.
3012
- *
3013
- * @internal - Users should use TransactionBuilder instead
3014
- */
3015
- static fromMessage(message: Message): Transaction;
3016
- /**
3017
- * Create transaction from message and existing signatures.
3018
- * @internal
3019
- */
3020
- static fromMessageAndSignatures(message: Message, signatures: readonly Uint8Array[]): Transaction;
3021
- /**
3022
- * Deserialize a transaction from wire format.
3023
- */
3024
- static deserialize(data: Uint8Array): Transaction;
3025
- getMessage(): Message;
3026
- /**
3027
- * Sign the transaction with a keypair.
3028
- * Returns a NEW Transaction instance.
3029
- *
3030
- * @param keypair - Keypair to sign with
3031
- * @returns New Transaction instance with signature added
3032
- *
3033
- * @example
3034
- * ```typescript
3035
- * const signedTx = tx.sign(keypair);
3036
- * await client.sendTransaction(signedTx.serialize());
3037
- * ```
3038
- */
3039
- sign(keypair: Keypair): Transaction;
3040
- /**
3041
- * Sign with multiple keypairs at once.
3042
- * Returns a NEW Transaction instance.
3043
- *
3044
- * @example
3045
- * ```typescript
3046
- * const signed = tx.signAll([keypair1, keypair2, keypair3]);
3047
- * ```
3048
- */
3049
- signAll(keypairs: Keypair[]): Transaction;
3050
- /**
3051
- * Sign the transaction with a Signer interface (async).
3052
- * Returns a NEW Transaction instance.
3053
- *
3054
- * @example
3055
- * ```typescript
3056
- * const signedTx = await tx.signWith(browserWallet);
3057
- * ```
3058
- */
3059
- signWith(signer: Signer): Promise<Transaction>;
3060
- /**
3061
- * Sign with multiple signers.
3062
- * Returns a NEW Transaction instance.
3063
- */
3064
- signAllWith(signers: Signer[]): Promise<Transaction>;
3065
- /**
3066
- * Partially sign the transaction (for multi-sig transactions).
3067
- * Returns a NEW Transaction instance.
3068
- *
3069
- * @example
3070
- * ```typescript
3071
- * const signedTx = tx
3072
- * .partialSign(signer1)
3073
- * .partialSign(signer2);
3074
- * ```
3075
- */
3076
- partialSign(keypair: Keypair): Transaction;
3077
- /**
3078
- * Partially sign with a Signer interface (async).
3079
- * Returns a NEW Transaction instance.
3080
- */
3081
- partialSignWith(signer: Signer): Promise<Transaction>;
3082
- /**
3083
- * Add a signature at a specific index.
3084
- * Returns a NEW Transaction instance.
3085
- *
3086
- * Most users should use sign() or signAll() instead.
3087
- */
3088
- addSignature(index: number, signature: Signature | Uint8Array): Transaction;
3089
- /**
3090
- * Add a signature for a specific public key.
3091
- * Returns a NEW Transaction instance.
3092
- *
3093
- * Most users should use sign() or signAll() instead.
3094
- */
3095
- addSignatureForPubkey(pubkey: PublicKey, signature: Signature | Uint8Array): Transaction;
3096
- /**
3097
- * Check if transaction is fully signed (all signatures present).
3098
- */
3099
- isSigned(): boolean;
3100
- /**
3101
- * Check if a specific signature slot is filled.
3102
- */
3103
- isSignaturePresent(index: number): boolean;
3104
- /**
3105
- * Get all signatures (returns copies to prevent mutation).
3106
- */
3107
- getSignatures(): readonly Uint8Array[];
3108
- /**
3109
- * Get a specific signature (returns copy).
3110
- */
3111
- getSignature(index: number): Uint8Array;
3112
- /**
3113
- * Get a specific signature for a public key.
3114
- */
3115
- getSignatureForPubkey(pubkey: PublicKey): Uint8Array;
3116
- /**
3117
- * Get required signers for this transaction.
3118
- */
3119
- getSigners(): readonly PublicKey[];
3120
- /**
3121
- * Get the number of required signatures.
3122
- */
3123
- getRequiredSignatureCount(): number;
3124
- /**
3125
- * Throw an error if the transaction is not fully signed.
3126
- *
3127
- * @throws {TransactionError} If transaction is not fully signed
3128
- *
3129
- * @example
3130
- * ```typescript
3131
- * signedTx.ensureSigned(); // Throws if not signed
3132
- * await client.sendTransaction(signedTx.serialize());
3133
- * ```
3134
- */
3135
- ensureSigned(): void;
3136
- /**
3137
- * Serialize transaction to wire format.
3138
- */
3139
- serialize(): Uint8Array;
3140
- }
3141
-
3142
- /**
3143
- * Fluent API for building transactions.
3144
- * Returns Transaction directly (not Message).
3145
- */
3146
-
3147
- /**
3148
- * Builder for creating transactions with a fluent API.
3149
- *
3150
- * Provides an intuitive interface for constructing transactions.
3151
- * Call build() to get an unsigned Transaction ready for signing.
3152
- *
3153
- * @example
3154
- * ```typescript
3155
- * // Simple transfer
3156
- * const tx = TransactionBuilder.create()
3157
- * .setPayer(payer)
3158
- * .setValidFrom(validFrom)
3159
- * .addInstruction(transfer(from, to, 1_000_000n))
3160
- * .build();
3161
- *
3162
- * const signedTx = tx.sign(keypair);
3163
- * await client.transaction.sendTransaction(signedTx.serialize());
3164
- * ```
3165
- *
3166
- * @example
3167
- * ```typescript
3168
- * // Multi-instruction transaction
3169
- * const tx = TransactionBuilder.create()
3170
- * .setPayer(payer)
3171
- * .setValidFrom(validFrom)
3172
- * .addInstruction(transfer(from, to, 1_000_000n))
3173
- * .addInstruction(memoInstruction("Payment for invoice #123"))
3174
- * .build();
3175
- * ```
3176
- */
3177
- declare class TransactionBuilder {
3178
- private payer?;
3179
- private validFrom?;
3180
- private configHashPrefix?;
3181
- private readonly instructions;
3182
- private constructor();
3183
- /**
3184
- * Create a new transaction builder.
3185
- */
3186
- static create(): TransactionBuilder;
3187
- /**
3188
- * Set the fee payer for this transaction.
3189
- *
3190
- * The payer will be the first account and must sign the transaction.
3191
- * The payer pays for transaction fees.
3192
- *
3193
- * @param payer - Public key of the fee payer
3194
- */
3195
- setPayer(payer: PublicKey): this;
3196
- /**
3197
- * Set the Transaction valid from.
3198
- *
3199
- * This is the time the transaction is valid from, in milliseconds since Unix epoch.
3200
- * It can be used for additional replay protection or auditing.
3201
- *
3202
- * @param validFrom - Transaction valid from in milliseconds since Unix epoch
3203
- */
3204
- setValidFrom(validFrom: bigint): this;
3205
- /**
3206
- * Set the config hash prefix for replay protection.
3207
- *
3208
- * This is the first 64 bits of the config hash, used to ensure
3209
- * transactions cannot be replayed on different chains.
3210
- *
3211
- * @param configHashPrefix - config hash prefix as a u64
3212
- */
3213
- setConfigHashPrefix(configHashPrefix: bigint): this;
3214
- /**
3215
- * Add an instruction to the transaction.
3216
- *
3217
- * @param instruction - Instruction to add
3218
- */
3219
- addInstruction(instruction: Instruction): this;
3220
- /**
3221
- * Add multiple instructions at once.
3222
- *
3223
- * @param instructions - Array of instructions to add
3224
- */
3225
- addInstructions(instructions: readonly Instruction[]): this;
3226
- /**
3227
- * Build the transaction (unsigned).
3228
- *
3229
- * Returns an unsigned Transaction that's ready to be signed.
3230
- *
3231
- * @returns Unsigned Transaction
3232
- * @throws {TransactionError} If payer, valid_from, or instructions are missing
3233
- *
3234
- * @example
3235
- * ```typescript
3236
- * const tx = builder.build();
3237
- * const signedTx = tx.sign(keypair);
3238
- * ```
3239
- */
3240
- build(): Transaction;
3241
- }
3242
-
3243
- /**
3244
- * Converts bytes to base64 string.
3245
- *
3246
- * Works in both browser and Node.js environments.
3247
- */
3248
- declare function toBase64(bytes: Uint8Array): string;
3249
- /**
3250
- * Converts base64 string to bytes.
3251
- *
3252
- * Works in both browser and Node.js environments.
3253
- */
3254
- declare function fromBase64(base64: string): Uint8Array;
3255
- /**
3256
- * Sleeps for the specified duration.
3257
- *
3258
- * @param ms - Milliseconds to sleep
3259
- */
3260
- declare function sleep(ms: number): Promise<void>;
3261
- /**
3262
- * Calculates exponential backoff delay with jitter.
3263
- *
3264
- * @param attempt - Current retry attempt (0-indexed)
3265
- * @param baseMs - Base delay in milliseconds
3266
- * @param maxMs - Maximum delay in milliseconds
3267
- * @returns Calculated delay with 30% random jitter
3268
- */
3269
- declare function calculateBackoff(attempt: number, baseMs?: number, maxMs?: number): number;
3270
- /**
3271
- * Returns the devnet RPC URL.
3272
- */
3273
- declare function getDevnetUrl(): string;
3274
- /**
3275
- * Returns the testnet RPC URL.
3276
- */
3277
- declare function getTestnetUrl(): string;
3278
- /**
3279
- * Returns the mainnet RPC URL.
3280
- */
3281
- declare function getMainnetUrl(): string;
3282
- /**
3283
- * Returns the localnet RPC URL.
3284
- */
3285
- declare function getLocalnetUrl(): string;
3286
-
3287
- export { type AccountFilter, type AccountInfo, type AccountMeta, AccountMetaTable, BASE_DERIVATION_PATH, BaseRpcClient, BincodeReader, type BincodeSchema, BincodeWriter, type Bump, CHACHA20_POLY1305_TAG_LENGTH, type ChainDefinition, type CompiledInstruction, type ConfirmTransactionOptions, type ConfirmedTransaction, CryptoError, CryptoErrorCode, DEFAULT_NUM_ACCOUNTS, ED25519_PUBLIC_KEY_LENGTH, type EnumVariant, type EpochInfoResponse, type EventData, type GetAccountsByOwnerConfig, type GetAccountsByOwnerResponse, type GetHealthResponse, type GetSecretSharingPubkeyResponse, type GetSignaturesForAddressConfig, type GetTransactionsResponse, type GetWorkflowLineageRequest, type GetWorkflowLineageResponse, HPKE_ENC_LENGTH, HPKE_OVERHEAD_LENGTH, HpkeError, HpkeErrorCode, HttpTransport, type HttpTransportConfig, type IdentifierString, type InferSchema, type Instruction, KELVIN_PER_RLO, Keypair, KeypairSigner, Message, type MessageHeader, Mnemonic, type MnemonicStrength, type OwnerAccount, type PDA, PUBLIC_KEY_LENGTH, type PaginationInfo, PublicKey, QueryRpcClient, RIALO_DEVNET_CHAIN, RIALO_LOCALNET_CHAIN, RIALO_MAINNET_CHAIN, RIALO_SHITNET_CHAIN, RIALO_TESTNET_CHAIN, RexValue, RexValueVariant, RialoClient, type RialoClientConfig, RialoError, RialoErrorType, type RialoNetwork, RpcError, RpcErrorCode, type RpcErrorDetails$1 as RpcErrorDetails, SECRET_KEY_LENGTH, SECRET_SHARING_HPKE_INFO, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, Schema, type Seed, type SendAndConfirmOptions, type SendTransactionOptions, Signature, type SignatureInfo, type SignatureStatus, type Signer, type StructField, type Subscription, type SubscriptionKind, SystemInstruction, type TimestampRange, Transaction, TransactionBuilder, TransactionError, TransactionErrorCode, type TransactionNodeData, type TransactionResponse, TransactionRpcClient, type TriggerInfo, type TriggeredTransaction, type TruncationReason, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_SHITNET, URL_TESTNET, USER_SECRET_AAD, type WorkflowLineage, type WorkflowNode, X25519_PUBLIC_KEY_LENGTH, allocateInstruction, assignInstruction, calculateBackoff, concatBytes, createAccount, createBorshInstruction, createRialoClient, deserialize, deserializeBorsh, deserializeCompactU16, deserializeStrict, encodeBorshData, encryptForRex, fromBase64, getCiphertextLength, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, hpkeEncrypt, isOnCurve, isValidCiphertextLength, seedToBytes, serialize, serializeBorsh, serializeCompactU16, sleep, toBase64, transferInstruction, writeCompactU16 };