@rialo/ts-cdk 0.4.2 → 0.8.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -730,129 +730,71 @@ declare class RialoError extends Error {
730
730
  static serialization(message: string): RialoError;
731
731
  }
732
732
 
733
- /**
734
- * Error codes for HPKE encryption operations.
735
- */
736
- declare enum HpkeErrorCode {
737
- /** Key length does not match expected size */
738
- INVALID_KEY_LENGTH = "INVALID_KEY_LENGTH",
739
- /** Ciphertext is shorter than minimum required length */
740
- CIPHERTEXT_TOO_SHORT = "CIPHERTEXT_TOO_SHORT",
741
- /** HPKE encryption operation failed */
733
+ declare enum EncryptionErrorCode {
734
+ /** Input validation failed (empty secret, oversized secret, invalid key length) */
735
+ INVALID_INPUT = "INVALID_INPUT",
736
+ /** Threshold public key is not a valid compressed Ristretto255 point */
737
+ INVALID_THRESHOLD_KEY = "INVALID_THRESHOLD_KEY",
738
+ /** DKG encryption operation failed */
742
739
  ENCRYPTION_FAILED = "ENCRYPTION_FAILED",
743
740
  /** Failed to deserialize Borsh data */
744
741
  BORSH_DESERIALIZE_FAILED = "BORSH_DESERIALIZE_FAILED",
745
742
  /** RexValue has invalid variant byte */
746
743
  INVALID_REX_VALUE = "INVALID_REX_VALUE"
747
744
  }
748
- /**
749
- * Error class for HPKE encryption operations.
750
- *
751
- * Provides detailed error information for encryption failures,
752
- * including error codes and contextual details.
753
- */
754
- declare class HpkeError extends Error {
755
- readonly code: HpkeErrorCode;
745
+ declare class EncryptionError extends Error {
746
+ readonly code: EncryptionErrorCode;
756
747
  readonly cause?: Error;
757
- constructor(code: HpkeErrorCode, message: string, cause?: Error);
758
- /**
759
- * Create an error for invalid key length.
760
- *
761
- * @param expected - Expected key length in bytes
762
- * @param actual - Actual key length in bytes
763
- * @param keyType - Description of the key type (e.g., "REX public key")
764
- */
765
- static invalidKeyLength(expected: number, actual: number, keyType: string): HpkeError;
766
- /**
767
- * Create an error for ciphertext that is too short.
768
- *
769
- * @param minLength - Minimum required length
770
- * @param actual - Actual length
771
- */
772
- static ciphertextTooShort(minLength: number, actual: number): HpkeError;
773
- /**
774
- * Create an error for encryption failure.
775
- *
776
- * @param cause - The underlying error
777
- */
778
- static encryptionFailed(cause: Error): HpkeError;
779
- /**
780
- * Create an error for Borsh deserialization failure.
781
- *
782
- * @param cause - The underlying error
783
- */
784
- static borshDeserializeFailed(cause: Error): HpkeError;
785
- /**
786
- * Create an error for invalid RexValue variant.
787
- *
788
- * @param variant - The invalid variant byte
789
- */
790
- static invalidRexValue(variant: number): HpkeError;
748
+ constructor(code: EncryptionErrorCode, message: string, cause?: Error);
749
+ static invalidInput(message: string): EncryptionError;
750
+ static invalidThresholdKey(cause: Error): EncryptionError;
751
+ static encryptionFailed(cause: Error): EncryptionError;
752
+ static borshDeserializeFailed(cause: Error): EncryptionError;
753
+ static invalidRexValue(variant: number): EncryptionError;
791
754
  }
792
755
 
793
756
  /**
794
- * Constants for REX HPKE encryption.
757
+ * Constants for DKG threshold encryption.
795
758
  *
796
759
  * These constants MUST match the Rust implementation exactly:
797
- * - `crates/tee/secret-sharing/src/constants.rs`
760
+ * - `crates/tee/secret-sharing/src/types.rs`
761
+ * - `developer-frameworks/cdk/rialo-rs-cdk/src/secret_encryption.rs`
798
762
  *
799
763
  * @module
800
764
  */
801
765
  /**
802
- * Additional Authenticated Data (AAD) prefix for user secrets.
803
- *
804
- * This 13-byte string is prepended to the sender's public key to form
805
- * the complete AAD for HPKE encryption. It provides domain separation
806
- * to prevent cross-protocol attacks.
766
+ * Version byte prepended to every DKG threshold-encrypted payload stored in
767
+ * `RexValue::Encrypted`. Format: `[DKG_PAYLOAD_VERSION] || borsh(DkgEncryptedPayload)`.
807
768
  *
808
- * Format: `USER_SECRET_AAD || senderPubkey` = 45 bytes total AAD
809
- *
810
- * @remarks
811
- * Must match Rust: `pub const USER_SECRET_AAD: &[u8] = b"rex-secret-v1";`
769
+ * Must match Rust: `pub const DKG_PAYLOAD_VERSION: u8 = 0x02`
812
770
  */
813
- declare const USER_SECRET_AAD: Uint8Array<ArrayBuffer>;
771
+ declare const DKG_PAYLOAD_VERSION = 2;
814
772
  /**
815
- * HPKE info string for secret sharing context.
816
- *
817
- * This 32-byte string is used as the `info` parameter in HPKE encryption,
818
- * providing domain separation for secret sharing operations.
773
+ * Maximum plaintext length accepted by `encryptSecretBytes` (64 KB).
819
774
  *
820
- * @remarks
821
- * Must match Rust: `pub const SECRET_SHARING_HPKE_INFO: &[u8; 32] = b"rialo/tee/secret-sharing-hpke/v1";`
775
+ * Must match Rust: `pub const MAX_SECRET_LENGTH: usize = 64 * 1024`
822
776
  */
823
- declare const SECRET_SHARING_HPKE_INFO: Uint8Array<ArrayBuffer>;
777
+ declare const MAX_SECRET_LENGTH: number;
824
778
  /**
825
- * Length of an X25519 public key in bytes.
779
+ * Length of a compressed Ristretto255 point in bytes.
826
780
  *
827
- * Used for the REX encryption public key (secret sharing key).
781
+ * Used for the DKG threshold public key and the ElGamal header point U.
828
782
  */
829
- declare const X25519_PUBLIC_KEY_LENGTH = 32;
783
+ declare const RISTRETTO_POINT_BYTES = 32;
830
784
  /**
831
785
  * Length of an Ed25519 public key in bytes.
832
786
  *
833
- * Used for sender identity binding in AAD construction.
787
+ * Used for the creator public key bound into the AAD.
834
788
  */
835
789
  declare const ED25519_PUBLIC_KEY_LENGTH = 32;
836
790
  /**
837
- * Length of the HPKE encapsulated key (enc) in bytes.
838
- *
839
- * For X25519, this is always 32 bytes.
791
+ * Length of the ChaCha20-Poly1305 nonce in bytes.
840
792
  */
841
- declare const HPKE_ENC_LENGTH = 32;
793
+ declare const CHACHA20_POLY1305_NONCE_LENGTH = 12;
842
794
  /**
843
795
  * Length of the ChaCha20-Poly1305 authentication tag in bytes.
844
796
  */
845
797
  declare const CHACHA20_POLY1305_TAG_LENGTH = 16;
846
- /**
847
- * Total overhead added by HPKE encryption.
848
- *
849
- * This is the additional bytes beyond the plaintext:
850
- * - enc (32 bytes): Encapsulated ephemeral public key
851
- * - tag (16 bytes): ChaCha20-Poly1305 authentication tag
852
- *
853
- * Ciphertext length = plaintext length + 48 bytes
854
- */
855
- declare const HPKE_OVERHEAD_LENGTH: number;
856
798
 
857
799
  /**
858
800
  * Variant discriminator for RexValue Borsh serialization.
@@ -886,7 +828,7 @@ declare enum RexValueVariant {
886
828
  * // Plain value (unencrypted)
887
829
  * const plain = RexValue.plain(new TextEncoder().encode("hello"));
888
830
  *
889
- * // Encrypted value (via HPKE)
831
+ * // Encrypted value (via DKG threshold encryption)
890
832
  * const encrypted = RexValue.encrypted(ciphertextBytes);
891
833
  *
892
834
  * // Serialize to Borsh
@@ -915,9 +857,9 @@ declare class RexValue {
915
857
  */
916
858
  static plainString(s: string): RexValue;
917
859
  /**
918
- * Create an encrypted RexValue from HPKE ciphertext.
860
+ * Create an encrypted RexValue from a DKG threshold-encrypted payload.
919
861
  *
920
- * @param ciphertext - The HPKE-encrypted ciphertext (enc || ct || tag)
862
+ * @param ciphertext - The DKG-encrypted payload bytes (`[0x02] || borsh(DkgEncryptedPayload)`)
921
863
  * @returns A new RexValue with Encrypted variant
922
864
  */
923
865
  static encrypted(ciphertext: Uint8Array): RexValue;
@@ -959,112 +901,11 @@ declare class RexValue {
959
901
  *
960
902
  * @param data - The Borsh-serialized bytes
961
903
  * @returns A new RexValue
962
- * @throws {HpkeError} If deserialization fails
904
+ * @throws {EncryptionError} If deserialization fails
963
905
  */
964
906
  static fromBorsh(data: Uint8Array): RexValue;
965
907
  }
966
908
 
967
- /**
968
- * Encrypt data using HPKE for REX secret sharing.
969
- *
970
- * This function performs HPKE encryption using the Base mode with:
971
- * - X25519 for key encapsulation
972
- * - HKDF-SHA256 for key derivation
973
- * - ChaCha20-Poly1305 for authenticated encryption
974
- *
975
- * The output format is: `enc (32 bytes) || ciphertext || tag (16 bytes)`
976
- *
977
- * @param rexPubkey - The REX X25519 public key (32 bytes)
978
- * @param data - The plaintext data to encrypt
979
- * @param senderPubkey - The sender's Ed25519 public key (32 bytes) for AAD construction
980
- * @returns The encrypted ciphertext including enc and tag
981
- * @throws {HpkeError} If key lengths are invalid or encryption fails
982
- *
983
- * @example
984
- * ```typescript
985
- * const rexPubkey = await client.getSecretSharingPubkey();
986
- * const ciphertext = await hpkeEncrypt(
987
- * rexPubkey,
988
- * new TextEncoder().encode("secret data"),
989
- * keypair.publicKey.toBytes()
990
- * );
991
- * ```
992
- */
993
- declare function hpkeEncrypt(rexPubkey: Uint8Array, data: Uint8Array, senderPubkey: Uint8Array): Promise<Uint8Array>;
994
- /**
995
- * Encrypt data for REX and wrap it in an RexValue.
996
- *
997
- * This is a convenience function that combines:
998
- * 1. HPKE encryption using `hpkeEncrypt`
999
- * 2. Wrapping the ciphertext in an `RexValue.encrypted`
1000
- *
1001
- * The resulting RexValue can be serialized to Borsh and sent to the network.
1002
- *
1003
- * @param rexPubkey - The REX X25519 public key (32 bytes)
1004
- * @param data - The plaintext data to encrypt
1005
- * @param senderPubkey - The sender's Ed25519 public key (32 bytes)
1006
- * @returns An RexValue containing the encrypted ciphertext
1007
- * @throws {HpkeError} If key lengths are invalid or encryption fails
1008
- *
1009
- * @example
1010
- * ```typescript
1011
- * import { RpcClient, Keypair } from "@rialo/ts-cdk";
1012
- * import { encryptForRex, RexValue } from "@rialo/ts-cdk/rex";
1013
- *
1014
- * // Get REX public key from the network
1015
- * const client = new RpcClient("https://rpc.rialo.xyz");
1016
- * const rexPubkey = await client.getSecretSharingPubkey();
1017
- *
1018
- * // Create keypair for signing
1019
- * const keypair = Keypair.generate();
1020
- *
1021
- * // Encrypt secret data
1022
- * const rexValue = await encryptForRex(
1023
- * rexPubkey,
1024
- * new TextEncoder().encode("my secret API key"),
1025
- * keypair.publicKey.toBytes()
1026
- * );
1027
- *
1028
- * // The RexValue can now be serialized and used in transactions
1029
- * const borshBytes = rexValue.toBorsh();
1030
- * ```
1031
- */
1032
- declare function encryptForRex(rexPubkey: Uint8Array, data: Uint8Array, senderPubkey: Uint8Array): Promise<RexValue>;
1033
- /**
1034
- * Calculate the expected ciphertext length for a given plaintext length.
1035
- *
1036
- * The ciphertext consists of:
1037
- * - enc (32 bytes): Encapsulated ephemeral public key
1038
- * - ciphertext (plaintext.length bytes): Encrypted data
1039
- * - tag (16 bytes): ChaCha20-Poly1305 authentication tag
1040
- *
1041
- * @param plaintextLength - Length of the plaintext in bytes
1042
- * @returns Expected ciphertext length
1043
- *
1044
- * @example
1045
- * ```typescript
1046
- * const ciphertextLen = getCiphertextLength(100);
1047
- * console.log(ciphertextLen); // 148 (32 + 100 + 16)
1048
- * ```
1049
- */
1050
- declare function getCiphertextLength(plaintextLength: number): number;
1051
- /**
1052
- * Validate that a ciphertext has a valid length.
1053
- *
1054
- * A valid HPKE ciphertext must be at least 48 bytes (32 enc + 16 tag).
1055
- *
1056
- * @param ciphertext - The ciphertext to validate
1057
- * @returns true if the ciphertext length is valid
1058
- *
1059
- * @example
1060
- * ```typescript
1061
- * if (!isValidCiphertextLength(ciphertext)) {
1062
- * throw new Error("Ciphertext too short");
1063
- * }
1064
- * ```
1065
- */
1066
- declare function isValidCiphertextLength(ciphertext: Uint8Array): boolean;
1067
-
1068
909
  /** A 32-byte public key, base58-encoded on the wire. */
1069
910
 
1070
911
  /** A 64-byte Ed25519 signature, base58-encoded on the wire. */
@@ -1103,6 +944,17 @@ interface CompiledInstruction$1 {
1103
944
  /** Instruction data (base58-encoded on the wire). */
1104
945
  data: string;
1105
946
  }
947
+ /**
948
+ * An inner instruction produced by a cross-program invocation (CPI).
949
+ * Contains the index of the top-level instruction that triggered it
950
+ * and the compiled instruction itself.
951
+ */
952
+ interface InnerInstruction {
953
+ /** Index of the top-level instruction that invoked this CPI. */
954
+ instructionIndex: number;
955
+ /** The compiled instruction produced by the CPI. */
956
+ instruction: CompiledInstruction$1;
957
+ }
1106
958
  /**
1107
959
  * Header of a transaction message.
1108
960
  */
@@ -1141,6 +993,12 @@ interface TransactionStatusMetadata {
1141
993
  err?: string;
1142
994
  /** Log messages emitted during execution (if available). */
1143
995
  logMessages?: string[];
996
+ /** Inner instructions produced by cross-program invocations (CPIs).
997
+ Critical for decoding token transfers — most Token-2022 Transfer
998
+ instructions are CPIs, not top-level instructions. */
999
+ innerInstructions?: InnerInstruction[];
1000
+ /** Compute units consumed by this transaction. */
1001
+ computeUnitsConsumed?: bigint;
1144
1002
  }
1145
1003
  /**
1146
1004
  * Full response for a transaction query.
@@ -1484,11 +1342,13 @@ interface ConnectedNode {
1484
1342
  connectedMs: bigint;
1485
1343
  }
1486
1344
  /**
1487
- * The TEE's X25519 public key for HPKE encryption.
1345
+ * The active secret-sharing public key exposed by the network.
1488
1346
  */
1489
1347
  interface SecretSharingPubkey {
1490
1348
  /** Hex-encoded public key. */
1491
1349
  publicKey: string;
1350
+ /** Active epoch for the threshold public key. */
1351
+ epoch: bigint;
1492
1352
  }
1493
1353
  /**
1494
1354
  * Request to submit an epoch change (admin-only).
@@ -1499,8 +1359,14 @@ interface ValidatorInfoRequest {
1499
1359
  stake: bigint;
1500
1360
  /** Consensus network address (Multiaddr string). */
1501
1361
  consensusAddress: string;
1502
- /** State sync network address (Multiaddr string). */
1503
- stateSyncAddress: string;
1362
+ /** Subdag sync network address (Multiaddr string). */
1363
+ subdagSyncAddress: string;
1364
+ /** Long-lived network-service address for snapshot serving /
1365
+ state-sync (Multiaddr string, TCP, e.g.
1366
+ "/ip4/127.0.0.1/tcp/4300/http"). Stable across all epochs
1367
+ and expected to match the value the validator advertised
1368
+ at genesis. */
1369
+ networkServiceAddress: string;
1504
1370
  /** Validator hostname. */
1505
1371
  hostname: string;
1506
1372
  /** Identity public key. */
@@ -1640,8 +1506,8 @@ interface ValidatorAccountInfo {
1640
1506
  stake: bigint;
1641
1507
  /** Network address for consensus communication. */
1642
1508
  address: string;
1643
- /** Network address for state synchronization. */
1644
- stateSyncAddress: string;
1509
+ /** Network address for consensus subdag synchronization. */
1510
+ subdagSyncAddress: string;
1645
1511
  }
1646
1512
  /**
1647
1513
  * SPL Token account balance information.
@@ -1707,6 +1573,149 @@ interface RexInfoAndDuties {
1707
1573
  /** List of duties expecting updates or commitment. */
1708
1574
  duties: RexDuty[];
1709
1575
  }
1576
+ /**
1577
+ * Keypair metadata — public information about a derived keypair.
1578
+ * Does NOT contain secret material. Safe to pass around freely.
1579
+ */
1580
+ interface DerivedKeypairInfo {
1581
+ /** Keypair index within the keyring. */
1582
+ index: number;
1583
+ /** Public key (32 bytes Ed25519). */
1584
+ pubkey: PublicKey;
1585
+ /** Base58-encoded public key string. */
1586
+ pubkeyString: string;
1587
+ /** HD derivation path, if available. */
1588
+ derivationPath?: string;
1589
+ }
1590
+ /**
1591
+ * Program loader type.
1592
+ */
1593
+ type LoaderType = "riscv" | "loaderV4";
1594
+ /**
1595
+ * Configuration for chunked program deployment.
1596
+ * retry delays are u64 to match the native Rust DeploymentConfig timers.
1597
+ * chunk-size and confirmation-batch-size are intentionally u32 (not usize)
1598
+ * because chunk sizes and batch counts never exceed 32-bit range in practice,
1599
+ * and u32 is the widest portable integer in WIT without crossing into u64.
1600
+ */
1601
+ interface DeploymentConfig$1 {
1602
+ /** Size of each data chunk in bytes. */
1603
+ chunkSize?: number;
1604
+ /** Maximum number of retry attempts per chunk. */
1605
+ maxRetries?: number;
1606
+ /** Initial retry delay in milliseconds. */
1607
+ retryBaseDelayMs?: bigint;
1608
+ /** Maximum retry delay in milliseconds. */
1609
+ retryMaxDelayMs?: bigint;
1610
+ /** Number of confirmations to batch. */
1611
+ confirmationBatchSize?: number;
1612
+ }
1613
+ /**
1614
+ * Account metadata for a program invocation instruction.
1615
+ */
1616
+ interface InvocationAccountMeta {
1617
+ /** Account public key. */
1618
+ pubkey: PublicKey;
1619
+ /** Whether this account is a signer. */
1620
+ isSigner: boolean;
1621
+ /** Whether this account is writable. */
1622
+ isWritable: boolean;
1623
+ }
1624
+ /**
1625
+ * A fully assembled program instruction.
1626
+ */
1627
+ interface ProgramInstruction {
1628
+ /** Program ID to invoke. */
1629
+ programId: PublicKey;
1630
+ /** Accounts required by the instruction. */
1631
+ accounts: InvocationAccountMeta[];
1632
+ /** Instruction data payload. */
1633
+ data: Uint8Array;
1634
+ }
1635
+
1636
+ /**
1637
+ * Encrypt raw bytes using the DKG threshold public key.
1638
+ *
1639
+ * Low-level variant for callers that supply an explicit epoch and hex-encoded
1640
+ * threshold public key rather than a full `SecretSharingPubkey` struct.
1641
+ *
1642
+ * Uses ElGamal-style ECIES over Ristretto255 with HKDF-SHA256 key derivation
1643
+ * and ChaCha20-Poly1305 AEAD. The output format is:
1644
+ * `[0x02] || borsh(DkgEncryptedPayload)` — matching the Rust CDK exactly.
1645
+ *
1646
+ * @param plaintext - Raw bytes to encrypt (non-empty, max 64 KB)
1647
+ * @param creatorPubkey - Ed25519 public key (32 bytes) bound into the AAD
1648
+ * @param epoch - DKG epoch identifying the joint public key
1649
+ * @param thresholdPubkeyHex - Hex-encoded compressed Ristretto255 joint public key (32 bytes)
1650
+ * @throws {EncryptionError} On invalid inputs or encryption failure
1651
+ */
1652
+ declare function encryptSecretBytesWithEpoch(plaintext: Uint8Array, creatorPubkey: Uint8Array, epoch: bigint, thresholdPubkeyHex: string): Uint8Array;
1653
+ /**
1654
+ * Encrypt raw bytes using the active DKG threshold public key.
1655
+ *
1656
+ * Accepts a `SecretSharingPubkey` (as returned by `getSecretSharingPubkey()`)
1657
+ * and produces a versioned `DkgEncryptedPayload` that the network can
1658
+ * threshold-decrypt during REX execution.
1659
+ *
1660
+ * @param plaintext - Raw bytes to encrypt (non-empty, max 64 KB)
1661
+ * @param creatorPubkey - Ed25519 public key (32 bytes) bound into the AAD
1662
+ * @param secretSharingPubkey - Active threshold key metadata from RPC
1663
+ * @throws {EncryptionError} On invalid inputs or encryption failure
1664
+ *
1665
+ * @example
1666
+ * ```typescript
1667
+ * const { publicKey, epoch } = await client.getSecretSharingPubkey();
1668
+ * const payload = encryptSecretBytes(
1669
+ * new TextEncoder().encode("my-api-key"),
1670
+ * keypair.publicKey.toBytes(),
1671
+ * { publicKey, epoch },
1672
+ * );
1673
+ * const rexValue = RexValue.encrypted(payload);
1674
+ * ```
1675
+ */
1676
+ declare function encryptSecretBytes(plaintext: Uint8Array, creatorPubkey: Uint8Array, secretSharingPubkey: SecretSharingPubkey): Uint8Array;
1677
+ /**
1678
+ * Encrypt a UTF-8 string using the active DKG threshold public key.
1679
+ *
1680
+ * Convenience wrapper around `encryptSecretBytes` for string secrets.
1681
+ *
1682
+ * @param secret - The plaintext string to encrypt (non-empty, max 64 KB)
1683
+ * @param creatorPubkey - Ed25519 public key (32 bytes)
1684
+ * @param secretSharingPubkey - Active threshold key metadata from RPC
1685
+ * @throws {EncryptionError} On invalid inputs or encryption failure
1686
+ *
1687
+ * @example
1688
+ * ```typescript
1689
+ * const payload = encryptSecret(
1690
+ * "Bearer sk-1234567890abcdef",
1691
+ * keypair.publicKey.toBytes(),
1692
+ * await client.getSecretSharingPubkey(),
1693
+ * );
1694
+ * ```
1695
+ */
1696
+ declare function encryptSecret(secret: string, creatorPubkey: Uint8Array, secretSharingPubkey: SecretSharingPubkey): Uint8Array;
1697
+ /**
1698
+ * Encrypt raw bytes for REX and wrap the result in a `RexValue`.
1699
+ *
1700
+ * Combines `encryptSecretBytes` with `RexValue.encrypted`. The resulting
1701
+ * `RexValue` can be serialized to Borsh and included in transactions.
1702
+ *
1703
+ * @param plaintext - Raw bytes to encrypt
1704
+ * @param creatorPubkey - Ed25519 public key (32 bytes)
1705
+ * @param secretSharingPubkey - Active threshold key metadata from RPC
1706
+ * @throws {EncryptionError} On invalid inputs or encryption failure
1707
+ *
1708
+ * @example
1709
+ * ```typescript
1710
+ * const rexValue = encryptForRex(
1711
+ * new TextEncoder().encode("my secret"),
1712
+ * keypair.publicKey.toBytes(),
1713
+ * await client.getSecretSharingPubkey(),
1714
+ * );
1715
+ * const borshBytes = rexValue.toBorsh();
1716
+ * ```
1717
+ */
1718
+ declare function encryptForRex(plaintext: Uint8Array, creatorPubkey: Uint8Array, secretSharingPubkey: SecretSharingPubkey): RexValue;
1710
1719
 
1711
1720
  /**
1712
1721
  * Base client with JSON-RPC protocol handling.
@@ -2103,19 +2112,19 @@ declare abstract class RpcClient {
2103
2112
  */
2104
2113
  abstract getConnectedFullNodes(): Promise<ConnectedNode[]>;
2105
2114
  /**
2106
- * Gets the TEE's secret sharing public key for HPKE encryption.
2115
+ * Gets the active threshold public key used for secret sharing.
2107
2116
  *
2108
- * This public key is used to encrypt secrets that only the TEE cluster
2109
- * can decrypt.
2117
+ * This public key is used to create threshold-encrypted payloads that
2118
+ * the crypto-service committee can decrypt.
2110
2119
  *
2111
2120
  * # Returns
2112
2121
  *
2113
- * The X25519 public key (hex-encoded) used for HPKE encryption.
2122
+ * The active threshold public key (hex-encoded) plus epoch metadata.
2114
2123
  *
2115
2124
  * # Errors
2116
2125
  *
2117
- * Returns an error if the RPC call fails, the TEE Registry state account
2118
- * doesn't exist, or the secret sharing public key has not been registered.
2126
+ * Returns an error if the RPC call fails or no active threshold public key
2127
+ * has been finalized yet.
2119
2128
  */
2120
2129
  abstract getSecretSharingPubkey(): Promise<SecretSharingPubkey>;
2121
2130
  /**
@@ -2629,7 +2638,7 @@ declare class RialoClient extends RpcClient {
2629
2638
  */
2630
2639
  getConnectedFullNodes(): Promise<ConnectedNode[]>;
2631
2640
  /**
2632
- * Gets the TEE's secret sharing public key for HPKE encryption.
2641
+ * Gets the active secret-sharing public key metadata.
2633
2642
  */
2634
2643
  getSecretSharingPubkey(): Promise<SecretSharingPubkey>;
2635
2644
  /**
@@ -2965,29 +2974,18 @@ declare class QueryRpcClient extends BaseRpcClient {
2965
2974
  */
2966
2975
  getTriggeredTransactions(subscriptionAccount: PublicKey, limit?: number): Promise<TriggeredTransaction[]>;
2967
2976
  /**
2968
- * Retrieve the REX X25519 public key for secret sharing encryption.
2977
+ * Retrieve the active threshold public key metadata.
2969
2978
  *
2970
- * This key is used for HPKE encryption when sending encrypted data
2971
- * that should only be decryptable within the REX execution environment.
2972
- *
2973
- * @returns The REX X25519 public key as a 32-byte Uint8Array
2974
- *
2975
- * @example
2976
- * ```typescript
2977
- * import { encryptForREX } from "@rialo/ts-cdk";
2978
- *
2979
- * // Get the REX public key
2980
- * const rexPubkey = await client.getSecretSharingPubkey();
2981
- *
2982
- * // Use it for HPKE encryption
2983
- * const encrypted = await encryptForRex(
2984
- * rexPubkey,
2985
- * new TextEncoder().encode("secret data"),
2986
- * keypair.publicKey.toBytes()
2987
- * );
2988
- * ```
2979
+ * Returns the active threshold public key (a compressed Ristretto point) and
2980
+ * its DKG epoch. Pass the result directly to `encryptSecretBytes`,
2981
+ * `encryptSecret`, or `encryptForRex` to produce a threshold-encrypted
2982
+ * `DkgEncryptedPayload` the network can decrypt during REX execution.
2983
+ */
2984
+ getSecretSharingPubkey(): Promise<SecretSharingPubkey>;
2985
+ /**
2986
+ * @deprecated Use `getSecretSharingPubkey()` instead.
2989
2987
  */
2990
- getSecretSharingPubkey(): Promise<Uint8Array>;
2988
+ getSecretSharingPubkeyInfo(): Promise<SecretSharingPubkey>;
2991
2989
  /**
2992
2990
  * Get the config hash prefix for replay protection.
2993
2991
  *
@@ -4505,6 +4503,212 @@ declare function getMainnetUrl(): string;
4505
4503
  */
4506
4504
  declare function getLocalnetUrl(): string;
4507
4505
 
4506
+ /**
4507
+ * A keyring managing one or more derived keypairs.
4508
+ * Secret material stays inside the keyring — callers interact via
4509
+ * indices and public metadata. No freely-passed keypair resources.
4510
+ *
4511
+ * No direct constructor — keyrings are created via KeyringProvider
4512
+ * (create, create-with-mnemonic, recover-from-mnemonic, load).
4513
+ * Active keypair contract: the active keypair is always index 0 at
4514
+ * creation time. Active-keypair switching is a facade operation not
4515
+ * in the generated contract.
4516
+ */
4517
+ /**
4518
+ * Resource `keyring` — generated from spec.wit.
4519
+ *
4520
+ * Extend this class to provide a concrete `Keyring` implementation.
4521
+ * Instance methods are abstract; static methods throw by default (override in subclass).
4522
+ */
4523
+ declare abstract class Keyring {
4524
+ /**
4525
+ * Sign a message with the active keypair.
4526
+ * Returns 64-byte Ed25519 signature.
4527
+ */
4528
+ abstract sign(message: Uint8Array): Uint8Array;
4529
+ /**
4530
+ * Verify a signature with the active keypair.
4531
+ */
4532
+ abstract verify(message: Uint8Array, sig: Uint8Array): boolean;
4533
+ /**
4534
+ * Active keypair's public key as base58 string.
4535
+ */
4536
+ abstract pubkeyString(): string;
4537
+ /**
4538
+ * Active keypair's public key (32 bytes).
4539
+ */
4540
+ abstract pubkey(): PublicKey;
4541
+ /**
4542
+ * Get public metadata for a keypair by index.
4543
+ */
4544
+ abstract getKeypairInfo(index: number): DerivedKeypairInfo | undefined;
4545
+ /**
4546
+ * List all keypair indices, sorted ascending.
4547
+ */
4548
+ abstract listKeypairs(): number[];
4549
+ /**
4550
+ * Get public metadata for all keypairs, sorted by ascending index.
4551
+ */
4552
+ abstract getKeypairsInfo(): DerivedKeypairInfo[];
4553
+ /**
4554
+ * Sign with a specific keypair by index.
4555
+ */
4556
+ abstract signWithKeypair(message: Uint8Array, index: number): Uint8Array;
4557
+ }
4558
+
4559
+ /**
4560
+ * Concrete keyring implementation backed by an in-memory map of derived keypairs.
4561
+ *
4562
+ * Keyrings are created via {@link InMemoryKeyringProvider}, not directly.
4563
+ * The active keypair defaults to index 0. Use {@link setActiveKeypair} to change it.
4564
+ * Secret material stays inside the keyring — callers interact via indices and public metadata.
4565
+ */
4566
+ declare class RialoKeyring extends Keyring {
4567
+ private readonly keypairs;
4568
+ private readonly derivationPaths;
4569
+ private activeIndex;
4570
+ constructor(keypairs: Map<number, Keypair>, derivationPaths: Map<number, string | undefined>);
4571
+ /**
4572
+ * Sets the active keypair index (facade operation, not in WIT contract).
4573
+ *
4574
+ * @param index - The keypair index to make active
4575
+ * @throws {RialoError} If the index does not exist in this keyring
4576
+ */
4577
+ setActiveKeypair(index: number): void;
4578
+ private activeKeypair;
4579
+ sign(message: Uint8Array): Uint8Array;
4580
+ verify(message: Uint8Array, sig: Uint8Array): boolean;
4581
+ pubkeyString(): string;
4582
+ pubkey(): PublicKey;
4583
+ getKeypairInfo(index: number): DerivedKeypairInfo | undefined;
4584
+ listKeypairs(): number[];
4585
+ getKeypairsInfo(): DerivedKeypairInfo[];
4586
+ signWithKeypair(message: Uint8Array, index: number): Uint8Array;
4587
+ /**
4588
+ * Securely erases all secret key material from this keyring snapshot.
4589
+ *
4590
+ * Calls {@link Keypair.dispose} on every keypair, zeroing private key bytes.
4591
+ * After disposal, signing and secret-key export will throw. Verification
4592
+ * still works (uses only the public key). Does not affect provider-stored
4593
+ * state or other snapshots.
4594
+ */
4595
+ dispose(): void;
4596
+ }
4597
+
4598
+ /**
4599
+ * Storage and lifecycle management for keyrings. All methods async (I/O).
4600
+ * No WIT constructor — concrete providers are language-specific
4601
+ * (e.g., InMemoryKeyringProvider::new(), new InMemoryKeyringProvider()).
4602
+ */
4603
+ /**
4604
+ * Resource `keyring-provider` — generated from spec.wit.
4605
+ *
4606
+ * Extend this class to provide a concrete `KeyringProvider` implementation.
4607
+ * Instance methods are abstract; static methods throw by default (override in subclass).
4608
+ */
4609
+ declare abstract class KeyringProvider {
4610
+ /**
4611
+ * Create a new keyring with a random keypair at index 0.
4612
+ */
4613
+ abstract create(name: string, password: string): Promise<Keyring>;
4614
+ /**
4615
+ * Create a keyring with a generated BIP39 mnemonic.
4616
+ * strength-bits: 128 (12 words) or 256 (24 words).
4617
+ * Initializes exactly one keypair at index 0 derived from the mnemonic.
4618
+ * Returns (keyring, mnemonic_phrase). The mnemonic is returned ONCE
4619
+ * for backup — it is NOT stored on the keyring contract.
4620
+ */
4621
+ abstract createWithMnemonic(name: string, strengthBits: number, password: string): Promise<[Keyring, string]>;
4622
+ /**
4623
+ * Recover a keyring from an existing BIP39 mnemonic phrase.
4624
+ * Initializes one keypair at index 0 derived from the mnemonic.
4625
+ */
4626
+ abstract recoverFromMnemonic(name: string, mnemonic: string, password: string): Promise<Keyring>;
4627
+ /**
4628
+ * Load an existing keyring by name. Active keypair defaults to index 0.
4629
+ */
4630
+ abstract load(name: string, password: string): Promise<Keyring>;
4631
+ /**
4632
+ * List all keyring names, sorted alphabetically.
4633
+ */
4634
+ abstract list(): Promise<string[]>;
4635
+ /**
4636
+ * Check if a keyring exists by name.
4637
+ */
4638
+ abstract exists(name: string): Promise<boolean>;
4639
+ /**
4640
+ * Get the active keypair's public key for a keyring (without loading).
4641
+ */
4642
+ abstract getPublicKey(name: string): Promise<PublicKey>;
4643
+ /**
4644
+ * List all keyrings with their active keypair's public info,
4645
+ * sorted alphabetically by keyring name.
4646
+ */
4647
+ abstract listPublicKeys(): Promise<[string, DerivedKeypairInfo][]>;
4648
+ /**
4649
+ * List keypair metadata for a specific keyring, sorted by ascending index.
4650
+ */
4651
+ abstract listKeypairs(keyringName: string): Promise<DerivedKeypairInfo[]>;
4652
+ /**
4653
+ * Derive a new keypair at the specified index.
4654
+ * Errors with DUPLICATE_KEYPAIR_INDEX if the index already exists.
4655
+ */
4656
+ abstract deriveKeypair(keyringName: string, keypairIndex: number, password: string): Promise<DerivedKeypairInfo>;
4657
+ /**
4658
+ * Import an existing 32-byte Ed25519 secret key into a keyring.
4659
+ * Assigns the next available index (max(existing) + 1).
4660
+ */
4661
+ abstract importSecretKey(keyringName: string, secretKey: Uint8Array, derivationPath: string | undefined, password: string): Promise<DerivedKeypairInfo>;
4662
+ /**
4663
+ * Get metadata for all keypairs in a keyring, sorted by ascending index.
4664
+ */
4665
+ abstract getKeypairsInfo(name: string): Promise<DerivedKeypairInfo[]>;
4666
+ /**
4667
+ * Get metadata for a specific keypair by index.
4668
+ */
4669
+ abstract getKeypairInfo(name: string, keypairIndex: number): Promise<DerivedKeypairInfo>;
4670
+ /**
4671
+ * Returns max(existing indices) + 1, or 0 if empty.
4672
+ * With sparse indices (e.g., 0 and 5 exist), returns 6, not 2.
4673
+ */
4674
+ abstract nextKeypairIndex(name: string): Promise<number>;
4675
+ }
4676
+
4677
+ /**
4678
+ * In-memory keyring provider for testing and ephemeral use.
4679
+ *
4680
+ * **Security note:** This provider stores keyrings, passwords, and mnemonic
4681
+ * phrases in plaintext memory. It is designed for development, testing, and
4682
+ * ephemeral use cases — NOT for production secret storage. Key material
4683
+ * persists in the JS heap until garbage collected. For production use,
4684
+ * implement a provider backed by encrypted storage or a hardware security module.
4685
+ *
4686
+ * Keyrings are stored in memory only — not persisted between restarts.
4687
+ * Implements the full keyring-provider contract from the WIT spec.
4688
+ */
4689
+ declare class InMemoryKeyringProvider extends KeyringProvider {
4690
+ private readonly keyrings;
4691
+ private getStored;
4692
+ private checkPassword;
4693
+ private buildKeyring;
4694
+ private toInfo;
4695
+ private nextIndex;
4696
+ create(name: string, password: string): Promise<Keyring>;
4697
+ createWithMnemonic(name: string, strengthBits: number, password: string): Promise<[Keyring, string]>;
4698
+ recoverFromMnemonic(name: string, mnemonicPhrase: string, password: string): Promise<Keyring>;
4699
+ load(name: string, password: string): Promise<Keyring>;
4700
+ list(): Promise<string[]>;
4701
+ exists(name: string): Promise<boolean>;
4702
+ getPublicKey(name: string): Promise<PublicKey>;
4703
+ listPublicKeys(): Promise<[string, DerivedKeypairInfo][]>;
4704
+ listKeypairs(keyringName: string): Promise<DerivedKeypairInfo[]>;
4705
+ deriveKeypair(keyringName: string, keypairIndex: number, password: string): Promise<DerivedKeypairInfo>;
4706
+ importSecretKey(keyringName: string, secretKey: Uint8Array, derivationPath: string | undefined, password: string): Promise<DerivedKeypairInfo>;
4707
+ getKeypairsInfo(name: string): Promise<DerivedKeypairInfo[]>;
4708
+ getKeypairInfo(name: string, keypairIndex: number): Promise<DerivedKeypairInfo>;
4709
+ nextKeypairIndex(name: string): Promise<number>;
4710
+ }
4711
+
4508
4712
  /** RISC-V loader program ID (PolkaVM bytecode). */
4509
4713
  declare const RISCV_LOADER_PROGRAM_ID = "RiscVLoader11111111111111111111111111111111";
4510
4714
  /** LoaderV4 program ID (eBPF programs). */
@@ -4635,4 +4839,4 @@ declare function deployInstruction(programAddress: PublicKey, authority: PublicK
4635
4839
  */
4636
4840
  declare function retractInstruction(programAddress: PublicKey, authority: PublicKey): Instruction;
4637
4841
 
4638
- export { type AccountFilter, type AccountFilterParam, type AccountInfo, type AccountMeta, AccountMetaTable, type AllAccountsEntry, BASE_DERIVATION_PATH, BUFFER_BALANCE_FACTOR, BaseRpcClient, BincodeReader, type BincodeSchema, BincodeWriter, type BlockInfo, type Bump, CHACHA20_POLY1305_TAG_LENGTH, type ChainDefinition, type ClusterNodeInfo, type CompiledInstruction, type ConfigHashPrefix, type ConfirmTransactionOptions, type ConfirmedTransaction, type ConnectedNode, CryptoError, CryptoErrorCode, DEFAULT_CHUNK_SIZE, DEFAULT_CONFIRMATION_BATCH_SIZE, DEFAULT_MAX_RETRIES, DEFAULT_NUM_ACCOUNTS, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_DELAY_MS, type DeploymentConfig, DeploymentError, DeploymentErrorCode, ED25519_PUBLIC_KEY_LENGTH, type EnumVariant, type EpochConsensusConfigRequest, type EpochInfo, type EventData, type FeeResponse, type GetAccountsByOwnerConfig, type GetAllAccountsConfig, type GetBlockConfig, type GetSignaturesForAddressConfig, type GetTransactionsConfig, type GetValidatorAccountsRequest, type GetWorkflowLineageRequest, type GetWorkflowLineageResponse, HPKE_ENC_LENGTH, HPKE_OVERHEAD_LENGTH, HpkeError, HpkeErrorCode, HttpTransport, type HttpTransportConfig, type IdentifierString, type InferSchema, type Instruction, type IsBlockhashValidResponse, KELVIN_PER_RLO, type Kelvin, Keypair, KeypairSigner, LOADER_V4_PROGRAM_ID, Message, type MessageHeader, Mnemonic, type MnemonicStrength, type OptionalAccountInfo, type OwnerAccount, type PDA, PROGRAM_DATA_OFFSET, PUBLIC_KEY_LENGTH, type PaginationInfo, ProgramDeployment, type ProgramDeploymentOptions, PublicKey, QueryRpcClient, RIALO_DEVNET_CHAIN, RIALO_LOCALNET_CHAIN, RIALO_MAINNET_CHAIN, RIALO_TESTNET_CHAIN, RISCV_LOADER_PROGRAM_ID, type RexDuty, type RexInfoAndDuties, RexValue, RexValueVariant, RialoClient, type RialoClientConfig, RialoError, RialoErrorType, type RialoNetwork, RiscVLoaderInstruction, RpcError, RpcErrorCode, type RpcErrorDetails$1 as RpcErrorDetails, SECRET_KEY_LENGTH, SECRET_SHARING_HPKE_INFO, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, Schema, type SecretSharingPubkey, type Seed, type SendAndConfirmOptions, type SendTransactionOptions, Signature$1 as Signature, type SignatureInfo, type SignatureStatus, type Signer, type StakeAccountInfo, type StakeState, type StructField, type SubmitEpochChangeRequest, type SubmitEpochChangeResponse, type Subscription, type SubscriptionAccountMeta, type SubscriptionInstruction, type SubscriptionKind, SystemInstruction, type TimestampRange, type TokenBalance, Transaction, TransactionBuilder, type TransactionData, TransactionError, TransactionErrorCode, type TransactionInfo, type TransactionMessage, type TransactionNodeData, type TransactionResponse, TransactionRpcClient, type TransactionStatusMetadata, type TransactionWithMeta, type TriggerInfo, type TriggeredTransaction, type TruncationReason, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_TESTNET, USER_SECRET_AAD, type ValidatorAccountInfo, type ValidatorHealth, type ValidatorInfoRequest, type WorkflowLineage, type WorkflowNode, X25519_PUBLIC_KEY_LENGTH, allocateInstruction, assignInstruction, calculateBackoff, concatBytes, createAccount, createBorshInstruction, createRialoClient, deployInstruction, deserialize, deserializeBorsh, deserializeCompactU16, deserializeStrict, encodeBorshData, encryptForRex, fromBase64, getCiphertextLength, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, hpkeEncrypt, isOnCurve, isValidCiphertextLength, retractInstruction, seedToBytes, serialize, serializeBorsh, serializeCompactU16, setProgramLengthInstruction, sleep, toBase64, transferInstruction, writeCompactU16, writeInstruction };
4842
+ export { type AccountFilter, type AccountFilterParam, type AccountInfo, type AccountMeta, AccountMetaTable, type AllAccountsEntry, BASE_DERIVATION_PATH, BUFFER_BALANCE_FACTOR, BaseRpcClient, BincodeReader, type BincodeSchema, BincodeWriter, type BlockInfo, type Bump, CHACHA20_POLY1305_NONCE_LENGTH, CHACHA20_POLY1305_TAG_LENGTH, type ChainDefinition, type ClusterNodeInfo, type CompiledInstruction, type ConfigHashPrefix, type ConfirmTransactionOptions, type ConfirmedTransaction, type ConnectedNode, CryptoError, CryptoErrorCode, DEFAULT_CHUNK_SIZE, DEFAULT_CONFIRMATION_BATCH_SIZE, DEFAULT_MAX_RETRIES, DEFAULT_NUM_ACCOUNTS, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_DELAY_MS, DKG_PAYLOAD_VERSION, type DeploymentConfig, DeploymentError, DeploymentErrorCode, type DerivedKeypairInfo, ED25519_PUBLIC_KEY_LENGTH, EncryptionError, EncryptionErrorCode, type EnumVariant, type EpochConsensusConfigRequest, type EpochInfo, type EventData, type FeeResponse, type DeploymentConfig$1 as GeneratedDeploymentConfig, type GetAccountsByOwnerConfig, type GetAllAccountsConfig, type GetBlockConfig, type GetSignaturesForAddressConfig, type GetTransactionsConfig, type GetValidatorAccountsRequest, type GetWorkflowLineageRequest, type GetWorkflowLineageResponse, HttpTransport, type HttpTransportConfig, type IdentifierString, InMemoryKeyringProvider, type InferSchema, type Instruction, type InvocationAccountMeta, type IsBlockhashValidResponse, KELVIN_PER_RLO, type Kelvin, Keypair, KeypairSigner, Keyring, KeyringProvider, LOADER_V4_PROGRAM_ID, type LoaderType, MAX_SECRET_LENGTH, Message, type MessageHeader, Mnemonic, type MnemonicStrength, type OptionalAccountInfo, type OwnerAccount, type PDA, PROGRAM_DATA_OFFSET, PUBLIC_KEY_LENGTH, type PaginationInfo, ProgramDeployment, type ProgramDeploymentOptions, type ProgramInstruction, PublicKey, QueryRpcClient, RIALO_DEVNET_CHAIN, RIALO_LOCALNET_CHAIN, RIALO_MAINNET_CHAIN, RIALO_TESTNET_CHAIN, RISCV_LOADER_PROGRAM_ID, RISTRETTO_POINT_BYTES, type RexDuty, type RexInfoAndDuties, RexValue, RexValueVariant, RialoClient, type RialoClientConfig, RialoError, RialoErrorType, RialoKeyring, type RialoNetwork, RiscVLoaderInstruction, RpcError, RpcErrorCode, type RpcErrorDetails$1 as RpcErrorDetails, SECRET_KEY_LENGTH, SIGNATURE_LENGTH, SYSTEM_PROGRAM_ID, Schema, type SecretSharingPubkey, type Seed, type SendAndConfirmOptions, type SendTransactionOptions, Signature$1 as Signature, type SignatureInfo, type SignatureStatus, type Signer, type StakeAccountInfo, type StakeState, type StructField, type SubmitEpochChangeRequest, type SubmitEpochChangeResponse, type Subscription, type SubscriptionAccountMeta, type SubscriptionInstruction, type SubscriptionKind, SystemInstruction, type TimestampRange, type TokenBalance, Transaction, TransactionBuilder, type TransactionData, TransactionError, TransactionErrorCode, type TransactionInfo, type TransactionMessage, type TransactionNodeData, type TransactionResponse, TransactionRpcClient, type TransactionStatusMetadata, type TransactionWithMeta, type TriggerInfo, type TriggeredTransaction, type TruncationReason, URL_DEVNET, URL_LOCALNET, URL_MAINNET, URL_TESTNET, type ValidatorAccountInfo, type ValidatorHealth, type ValidatorInfoRequest, type WorkflowLineage, type WorkflowNode, allocateInstruction, assignInstruction, calculateBackoff, concatBytes, createAccount, createBorshInstruction, createRialoClient, deployInstruction, deserialize, deserializeBorsh, deserializeCompactU16, deserializeStrict, encodeBorshData, encryptForRex, encryptSecret, encryptSecretBytes, encryptSecretBytesWithEpoch, fromBase64, getDefaultRialoClientConfig, getDevnetUrl, getLocalnetUrl, getMainnetUrl, getTestnetUrl, isOnCurve, retractInstruction, seedToBytes, serialize, serializeBorsh, serializeCompactU16, setProgramLengthInstruction, sleep, toBase64, transferInstruction, writeCompactU16, writeInstruction };