@terminal3/t3n-sdk 0.13.1 → 1.0.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
@@ -515,6 +515,128 @@ interface T3nClientConfig {
515
515
  handlers?: GuestToHostHandlers;
516
516
  }
517
517
 
518
+ /**
519
+ * Error classes for T3n SDK
520
+ */
521
+ /**
522
+ * Base error class for T3n SDK errors
523
+ */
524
+ declare class T3nError extends Error {
525
+ readonly code?: string | undefined;
526
+ constructor(message: string, code?: string | undefined);
527
+ }
528
+ /**
529
+ * Error thrown when session is in invalid state for operation
530
+ */
531
+ declare class SessionStateError extends T3nError {
532
+ readonly currentState: string;
533
+ constructor(message: string, currentState: string);
534
+ }
535
+ /**
536
+ * Error thrown during authentication process
537
+ */
538
+ declare class AuthenticationError extends T3nError {
539
+ readonly authMethod?: string | undefined;
540
+ constructor(message: string, authMethod?: string | undefined);
541
+ }
542
+ /**
543
+ * Error thrown during handshake process
544
+ */
545
+ declare class HandshakeError extends T3nError {
546
+ constructor(message: string);
547
+ }
548
+ /**
549
+ * Error thrown during RPC communication
550
+ */
551
+ declare class RpcError extends T3nError {
552
+ readonly rpcMethod?: string | undefined;
553
+ readonly httpStatus?: number | undefined;
554
+ constructor(message: string, rpcMethod?: string | undefined, httpStatus?: number | undefined);
555
+ }
556
+ /**
557
+ * Error thrown when WASM operations fail
558
+ */
559
+ declare class WasmError extends T3nError {
560
+ readonly operation?: string | undefined;
561
+ readonly payload?: unknown | undefined;
562
+ constructor(message: string, operation?: string | undefined, payload?: unknown | undefined);
563
+ }
564
+ /**
565
+ * Decode WASM error message from comma-separated byte array format
566
+ * WASM errors often come as "83,101,114,100,101..." which represents ASCII bytes
567
+ *
568
+ * @param errorMessage - The error message string that may contain comma-separated bytes
569
+ * @returns Decoded error message if it was encoded, otherwise original message
570
+ */
571
+ declare function decodeWasmErrorMessage(errorMessage: string): string;
572
+ /**
573
+ * Extract and decode error from WASM ComponentError
574
+ *
575
+ * @param error - The error object from WASM
576
+ * @returns Decoded error message
577
+ */
578
+ declare function extractWasmError(error: unknown): string;
579
+
580
+ /**
581
+ * Contract response decoding for {@link T3nClient.execute}.
582
+ *
583
+ * ## On-wire shape
584
+ *
585
+ * Trinity contracts are declared as `result<list<u8>, string>` in WIT and
586
+ * return JSON-encoded bytes. The server-side pipeline is:
587
+ *
588
+ * 1. `node/wasm/src/dynamic.rs:component_val_to_json` deserializes those
589
+ * bytes to a JSON `Value` (the contract's decoded return value).
590
+ * 2. `node/wasm/src/runner.rs:run_dynamic` wraps that value in a
591
+ * `ContractResponse` struct internally for host-side bookkeeping —
592
+ * it carries an extracted `otp_state` alongside the response.
593
+ * 3. **`node/app/src/services/wasm.rs:200`** then unwraps the struct with
594
+ * `Ok((response.response, tx_back))`, discarding the `otp_state` field
595
+ * and returning only the inner `Value` across the `WasmExecutor` trait
596
+ * boundary.
597
+ * 4. `node/service/src/action.rs` serialises that plain `Value` through
598
+ * the session channel.
599
+ *
600
+ * The client therefore receives the contract's **decoded JSON value
601
+ * directly** — no `{response, otp_state}` envelope, despite what the
602
+ * struct name suggests. `parseContractResponse` reflects that reality:
603
+ * it does a typed `JSON.parse` with optional schema validation, nothing
604
+ * more. OTP flows read their `otp_status` / OTP fields directly off the
605
+ * contract's response body; there is no separate envelope field for them
606
+ * on this path.
607
+ */
608
+
609
+ /**
610
+ * Minimal validator interface. Any library that exposes `.parse(value) -> T`
611
+ * (zod, valibot, superstruct, custom) is compatible.
612
+ */
613
+ interface ContractResponseSchema<T> {
614
+ parse(value: unknown): T;
615
+ }
616
+ /**
617
+ * Thrown when the response string from {@link T3nClient.execute} cannot
618
+ * be parsed as JSON.
619
+ *
620
+ * Schema-validation failures are NOT wrapped — they surface as whatever
621
+ * error the caller's validator throws, preserving the rich diagnostics
622
+ * those libraries already provide.
623
+ */
624
+ declare class ContractResponseError extends T3nError {
625
+ readonly raw?: string | undefined;
626
+ constructor(message: string, raw?: string | undefined);
627
+ }
628
+ /**
629
+ * Parse the JSON-encoded response returned by {@link T3nClient.execute}
630
+ * into a typed value.
631
+ *
632
+ * @param raw - the string returned by {@link T3nClient.execute}
633
+ * @param schema - optional validator applied to the parsed value
634
+ * @returns the decoded response, typed as `T`
635
+ * @throws {ContractResponseError} when `raw` is not valid JSON
636
+ * @throws whatever the schema throws on validation failure (e.g. `ZodError`)
637
+ */
638
+ declare function parseContractResponse<T = unknown>(raw: string, schema?: ContractResponseSchema<T>): T;
639
+
518
640
  /**
519
641
  * T3n Client - Main SDK class
520
642
  *
@@ -599,9 +721,48 @@ declare class T3nClient {
599
721
  */
