@terminal3/t3n-sdk 2.10.1 → 2.12.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/README.md CHANGED
@@ -764,6 +764,72 @@ The algorithm matches `node/wasm/src/otp.rs` byte-for-byte: `String((hash * 31 +
764
764
  - **Spec alignment.** The walkthrough follows the as-built code, which differs from earlier T3-TS-026 versions on two points: `user-upsert` has no `op:` discriminator (dispatch is implicit on input shape), and the function for L2 session creation is `tee:user/contracts::create-kyc-provider-session` rather than `tee:kyc/contracts::create-session`. See [T3-TS-026 v0.6.0 changelog](../../docs/specs/T3-TS-026-kyc-frontend-integration.md) and [MAT-1374](https://linear.app/terminal3/issue/MAT-1374) for the deferred discriminator-vs-split decision.
765
765
  - **`STRICT_SCENARIO=true`** in the environment turns scenario assertion failures into a non-zero exit code (otherwise they're logged but the demo exits zero). `--scenario` always exits non-zero on a terminal-status mismatch.
766
766
 
767
+ ### Tenant Developer Demo
768
+
769
+ Three-entity walkthrough: an **Admin** admits a tenant, the **Tenant** registers the Duffel flight contract and seeds credentials, a **User** (created via `demo:dev`) authenticates and searches / books flights. Each step is a separate command so you can run them independently.
770
+
771
+ #### Three entities
772
+
773
+ | Entity | Key env var | Role |
774
+ |---|---|---|
775
+ | Admin | `ADMIN_KEY` | Signs `tenant.admit` via the admin API |
776
+ | Tenant | `TENANT_KEY` | Registers contract, creates KV map, injects Duffel API key |
777
+ | User | `USER_KEY` | Authenticates and calls `search-offers` / `book-offer` on behalf of an AI agent |
778
+
779
+ #### Environment variables
780
+
781
+ | Variable | Default | Used by |
782
+ |---|---|---|
783
+ | `CRYPTO_NODE_URL` | `http://localhost:3000` | all commands |
784
+ | `ADMIN_KEY` | `0x000...0001` | `admit` |
785
+ | `TENANT_KEY` | `0x000...0002` | `admit`, `setup` |
786
+ | `DUFFEL_API_KEY` | `duffel_test_placeholder` | `setup` |
787
+ | `FLIGHT_WASM_PATH` | _(unset)_ | `setup` — path to compiled `z-tenant-flight` WASM; falls back to a placeholder |
788
+ | `USER_KEY` | `0x000...0003` | `search`, `book` — ETH key of a user already registered via `demo:dev` |
789
+ | `OFFER_ID` | _(required)_ | `book` — offer ID printed by `search` |
790
+ | `TOTAL_AMOUNT` | _(required)_ | `book` — total price printed by `search` |
791
+ | `TOTAL_CURRENCY` | _(required)_ | `book` — currency code printed by `search` |
792
+
793
+ #### Step 1 — Admit the tenant (Admin)
794
+
795
+ ```bash
796
+ ADMIN_KEY=0x... TENANT_KEY=0x... pnpm demo:tenant:admit
797
+ ```
798
+
799
+ #### Step 2 — Register contract + seed credentials (Tenant)
800
+
801
+ ```bash
802
+ TENANT_KEY=0x... DUFFEL_API_KEY=duffel_test_... FLIGHT_WASM_PATH=../z-tenant-flight/target/wasm32-wasip2/release/z_tenant_flight.wasm pnpm demo:tenant:setup
803
+ ```
804
+
805
+ This registers `z:<tid>:duffel-flight`, creates the `z:<tid>:secrets` KV map restricted to that contract, then calls `store-credentials` on the contract to write the Duffel API key into the map.
806
+
807
+ #### Step 3 — Create the user (User)
808
+
809
+ Use the standard user demo — no changes needed:
810
+
811
+ ```bash
812
+ USER_KEY=0x... pnpm demo:dev
813
+ ```
814
+
815
+ #### Step 4 — Search for flights (User / Agent)
816
+
817
+ ```bash
818
+ USER_KEY=0x... pnpm demo:tenant:search
819
+ ```
820
+
821
+ Prints up to 5 offers. The last line of output is the exact `book` command with the correct `OFFER_ID`, `TOTAL_AMOUNT`, and `TOTAL_CURRENCY` pre-filled.
822
+
823
+ #### Step 5 — Book a flight (User / Agent)
824
+
825
+ ```bash
826
+ USER_KEY=0x... OFFER_ID=off_... TOTAL_AMOUNT=199.00 TOTAL_CURRENCY=GBP pnpm demo:tenant:book
827
+ ```
828
+
829
+ The passenger record is a hardcoded fixture (Jane Doe, GB passport). PII enters the TEE enclave and is never returned — only `booking_id`, `pnr`, and `status` cross the WIT boundary back to the caller.
830
+
831
+ ---
832
+
767
833
  ## WASM Integration
