@rialo/ts-cdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1774 @@
1
+ /**
2
+ * Error handling for the Rialo CDK.
3
+ *
4
+ * This module defines the common error types used throughout the Rialo CDK.
5
+ * It provides a centralized error handling mechanism for all operations.
6
+ */
7
+ /**
8
+ * Structured RPC error information parsed from JSON-RPC error responses.
9
+ */
10
+ interface RpcErrorDetails$1 {
11
+ /** HTTP status code (e.g., 200, 422, 500) */
12
+ status?: number;
13
+ /** JSON-RPC error code (e.g., -32002) */
14
+ code: number;
15
+ /** Human-readable error message */
16
+ message: string;
17
+ }
18
+ /**
19
+ * Error types for different subsystems in the Rialo CDK.
20
+ */
21
+ declare enum RialoErrorType {
22
+ /** Errors related to file or system I/O operations */
23
+ IO = "IO",
24
+ /** Errors occurring during RPC communication with blockchain nodes */
25
+ RPC = "RPC",
26
+ /** Errors related to public key parsing or validation */
27
+ PARSE_PUBKEY = "PARSE_PUBKEY",
28
+ /** Errors related to blockhash parsing or validation */
29
+ INVALID_BLOCKHASH_FORMAT = "INVALID_BLOCKHASH_FORMAT",
30
+ /** Errors related to wallet operations such as creation, loading, or signing */
31
+ WALLET = "WALLET",
32
+ /** Errors related to configuration loading, parsing, or validation */
33
+ CONFIG = "CONFIG",
34
+ /** Errors occurring during transaction building, signing, or submission */
35
+ TRANSACTION = "TRANSACTION",
36
+ /** Network-related errors, including HTTP client errors */
37
+ NETWORK = "NETWORK",
38
+ /** Errors related to password handling, validation, or verification */
39
+ PASSWORD = "PASSWORD",
40
+ /** Errors related to encryption or decryption operations */
41
+ ENCRYPTION = "ENCRYPTION",
42
+ /** Errors occurring during JSON parsing, serialization, or deserialization */
43
+ JSON = "JSON",
44
+ /** Errors related to BIP32 key derivation */
45
+ BIP32 = "BIP32",
46
+ /** Errors related to invalid input parameters or data */
47
+ INVALID_INPUT = "INVALID_INPUT",
48
+ /** Errors related to serialization/deserialization */
49
+ SERIALIZATION = "SERIALIZATION"
50
+ }
51
+ /**
52
+ * Base error class for all Rialo CDK errors.
53
+ *
54
+ * Provides structured error handling with type categorization and optional
55
+ * cause tracking for error chains. Use the static factory methods for
56
+ * consistent error creation across the SDK.
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // Create typed errors using factory methods
61
+ * throw RialoError.invalidInput("Amount must be positive");
62
+ * throw RialoError.network("Connection failed", originalError);
63
+ * throw RialoError.rpc({ code: -32002, message: "Invalid params" });
64
+ *
65
+ * // Handle errors with type information
66
+ * try {
67
+ * await client.sendTransaction(tx);
68
+ * } catch (error) {
69
+ * if (error instanceof RialoError && error.type === RialoErrorType.NETWORK) {
70
+ * console.log("Network error, retrying...");
71
+ * }
72
+ * }
73
+ * ```
74
+ */
75
+ declare class RialoError extends Error {
76
+ readonly type: RialoErrorType;
77
+ readonly cause?: Error;
78
+ readonly details?: RpcErrorDetails$1;
79
+ constructor(type: RialoErrorType, message: string, cause?: Error, details?: RpcErrorDetails$1);
80
+ /**
81
+ * Creates an IO error.
82
+ */
83
+ static io(message: string, cause?: Error): RialoError;
84
+ /**
85
+ * Creates an RPC error.
86
+ */
87
+ static rpc(details: RpcErrorDetails$1): RialoError;
88
+ /**
89
+ * Creates a public key parsing error.
90
+ */
91
+ static parsePubkey(message: string): RialoError;
92
+ /**
93
+ * Creates a blockhash format error.
94
+ */
95
+ static invalidBlockhash(message: string): RialoError;
96
+ /**
97
+ * Creates a wallet error.
98
+ */
99
+ static wallet(message: string): RialoError;
100
+ /**
101
+ * Creates a configuration error.
102
+ */
103
+ static config(message: string): RialoError;
104
+ /**
105
+ * Creates a transaction error.
106
+ */
107
+ static transaction(message: string): RialoError;
108
+ /**
109
+ * Creates a network error.
110
+ */
111
+ static network(message: string, cause?: Error): RialoError;
112
+ /**
113
+ * Creates a password error.
114
+ */
115
+ static password(message: string): RialoError;
116
+ /**
117
+ * Creates an encryption error.
118
+ */
119
+ static encryption(message: string): RialoError;
120
+ /**
121
+ * Creates a JSON error.
122
+ */
123
+ static json(message: string, cause?: Error): RialoError;
124
+ /**
125
+ * Creates a BIP32 error.
126
+ */
127
+ static bip32(message: string): RialoError;
128
+ /**
129
+ * Creates an invalid input error.
130
+ */
131
+ static invalidInput(message: string): RialoError;
132
+ /**
133
+ * Creates a serialization error.
134
+ */
135
+ static serialization(message: string): RialoError;
136
+ }
137
+
138
+ /** Default number of accounts to derive in HD wallets */
139
+ declare const DEFAULT_NUM_ACCOUNTS: number;
140
+ /** Rialo mainnet RPC URL */
141
+ declare const URL_MAINNET: string;
142
+ /** Rialo testnet RPC URL */
143
+ declare const URL_TESTNET: string;
144
+ /** Rialo devnet RPC URL */
145
+ declare const URL_DEVNET: string;
146
+ /** Rialo localnet RPC URL */
147
+ declare const URL_LOCALNET: string;
148
+ /** System program ID */
149
+ declare const SYSTEM_PROGRAM_ID: string;
150
+ /** Base derivation path for Rialo wallets (BIP44 coin type 756) */
151
+ /** Coin type 756 follows the telephone keypad convention: R=7, L=5, O=6 */
152
+ declare const BASE_DERIVATION_PATH: string;
153
+ declare const KELVIN_PER_RLO: number;
154
+ declare const PUBLIC_KEY_LENGTH: number;
155
+ declare const SECRET_KEY_LENGTH: number;
156
+ declare const SIGNATURE_LENGTH: number;
157
+ declare const BLOCKHASH_LENGTH: number;
158
+
159
+ /**
160
+ * Represents a 32-byte blockhash used for transaction replay protection.
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // From RPC response
165
+ * const blockhash = Blockhash.fromString(rpcBlockhash);
166
+ *
167
+ * // Comparison
168
+ * if (blockhash1.equals(blockhash2)) {
169
+ * console.log("Same blockhash");
170
+ * }
171
+ * ```
172
+ */
173
+ declare class Blockhash {
174
+ private readonly bytes;
175
+ private constructor();
176
+ /**
177
+ * Creates a Blockhash from raw bytes.
178
+ *
179
+ * @param bytes - 32-byte blockhash
180
+ * @throws {CryptoError} If bytes length is not 32
181
+ */
182
+ static fromBytes(bytes: Uint8Array): Blockhash;
183
+ /**
184
+ * Creates a Blockhash from a base58-encoded string.
185
+ *
186
+ * @param str - Base58-encoded blockhash
187
+ * @throws {CryptoError} If string is invalid or decodes to wrong length
188
+ */
189
+ static fromString(str: string): Blockhash;
190
+ /**
191
+ * Returns a copy of the raw bytes.
192
+ */
193
+ toBytes(): Uint8Array;
194
+ /**
195
+ * Returns the base58-encoded string representation.
196
+ */
197
+ toString(): string;
198
+ /**
199
+ * Checks equality with another blockhash using constant-time comparison.
200
+ */
201
+ equals(other: Blockhash): boolean;
202
+ /**
203
+ * JSON serialization (returns base58 string).
204
+ */
205
+ toJSON(): string;
206
+ }
207
+
208
+ /**
209
+ * Error codes for cryptographic operations.
210
+ */
211
+ declare enum CryptoErrorCode {
212
+ INVALID_KEY_LENGTH = "INVALID_KEY_LENGTH",
213
+ INVALID_SIGNATURE = "INVALID_SIGNATURE",
214
+ INVALID_PUBLIC_KEY = "INVALID_PUBLIC_KEY",
215
+ INVALID_BLOCKHASH = "INVALID_BLOCKHASH",
216
+ INVALID_MNEMONIC = "INVALID_MNEMONIC",
217
+ KEY_DERIVATION_FAILED = "KEY_DERIVATION_FAILED",
218
+ KEYPAIR_DISPOSED = "KEYPAIR_DISPOSED"
219
+ }
220
+ /**
221
+ * Error class for cryptographic operations.
222
+ *
223
+ * Provides structured error information with error codes and contextual details
224
+ * for better debugging and error handling.
225
+ */
226
+ declare class CryptoError extends Error {
227
+ readonly code: CryptoErrorCode;
228
+ readonly details?: Record<string, unknown>;
229
+ constructor(code: CryptoErrorCode, message: string, details?: Record<string, unknown>);
230
+ static invalidKeyLength(expected: number, actual: number): CryptoError;
231
+ static invalidMnemonic(reason?: string): CryptoError;
232
+ static keyDerivationFailed(path: string, cause?: Error): CryptoError;
233
+ static keypairDisposed(): CryptoError;
234
+ }
235
+
236
+ /**
237
+ * Represents a 64-byte Ed25519 signature.
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * // From bytes
242
+ * const sig = Signature.fromBytes(signatureBytes);
243
+ *
244
+ * // From base58 string
245
+ * const sig = Signature.fromString("3Bxs4h...");
246
+ *
247
+ * // Serialize
248
+ * const base58 = sig.toString();
249
+ * ```
250
+ */
251
+ declare class Signature {
252
+ private readonly bytes;
253
+ private constructor();
254
+ /**
255
+ * Creates a Signature from raw bytes.
256
+ *
257
+ * @param bytes - 64-byte Ed25519 signature
258
+ * @throws {CryptoError} If bytes length is not 64
259
+ */
260
+ static fromBytes(bytes: Uint8Array): Signature;
261
+ /**
262
+ * Creates a Signature from a base58-encoded string.
263
+ *
264
+ * @param str - Base58-encoded signature
265
+ * @throws {CryptoError} If string is invalid or decodes to wrong length
266
+ */
267
+ static fromString(str: string): Signature;
268
+ /**
269
+ * Returns a copy of the raw bytes.
270
+ */
271
+ toBytes(): Uint8Array;
272
+ /**
273
+ * Returns the base58-encoded string representation.
274
+ */
275
+ toString(): string;
276
+ /**
277
+ * JSON serialization (returns base58 string).
278
+ */
279
+ toJSON(): string;
280
+ }
281
+
282
+ /**
283
+ * Represents a 32-byte Ed25519 public key.
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * // From base58 string
288
+ * const pubkey = PublicKey.fromString("5ZqB9U...");
289
+ *
290
+ * // From bytes
291
+ * const pubkey = PublicKey.fromBytes(new Uint8Array(32));
292
+ *
293
+ * // Comparison
294
+ * if (pubkey1.equals(pubkey2)) {
295
+ * console.log("Keys match");
296
+ * }
297
+ * ```
298
+ */
299
+ declare class PublicKey {
300
+ private readonly bytes;
301
+ private constructor();
302
+ /**
303
+ * Creates a PublicKey from raw bytes.
304
+ *
305
+ * @param bytes - 32-byte Ed25519 public key
306
+ * @throws {CryptoError} If bytes length is not 32
307
+ */
308
+ static fromBytes(bytes: Uint8Array): PublicKey;
309
+ /**
310
+ * Creates a PublicKey from a base58-encoded string.
311
+ *
312
+ * @param str - Base58-encoded public key
313
+ * @throws {CryptoError} If string is invalid or decodes to wrong length
314
+ */
315
+ static fromString(str: string): PublicKey;
316
+ /**
317
+ * Returns a copy of the raw bytes.
318
+ */
319
+ toBytes(): Uint8Array;
320
+ /**
321
+ * Returns the base58-encoded string representation.
322
+ */
323
+ toString(): string;
324
+ /**
325
+ * Checks equality with another public key using constant-time comparison.
326
+ */
327
+ equals(other: PublicKey): boolean;
328
+ /**
329
+ * Verifies an Ed25519 signature over a message.
330
+ *
331
+ * @param message - Message bytes that were signed
332
+ * @param signature - Signature to verify
333
+ * @returns True if signature is valid, false otherwise
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * const message = new Uint8Array([1, 2, 3]);
338
+ * const signature = keypair.sign(message);
339
+ * const isValid = keypair.publicKey.verify(message, signature);
340
+ * ```
341
+ */
342
+ verify(message: Uint8Array, signature: Signature): boolean;
343
+ /**
344
+ * JSON serialization (returns base58 string).
345
+ */
346
+ toJSON(): string;
347
+ }
348
+
349
+ /**
350
+ * Represents an Ed25519 keypair for signing transactions.
351
+ *
352
+ * Provides secure key generation, signing, and disposal capabilities.
353
+ * Call {@link dispose} when finished to securely erase the private key from memory.
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * // Generate random keypair
358
+ * const keypair = Keypair.generate();
359
+ *
360
+ * // Sign a message
361
+ * const message = new TextEncoder().encode("Hello");
362
+ * const signature = keypair.sign(message);
363
+ *
364
+ * // Verify signature
365
+ * const isValid = keypair.verify(message, signature);
366
+ *
367
+ * // Secure cleanup
368
+ * keypair.dispose();
369
+ * ```
370
+ */
371
+ declare class Keypair {
372
+ readonly publicKey: PublicKey;
373
+ private secretKey;
374
+ private disposed;
375
+ private constructor();
376
+ /**
377
+ * Generates a random keypair using cryptographically secure randomness.
378
+ */
379
+ static generate(): Keypair;
380
+ /**
381
+ * Creates a keypair from a 32-byte secret key.
382
+ * The public key will be derived from the secret key.
383
+ *
384
+ * @param secretKey - 32-byte Ed25519 secret key
385
+ */
386
+ static fromSecretKey(secretKey: Uint8Array): Keypair;
387
+ /**
388
+ * Creates a keypair from a secret key and pre-computed public key.
389
+ *
390
+ * Use this for SLIP-0010/BIP32 derived keys where the public key
391
+ * should NOT be re-derived (compatibility with hierarchical derivation).
392
+ *
393
+ * @param secretKey - 32-byte Ed25519 secret key
394
+ * @param publicKey - 32-byte Ed25519 public key (pre-computed)
395
+ */
396
+ static fromKeyPair(secretKey: Uint8Array, publicKey: Uint8Array): Keypair;
397
+ /**
398
+ * Signs a message with this keypair.
399
+ *
400
+ * @param message - Message bytes to sign
401
+ * @returns Ed25519 signature
402
+ * @throws {CryptoError} If keypair has been disposed
403
+ */
404
+ sign(message: Uint8Array): Signature;
405
+ /**
406
+ * Verifies a signature against a message using this keypair's public key.
407
+ *
408
+ * @param message - Original message that was signed
409
+ * @param signature - Signature to verify
410
+ * @returns true if signature is valid
411
+ */
412
+ verify(message: Uint8Array, signature: Signature): boolean;
413
+ /**
414
+ * Exports the secret key for storage.
415
+ *
416
+ * **WARNING**: Keep this secret! Never expose it in logs, APIs, or client-side code.
417
+ *
418
+ * @returns Copy of the 32-byte secret key
419
+ * @throws {CryptoError} If keypair has been disposed
420
+ */
421
+ secretKeyBytes(): Uint8Array;
422
+ /**
423
+ * Checks if this keypair has been disposed.
424
+ */
425
+ isDisposed(): boolean;
426
+ /**
427
+ * Securely erases the secret key from memory.
428
+ *
429
+ * After calling this method, the keypair can no longer be used for signing.
430
+ * This is important for security when the keypair is no longer needed.
431
+ */
432
+ dispose(): void;
433
+ private ensureNotDisposed;
434
+ }
435
+
436
+ type MnemonicStrength = 128 | 256;
437
+ /**
438
+ * Represents a validated BIP39 mnemonic phrase with SLIP-0010 Ed25519 hierarchical key derivation.
439
+ *
440
+ * Implements the SLIP-0010 standard for Ed25519 key derivation, ensuring compatibility
441
+ * with other implementations (e.g., Rust CDK). The default derivation path uses coin type
442
+ * 756 (R=7, L=5, O=6 on telephone keypad).
443
+ *
444
+ * @example
445
+ * ```typescript
446
+ * // Generate new mnemonic (12 or 24 words)
447
+ * const mnemonic = Mnemonic.generate(128); // 12 words
448
+ *
449
+ * // Restore from existing phrase
450
+ * const restored = Mnemonic.fromPhrase("word1 word2 ...");
451
+ *
452
+ * // Derive keypairs at specific account indices
453
+ * const keypair0 = await mnemonic.toKeypair(0); // m/44'/756'/0'/0'
454
+ * const keypair1 = await mnemonic.toKeypair(1); // m/44'/756'/1'/0'
455
+ *
456
+ * // With custom passphrase (BIP39 extension)
457
+ * const secure = await mnemonic.toKeypair(0, {
458
+ * passphrase: "my-secret"
459
+ * });
460
+ * ```
461
+ *
462
+ * @see {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md SLIP-0010 Specification}
463
+ */
464
+ declare class Mnemonic {
465
+ private readonly phrase;
466
+ private constructor();
467
+ /**
468
+ * Generates a new random BIP39 mnemonic phrase.
469
+ *
470
+ * @param strength - Entropy strength (128 = 12 words, 256 = 24 words). Default: 128
471
+ * @returns Validated Mnemonic instance
472
+ */
473
+ static generate(strength?: MnemonicStrength): Mnemonic;
474
+ /**
475
+ * Creates a Mnemonic from an existing phrase.
476
+ *
477
+ * @param phrase - BIP39 mnemonic phrase (12 or 24 space-separated words)
478
+ * @returns Validated Mnemonic instance
479
+ * @throws {CryptoError} If phrase is invalid (wrong words or checksum)
480
+ */
481
+ static fromPhrase(phrase: string): Mnemonic;
482
+ /**
483
+ * Validates a phrase without creating an instance.
484
+ *
485
+ * Checks both word validity and BIP39 checksum.
486
+ *
487
+ * @param phrase - Mnemonic phrase to validate
488
+ * @returns true if phrase is valid
489
+ */
490
+ static isValid(phrase: string): boolean;
491
+ private getMasterKeyFromSeed;
492
+ private deriveChildKey;
493
+ private derivePath;
494
+ /**
495
+ * Derives a keypair at a specific account index.
496
+ *
497
+ * Uses SLIP-0010 Ed25519 derivation with the default path:
498
+ * `m/44'/756'/{accountIndex}'/0'`
499
+ *
500
+ * Coin type 756 follows the telephone keypad convention (R=7, L=5, O=6).
501
+ *
502
+ * @param accountIndex - Account index to derive (default: 0)
503
+ * @param options - Derivation options
504
+ * @param options.passphrase - Optional BIP39 passphrase for additional security
505
+ * @param options.baseDerivationPath - Base path (default: "m/44'/756'")
506
+ * @returns Keypair for the derived account
507
+ */
508
+ toKeypair(accountIndex?: number, options?: {
509
+ passphrase?: string;
510
+ baseDerivationPath?: string;
511
+ }): Promise<Keypair>;
512
+ /**
513
+ * Derives a keypair using an explicit full derivation path.
514
+ *
515
+ * @param fullPath - Complete derivation path (e.g., "m/44'/756'/0'/0'")
516
+ * @param passphrase - Optional BIP39 passphrase
517
+ */
518
+ toKeypairWithPath(fullPath: string, passphrase?: string): Promise<Keypair>;
519
+ /**
520
+ * Derives multiple keypairs sequentially from this mnemonic.
521
+ *
522
+ * @param count - Number of keypairs to derive
523
+ * @param startIndex - Starting account index (default: 0)
524
+ * @param options - Derivation options (passphrase and path)
525
+ */
526
+ deriveKeypairs(count: number, startIndex?: number, options?: {
527
+ passphrase?: string;
528
+ baseDerivationPath?: string;
529
+ }): Promise<Keypair[]>;
530
+ /**
531
+ * Converts the mnemonic to a BIP39 seed.
532
+ *
533
+ * @param passphrase - Optional BIP39 passphrase for additional security
534
+ * @returns 64-byte seed
535
+ */
536
+ toSeed(passphrase?: string): Promise<Uint8Array>;
537
+ /**
538
+ * Returns the mnemonic phrase as a string.
539
+ */
540
+ toString(): string;
541
+ /**
542
+ * Returns the individual words of the mnemonic.
543
+ */
544
+ getWords(): string[];
545
+ /**
546
+ * Returns the word count (12 or 24).
547
+ */
548
+ getWordCount(): 12 | 24;
549
+ /**
550
+ * Returns the entropy strength (128 or 256 bits).
551
+ */
552
+ getStrength(): MnemonicStrength;
553
+ /**
554
+ * Checks equality with another mnemonic using constant-time comparison.
555
+ */
556
+ equals(other: Mnemonic): boolean;
557
+ /**
558
+ * JSON serialization (returns the mnemonic phrase).
559
+ */
560
+ toJSON(): string;
561
+ private buildFullPath;
562
+ }
563
+
564
+ /**
565
+ * Metadata about an account in a transaction.
566
+ */
567
+ interface AccountMeta {
568
+ /** Account public key */
569
+ readonly pubkey: PublicKey;
570
+ /** Whether this account must sign the transaction */
571
+ readonly isSigner: boolean;
572
+ /** Whether this account's data will be modified */
573
+ readonly isWritable: boolean;
574
+ }
575
+ /**
576
+ * An instruction to execute on-chain.
577
+ */
578
+ interface Instruction {
579
+ /** Program that will execute this instruction */
580
+ readonly programId: PublicKey;
581
+ /** Accounts used by this instruction */
582
+ readonly accounts: readonly AccountMeta[];
583
+ /** Instruction-specific data */
584
+ readonly data: Uint8Array;
585
+ }
586
+ /**
587
+ * Message header containing signature requirements.
588
+ */
589
+ interface MessageHeader {
590
+ /** Number of signatures required */
591
+ readonly numRequiredSignatures: number;
592
+ /** Number of read-only signed accounts */
593
+ readonly numReadonlySignedAccounts: number;
594
+ /** Number of read-only unsigned accounts */
595
+ readonly numReadonlyUnsignedAccounts: number;
596
+ }
597
+ /**
598
+ * Compiled instruction with account indices.
599
+ */
600
+ interface CompiledInstruction {
601
+ /** Index of program in account keys array */
602
+ readonly programIdIndex: number;
603
+ /** Indices of accounts in account keys array */
604
+ readonly accountKeyIndexes: readonly number[];
605
+ /** Instruction data */
606
+ readonly data: Uint8Array;
607
+ }
608
+
609
+ /**
610
+ * Account metadata table for deduplication and sorting.
611
+ * Avoids: Complex account sorting logic scattered throughout builder
612
+ */
613
+
614
+ /**
615
+ * Internal account entry with aggregated metadata.
616
+ */
617
+ interface AccountEntry {
618
+ pubkey: PublicKey;
619
+ isSigner: boolean;
620
+ isWritable: boolean;
621
+ }
622
+ /**
623
+ * Manages account deduplication and sorting for transaction messages.
624
+ *
625
+ * Accounts are sorted according to these rules:
626
+ * 1. Signer + writable accounts first
627
+ * 2. Then signer + readonly accounts
628
+ * 3. Then non-signer + writable accounts
629
+ * 4. Finally non-signer + readonly accounts
630
+ * 5. Within each group, sort by public key bytes
631
+ *
632
+ * This matches Solana's account sorting rules for compatibility.
633
+ */
634
+ declare class AccountMetaTable {
635
+ private readonly accounts;
636
+ private readonly accountOrder;
637
+ /**
638
+ * Add or update an account in the table.
639
+ * If account already exists, merges signer/writable flags (OR operation).
640
+ */
641
+ add(meta: AccountMeta): void;
642
+ /**
643
+ * Add multiple accounts at once.
644
+ */
645
+ addAll(metas: readonly AccountMeta[]): void;
646
+ /**
647
+ * Get the index of an account in the sorted order.
648
+ * Returns -1 if account not found.
649
+ */
650
+ getIndex(pubkey: PublicKey): number;
651
+ /**
652
+ * Get sorted accounts according to transaction rules.
653
+ */
654
+ getSortedAccounts(): readonly AccountEntry[];
655
+ /**
656
+ * Get the message header based on sorted accounts.
657
+ */
658
+ getHeader(): MessageHeader;
659
+ /**
660
+ * Get sorted public keys.
661
+ */
662
+ getPublicKeys(): readonly PublicKey[];
663
+ /**
664
+ * Get number of accounts in table.
665
+ */
666
+ size(): number;
667
+ }
668
+
669
+ /**
670
+ * Error codes for transaction operations.
671
+ */
672
+ declare enum TransactionErrorCode {
673
+ INVALID_INSTRUCTION = "INVALID_INSTRUCTION",
674
+ INVALID_ACCOUNT_META = "INVALID_ACCOUNT_META",
675
+ NO_INSTRUCTIONS = "NO_INSTRUCTIONS",
676
+ DUPLICATE_ACCOUNT = "DUPLICATE_ACCOUNT",
677
+ MISSING_SIGNATURE = "MISSING_SIGNATURE",
678
+ INVALID_SIGNATURE = "INVALID_SIGNATURE",
679
+ SIGNATURE_OUT_OF_BOUNDS = "SIGNATURE_OUT_OF_BOUNDS",
680
+ SIGNER_NOT_FOUND = "SIGNER_NOT_FOUND",
681
+ ALREADY_SIGNED = "ALREADY_SIGNED",
682
+ INVALID_MESSAGE_FORMAT = "INVALID_MESSAGE_FORMAT",
683
+ INSUFFICIENT_DATA = "INSUFFICIENT_DATA",
684
+ SERIALIZATION_FAILED = "SERIALIZATION_FAILED",
685
+ SIMULATION_FAILED = "SIMULATION_FAILED",
686
+ INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
687
+ BLOCKHASH_EXPIRED = "BLOCKHASH_EXPIRED"
688
+ }
689
+ /**
690
+ * Error class for transaction operations with structured error information.
691
+ */
692
+ declare class TransactionError extends Error {
693
+ readonly code: TransactionErrorCode;
694
+ readonly details?: Record<string, unknown> | undefined;
695
+ constructor(code: TransactionErrorCode, message: string, details?: Record<string, unknown> | undefined);
696
+ static noInstructions(): TransactionError;
697
+ static signerNotFound(pubkey: string): TransactionError;
698
+ static missingSignature(index: number, pubkey: string): TransactionError;
699
+ static simulationFailed(logs: string[], error: string): TransactionError;
700
+ static insufficientFunds(required: bigint, available: bigint): TransactionError;
701
+ toJSON(): {
702
+ code: TransactionErrorCode;
703
+ message: string;
704
+ details?: Record<string, unknown>;
705
+ };
706
+ }
707
+
708
+ /**
709
+ * Create an instruction with Borsh-encoded data.
710
+ *
711
+ * @example
712
+ * ```typescript
713
+ * // Define your instruction data class
714
+ * class MyInstructionData {
715
+ * @field({ type: 'u8' })
716
+ * instruction: number;
717
+ *
718
+ * @field({ type: 'u64' })
719
+ * amount: bigint;
720
+ *
721
+ * @field({ type: option('string') })
722
+ * memo?: string;
723
+ * }
724
+ *
725
+ * // Create instruction
726
+ * const instruction = createBorshInstruction({
727
+ * programId: myProgramId,
728
+ * accounts: [
729
+ * { pubkey: account1, isSigner: true, isWritable: true },
730
+ * { pubkey: account2, isSigner: false, isWritable: false },
731
+ * ],
732
+ * data: new MyInstructionData({
733
+ * instruction: 5,
734
+ * amount: 1000n,
735
+ * memo: "Hello, Rialo!",
736
+ * }),
737
+ * });
738
+ * ```
739
+ */
740
+ declare function createBorshInstruction<T>(params: {
741
+ programId: PublicKey;
742
+ accounts: AccountMeta[];
743
+ data: T;
744
+ }): Instruction;
745
+ /**
746
+ * Helper for creating Borsh-serialized instruction data from a plain object.
747
+ *
748
+ * This is useful when you don't want to define a class with decorators.
749
+ *
750
+ * @example
751
+ * ```typescript
752
+ * const data = encodeBorshData({
753
+ * instruction: { type: 'u8', value: 1 },
754
+ * amount: { type: 'u64', value: 1000n },
755
+ * recipient: { type: fixedArray('u8', 32), value: recipientBytes },
756
+ * });
757
+ * ```
758
+ */
759
+ declare function encodeBorshData(_schema: Record<string, {
760
+ type: unknown;
761
+ value: unknown;
762
+ }>): Uint8Array;
763
+
764
+ /**
765
+ * System program instruction types.
766
+ */
767
+ declare enum SystemInstruction {
768
+ CreateAccount = 0,
769
+ Assign = 1,
770
+ Transfer = 2,
771
+ CreateAccountWithSeed = 3,
772
+ AdvanceNonceAccount = 4,
773
+ WithdrawNonceAccount = 5,
774
+ InitializeNonceAccount = 6,
775
+ AuthorizeNonceAccount = 7,
776
+ Allocate = 8,
777
+ AllocateWithSeed = 9,
778
+ AssignWithSeed = 10,
779
+ TransferWithSeed = 11
780
+ }
781
+ /**
782
+ * Create a transfer instruction.
783
+ *
784
+ * Transfers native tokens from one account to another.
785
+ *
786
+ * @param from - Source account (must be signer)
787
+ * @param to - Destination account
788
+ * @param amount - Amount to transfer in smallest denomination (lamports)
789
+ *
790
+ * @example
791
+ * ```typescript
792
+ * const instruction = transferInstruction(fromPubkey, toPubkey, 1_000_000n);
793
+ *
794
+ * const tx = TransactionBuilder.create()
795
+ * .setPayer(fromPubkey)
796
+ * .setRecentBlockhash(blockhash)
797
+ * .addInstruction(instruction)
798
+ * .build();
799
+ * ```
800
+ */
801
+ declare function transferInstruction(from: PublicKey, to: PublicKey, amount: bigint): Instruction;
802
+ /**
803
+ * Create an account creation instruction.
804
+ *
805
+ * @param from - Funding account (must be signer)
806
+ * @param newAccount - New account to create (must be signer)
807
+ * @param lamports - Initial balance for new account
808
+ * @param space - Number of bytes to allocate for account data
809
+ * @param owner - Program that will own the new account
810
+ */
811
+ declare function createAccount(from: PublicKey, newAccount: PublicKey, lamports: bigint, space: bigint, owner: PublicKey): Instruction;
812
+
813
+ interface HttpTransportConfig {
814
+ /** Request timeout in milliseconds */
815
+ timeout?: number;
816
+ /** Maximum number of retry attempts */
817
+ maxRetries?: number;
818
+ /** Base delay for exponential backoff (ms) */
819
+ retryBaseDelay?: number;
820
+ /** Maximum retry delay (ms) */
821
+ retryMaxDelay?: number;
822
+ /** Custom headers to include in requests */
823
+ headers?: Record<string, string>;
824
+ }
825
+ /**
826
+ * HTTP transport with built-in retry logic and timeout handling.
827
+ *
828
+ * Features:
829
+ * - Automatic retries with exponential backoff
830
+ * - Request timeouts using AbortController
831
+ * - Network error recovery
832
+ * - Rate limit handling
833
+ * - Proper HTTP status code handling
834
+ */
835
+ declare class HttpTransport {
836
+ private readonly url;
837
+ private readonly config;
838
+ constructor(url: string, config?: HttpTransportConfig);
839
+ /**
840
+ * Makes an HTTP request with automatic retry logic.
841
+ *
842
+ * Retries are attempted for network errors and server errors (5xx).
843
+ * Uses exponential backoff between retry attempts.
844
+ */
845
+ request(body: string, requestDetails?: Record<string, unknown>): Promise<unknown>;
846
+ /**
847
+ * Make a single HTTP request with timeout
848
+ */
849
+ private makeRequest;
850
+ /**
851
+ * Handle HTTP error responses
852
+ */
853
+ private handleHttpError;
854
+ /**
855
+ * Returns the configured RPC endpoint URL.
856
+ */
857
+ getUrl(): string;
858
+ }
859
+
860
+ /**
861
+ * Base client with JSON-RPC protocol handling.
862
+ *
863
+ * All specific clients (QueryClient, TransactionClient) extend this.
864
+ */
865
+ declare class BaseRpcClient {
866
+ protected readonly transport: HttpTransport;
867
+ private requestId;
868
+ constructor(transport: HttpTransport);
869
+ /**
870
+ * Makes a JSON-RPC 2.0 method call with type safety.
871
+ *
872
+ * Handles request serialization, response validation, and error mapping.
873
+ */
874
+ protected call<T>(method: string, params?: unknown[]): Promise<T>;
875
+ /**
876
+ * Validate JSON-RPC response structure
877
+ */
878
+ private isValidJsonRpcResponse;
879
+ /**
880
+ * Returns the configured RPC endpoint URL.
881
+ */
882
+ getUrl(): string;
883
+ }
884
+
885
+ /**
886
+ * RPC type definitions for the Rialo blockchain.
887
+ */
888
+
889
+ /**
890
+ * Account information response.
891
+ */
892
+ interface AccountInfo {
893
+ /** Account balance in smallest denomination */
894
+ balance: bigint;
895
+ /** Owner program public key */
896
+ owner: PublicKey;
897
+ /** Account data */
898
+ data: Uint8Array;
899
+ /** Whether the account is executable */
900
+ executable: boolean;
901
+ /** Rent epoch */
902
+ rentEpoch: bigint;
903
+ }
904
+ /**
905
+ * Transaction response.
906
+ */
907
+ interface TransactionResponse {
908
+ /** Transaction signature */
909
+ signature: string;
910
+ /** Slot in which the transaction was processed */
911
+ slot: bigint;
912
+ /** Block time (Unix timestamp) */
913
+ blockTime?: bigint;
914
+ /** Error message if transaction failed */
915
+ err?: string;
916
+ }
917
+ /**
918
+ * Signature status.
919
+ */
920
+ interface SignatureStatus {
921
+ /** Slot in which the transaction was processed */
922
+ slot: bigint;
923
+ /** Number of confirmations */
924
+ confirmations?: number;
925
+ /** Error message if transaction failed */
926
+ err?: string;
927
+ }
928
+ /**
929
+ * Options for sending a transaction.
930
+ */
931
+ interface SendTransactionOptions {
932
+ /** Skip preflight transaction checks */
933
+ skipPreflight?: boolean;
934
+ /** Maximum number of times to retry */
935
+ maxRetries?: number;
936
+ }
937
+ /**
938
+ * Epoch information response.
939
+ */
940
+ interface EpochInfoResponse {
941
+ /** Current epoch */
942
+ epoch: bigint;
943
+ /** Current slot in the epoch */
944
+ slotIndex: bigint;
945
+ /** Total slots in the epoch */
946
+ slotsInEpoch: bigint;
947
+ /** Absolute slot number */
948
+ absoluteSlot: bigint;
949
+ /** Block height */
950
+ blockHeight: bigint;
951
+ /** Transaction count */
952
+ transactionCount?: bigint;
953
+ }
954
+ /**
955
+ * Fee for message response.
956
+ */
957
+ interface GetFeeForMessageResponse {
958
+ /** Fee in smallest denomination */
959
+ value: bigint;
960
+ }
961
+ /**
962
+ * Multiple accounts response.
963
+ */
964
+ interface MultipleAccountsResponse {
965
+ /** Array of account information */
966
+ value: Array<AccountInfo | null>;
967
+ }
968
+ /**
969
+ * Get subscriptions response.
970
+ */
971
+ interface GetSubscriptionsResponse {
972
+ /** Array of subscription data */
973
+ subscriptions: Array<Record<string, unknown>>;
974
+ }
975
+ /**
976
+ * Get triggered transactions response.
977
+ */
978
+ interface GetTriggeredTransactionsResponse {
979
+ /** Array of triggered transaction data */
980
+ transactions: Array<Record<string, unknown>>;
981
+ }
982
+ /**
983
+ * Get workflow lineage request.
984
+ */
985
+ interface GetWorkflowLineageRequest {
986
+ /** Workflow account public key */
987
+ workflowAccount: PublicKey;
988
+ /** Optional limit on results */
989
+ limit?: number;
990
+ }
991
+ /**
992
+ * Get workflow lineage response.
993
+ */
994
+ interface GetWorkflowLineageResponse {
995
+ /** Workflow lineage data */
996
+ lineage: Array<Record<string, unknown>>;
997
+ }
998
+ /**
999
+ * Get signatures for address configuration.
1000
+ */
1001
+ interface GetSignaturesForAddressConfig {
1002
+ /** Maximum number of signatures to return */
1003
+ limit?: number;
1004
+ /** Start searching backwards from this signature */
1005
+ before?: string;
1006
+ /** Start searching forwards from this signature */
1007
+ until?: string;
1008
+ }
1009
+ /**
1010
+ * Get signatures for address response.
1011
+ */
1012
+ interface GetSignaturesForAddressResponse {
1013
+ /** Array of signature information */
1014
+ signatures: Array<{
1015
+ signature: string;
1016
+ slot: bigint;
1017
+ err?: string;
1018
+ memo?: string;
1019
+ blockTime?: bigint;
1020
+ }>;
1021
+ }
1022
+ /**
1023
+ * Is blockhash valid response.
1024
+ */
1025
+ interface IsBlockhashValidResponse {
1026
+ /** Whether the blockhash is valid */
1027
+ value: boolean;
1028
+ }
1029
+ /**
1030
+ * Get health response.
1031
+ */
1032
+ type GetHealthResponse = "ok" | string;
1033
+ /**
1034
+ * Get validator health response.
1035
+ */
1036
+ type GetValidatorHealthResponse = "ok" | string;
1037
+ /**
1038
+ * Get connected full nodes response.
1039
+ */
1040
+ interface GetConnectedFullNodesResponse {
1041
+ /** Array of connected nodes */
1042
+ nodes: Array<{
1043
+ publicKey: string;
1044
+ connectedTime: bigint;
1045
+ }>;
1046
+ }
1047
+ /**
1048
+ * Get transactions configuration.
1049
+ */
1050
+ interface GetTransactionsConfig {
1051
+ /** Maximum number of transactions to return */
1052
+ limit?: number;
1053
+ /** Encoding format */
1054
+ encoding?: "json" | "base58" | "base64";
1055
+ }
1056
+ /**
1057
+ * Get transactions response.
1058
+ */
1059
+ interface GetTransactionsResponse {
1060
+ /** Array of transaction data */
1061
+ transactions: Array<Record<string, unknown>>;
1062
+ }
1063
+
1064
+ /**
1065
+ * Main Rialo RPC client for blockchain interactions.
1066
+ */
1067
+
1068
+ /**
1069
+ * High-level Rialo RPC client for blockchain interactions.
1070
+ *
1071
+ * Provides a unified interface for querying blockchain state and
1072
+ * sending transactions. Internally delegates to specialized clients
1073
+ * (QueryRpcClient, TransactionRpcClient) for modular organization.
1074
+ *
1075
+ * @example
1076
+ * ```typescript
1077
+ * const client = createRialoClient(URL_DEVNET);
1078
+ *
1079
+ * // Query operations
1080
+ * const balance = await client.getBalance(publicKey);
1081
+ * const blockhash = await client.getLatestBlockhash();
1082
+ *
1083
+ * // Transaction operations
1084
+ * const signature = await client.sendTransaction(signedTx);
1085
+ * ```
1086
+ */
1087
+ declare class RialoClient {
1088
+ private readonly queryClient;
1089
+ private readonly transactionClient;
1090
+ private readonly transport;
1091
+ constructor(transport: HttpTransport);
1092
+ /**
1093
+ * Returns the configured RPC endpoint URL.
1094
+ */
1095
+ getUrl(): string;
1096
+ /**
1097
+ * Retrieves the latest blockhash from the blockchain.
1098
+ *
1099
+ * Required for transaction creation and replay protection.
1100
+ */
1101
+ getLatestBlockhash(): Promise<Blockhash>;
1102
+ /**
1103
+ * Retrieves the balance of an account in kelvins (smallest unit).
1104
+ */
1105
+ getBalance(pubkey: PublicKey): Promise<bigint>;
1106
+ /**
1107
+ * Retrieves detailed information about an account.
1108
+ *
1109
+ * @returns Account info or null if account doesn't exist
1110
+ */
1111
+ getAccountInfo(pubkey: PublicKey): Promise<AccountInfo | null>;
1112
+ /**
1113
+ * Retrieves the current block height.
1114
+ */
1115
+ getBlockHeight(): Promise<bigint>;
1116
+ /**
1117
+ * Retrieves detailed information about a transaction.
1118
+ *
1119
+ * @returns Transaction info or null if transaction not found
1120
+ */
1121
+ getTransaction(signature: string): Promise<TransactionResponse | null>;
1122
+ /**
1123
+ * Retrieves the total number of transactions processed since genesis.
1124
+ */
1125
+ getTransactionCount(): Promise<bigint>;
1126
+ /**
1127
+ * Retrieves the status of multiple transaction signatures.
1128
+ */
1129
+ getSignatureStatuses(signatures: string[]): Promise<(SignatureStatus | null)[]>;
1130
+ /**
1131
+ * Retrieves current epoch information.
1132
+ */
1133
+ getEpochInfo(): Promise<EpochInfoResponse>;
1134
+ /**
1135
+ * Checks the health status of the RPC node.
1136
+ *
1137
+ * @returns "ok" if healthy, error message otherwise
1138
+ */
1139
+ getHealth(): Promise<"ok" | string>;
1140
+ /**
1141
+ * Submits a signed transaction to the blockchain.
1142
+ *
1143
+ * @param transaction - Serialized signed transaction bytes
1144
+ * @param options - Transaction submission options
1145
+ * @returns Transaction signature
1146
+ */
1147
+ sendTransaction(transaction: Uint8Array, options?: SendTransactionOptions): Promise<string>;
1148
+ /**
1149
+ * Requests an airdrop of tokens to an account.
1150
+ *
1151
+ * **Note**: Only available on devnet and testnet.
1152
+ *
1153
+ * @param pubkey - Account to receive the airdrop
1154
+ * @param amount - Amount in kelvins (smallest unit)
1155
+ * @returns Transaction signature
1156
+ */
1157
+ requestAirdrop(pubkey: PublicKey, amount: bigint): Promise<string>;
1158
+ }
1159
+
1160
+ /**
1161
+ * Query client for read-only RPC operations.
1162
+ */
1163
+
1164
+ /**
1165
+ * Client for querying blockchain state.
1166
+ *
1167
+ * Handles all read-only operations like getting balances, account info, etc.
1168
+ */
1169
+ declare class QueryRpcClient extends BaseRpcClient {
1170
+ /**
1171
+ * Get the latest blockhash from the blockchain
1172
+ */
1173
+ getLatestBlockhash(): Promise<Blockhash>;
1174
+ /**
1175
+ * Get the balance of an account
1176
+ */
1177
+ getBalance(pubkey: PublicKey): Promise<bigint>;
1178
+ /**
1179
+ * Get detailed information about an account
1180
+ */
1181
+ getAccountInfo(pubkey: PublicKey): Promise<AccountInfo | null>;
1182
+ /**
1183
+ * Get the current block height
1184
+ */
1185
+ getBlockHeight(): Promise<bigint>;
1186
+ /**
1187
+ * Get detailed information about a transaction
1188
+ */
1189
+ getTransaction(signature: string): Promise<TransactionResponse | null>;
1190
+ /**
1191
+ * Get the total number of transactions processed since genesis
1192
+ */
1193
+ getTransactionCount(): Promise<bigint>;
1194
+ /**
1195
+ * Get the status of multiple transaction signatures
1196
+ */
1197
+ getSignatureStatuses(signatures: string[]): Promise<(SignatureStatus | null)[]>;
1198
+ /**
1199
+ * Get epoch information
1200
+ */
1201
+ getEpochInfo(): Promise<EpochInfoResponse>;
1202
+ /**
1203
+ * Get the health status of the node
1204
+ */
1205
+ getHealth(): Promise<"ok" | string>;
1206
+ }
1207
+
1208
+ /**
1209
+ * Query client for read-only RPC operations.
1210
+ */
1211
+
1212
+ /**
1213
+ * Client for sending/simulating transactions and requesting airdrops.
1214
+ *
1215
+ * Handles all transaction operations like sending transactions, requesting airdrops, etc.
1216
+ */
1217
+ declare class TransactionRpcClient extends BaseRpcClient {
1218
+ /**
1219
+ * Submit a signed transaction to the blockchain
1220
+ */
1221
+ sendTransaction(transaction: Uint8Array, options?: SendTransactionOptions): Promise<string>;
1222
+ /**
1223
+ * Request an airdrop of tokens to an account (devnet/testnet only)
1224
+ */
1225
+ requestAirdrop(pubkey: PublicKey, amount: bigint): Promise<string>;
1226
+ }
1227
+
1228
+ /**
1229
+ * Error codes for RPC operations, categorized by type.
1230
+ */
1231
+ declare enum RpcErrorCode {
1232
+ REQUEST_TIMEOUT = "REQUEST_TIMEOUT",
1233
+ NETWORK_ERROR = "NETWORK_ERROR",
1234
+ CONNECTION_REFUSED = "CONNECTION_REFUSED",
1235
+ INVALID_RESPONSE = "INVALID_RESPONSE",
1236
+ PARSE_ERROR = "PARSE_ERROR",
1237
+ INVALID_REQUEST = "INVALID_REQUEST",
1238
+ METHOD_NOT_FOUND = "METHOD_NOT_FOUND",
1239
+ INVALID_PARAMS = "INVALID_PARAMS",
1240
+ INTERNAL_ERROR = "INTERNAL_ERROR",
1241
+ TRANSACTION_REJECTED = "TRANSACTION_REJECTED",
1242
+ INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
1243
+ ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND",
1244
+ BLOCKHASH_NOT_FOUND = "BLOCKHASH_NOT_FOUND",
1245
+ RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED",
1246
+ NODE_UNHEALTHY = "NODE_UNHEALTHY"
1247
+ }
1248
+ /**
1249
+ * Detailed error context for debugging and error handling.
1250
+ */
1251
+ interface RpcErrorDetails {
1252
+ method?: string;
1253
+ params?: unknown;
1254
+ requestId?: number;
1255
+ url?: string;
1256
+ httpStatus?: number;
1257
+ rpcCode?: number;
1258
+ timeout?: number;
1259
+ attempts?: number;
1260
+ [key: string]: unknown;
1261
+ }
1262
+ /**
1263
+ * Error class for RPC operations with structured error information.
1264
+ *
1265
+ * Provides actionable error messages and indicates whether errors are retryable.
1266
+ */
1267
+ declare class RpcError extends Error {
1268
+ readonly code: RpcErrorCode;
1269
+ readonly details: RpcErrorDetails;
1270
+ readonly retryable: boolean;
1271
+ constructor(code: RpcErrorCode, message: string, details?: RpcErrorDetails, retryable?: boolean);
1272
+ static requestTimeout(timeoutMs: number, details: RpcErrorDetails): RpcError;
1273
+ static networkError(message: string, details: RpcErrorDetails): RpcError;
1274
+ static invalidResponse(details: RpcErrorDetails): RpcError;
1275
+ static accountNotFound(pubkey: string): RpcError;
1276
+ static rateLimitExceeded(details: RpcErrorDetails): RpcError;
1277
+ static fromRpcCode(rpcCode: number, message: string, details: RpcErrorDetails): RpcError;
1278
+ toJSON(): {
1279
+ code: RpcErrorCode;
1280
+ message: string;
1281
+ details?: Record<string, unknown>;
1282
+ retryable: boolean;
1283
+ };
1284
+ }
1285
+
1286
+ /**
1287
+ * RPC client module for communicating with Rialo blockchain nodes.
1288
+ *
1289
+ * Provides a high-level client interface with automatic retry logic,
1290
+ * connection management, and type-safe RPC methods.
1291
+ *
1292
+ * @example
1293
+ * ```typescript
1294
+ * import { createRialoClient, URL_DEVNET } from '@rialo/ts-cdk';
1295
+ *
1296
+ * // Create client with custom configuration
1297
+ * const client = createRialoClient(URL_DEVNET, {
1298
+ * timeout: 30000,
1299
+ * maxRetries: 3,
1300
+ * });
1301
+ *
1302
+ * // Query blockchain state
1303
+ * const balance = await client.getBalance(publicKey);
1304
+ * const blockHeight = await client.getBlockHeight();
1305
+ *
1306
+ * // Send transactions
1307
+ * const signature = await client.sendTransaction(signedTx);
1308
+ * ```
1309
+ */
1310
+
1311
+ /**
1312
+ * Creates an RPC client with automatic retry and timeout handling.
1313
+ *
1314
+ * @param url - RPC endpoint URL (e.g., URL_DEVNET, URL_MAINNET)
1315
+ * @param config - Transport configuration (timeout, retries, headers)
1316
+ * @returns Configured RialoClient instance
1317
+ */
1318
+ declare function createRialoClient(url: string, config?: HttpTransportConfig): RialoClient;
1319
+
1320
+ /**
1321
+ * An unsigned transaction message ready to be signed.
1322
+ *
1323
+ * This is the data that gets signed by transaction signers.
1324
+ * It's immutable to prevent accidental modification after creation.
1325
+ *
1326
+ * @example
1327
+ * ```typescript
1328
+ * const message = MessageBuilder.create()
1329
+ * .setPayer(payer)
1330
+ * .setRecentBlockhash(blockhash)
1331
+ * .setCreationTime(txCreationTime)
1332
+ * .addInstruction(transferInstruction)
1333
+ * .build();
1334
+ *
1335
+ * // Serialize for signing
1336
+ * const messageBytes = message.serialize();
1337
+ * ```
1338
+ */
1339
+ declare class Message {
1340
+ /** Message header with signature requirements */
1341
+ readonly header: MessageHeader;
1342
+ /** All account public keys referenced in the transaction */
1343
+ readonly accountKeys: readonly PublicKey[];
1344
+ /** Recent blockhash for replay protection */
1345
+ readonly recentBlockhash: Blockhash;
1346
+ /** Transaction creation timestamp (milliseconds since Unix epoch) */
1347
+ txCreationTime?: bigint;
1348
+ /** Compiled instructions with account indices */
1349
+ readonly instructions: readonly CompiledInstruction[];
1350
+ /** Cached serialized bytes */
1351
+ private serializedCache?;
1352
+ constructor(header: MessageHeader, accountKeys: readonly PublicKey[], recentBlockhash: Blockhash, txCreationTime: bigint, instructions: readonly CompiledInstruction[]);
1353
+ /**
1354
+ * Serialize message to bytes for signing.
1355
+ * Result is cached for performance.
1356
+ */
1357
+ serialize(): Uint8Array;
1358
+ /**
1359
+ * Deserialize a message from wire format.
1360
+ *
1361
+ * @param data - Serialized message bytes
1362
+ * @returns Deserialized Message
1363
+ */
1364
+ static deserialize(data: Uint8Array): Message;
1365
+ private serializeInternal;
1366
+ private serializeCompactArray;
1367
+ private serializeCompactU16;
1368
+ /**
1369
+ * Get all signers required for this message.
1370
+ */
1371
+ getSigners(): readonly PublicKey[];
1372
+ /**
1373
+ * Check if a public key is a required signer.
1374
+ */
1375
+ isSignerRequired(pubkey: PublicKey): boolean;
1376
+ /**
1377
+ * Get the index of a signer in the signers array.
1378
+ * Returns -1 if not a signer.
1379
+ */
1380
+ getSignerIndex(pubkey: PublicKey): number;
1381
+ }
1382
+
1383
+ /**
1384
+ * Interface for signing messages and transactions.
1385
+ *
1386
+ * Enables multiple signing strategies:
1387
+ * - **KeypairSigner**: Local keypair signing
1388
+ * - **Browser Wallet**: Browser extension integration
1389
+ * - **Hardware Wallet**: Ledger, Trezor, etc.
1390
+ * - **Remote Signer**: API-based signing services
1391
+ *
1392
+ * @example
1393
+ * ```typescript
1394
+ * // Browser wallet implementation
1395
+ * class BrowserWalletSigner implements Signer {
1396
+ * async getPublicKey(): Promise<PublicKey> {
1397
+ * const pubkey = await window.rialoWallet.getPublicKey();
1398
+ * return PublicKey.fromString(pubkey);
1399
+ * }
1400
+ *
1401
+ * async signMessage(message: Uint8Array): Promise<Signature> {
1402
+ * const sig = await window.rialoWallet.signMessage(message);
1403
+ * return Signature.fromBytes(sig);
1404
+ * }
1405
+ * }
1406
+ *
1407
+ * // Usage
1408
+ * const signer = new BrowserWalletSigner();
1409
+ * const publicKey = await signer.getPublicKey();
1410
+ * const signature = await signer.signMessage(message);
1411
+ * ```
1412
+ */
1413
+ interface Signer {
1414
+ /**
1415
+ * Retrieves the signer's public key.
1416
+ *
1417
+ * **Note**: May trigger wallet connection prompts for browser wallets.
1418
+ */
1419
+ getPublicKey(): Promise<PublicKey>;
1420
+ /**
1421
+ * Signs arbitrary message bytes.
1422
+ *
1423
+ * @param message - Message bytes to sign
1424
+ * @returns Ed25519 signature over the message
1425
+ */
1426
+ signMessage(message: Uint8Array): Promise<Signature>;
1427
+ }
1428
+
1429
+ /**
1430
+ * Signer implementation using a local Ed25519 keypair.
1431
+ *
1432
+ * Provides synchronous signing without external dependencies.
1433
+ * Suitable for server-side applications, CLIs, and testing.
1434
+ *
1435
+ * @example
1436
+ * ```typescript
1437
+ * import { Keypair, KeypairSigner } from '@rialo/ts-cdk';
1438
+ *
1439
+ * // Generate new keypair
1440
+ * const keypair = Keypair.generate();
1441
+ * const signer = new KeypairSigner(keypair);
1442
+ *
1443
+ * // Or from mnemonic
1444
+ * const mnemonic = Mnemonic.generate();
1445
+ * const keypair = await mnemonic.toKeypair(0);
1446
+ * const signer = new KeypairSigner(keypair);
1447
+ *
1448
+ * // Sign messages
1449
+ * const publicKey = await signer.getPublicKey();
1450
+ * const signature = await signer.signMessage(message);
1451
+ * ```
1452
+ */
1453
+ declare class KeypairSigner implements Signer {
1454
+ private readonly keypair;
1455
+ constructor(keypair: Keypair);
1456
+ /**
1457
+ * Returns the keypair's public key.
1458
+ */
1459
+ getPublicKey(): Promise<PublicKey>;
1460
+ /**
1461
+ * Signs a message using the keypair's private key.
1462
+ */
1463
+ signMessage(message: Uint8Array): Promise<Signature>;
1464
+ }
1465
+
1466
+ /**
1467
+ * A transaction with zero or more signatures.
1468
+ *
1469
+ * Transactions are immutable - signing methods return new instances.
1470
+ * This prevents accidental modification and signature tampering.
1471
+ *
1472
+ * @example
1473
+ * ```typescript
1474
+ * // Simple signing
1475
+ * const tx = builder.build();
1476
+ * const signed = tx.sign(keypair);
1477
+ *
1478
+ * // Method chaining
1479
+ * const signed = tx
1480
+ * .sign(keypair1)
1481
+ * .sign(keypair2)
1482
+ * .sign(keypair3);
1483
+ *
1484
+ * // Multi-sig convenience
1485
+ * const signed = tx.signAll([keypair1, keypair2, keypair3]);
1486
+ * ```
1487
+ */
1488
+ declare class Transaction {
1489
+ /** The unsigned message */
1490
+ private readonly message;
1491
+ /** Signatures (64 bytes each), aligned with message.header.numRequiredSignatures */
1492
+ private readonly signatures;
1493
+ private constructor();
1494
+ /**
1495
+ * Create an unsigned transaction from a message.
1496
+ * All signature slots are initialized to zero.
1497
+ *
1498
+ * @internal - Users should use TransactionBuilder instead
1499
+ */
1500
+ static fromMessage(message: Message): Transaction;
1501
+ /**
1502
+ * Create transaction from message and existing signatures.
1503
+ * @internal
1504
+ */
1505
+ static fromMessageAndSignatures(message: Message, signatures: readonly Uint8Array[]): Transaction;
1506
+ /**
1507
+ * Deserialize a transaction from wire format.
1508
+ */
1509
+ static deserialize(data: Uint8Array): Transaction;
1510
+ getMessage(): Message;
1511
+ /**
1512
+ * Sign the transaction with a keypair.
1513
+ * Returns a NEW Transaction instance.
1514
+ *
1515
+ * @param keypair - Keypair to sign with
1516
+ * @returns New Transaction instance with signature added
1517
+ *
1518
+ * @example
1519
+ * ```typescript
1520
+ * const signedTx = tx.sign(keypair);
1521
+ * await client.sendTransaction(signedTx.serialize());
1522
+ * ```
1523
+ */
1524
+ sign(keypair: Keypair): Transaction;
1525
+ /**
1526
+ * Sign with multiple keypairs at once.
1527
+ * Returns a NEW Transaction instance.
1528
+ *
1529
+ * @example
1530
+ * ```typescript
1531
+ * const signed = tx.signAll([keypair1, keypair2, keypair3]);
1532
+ * ```
1533
+ */
1534
+ signAll(keypairs: Keypair[]): Transaction;
1535
+ /**
1536
+ * Sign the transaction with a Signer interface (async).
1537
+ * Returns a NEW Transaction instance.
1538
+ *
1539
+ * @example
1540
+ * ```typescript
1541
+ * const signedTx = await tx.signWith(browserWallet);
1542
+ * ```
1543
+ */
1544
+ signWith(signer: Signer): Promise<Transaction>;
1545
+ /**
1546
+ * Sign with multiple signers.
1547
+ * Returns a NEW Transaction instance.
1548
+ */
1549
+ signAllWith(signers: Signer[]): Promise<Transaction>;
1550
+ /**
1551
+ * Partially sign the transaction (for multi-sig transactions).
1552
+ * Returns a NEW Transaction instance.
1553
+ *
1554
+ * @example
1555
+ * ```typescript
1556
+ * const signedTx = tx
1557
+ * .partialSign(signer1)
1558
+ * .partialSign(signer2);
1559
+ * ```
1560
+ */
1561
+ partialSign(keypair: Keypair): Transaction;
1562
+ /**
1563
+ * Partially sign with a Signer interface (async).
1564
+ * Returns a NEW Transaction instance.
1565
+ */
1566
+ partialSignWith(signer: Signer): Promise<Transaction>;
1567
+ /**
1568
+ * Add a signature at a specific index.
1569
+ * Returns a NEW Transaction instance.
1570
+ *
1571
+ * Most users should use sign() or signAll() instead.
1572
+ */
1573
+ addSignature(index: number, signature: Signature | Uint8Array): Transaction;
1574
+ /**
1575
+ * Add a signature for a specific public key.
1576
+ * Returns a NEW Transaction instance.
1577
+ *
1578
+ * Most users should use sign() or signAll() instead.
1579
+ */
1580
+ addSignatureForPubkey(pubkey: PublicKey, signature: Signature | Uint8Array): Transaction;
1581
+ /**
1582
+ * Check if transaction is fully signed (all signatures present).
1583
+ */
1584
+ isSigned(): boolean;
1585
+ /**
1586
+ * Check if a specific signature slot is filled.
1587
+ */
1588
+ isSignaturePresent(index: number): boolean;
1589
+ /**
1590
+ * Get all signatures (returns copies to prevent mutation).
1591
+ */
1592
+ getSignatures(): readonly Uint8Array[];
1593
+ /**
1594
+ * Get a specific signature (returns copy).
1595
+ */
1596
+ getSignature(index: number): Uint8Array;
1597
+ /**
1598
+ * Get a specific signature for a public key.
1599
+ */
1600
+ getSignatureForPubkey(pubkey: PublicKey): Uint8Array;
1601
+ /**
1602
+ * Get required signers for this transaction.
1603
+ */
1604
+ getSigners(): readonly PublicKey[];
1605
+ /**
1606
+ * Get the number of required signatures.
1607
+ */
1608
+ getRequiredSignatureCount(): number;
1609
+ /**
1610
+ * Throw an error if the transaction is not fully signed.
1611
+ *
1612
+ * @throws {TransactionError} If transaction is not fully signed
1613
+ *
1614
+ * @example
1615
+ * ```typescript
1616
+ * signedTx.ensureSigned(); // Throws if not signed
1617
+ * await client.sendTransaction(signedTx.serialize());
1618
+ * ```
1619
+ */
1620
+ ensureSigned(): void;
1621
+ /**
1622
+ * Serialize transaction to wire format.
1623
+ */
1624
+ serialize(): Uint8Array;
1625
+ }
1626
+
1627
+ /**
1628
+ * Fluent API for building transactions.
1629
+ * Returns Transaction directly (not Message).
1630
+ */
1631
+
1632
+ /**
1633
+ * Builder for creating transactions with a fluent API.
1634
+ *
1635
+ * Provides an intuitive interface for constructing transactions.
1636
+ * Call build() to get an unsigned Transaction ready for signing.
1637
+ *
1638
+ * @example
1639
+ * ```typescript
1640
+ * // Simple transfer
1641
+ * const tx = TransactionBuilder.create()
1642
+ * .setPayer(payer)
1643
+ * .setRecentBlockhash(blockhash)
1644
+ * .setTxCreationTime(txCreationTime)
1645
+ * .addInstruction(transfer(from, to, 1_000_000n))
1646
+ * .build();
1647
+ *
1648
+ * const signedTx = tx.sign(keypair);
1649
+ * await client.transaction.sendTransaction(signedTx.serialize());
1650
+ * ```
1651
+ *
1652
+ * @example
1653
+ * ```typescript
1654
+ * // Multi-instruction transaction
1655
+ * const tx = TransactionBuilder.create()
1656
+ * .setPayer(payer)
1657
+ * .setRecentBlockhash(blockhash)
1658
+ * .setTxCreationTime(txCreationTime)
1659
+ * .addInstruction(transfer(from, to, 1_000_000n))
1660
+ * .addInstruction(memoInstruction("Payment for invoice #123"))
1661
+ * .build();
1662
+ * ```
1663
+ */
1664
+ declare class TransactionBuilder {
1665
+ private payer?;
1666
+ private recentBlockhash?;
1667
+ private txCreationTime?;
1668
+ private readonly instructions;
1669
+ private constructor();
1670
+ /**
1671
+ * Create a new transaction builder.
1672
+ */
1673
+ static create(): TransactionBuilder;
1674
+ /**
1675
+ * Set the fee payer for this transaction.
1676
+ *
1677
+ * The payer will be the first account and must sign the transaction.
1678
+ * The payer pays for transaction fees.
1679
+ *
1680
+ * @param payer - Public key of the fee payer
1681
+ */
1682
+ setPayer(payer: PublicKey): this;
1683
+ /**
1684
+ * Set the recent blockhash for replay protection.
1685
+ *
1686
+ * Get this from client.getLatestBlockhash().
1687
+ * Transactions are only valid for ~60 seconds after the blockhash.
1688
+ *
1689
+ * @param blockhash - Recent blockhash from the network
1690
+ */
1691
+ setRecentBlockhash(blockhash: Blockhash): this;
1692
+ /**
1693
+ * Set the transaction creation timestamp.
1694
+ *
1695
+ * This is the time the transaction was created, in milliseconds since Unix epoch.
1696
+ * It can be used for additional replay protection or auditing.
1697
+ *
1698
+ * @param txCreationTime - Transaction creation time in milliseconds since Unix epoch
1699
+ */
1700
+ setTxCreationTime(txCreationTime: bigint): this;
1701
+ /**
1702
+ * Add an instruction to the transaction.
1703
+ *
1704
+ * @param instruction - Instruction to add
1705
+ */
1706
+ addInstruction(instruction: Instruction): this;
1707
+ /**
1708
+ * Add multiple instructions at once.
1709
+ *
1710
+ * @param instructions - Array of instructions to add
1711
+ */
1712
+ addInstructions(instructions: readonly Instruction[]): this;
1713
+ /**
1714
+ * Build the transaction (unsigned).
1715
+ *
1716
+ * Returns an unsigned Transaction that's ready to be signed.
1717
+ *
1718
+ * @returns Unsigned Transaction
1719
+ * @throws {TransactionError} If payer, blockhash, or instructions are missing
1720
+ *
1721
+ * @example
1722
+ * ```typescript
1723
+ * const tx = builder.build();
1724
+ * const signedTx = tx.sign(keypair);
1725
+ * ```
1726
+ */
1727
+ build(): Transaction;
1728
+ }
1729
+
1730
+ /**
1731
+ * Converts bytes to base64 string.
1732
+ *
1733
+ * Works in both browser and Node.js environments.
1734
+ */
1735
+ declare function toBase64(bytes: Uint8Array): string;
1736
+ /**
1737
+ * Converts base64 string to bytes.
1738
+ *
1739
+ * Works in both browser and Node.js environments.
1740
+ */
1741
+ declare function fromBase64(base64: string): Uint8Array;
1742
+ /**
1743
+ * Sleeps for the specified duration.
1744
+ *
1745
+ * @param ms - Milliseconds to sleep
1746
+ */
1747
+ declare function sleep(ms: number): Promise<void>;
1748
+ /**
1749
+ * Calculates exponential backoff delay with jitter.
1750
+ *
1751
+ * @param attempt - Current retry attempt (0-indexed)
1752
+ * @param baseMs - Base delay in milliseconds
1753
+ * @param maxMs - Maximum delay in milliseconds
1754
+ * @returns Calculated delay with 30% random jitter
1755
+ */
1756
+ declare function calculateBackoff(attempt: number, baseMs?: number, maxMs?: number): number;
1757
+ /**
1758
+ * Returns the devnet RPC URL.
1759
+ */
1760
+ declare function getDevnetUrl(): string;
1761
+ /**
1762
+ * Returns the testnet RPC URL.
1763
+ */
1764
+ declare function getTestnetUrl(): string;
1765
+ /**
1766
+ * Returns the mainnet RPC URL.
1767
+ */
1768
+ declare function getMainnetUrl(): string;
1769
+ /**
1770
+ * Returns the localnet RPC URL.
1771
+ */
1772
+ declare function getLocalnetUrl(): string;
1773
+
1774
+ export { type AccountInfo, type AccountMeta, AccountMetaTable, BASE_DERIVATION_PATH, BLOCKHASH_LENGTH, BaseRpcClient, Blockhash, type CompiledInstruction, CryptoError, CryptoErrorCode, DEFAULT_NUM_ACCOUNTS, type EpochInfoResponse, type GetConnectedFullNodesResponse, type GetFeeForMessageResponse, type GetHealthResponse, type GetSignaturesForAddressConfig, type GetSignaturesForAddressResponse, type GetSubscriptionsResponse, type GetTransactionsConfig, type GetTransactionsResponse, type GetTriggeredTransactionsResponse, type GetValidatorHealthResponse, type GetWorkflowLineageRequest, type GetWorkflowLineageResponse, HttpTransport, type HttpTransportConfig, type Instruction, type IsBlockhashValidResponse, KELVIN_PER_RLO, Keypair, KeypairSigner, Message, type MessageHeader, Mnemonic, type MnemonicStrength, type MultipleAccountsResponse, PUBLIC_KEY_LENGTH, PublicKey, QueryRpcClient, RialoClient, RialoError, RialoErrorType, RpcError, RpcErrorCode, type RpcErrorDetails$1 as RpcErrorDetails, SECRET_KEY_LENGTH, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, type SendTransactionOptions, Signature, type SignatureStatus, type Signer, SystemInstruction, Transaction, TransactionBuilder, TransactionError, TransactionErrorCode, type TransactionResponse, TransactionRpcClient, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_TESTNET, calculateBackoff, createAccount, createBorshInstruction, createRialoClient, encodeBorshData, fromBase64, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, sleep, toBase64, transferInstruction };