600
722
  private authenticateOidc;
601
723
  /**
602
- * Execute an action on the T3n node
724
+ * Execute an action on the T3n node.
725
+ *
726
+ * Returns the JSON-stringified contract response. Most callers should
727
+ * prefer {@link executeAndDecode}, which JSON-parses the response and
728
+ * optionally validates it with a schema.
603
729
  */
604
730
  execute(payload: unknown): Promise<string>;
731
+ /**
732
+ * Execute an action and JSON-decode the response.
733
+ *
734
+ * The server strips its internal `ContractResponse` wrapper at
735
+ * `node/app/src/services/wasm.rs` before sending — the string returned
736
+ * by {@link execute} is the contract's decoded return value directly
737
+ * (no `{response, otp_state}` envelope). This helper is a typed
738
+ * `JSON.parse` with optional schema validation so callers stop
739
+ * reimplementing it at every call site.
740
+ *
741
+ * @param payload - action payload, identical to {@link execute}
742
+ * @param schema - optional validator applied to the parsed value
743
+ * (e.g. a zod schema); anything exposing `.parse(value)` is accepted
744
+ * @returns the decoded response, typed as `T`
745
+ * @throws {ContractResponseError} when the response is not valid JSON
746
+ */
747
+ executeAndDecode<T = unknown>(payload: unknown, schema?: ContractResponseSchema<T>): Promise<T>;
748
+ /**
749
+ * Return the authenticated user's Ethereum address from their
750
+ * T3N-hosted per-user wallet, as a 0x-prefixed lowercase hex string.
751
+ * Returns `null` if the user has no wallet yet (pre-backfill edge
752
+ * case — `tee:user` has not yet been migrated for this DID).
753
+ *
754
+ * Backed by the `tee:user/get-self-eth-address` contract function,
755
+ * which delegates to the signing host's `get-user-eth-address`
756
+ * primitive (T3-TS-027 §7.1). The request carries no body; the
757
+ * authenticated user's DID is read from session context by the host.
758
+ *
759
+ * Requires the session to be Authenticated (same precondition as
760
+ * {@link execute}).
761
+ *
762
+ * @throws if unauthenticated, if the node rejects the action, or if
763
+ * the response is not a JSON string / `null`.
764
+ */
765
+ getSelfEthAddress(): Promise<string | null>;
605
766
  /**
606
767
  * The server-minted session ID once handshake has completed, or
607
768
  * `null` beforehand (pentest M-1 / MAT-983).
@@ -780,68 +941,6 @@ declare function bytesToString(bytes: Uint8Array): string;
780
941
 
781
942
  declare function getScriptVersion(rpcUrl: string, scriptName: string): Promise<string>;
782
943
 
783
- /**
784
- * Error classes for T3n SDK
785
- */
786
- /**
787
- * Base error class for T3n SDK errors
788
- */
789
- declare class T3nError extends Error {
790
- readonly code?: string | undefined;
791
- constructor(message: string, code?: string | undefined);
792
- }
793
- /**
794
- * Error thrown when session is in invalid state for operation
795
- */
796
- declare class SessionStateError extends T3nError {
797
- readonly currentState: string;
798
- constructor(message: string, currentState: string);
799
- }
800
- /**
801
- * Error thrown during authentication process
802
- */
803
- declare class AuthenticationError extends T3nError {
804
- readonly authMethod?: string | undefined;
805
- constructor(message: string, authMethod?: string | undefined);
806
- }
807
- /**
808
- * Error thrown during handshake process
809
- */
810
- declare class HandshakeError extends T3nError {
811
- constructor(message: string);
812
- }
813
- /**
814
- * Error thrown during RPC communication
815
- */
816
- declare class RpcError extends T3nError {
817
- readonly rpcMethod?: string | undefined;
818
- readonly httpStatus?: number | undefined;
819
- constructor(message: string, rpcMethod?: string | undefined, httpStatus?: number | undefined);
820
- }
821
- /**
822
- * Error thrown when WASM operations fail
823
- */
824
- declare class WasmError extends T3nError {
825
- readonly operation?: string | undefined;
826
- readonly payload?: unknown | undefined;
827
- constructor(message: string, operation?: string | undefined, payload?: unknown | undefined);
828
- }
829
- /**
830
- * Decode WASM error message from comma-separated byte array format
831
- * WASM errors often come as "83,101,114,100,101..." which represents ASCII bytes
832
- *
833
- * @param errorMessage - The error message string that may contain comma-separated bytes
834
- * @returns Decoded error message if it was encoded, otherwise original message
835
- */
836
- declare function decodeWasmErrorMessage(errorMessage: string): string;
837
- /**
838
- * Extract and decode error from WASM ComponentError
839
- *
840
- * @param error - The error object from WASM
841
- * @returns Decoded error message
842
- */
843
- declare function extractWasmError(error: unknown): string;
844
-
845
944
  /**
846
945
  * Secret redaction utilities for T3n SDK
847
946
  *
@@ -1029,5 +1128,5 @@ declare function clearKeyCache(): void;
1029
1128
  */