768
834
 
769
835
  The SDK can work with both real T3n WASM components and mock components for testing.
package/dist/index.d.ts CHANGED
@@ -573,6 +573,41 @@ interface SubmitUserInputArgs {
573
573
  * Most callers should leave this `undefined`.
574
574
  */
575
575
  requireExistingUser?: boolean;
576
+ /**
577
+ * MAT-1618 testnet self-admit. When `true`, the contract additionally
578
+ * runs the self-admit side-effect after the profile commit: writes
579
+ * the caller's DID into `idx:_tenants` + `idx:_tenant_quotas` and
580
+ * mints any operator-configured welcome credits. Inspect the
581
+ * `tenantAdmit` field on the response for the outcome.
582
+ *
583
+ * Testnet-only. Production clusters return
584
+ * `tenantAdmit.status = "refused"` with
585
+ * `reason = "not_testnet" | "self_admit_disabled" | "not_eth_derived"`.
586
+ * The profile commit always succeeds regardless of the inner outcome.
587
+ *
588
+ * Most callers should leave this `undefined`.
589
+ */
590
+ becomeDevTenant?: boolean;
591
+ }
592
+ /**
593
+ * MAT-1618 self-admit projection from `user-upsert`. Present only
594
+ * when the caller set `becomeDevTenant: true` on the request.
595
+ *
596
+ * - `status: "admitted"` — first call for this DID; tenant record
597
+ * committed and (if configured) welcome credits minted into
598
+ * `grantedCredits`.
599
+ * - `status: "already-admitted"` — replay; idempotent no-op.
600
+ * - `status: "refused"` — the cluster declined the self-admit;
601
+ * `reason` is the machine-readable cause (`not_testnet`,
602
+ * `self_admit_disabled`, `not_eth_derived`), `detail` is a
603
+ * human-readable string.
604
+ */
605
+ type TenantAdmitStatus = "admitted" | "already-admitted" | "refused";
606
+ interface TenantAdmitProjection {
607
+ status: TenantAdmitStatus;
608
+ grantedCredits?: string;
609
+ reason?: string;
610
+ detail?: string;
576
611
  }
577
612
  /**
578
613
  * Response shape returned by the slim `user-upsert`. Carries the
@@ -585,6 +620,11 @@ interface SubmitUserInputResult {
585
620
  refusedFields?: string[];
586
621
  mergeSuggestion?: OtpMergeSuggestion;
587
622
  userFound?: boolean;
623
+ /**
624
+ * MAT-1618 self-admit projection. Present only when the caller
625
+ * set `becomeDevTenant: true` on the request.
626
+ */
627
+ tenantAdmit?: TenantAdmitProjection;
588
628
  }
589
629
  /**
590
630
  * Discriminator for {@link UserUpsertError}. Mirrors the
@@ -809,6 +849,109 @@ interface OrgDataActionWire {
809
849
  signature: string;
810
850
  }
811
851
 
852
+ /**
853
+ * Token-metering types — T3-TS-030 wire shapes.
854
+ *
855
+ * Mirrors `node/primitives/src/token.rs`. `u128` fields land on the
856
+ * wire as JSON numbers (same convention as the existing
857
+ * `token.get-balance` response) — JS clients with histories that
858
+ * exceed 2⁵³ tokens should switch to a streaming JSON parser; the
859
+ * common case fits in `number` losslessly.
860
+ */
861
+ /**
862
+ * `primitives::token::BalanceRow` — caller's credit row.
863
+ *
864
+ * `available` and `reserved` are `u128` on the server; the wire
865
+ * format is a JSON number. Callers should not assume bigint until
866
+ * the SDK migrates to a streaming parser (tracked separately).
867
+ */
868
+ interface BalanceRow {
869
+ available: number;
870
+ reserved: number;
871
+ last_settled_seq_no: number;
872
+ version: number;
873
+ credit_exhausted: boolean;
874
+ }
875
+ /**
876
+ * `primitives::token::TokenTxKind` snake_case wire alphabet. Every
877
+ * value listed here is accepted by the server-side
878
+ * `token.get-usage` `kinds` filter.
879
+ */
880
+ type TokenTxKind = "mint" | "burn" | "charge" | "transfer" | "bridge_mint_attest" | "bridge_burn_attest";
881
+ /**
882
+ * Per-caller view direction. `"in"` = caller's balance went up;
883
+ * `"out"` = caller's balance went down. Derived host-side from
884
+ * `(caller_did, tx.src, tx.dst)`; the same `seq_no` appears in both
885
+ * parties' usage feeds with opposite directions on a transfer.
886
+ */
887
+ type Direction = "in" | "out";
888
+ /**
889
+ * Discriminated union mirroring `primitives::token::ChargeReason`.
890
+ * Present only when the row's `kind === "charge"`.
891
+ */
892
+ type ChargeReason = {
893
+ kind: "contract_register";
894
+ script_name: string;
895
+ version: string;
896
+ } | {
897
+ kind: "invocation";
898
+ script_name: string;
899
+ function: string;
900
+ fuel_consumed: number;
901
+ fuel_tokens: number;
902
+ host_call_count: number;
903
+ host_call_tokens: number;
904
+ } | {
905
+ kind: "kv_bytes";
906
+ map: string;
907
+ } | {
908
+ kind: "cas_bytes";
909
+ backend: string;
910
+ } | {
911
+ kind: "outbox_egress";
912
+ upstream: string;
913
+ };
914
+ /**
915
+ * One row in the caller's usage feed — a per-caller projection of
916
+ * the underlying `TokenTx`. `counterparty` is the other party from
917
+ * the caller's perspective: `tx.dst` on outbound entries, `tx.src`
918
+ * on inbound. `null` when the underlying tx has no counterparty
919
+ * (mints have no `src`; burns and charges have no `dst`).
920
+ */
921
+ interface UsageEntry {
922
+ seq_no: number;
923
+ kind: TokenTxKind;
924
+ amount: number;
925
+ timestamp_ms: number;
926
+ direction: Direction;
927
+ counterparty?: string | null;
928
+ reason?: ChargeReason | null;
929
+ note?: string | null;
930
+ }
931
+ /**
932
+ * Response shape of `token.get-usage` — caller's balance plus a
933
+ * paginated slice of their most-recent `token:tx_log` entries.
934
+ *
935
+ * `next_cursor` is the inclusive upper-bound `seq_no` to pass back
936
+ * as `after_seq` to fetch the next page. `null` (or absent) means
937
+ * the caller's history is fully drained.
938
+ */
939
+ interface UsagePage {
940
+ balance: BalanceRow;
941
+ entries: UsageEntry[];
942
+ next_cursor?: number | null;
943
+ }
944
+ /**
945
+ * Request shape — all fields optional. `limit` clamps to
946
+ * `1..=200` server-side; out-of-range values snap silently to the
947
+ * bounds. `kinds: []` is treated as "no filter".
948
+ */
949
+ interface GetUsageOptions {
950
+ limit?: number;
951
+ after_seq?: number;
952
+ kinds?: TokenTxKind[];
953
+ }
954
+
812
955
  /**
813
956
  * Public types export for T3n SDK
814
957
  */