1030
1129
  declare function loadConfig(baseUrl?: string): SdkConfig;
1031
1130
 
1032
- export { AuthMethod, AuthenticationError, HandshakeError, HttpTransport, LogLevel, MockTransport, NODE_URLS, RpcError, SessionStateError, SessionStatus, T3nClient, T3nError, WasmError, bytesToString, clearKeyCache, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createRandomHandler, decodeWasmErrorMessage, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, redactSecrets, redactSecretsFromJson, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, validateConfig, verifyDkgAttestation, verifyTdxQuote };
1033
- export type { AuthInput, ClientAuth, ClientHandshake, ConfigValidationResult, Did, DkgAttestation, DkgVerifyResult, Environment, EthAuthInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, Logger, OidcAuthInput, OidcCredentials, PeerQuoteResult, QuoteVerifyResult, SdkConfig, SessionCrypto, SessionId, T3nClientConfig, Transport, WasmComponent, WasmNextResult };
1131
+ export { AuthMethod, AuthenticationError, ContractResponseError, HandshakeError, HttpTransport, LogLevel, MockTransport, NODE_URLS, RpcError, SessionStateError, SessionStatus, T3nClient, T3nError, WasmError, bytesToString, clearKeyCache, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createRandomHandler, decodeWasmErrorMessage, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, parseContractResponse, redactSecrets, redactSecretsFromJson, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, validateConfig, verifyDkgAttestation, verifyTdxQuote };
1132
+ export type { AuthInput, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, Did, DkgAttestation, DkgVerifyResult, Environment, EthAuthInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, Logger, OidcAuthInput, OidcCredentials, PeerQuoteResult, QuoteVerifyResult, SdkConfig, SessionCrypto, SessionId, T3nClientConfig, Transport, WasmComponent, WasmNextResult };