@@ -890,7 +1033,9 @@ interface Transport {
890
1033
  */
891
1034
  send(request: JsonRpcRequest, headers: Record<string, string>): Promise<JsonRpcResponse>;
892
1035
  /**
893
- * Optionally send a JSON-RPC request with an attached binary blob.
1036
+ * Send a JSON-RPC request with an attached binary blob (multipart/form-data).
1037
+ * Part 1 (name=jsonrpc): JSON-RPC envelope.
1038
+ * Part 2 (name=blob): raw binary bytes (e.g. WASM bytecode).
894
1039
  */
895
1040
  sendMultipart?(request: JsonRpcRequest, headers: Record<string, string>, blob: Blob): Promise<JsonRpcResponse>;
896
1041
  /**
@@ -1306,6 +1451,22 @@ declare class T3nClient {
1306
1451
  * optionally validates it with a schema.
1307
1452
  */
1308
1453
  execute(payload: unknown): Promise<string>;
1454
+ /**
1455
+ * Fetch the caller's usage feed — balance plus a bounded slice of
1456
+ * recent token-ledger entries (charges, mints, transfers), newest
1457
+ * first. T3-TS-030 Phase 1D step A (`token.get-usage`).
1458
+ *
1459
+ * `limit` defaults to 50 server-side and clamps silently to
1460
+ * `1..=200`. `afterSeq` is the inclusive upper-bound `seq_no`
1461
+ * passed back from a previous page's `next_cursor` to walk older
1462
+ * entries. `kinds` filters by `TokenTxKind`; an empty array is
1463
+ * treated as "no filter".
1464
+ *
1465
+ * Unlike {@link execute}, the body of this RPC is plaintext —
1466
+ * `token.get-usage` is a session-authed read endpoint and the
1467
+ * server-side handler does not run the encryption layer.
1468
+ */
1469
+ getUsage(opts?: GetUsageOptions): Promise<UsagePage>;
1309
1470
  /**
1310
1471
  * Execute an action with an attached binary blob using multipart RPC.
1311
1472
  */
@@ -1558,6 +1719,12 @@ declare class T3nClient {
1558
1719
  organisationDid?: string;
1559
1720
  attestations?: unknown;
1560
1721
  keys?: Record<string, unknown>;
1722
+ /**
1723
+ * MAT-1618 testnet self-admit, propagated to the inner
1724
+ * {@link submitUserInput} call. Inspect `result.tenantAdmit` for
1725
+ * the outcome.
1726
+ */
1727
+ becomeDevTenant?: boolean;
1561
1728
  getOtpCode: (contact: string, channel: OtpChannel) => Promise<string> | string;
1562
1729
  }): Promise<SubmitUserInputResult>;
1563
1730
  /**
@@ -1650,6 +1817,41 @@ declare class T3nClient {
1650
1817
  * Send an RPC request with automatic encryption/decryption
1651
1818
  */
1652
1819
  private sendRpcRequest;
1820
+ /**
1821
+ * Send a session-authenticated JSON-RPC request with plaintext
1822
+ * params/result (no SessionEncryption layer). Used for tenant-facing
1823
+ * read endpoints (`token.get-balance`, `token.get-usage`) where the
1824
+ * server-side handler reads the JSON envelope directly.
1825
+ *
1826
+ * Auto-attaches the `Session-Id` header; surfaces JSON-RPC errors
1827
+ * the same way as {@link sendRpcRequest} (typed
1828
+ * `InsufficientCreditError` when applicable, `RpcError` otherwise).
1829
+ * Returns the parsed `result` field — typically a JSON object the
1830
+ * caller will narrow to the endpoint's response type.
1831
+ */
1832
+ private sendUnencryptedSessionRpc;
1833
+ /**
1834
+ * Inspect a JSON-RPC response for an `error` field and throw the
1835
+ * appropriate typed exception. No-op when `response.error` is
1836
+ * absent. Shared by every RPC path so wire-shape changes in the
1837
+ * server's error envelope (typed-error subclasses, request-id
1838
+ * placement, detail formatting) only need to land in one place.
1839
+ *
1840
+ * JSON-RPC `error.message` is the generic category string
1841
+ * ("Invalid params", "Internal error", …). The node attaches the
1842
+ * actionable text and per-request correlation id in `error.data`
1843
+ * — see `node/api/src/responses/rpc.rs::from_service_error`.
1844
+ * Extract both so callers (and toasts that only render `.message`)
1845
+ * get the real reason plus an id an operator can grep in
1846
+ * `api::error` logs.
1847
+ *
1848
+ * T3-TS-030 chargepoint denials surface as a typed
1849
+ * `InsufficientCreditError` so frontends can branch on
1850
+ * `instanceof` to render an "out of credit" UI without
1851
+ * prefix-matching the message themselves. Wire format is pinned
1852
+ * by `api/src/error.rs::service_insufficient_credit_wire_format_is_stable`.
1853
+ */
1854
+ private throwIfRpcError;
1653
1855
  private sendMultipartRpcRequest;
1654
1856
  /**
1655
1857
  * Capture the server-minted `Session-Id` from the last handshake
@@ -2566,4 +2768,4 @@ declare function clearKeyCache(): void;
2566
2768
  declare function loadConfig(baseUrl?: string): SdkConfig;
2567
2769
 
2568
2770
  export { AGENT_PUBKEY_LEN, AuthMethod, AuthenticationError, ContractResponseError, DEFAULT_INDIVIDUAL_THRESHOLD_CENTS, DEFAULT_KYC_POLL_CADENCE, DELEGATION_CREDENTIAL_DOMAIN, DELEGATION_INVOCATION_DOMAIN, DelegationCustodialClient, ETH_SIG_LEN, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, NONCE_LEN, OrgDataClient, REQUEST_HASH_LEN, RpcError, SessionExpiredError, SessionOrgDataClient, SessionStateError, SessionStatus, T3nClient, T3nError, TERMINAL_KYC_STATUSES, UserUpsertError, VC_ID_LEN, WasmError, _b64uEncode, assertShape, b64uDecodeStrict, b64uEncodeBytes, buildDelegationCredential, buildInvocationPreimage, buildPayrollDirectInvocation, buildPayrollInvocation, bytesToString, canonicaliseCredential, canonicaliseRequest, clearKeyCache, compactDidFromBytes, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createOrgDataClientFromSession, createRandomHandler, decodeWasmErrorMessage, eip191Digest, ethRecoverEip191, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, isDataGetResponse, isDataListResponse, isMutationResponse, isObject, isOrgContractGrants, isOrgPolicyMeta, isOrgWriters, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, parseContractResponse, redactSecrets, redactSecretsFromJson, requestHash, setEnvironment, setGlobalLogLevel, setNodeUrl, signAgentInvocation, signCredential, stringToBytes, validateConfig, validateCredentialBody, verifyDkgAttestation, verifyTdxQuote };
2569
- export type { AgeBand, AuthInput, BuildDelegationCredentialOpts, BuildPayrollDirectInvocationOpts, BuildPayrollInvocationOpts, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationCredential, DelegationCustodialClientOpts, DelegationEnvelope, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, Did, DkgAttestation, DkgVerifyResult, EmployeeRecord, EmploymentStatus, Environment, EthAuthInput, ExecuteOrgDataActionOptions, ExpenseClaim, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, MutationResponse, OidcAuthInput, OidcCredentials, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollInvocation, PayrollInvocationDelegated, PayrollInvocationDirect, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, QuoteVerifyResult, ResidencyCategory, SdkConfig, SessionCrypto, SessionId, SetGrantsInput, SetWritersInput, SignCustodialResult, SignDelegationResponse, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, Transport, UpdateMetaInput, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WriteDataInput, WritersGetInput };
2771
+ export type { AgeBand, AuthInput, BuildDelegationCredentialOpts, BuildPayrollDirectInvocationOpts, BuildPayrollInvocationOpts, ClientAuth, ClientHandshake, ConfigValidationResult, ContractResponseSchema, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationCredential, DelegationCustodialClientOpts, DelegationEnvelope, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, Did, DkgAttestation, DkgVerifyResult, EmployeeRecord, EmploymentStatus, Environment, EthAuthInput, ExecuteOrgDataActionOptions, ExpenseClaim, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, MutationResponse, OidcAuthInput, OidcCredentials, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollInvocation, PayrollInvocationDelegated, PayrollInvocationDirect, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, QuoteVerifyResult, ResidencyCategory, SdkConfig, SessionCrypto, SessionId, SetGrantsInput, SetWritersInput, SignCustodialResult, SignDelegationResponse, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, TenantAdmitProjection, TenantAdmitStatus, Transport, UpdateMetaInput, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WriteDataInput, WritersGetInput };