@hsuite/smart-engines-sdk 4.2.0 → 5.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/CHANGELOG.md +14 -0
- package/dist/index.d.ts +432 -350
- package/dist/index.js +59 -10
- package/dist/index.js.map +1 -1
- package/dist/nestjs/index.d.ts +1256 -1175
- package/dist/nestjs/index.js +59 -10
- package/dist/nestjs/index.js.map +1 -1
- package/package.json +2 -2
package/dist/nestjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_vendor/chain.schema.ts","../../src/_vendor/capabilities.schema.ts","../../src/_vendor/account.schema.ts","../../src/_vendor/sovereignty.schema.ts","../../src/_vendor/api.schema.ts","../../src/discovery/mirror-node.ts","../../src/discovery/validator-discovery.ts","../../src/discovery/cluster-discovery.ts","../../src/http/index.ts","../../src/discovery/discovery-client.ts","../../src/network-presets.ts","../../src/discovery/resolve-cluster.ts","../../src/auth/validator-auth.ts","../../src/subscription/index.ts","../../src/faucet/index.ts","../../src/tss/index.ts","../../src/ipfs/index.ts","../../src/hedera-tss/index.ts","../../src/transactions/chains/hedera.ts","../../src/transactions/chains/xrpl.ts","../../src/transactions/chains/solana.ts","../../src/transactions/chains/polkadot.ts","../../src/transactions/index.ts","../../src/snapshots/index.ts","../../src/historical-balance/historical-balance-client.ts","../../src/settlement/index.ts","../../src/governance/governance-client.ts","../../src/dao/dashboard-client.ts","../../src/dao/dao-client.ts","../../src/personhood/personhood-client.ts","../../src/baas/agents/index.ts","../../src/baas/deployment/index.ts","../../src/bridge/bridge-client.ts","../../src/resources/resources-client.ts","../../src/envelope/envelope-client.ts","../../src/tokens/tokens-client.ts","../../src/operator/operator-client.ts","../../src/client.ts","../../src/gateway/routing/index.ts","../../src/gateway/domains/index.ts","../../src/gateway/dns/index.ts","../../src/gateway/health/index.ts","../../src/gateway/client.ts","../../src/baas/database/index.ts","../../src/baas/storage/index.ts","../../src/baas/functions/index.ts","../../src/baas/messaging/index.ts","../../src/baas/customer-session/index.ts","../../src/baas/rules/client.ts","../../src/baas/entities/client.ts","../../src/baas/client.ts","../../src/nestjs/smart-engine.service.ts","../../src/nestjs/smart-engine.module.ts"],"names":["z","buildQuery","validateUrl","SmartEngineService","Logger","Injectable","Optional","SmartEngineModule","Module"],"mappings":";;;;;;;;;;;;;;AAKO,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK;AAAA,EACpC,QAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC,CAAA;AAOM,IAAM,iBAAA,GAAoBA,MAAE,IAAA,CAAK,CAAC,WAAW,SAAA,EAAW,QAAA,EAAU,OAAO,CAAC,CAAA;AAO9CA,MAAE,MAAA,CAAO;AAAA,EAC1C,KAAA,EAAO,eAAA;AAAA,EACP,OAAA,EAAS,iBAAA;AAAA,EACT,cAAA,EAAgBA,MAAE,MAAA,CAAO;AAAA,IACvB,IAAA,EAAMA,MAAE,MAAA,EAAO;AAAA,IACf,MAAA,EAAQA,MAAE,MAAA,EAAO;AAAA,IACjB,UAAUA,KAAA,CAAE,MAAA,GAAS,GAAA,EAAI,CAAE,IAAI,CAAC;AAAA,GACjC,CAAA;AAAA,EACD,SAAA,EAAWA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC/B,aAAaA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA;AAChC,CAAC;ACzBM,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9C,QAAA,EAAUA,KAAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAA,EAAcA,KAAAA,CAAE,OAAA,E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A,UACE,OAAA,EAAS,mBAAA;AAAA,UACT,UAAA,EAAY,OAAO,cAAA,KACjB,cAAA,CAAe,wBAAA,EAAyB;AAAA,UAC1C,MAAA,EAAQ,CAAC,OAAA,CAAQ,QAAQ;AAAA;AAC3B,OACF;AAAA,IACF;AAEA,IAAA,IAAI,QAAQ,WAAA,EAAa;AACvB,MAAA,OAAO;AAAA,QACL;AAAA,UACE,OAAA,EAAS,mBAAA;AAAA,UACT,UAAA,EAAY,OAAO,cAAA,KACjB,cAAA,CAAe,wBAAA,EAAyB;AAAA,UAC1C,MAAA,EAAQ,CAAC,OAAA,CAAQ,WAAW;AAAA;AAC9B,OACF;AAAA,IACF;AAEA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACF;AA5IaI,yBAAA,GAAN,eAAA,CAAA;AAAA,EADNC,aAAA,CAAO,EAAE;AAAA,CAAA,EACGD,yBAAA,CAAA","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n/**\n * Supported blockchain types\n */\nexport const ChainTypeSchema = z.enum([\n 'hedera',\n 'xrpl',\n 'polkadot',\n 'solana',\n 'stellar',\n 'ethereum',\n 'polygon',\n 'bitcoin',\n 'cardano',\n]);\n\nexport type ChainType = z.infer<typeof ChainTypeSchema>;\n\n/**\n * Network environment types\n */\nexport const NetworkTypeSchema = z.enum(['mainnet', 'testnet', 'devnet', 'local']);\n\nexport type NetworkType = z.infer<typeof NetworkTypeSchema>;\n\n/**\n * Chain metadata schema\n */\nexport const ChainMetadataSchema = z.object({\n chain: ChainTypeSchema,\n network: NetworkTypeSchema,\n nativeCurrency: z.object({\n name: z.string(),\n symbol: z.string(),\n decimals: z.number().int().min(0),\n }),\n blockTime: z.number().optional(),\n rpcEndpoint: z.string().url().optional(),\n});\n\nexport type ChainMetadata = z.infer<typeof ChainMetadataSchema>;\n","/**\n * Token Capabilities Schema\n *\n * Defines universal token capabilities that are chain-agnostic.\n * Each capability maps to chain-specific implementations.\n */\nimport { z } from 'zod';\n\n/**\n * Token Capabilities Schema\n *\n * These capabilities define what operations a token supports.\n * The validator layer translates these to chain-specific implementations.\n */\nexport const TokenCapabilitiesSchema = z.object({\n /**\n * Pause all token operations globally\n * - Hedera: Adds pauseKey to token\n * - XRPL: Enables GlobalFreeze flag on issuer account\n */\n pausable: z.boolean().default(false),\n\n /**\n * Freeze/restrict specific accounts from transacting\n * - Hedera: Adds freezeKey to token\n * - XRPL: Enables trust line freeze capability\n */\n restrictable: z.boolean().default(false),\n\n /**\n * KYC/compliance controls for accounts\n * - Hedera: Adds kycKey to token\n * - XRPL: Requires authorized trust lines (RequireAuth)\n */\n compliant: z.boolean().default(false),\n\n /**\n * Force remove tokens from accounts (compliance wipe)\n * - Hedera: Adds wipeKey to token\n * - XRPL: Enables clawback (lsfAllowTrustLineClawback)\n */\n wipeable: z.boolean().default(false),\n\n /**\n * Mint additional supply after creation\n * - Hedera: Adds supplyKey to token\n * - XRPL: Issuer can always issue more via Payment\n */\n mintable: z.boolean().default(true),\n\n /**\n * Burn tokens (reduce supply)\n * - Hedera: Requires supplyKey\n * - XRPL: Send back to issuer (reduces supply)\n */\n burnable: z.boolean().default(true),\n\n /**\n * Allow transfers between accounts\n * - All chains: Generally always supported\n */\n transferable: z.boolean().default(true),\n});\n\nexport type TokenCapabilities = z.infer<typeof TokenCapabilitiesSchema>;\n\n/**\n * Capability names as a type\n */\nexport type CapabilityName = keyof TokenCapabilities;\n\n/**\n * List of all capability names\n */\nexport const CAPABILITY_NAMES: CapabilityName[] = [\n 'pausable',\n 'restrictable',\n 'compliant',\n 'wipeable',\n 'mintable',\n 'burnable',\n 'transferable',\n];\n","import { z } from 'zod';\nimport { ChainTypeSchema } from './chain.schema';\n\n/**\n * Account identifier schema - generic string that works across chains\n */\nexport const AccountIdSchema = z.string().min(1);\n\n// Note: Export as AccountIdString to avoid collision with AccountId value object\nexport type AccountIdString = z.infer<typeof AccountIdSchema>;\n\n/**\n * Account information schema\n */\nexport const AccountInfoSchema = z.object({\n accountId: AccountIdSchema,\n balance: z.string(), // String to handle large numbers and decimals\n chain: ChainTypeSchema,\n publicKey: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n});\n\nexport type AccountInfo = z.infer<typeof AccountInfoSchema>;\n\n/**\n * Account balance schema with token details\n */\nexport const AccountBalanceSchema = z.object({\n accountId: AccountIdSchema,\n chain: ChainTypeSchema,\n nativeBalance: z.string(),\n tokens: z\n .array(\n z.object({\n tokenId: z.string(),\n balance: z.string(),\n decimals: z.number().int().min(0),\n symbol: z.string().optional(),\n })\n )\n .optional(),\n timestamp: z.date(),\n});\n\nexport type AccountBalance = z.infer<typeof AccountBalanceSchema>;\n","import { z } from 'zod';\n\n/**\n * Sovereignty mode for entity creation.\n * - 'partial': user + validator both sign; on-chain = nested KeyList/SignerList\n * - 'full': validator-only signs; on-chain = validator multisig alone\n *\n * \"partial\" is product-facing \"mixed\".\n *\n * The schema accepts only 'partial' and 'full'. There is no owner-only mode\n * (no validator in the signing path); any payload carrying an unrecognized\n * `securityMode` fails safeParse at the schema boundary.\n */\nexport const SecurityModeSchema = z.enum(['partial', 'full']);\nexport type SecurityMode = z.infer<typeof SecurityModeSchema>;\n\n/**\n * Single source of truth for the sovereignty field invariant.\n *\n * - partial: requires BOTH entityId and appOwnerPublicKey\n * - full: requires entityId (appOwnerPublicKey is ignored, not an error)\n *\n * Exported so merged schemas in api.schema.ts can delegate here\n * instead of duplicating the predicate logic.\n */\nexport const sovereigntyRefinePredicate = (v: {\n securityMode: SecurityMode;\n entityId?: string;\n appOwnerPublicKey?: string;\n}): boolean => {\n if (v.securityMode === 'partial') {\n return !!v.entityId && !!v.appOwnerPublicKey;\n }\n // 'full': requires entityId\n return !!v.entityId;\n};\n\nexport const SOVEREIGNTY_REFINE_MESSAGE =\n \"securityMode='partial' requires entityId+appOwnerPublicKey; 'full' requires entityId\";\n\n/**\n * Shared fragment for every entity-creation prepare schema.\n *\n * Invariants enforced via refine:\n * - partial mode requires BOTH entityId and appOwnerPublicKey\n * - full mode requires entityId (appOwnerPublicKey ignored)\n */\n// Internal: the raw object so callers can `.merge()` it without needing\n// Zod-version-specific `.innerType()` unwrapping (v3 vs v4 API drift).\nexport const SovereigntyFieldsRawSchema = z.object({\n securityMode: SecurityModeSchema.default('full'),\n entityId: z.string().optional(),\n appOwnerPublicKey: z.string().optional(),\n});\n\nexport const SovereigntyFieldsSchema = SovereigntyFieldsRawSchema\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type SovereigntyFields = z.infer<typeof SovereigntyFieldsSchema>;\n\n/**\n * ---------------------------------------------------------------------------\n * Response-side metadata: the `sovereignty` block on PreparedTransaction\n * ---------------------------------------------------------------------------\n *\n * Every `PreparedTransactionResponse` carries a `sovereignty` block so smart-\n * apps and tests can inspect the on-chain authorization topology the\n * validator is building, without decoding raw chain-native bytes.\n *\n * - `mode: 'partial'|'full'` carries the entity id, the raw BLS hex pubkeys\n * from the entity's DKG binding, and a chain-native authorization-set\n * descriptor (KeyList for Hedera, SignerList for XRPL, weighted signer set\n * for Stellar).\n */\n\n/**\n * Recursive JSON shape for a Hedera authorization key.\n *\n * A Hedera `adminKey` / `supplyKey` / capability-key value is either a single\n * ed25519 public key or a threshold KeyList whose members are themselves\n * keys. Kept JSON-serializable (ed25519 keys as hex strings) so callers can\n * walk the structure without a `@hashgraph/sdk` dep.\n */\nexport type HederaKeyShape =\n | { type: 'ed25519'; key: string }\n | { type: 'keyList'; threshold: number; keys: HederaKeyShape[] };\n\nexport const HederaKeyShapeSchema: z.ZodType<HederaKeyShape> = z.lazy(() =>\n z.union([\n z.object({ type: z.literal('ed25519'), key: z.string() }),\n z.object({\n type: z.literal('keyList'),\n threshold: z.number().int().nonnegative(),\n keys: z.array(HederaKeyShapeSchema),\n }),\n ]),\n);\n\nexport const HederaAuthorizationSetShapeSchema = z.object({\n chain: z.literal('hedera'),\n adminKey: HederaKeyShapeSchema,\n supplyKey: HederaKeyShapeSchema.optional(),\n freezeKey: HederaKeyShapeSchema.optional(),\n wipeKey: HederaKeyShapeSchema.optional(),\n pauseKey: HederaKeyShapeSchema.optional(),\n kycKey: HederaKeyShapeSchema.optional(),\n});\n\nexport const XrplAuthorizationSetShapeSchema = z.object({\n chain: z.literal('xrpl'),\n signerEntries: z.array(\n z.object({\n account: z.string(),\n weight: z.number().int().nonnegative(),\n }),\n ),\n signerQuorum: z.number().int().nonnegative(),\n masterDisabled: z.boolean(),\n});\n\nexport const StellarAuthorizationSetShapeSchema = z.object({\n chain: z.literal('stellar'),\n signers: z.array(\n z.object({\n key: z.string(),\n weight: z.number().int().nonnegative(),\n }),\n ),\n thresholds: z.object({\n low: z.number().int().nonnegative(),\n med: z.number().int().nonnegative(),\n high: z.number().int().nonnegative(),\n }),\n masterWeight: z.number().int().nonnegative(),\n});\n\n/**\n * Recursive JSON shape for a Polkadot authorization signatory.\n *\n * A Polkadot sovereignty set resolves to a single on-chain controlling\n * `address`. That address is either a native `pallet_multisig` address\n * whose signatories may themselves be multisig accounts (`'full'` = flat\n * validator multisig; `'partial'` = nested outer multisig\n * `[userAddress, innerValidatorMultisig]`).\n *\n * Kept JSON-serializable (SS58 addresses as strings) so callers can walk the\n * structure without a `@polkadot/*` dep.\n */\nexport type PolkadotSignatoryShape =\n | { type: 'account'; address: string }\n | {\n type: 'multisig';\n address: string;\n threshold: number;\n signatories: PolkadotSignatoryShape[];\n };\n\nexport const PolkadotSignatoryShapeSchema: z.ZodType<PolkadotSignatoryShape> = z.lazy(() =>\n z.union([\n z.object({ type: z.literal('account'), address: z.string() }),\n z.object({\n type: z.literal('multisig'),\n address: z.string(),\n threshold: z.number().int().positive(),\n signatories: z.array(PolkadotSignatoryShapeSchema),\n }),\n ]),\n);\n\nexport const PolkadotAuthorizationSetShapeSchema = z.object({\n chain: z.literal('polkadot'),\n address: z.string(),\n signatory: PolkadotSignatoryShapeSchema,\n ss58Format: z.number().int().nonnegative(),\n});\n\nexport const PreparedTransactionAuthorizationSetSchema = z.discriminatedUnion('chain', [\n HederaAuthorizationSetShapeSchema,\n XrplAuthorizationSetShapeSchema,\n StellarAuthorizationSetShapeSchema,\n PolkadotAuthorizationSetShapeSchema,\n]);\n\nexport type HederaAuthorizationSetShape = z.infer<typeof HederaAuthorizationSetShapeSchema>;\nexport type XrplAuthorizationSetShape = z.infer<typeof XrplAuthorizationSetShapeSchema>;\nexport type StellarAuthorizationSetShape = z.infer<typeof StellarAuthorizationSetShapeSchema>;\nexport type PolkadotAuthorizationSetShape = z.infer<typeof PolkadotAuthorizationSetShapeSchema>;\nexport type PreparedTransactionAuthorizationSet = z.infer<\n typeof PreparedTransactionAuthorizationSetSchema\n>;\n\n/**\n * `authorizationSet` is REQUIRED for prepare endpoints that build the on-chain\n * authorization at create time (token create, account create, account setup)\n * and OPTIONAL for prepare endpoints that invoke an already-configured\n * authorization (mint, burn, transfer, payment). In the latter case the\n * authorization set lives on-chain from a prior create and smart-apps already\n * have its shape from the original create response.\n *\n * The union has two arms: `'partial'` and `'full'`. There is no owner-only\n * `'none'` arm.\n */\nexport const PreparedTransactionSovereigntySchema = z.discriminatedUnion('mode', [\n z.object({\n mode: z.literal('partial'),\n entityId: z.string(),\n validatorPublicKeys: z.array(z.string()),\n authorizationSet: PreparedTransactionAuthorizationSetSchema.optional(),\n }),\n z.object({\n mode: z.literal('full'),\n entityId: z.string(),\n validatorPublicKeys: z.array(z.string()),\n authorizationSet: PreparedTransactionAuthorizationSetSchema.optional(),\n }),\n]);\n\nexport type PreparedTransactionSovereignty = z.infer<typeof PreparedTransactionSovereigntySchema>;\n","import { z } from 'zod';\nimport { ChainTypeSchema } from './chain.schema';\nimport { AccountIdSchema } from './account.schema';\nimport { TokenCapabilitiesSchema } from './capabilities.schema';\nimport {\n SovereigntyFieldsRawSchema,\n sovereigntyRefinePredicate,\n SOVEREIGNTY_REFINE_MESSAGE,\n PreparedTransactionSovereigntySchema,\n} from './sovereignty.schema';\n\n/**\n * Vendored mirror of `RuleRefSchema` from\n * `libs/shared/src/schemas/api.schema.ts`. An HCS pointer to a published\n * `ValidatorRules`: the chain whose HCS carries it, the topic id, and the\n * rule message's consensus timestamp. Supplied on a create request so the\n * chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) instead of the degraded\n * `rule:bootstrap:<entityType>` marker (RFC 2026-06-15-onchain-rule-anchor §6.1).\n * Keep byte-identical with the shared definition when that schema changes.\n */\nexport const RuleRefSchema = z.object({\n /** Chain whose HCS the rule was published on (canonically 'hedera'). */\n chain: ChainTypeSchema,\n /** HCS topic ID the rule message was published to. */\n topicId: z.string().min(1),\n /** HCS consensus timestamp of the rule message. */\n consensusTimestamp: z.string().min(1),\n});\n\nexport type RuleRefInput = z.infer<typeof RuleRefSchema>;\n\n/**\n * Create account request schema\n *\n * @important validatorTimestamp is REQUIRED - all entities must be bound to a validator.\n * The validator rules are stored on HCS and referenced by consensus timestamp.\n */\nexport const CreateAccountRequestSchema = z.object({\n chain: ChainTypeSchema,\n initialBalance: z.string(),\n publicKey: z.string().optional(),\n memo: z.string().optional(),\n /**\n * Who pays the chain fee for this transaction. Resolution happens in the\n * controller layer (`resolvePayerAccountId`): explicit `payerAccountId`\n * wins, else the JWT-authenticated smart-app's wallet address, else the\n * request is rejected with 400. The validator **never** silently falls\n * back to its own operator account.\n */\n payerAccountId: z.string().optional(),\n /**\n * HCS consensus timestamp of the validator rules (REQUIRED).\n * Format: \"1766490325.123456789\"\n */\n validatorTimestamp: z.string().min(1, 'validatorTimestamp is required'),\n /**\n * HCS topic ID where validator rules are stored (REQUIRED).\n */\n validatorTopicId: z.string().min(1, 'validatorTopicId is required'),\n /**\n * Whether to remove admin key after creation (makes entity immutable).\n * Default: true for production-grade immutability.\n */\n immutable: z.boolean().default(true),\n /**\n * Smart node security mode for the account key structure.\n * - 'partial': threshold(2, [appOwnerKey, tssKeyList]) — co-control\n * - 'full': TSS KeyList only — full validator network control\n * @defaultValue 'full'\n */\n securityMode: z.enum(['partial', 'full']).default('full'),\n /**\n * App owner's public key (required for 'partial' security mode).\n * The owner key + TSS network key form a threshold-2 multi-sig.\n */\n appOwnerPublicKey: z.string().optional(),\n /**\n * The entity's canonical `ruleRef` (HCS pointer to its `ValidatorRules`). When\n * present, the chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) — distinct from the\n * mutable validator-binding memo — so the sign-gate resolves the rule on-chain\n * (kind:'ref') rather than trusting the replicated binding\n * (RFC 2026-06-15-onchain-rule-anchor §6.1). Absent ⇒ the degraded\n * `rule:bootstrap:<entityType>` marker when `entityType` is supplied.\n */\n ruleRef: RuleRefSchema.optional(),\n /**\n * Entity-type tag stamped into the rule anchor (e.g. 'wallet', 'account').\n * Supply it to enable the on-chain anchor; omit for the prior memo-less\n * (legacy) behaviour.\n */\n entityType: z.string().min(1).optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type CreateAccountRequest = z.infer<typeof CreateAccountRequestSchema>;\n\n/**\n * Create account response schema\n */\nexport const CreateAccountResponseSchema = z.object({\n accountId: AccountIdSchema,\n publicKey: z.string().optional(),\n privateKey: z.string().optional(), // Only returned on creation, store securely!\n transactionId: z.string(),\n chain: ChainTypeSchema,\n timestamp: z.date().optional(),\n});\n\nexport type CreateAccountResponse = z.infer<typeof CreateAccountResponseSchema>;\n\n/**\n * Transfer request schema\n */\nexport const TransferRequestSchema = z.object({\n chain: ChainTypeSchema,\n from: AccountIdSchema,\n to: AccountIdSchema,\n amount: z.string(),\n tokenId: z.string().optional(), // undefined = native token\n memo: z.string().optional(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type TransferRequest = z.infer<typeof TransferRequestSchema>;\n\n/**\n * Transfer response schema\n */\nexport const TransferResponseSchema = z.object({\n transactionId: z.string(),\n status: z.enum(['pending', 'success', 'failed']),\n chain: ChainTypeSchema,\n fee: z.string().optional(),\n timestamp: z.date().optional(),\n});\n\nexport type TransferResponse = z.infer<typeof TransferResponseSchema>;\n\n/**\n * Query balance request schema\n */\nexport const QueryBalanceRequestSchema = z.object({\n chain: ChainTypeSchema,\n accountId: AccountIdSchema,\n});\n\nexport type QueryBalanceRequest = z.infer<typeof QueryBalanceRequestSchema>;\n\n/**\n * Query transaction request schema\n */\nexport const QueryTransactionRequestSchema = z.object({\n chain: ChainTypeSchema,\n transactionId: z.string(),\n});\n\nexport type QueryTransactionRequest = z.infer<typeof QueryTransactionRequestSchema>;\n\n/**\n * Create token request schema (v2 with capabilities)\n *\n * Supports universal token capabilities that are validated against chain support.\n * If a capability is requested but not supported on the target chain, an error is thrown.\n */\nexport const CreateTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n name: z.string().min(1).max(100),\n symbol: z.string().min(1).max(10),\n decimals: z.number().int().min(0).max(18),\n initialSupply: z.string(),\n type: z.enum(['fungible', 'nft']),\n treasury: AccountIdSchema.optional(),\n /**\n * Token capabilities define what operations the token supports.\n * These are validated against chain support and translated to native implementations.\n *\n * @example\n * ```typescript\n * capabilities: {\n * pausable: true, // Hedera: pauseKey, XRPL: GlobalFreeze\n * restrictable: true, // Hedera: freezeKey, XRPL: TrustLineFreeze\n * compliant: true, // Hedera: kycKey, XRPL: RequireAuth\n * wipeable: true, // Hedera: wipeKey, XRPL: Clawback\n * mintable: true, // Allow additional minting\n * burnable: true, // Allow burning\n * }\n * ```\n */\n capabilities: TokenCapabilitiesSchema.optional().default({\n pausable: false,\n restrictable: false,\n compliant: false,\n wipeable: false,\n mintable: true,\n burnable: true,\n transferable: true,\n }),\n /**\n * HCS consensus timestamp of the validator rules (REQUIRED).\n * Format: \"1766490325.123456789\"\n */\n validatorTimestamp: z.string().min(1, 'validatorTimestamp is required'),\n /**\n * HCS topic ID where validator rules are stored (REQUIRED).\n */\n validatorTopicId: z.string().min(1, 'validatorTopicId is required'),\n /**\n * Whether to remove admin key after creation (makes entity immutable).\n * Default: true for production-grade immutability.\n */\n immutable: z.boolean().default(true),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n /**\n * The entity's canonical `ruleRef` (HCS pointer to its `ValidatorRules`). When\n * present, the chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) — distinct from the\n * mutable validator-binding token memo — so the sign-gate resolves the rule\n * on-chain (kind:'ref') rather than trusting the replicated binding\n * (RFC 2026-06-15-onchain-rule-anchor §6.1). Absent ⇒ the degraded\n * `rule:bootstrap:<entityType>` marker when `entityType` is supplied.\n */\n ruleRef: RuleRefSchema.optional(),\n /**\n * Entity-type tag stamped into the rule anchor (e.g. 'token'). Supply it to\n * enable the on-chain anchor; omit for the prior memo-less behaviour.\n */\n entityType: z.string().min(1).optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type CreateTokenRequest = z.infer<typeof CreateTokenRequestSchema>;\n\n/**\n * Create token response schema\n */\nexport const CreateTokenResponseSchema = z.object({\n tokenId: z.string(),\n transactionId: z.string(),\n chain: ChainTypeSchema,\n timestamp: z.date().optional(),\n});\n\nexport type CreateTokenResponse = z.infer<typeof CreateTokenResponseSchema>;\n\n/**\n * Mint token request schema\n */\n/**\n * Mint token request schema\n *\n * Supports both fungible and non-fungible token minting:\n * - Fungible: requires `amount` (e.g. \"1000\")\n * - NFT: requires `nftMetadata` (array of byte-encodable entries, one per NFT to mint)\n *\n * The chain adapter determines the appropriate native operation based on the token type.\n */\nexport const MintTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n\n /** Amount to mint (fungible tokens). Ignored for NFTs. */\n amount: z.string().optional(),\n\n /** Recipient account (fungible: transfer after mint; NFT: Hedera mints to treasury). */\n recipient: AccountIdSchema.optional(),\n\n /**\n * NFT metadata entries — one per NFT to mint.\n * Each entry becomes on-chain metadata (e.g. IPFS CID, encoded memo).\n * On Hedera: passed to TokenMintTransaction.setMetadata().\n * On XRPL: used as URI in NFTokenMint.\n */\n nftMetadata: z.array(z.string()).optional(),\n\n /** Additional chain-specific options. */\n metadata: z.record(z.any()).optional(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n});\n\nexport type MintTokenRequest = z.infer<typeof MintTokenRequestSchema>;\n\n/**\n * Burn token request schema\n */\nexport const BurnTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n amount: z.string(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type BurnTokenRequest = z.infer<typeof BurnTokenRequestSchema>;\n\n/**\n * Token action request schema (for pause, restrict, etc.)\n */\nexport const TokenActionRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n accountId: AccountIdSchema.optional(), // Required for account-specific actions\n amount: z.string().optional(), // Required for wipe action\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type TokenActionRequest = z.infer<typeof TokenActionRequestSchema>;\n\n/**\n * Action result schema - unified response for all token actions\n */\nexport const ActionResultSchema = z.object({\n success: z.boolean(),\n transactionId: z.string(),\n chain: ChainTypeSchema,\n /** The native chain operation that was executed */\n chainOperation: z.string(),\n /** Additional context or notes about the operation */\n notes: z.array(z.string()).optional(),\n /** Timestamp of the operation */\n timestamp: z.date().optional(),\n});\n\nexport type ActionResult = z.infer<typeof ActionResultSchema>;\n\n/**\n * Create token result schema - extends ActionResult with token info\n */\nexport const CreateTokenResultSchema = ActionResultSchema.extend({\n tokenId: z.string(),\n /** The capabilities that were enabled for this token */\n enabledCapabilities: z.array(z.string()),\n});\n\nexport type CreateTokenResult = z.infer<typeof CreateTokenResultSchema>;\n\n// =============================================================================\n// PREPARED TRANSACTION RESPONSE TYPES (v3 API - Transaction Sovereignty)\n// =============================================================================\n\n/**\n * Validator signature for a prepared transaction\n */\nexport const ValidatorSignatureSchema = z.object({\n /** Validator's node ID */\n validatorId: z.string(),\n /** Validator's public key (hex-encoded) */\n publicKey: z.string(),\n /** Signature over the transaction bytes (hex-encoded) */\n signature: z.string(),\n /** When this signature was created */\n signedAt: z.date(),\n /** Signature algorithm used */\n algorithm: z.enum(['ed25519', 'ecdsa-secp256k1', 'bls12-381']).optional(),\n});\n\nexport type ValidatorSignature = z.infer<typeof ValidatorSignatureSchema>;\n\n/**\n * Hedera-specific metadata for prepared transactions\n */\nexport const HederaPreparedMetadataSchema = z.object({\n /** Hedera node account IDs that will process this transaction */\n nodeAccountIds: z.array(z.string()).optional(),\n /** Maximum transaction fee in tinybars */\n maxTransactionFee: z.string().optional(),\n /** Transaction memo */\n memo: z.string().optional(),\n /** Schedule info if this is a scheduled transaction */\n scheduleInfo: z\n .object({\n scheduleId: z.string(),\n adminKey: z.string().optional(),\n })\n .optional(),\n});\n\nexport type HederaPreparedMetadata = z.infer<typeof HederaPreparedMetadataSchema>;\n\n/**\n * XRPL-specific metadata for prepared transactions\n */\nexport const XRPLPreparedMetadataSchema = z.object({\n /** Sequence number for this transaction */\n sequence: z.number().optional(),\n /** Last ledger sequence for expiration */\n lastLedgerSequence: z.number().optional(),\n /** Signer list info for multi-sig */\n signerList: z\n .array(\n z.object({\n account: z.string(),\n signerWeight: z.number(),\n })\n )\n .optional(),\n /** Quorum weight required */\n signerQuorum: z.number().optional(),\n});\n\nexport type XRPLPreparedMetadata = z.infer<typeof XRPLPreparedMetadataSchema>;\n\n/**\n * Solana-specific metadata for prepared transactions\n */\nexport const SolanaPreparedMetadataSchema = z.object({\n /** Recent blockhash for transaction validity */\n recentBlockhash: z.string().optional(),\n /** Fee payer account */\n feePayer: z.string().optional(),\n /** Program IDs involved */\n programIds: z.array(z.string()).optional(),\n /** Squads v4 multisig PDA address (partial/full modes) */\n squadsMultisigPda: z.string().optional(),\n /** Squads v4 vault PDA address (partial/full modes) */\n squadsVaultPda: z.string().optional(),\n /** Index of the vault transaction proposal */\n squadsTransactionIndex: z.number().optional(),\n /** Proposal PDA address */\n squadsProposalAddress: z.string().optional(),\n /** Whether the multisig was created in this call (vs already existed) */\n multisigCreated: z.boolean().optional(),\n /** Security mode used to prepare this transaction */\n securityMode: z.enum(['partial', 'full']).optional(),\n /** SPL Token mint address (token-create and all SPL operations) */\n splMint: z.string().optional(),\n});\n\nexport type SolanaPreparedMetadata = z.infer<typeof SolanaPreparedMetadataSchema>;\n\n/**\n * Polkadot-specific metadata for prepared transactions\n */\nexport const PolkadotPreparedMetadataSchema = z.object({\n /** Era for transaction mortality */\n era: z.string().optional(),\n /** Nonce for the sender */\n nonce: z.number().optional(),\n /** Tip for priority */\n tip: z.string().optional(),\n /** Spec version for runtime */\n specVersion: z.number().optional(),\n});\n\nexport type PolkadotPreparedMetadata = z.infer<typeof PolkadotPreparedMetadataSchema>;\n\n/**\n * Union of all chain-specific metadata types\n */\nexport const ChainPreparedMetadataSchema = z.union([\n HederaPreparedMetadataSchema,\n XRPLPreparedMetadataSchema,\n SolanaPreparedMetadataSchema,\n PolkadotPreparedMetadataSchema,\n z.record(z.any()), // Allow extension for future chains\n]);\n\nexport type ChainPreparedMetadata = z.infer<typeof ChainPreparedMetadataSchema>;\n\n/**\n * Prepared transaction response - the core type for v3 API\n *\n * IMPORTANT: This is the unified response type for all transaction operations.\n * The transaction is frozen/prepared but NOT submitted. The caller is responsible\n * for submitting the transaction to the network.\n *\n * SECURITY PRINCIPLES:\n * 1. Validators NEVER pay fees - caller provides payerAccountId\n * 2. Validators NEVER submit transactions - they return signed bytes\n * 3. All operations use multi-sig - no single-key fallbacks\n * 4. Transaction ID is pre-assigned for deterministic tracking\n */\nexport const PreparedTransactionResponseSchema = z.object({\n /** The blockchain this transaction is for */\n chain: ChainTypeSchema,\n /** Type of transaction (e.g., 'TokenCreate', 'Payment', 'NFTMint') */\n transactionType: z.string(),\n /** Pre-assigned transaction ID for tracking */\n transactionId: z.string(),\n /** Base64-encoded frozen transaction bytes ready for submission */\n transactionBytes: z.string(),\n /** When this prepared transaction expires */\n expiresAt: z.date(),\n /** Validator signatures collected for this transaction */\n validatorSignatures: z.array(ValidatorSignatureSchema),\n /** Required payer account ID (caller must fund this account) */\n payerAccountId: z.string().optional(),\n /** Estimated network fee */\n estimatedFee: z.string().optional(),\n /** Number of signatures required for submission */\n requiredSignatures: z.number().optional(),\n /** Whether the transaction has enough signatures to submit */\n readyToSubmit: z.boolean().default(false),\n /** Chain-specific metadata */\n metadata: ChainPreparedMetadataSchema.optional(),\n /**\n * Sovereignty metadata: the mode and (for partial/full) the on-chain\n * authorization set the validator is binding to. Lets smart-apps and tests\n * inspect the authorization topology without decoding chain-native bytes.\n */\n sovereignty: PreparedTransactionSovereigntySchema.optional(),\n});\n\nexport type PreparedTransactionResponse = z.infer<typeof PreparedTransactionResponseSchema>;\n\n/**\n * Generic prepared transaction response with typed metadata\n */\nexport type PreparedTransactionResponseWithMetadata<T extends ChainPreparedMetadata> = Omit<\n PreparedTransactionResponse,\n 'metadata'\n> & {\n metadata?: T;\n};\n\n/**\n * Type-safe prepared transaction responses for each chain\n */\nexport type HederaPreparedTransaction =\n PreparedTransactionResponseWithMetadata<HederaPreparedMetadata>;\n/**\n * XRPL prepared transaction response.\n *\n * Includes `transactionJson` alongside `transactionBytes` so xrpl.js-native\n * clients can sign the autofilled transaction object directly without having\n * to decode the binary blob. See Transaction Sovereignty Parity Part A.4.\n *\n * `transactionJson` is typed as the structural minimum — the fields every\n * autofilled XRPL tx carries — so `@hsuite/smart-engines-shared` stays\n * decoupled from the xrpl.js package. Callers that need the full\n * `SubmittableTransaction` union (see xrpl.js) should consume the stronger\n * local type exported from `@hsuite/smart-engines-chain-xrpl`, which is\n * typed against xrpl.js directly.\n */\nexport type XRPLPreparedTransactionJson = {\n TransactionType: string;\n Account: string;\n Fee?: string;\n Sequence?: number;\n LastLedgerSequence?: number;\n [extra: string]: unknown;\n};\n\nexport type XRPLPreparedTransaction = PreparedTransactionResponseWithMetadata<XRPLPreparedMetadata> & {\n /** Autofilled XRPL transaction object (post-autofill, pre-sign) for xrpl.js-native callers */\n transactionJson: XRPLPreparedTransactionJson;\n};\nexport type SolanaPreparedTransaction =\n PreparedTransactionResponseWithMetadata<SolanaPreparedMetadata>;\nexport type PolkadotPreparedTransaction =\n PreparedTransactionResponseWithMetadata<PolkadotPreparedMetadata>;\n\n/**\n * Submission result after caller submits the prepared transaction\n */\nexport const TransactionSubmissionResultSchema = z.object({\n /** The original transaction ID */\n transactionId: z.string(),\n /** The blockchain */\n chain: ChainTypeSchema,\n /** Whether submission was successful */\n success: z.boolean(),\n /** Consensus timestamp (Hedera) or ledger/block info */\n consensusTimestamp: z.string().optional(),\n /** Block or ledger number */\n blockNumber: z.number().optional(),\n /** Actual fee paid */\n actualFee: z.string().optional(),\n /** Receipt or confirmation data */\n receipt: z.record(z.any()).optional(),\n /** Error message if submission failed */\n error: z.string().optional(),\n});\n\nexport type TransactionSubmissionResult = z.infer<typeof TransactionSubmissionResultSchema>;\n\n// =============================================================================\n// PREPARE REQUEST SCHEMAS (v3 API - Transaction Sovereignty Mixed Layer)\n// =============================================================================\n\n/**\n * Prepare token-create request schema (Hedera HTS).\n *\n * Merges SovereigntyFieldsSchema so securityMode, entityId, and\n * appOwnerPublicKey carry the same cross-chain invariants.\n */\nexport const PrepareTokenCreateRequestSchema = z\n .object({\n chain: z.literal('hedera'),\n payerAccountId: z.string().optional(),\n name: z.string().min(1).max(100),\n symbol: z.string().min(1).max(10),\n decimals: z.number().int().min(0).max(18),\n initialSupply: z.string(),\n treasuryAccountId: z.string().min(1, 'treasuryAccountId is required'),\n memo: z.string().optional(),\n tokenType: z.enum(['FUNGIBLE_COMMON', 'NON_FUNGIBLE_UNIQUE']).default('FUNGIBLE_COMMON'),\n supplyKey: z.string().optional(),\n adminKey: z.string().optional(),\n pauseKey: z.string().optional(),\n freezeKey: z.string().optional(),\n kycKey: z.string().optional(),\n wipeKey: z.string().optional(),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n // SovereigntyFieldsRawSchema is the unrefined object (no .refine wrapping)\n // the sovereignty invariant is re-applied by the .refine() below.\n .merge(SovereigntyFieldsRawSchema)\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type PrepareTokenCreateRequest = z.infer<typeof PrepareTokenCreateRequestSchema>;\n\n/**\n * Prepare XRPL account-setup request schema.\n *\n * Used to configure the authorization (signer list / AccountSet flags) on an\n * existing XRPL account as part of the sovereignty key setup.\n */\nexport const PrepareXrplAccountSetupRequestSchema = z\n .object({\n chain: z.literal('xrpl'),\n payerAccountId: z.string().optional(),\n // User's XRPL account whose authorization we're configuring.\n accountAddress: z.string().min(25).max(34),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n .merge(SovereigntyFieldsRawSchema)\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type PrepareXrplAccountSetupRequest = z.infer<typeof PrepareXrplAccountSetupRequestSchema>;\n\n/**\n * Prepare Stellar account-create request schema.\n *\n * Creates a new Stellar account and optionally configures sovereignty signers.\n */\nexport const PrepareStellarAccountCreateRequestSchema = z\n .object({\n chain: z.literal('stellar'),\n payerAccountId: z.string().optional(),\n // The master public key of the new Stellar account.\n publicKey: z.string().min(56).max(56),\n startingBalance: z.string().regex(/^\\d+(\\.\\d+)?$/),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n .merge(SovereigntyFieldsRawSchema)\n // Stellar's partial mode uses the new account's OWN master key as the\n // \"user\" signer (via SetOptions(masterWeight=2)) — there is NO separate\n // appOwnerPublicKey because Stellar allows the master key to satisfy\n // authorization directly. Only entityId is required for partial/full.\n .refine(\n (v) => !!v.entityId,\n { message: \"securityMode='partial'/'full' requires entityId\" },\n );\n\nexport type PrepareStellarAccountCreateRequest = z.infer<\n typeof PrepareStellarAccountCreateRequestSchema\n>;\n","/**\n * Hedera Mirror Node Client\n *\n * Lightweight client for querying Hedera mirror node REST API.\n * Used for validator discovery by reading HCS topic messages.\n */\n\n/**\n * Mirror node configuration\n */\nexport interface MirrorNodeConfig {\n /** Mirror node base URL (e.g., https://testnet.mirrornode.hedera.com) */\n baseUrl: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP (insecure) connections - default false */\n allowInsecure?: boolean;\n}\n\n/**\n * Validate and sanitize a URL\n * Prevents SSRF and ensures HTTPS for security\n */\nfunction validateUrl(url: string, allowInsecure = false): URL {\n try {\n const parsed = new URL(url);\n\n // Only allow http/https protocols\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new Error(`Invalid protocol: ${parsed.protocol}`);\n }\n\n // Enforce HTTPS unless explicitly allowed\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new Error(\n 'HTTPS is required for secure connections. Set allowInsecure=true to override.'\n );\n }\n\n // Block private/internal IP ranges to prevent SSRF\n const hostname = parsed.hostname.toLowerCase();\n const blockedPatterns = [\n /^localhost$/i,\n /^127\\./,\n /^10\\./,\n /^172\\.(1[6-9]|2[0-9]|3[01])\\./,\n /^192\\.168\\./,\n /^169\\.254\\./,\n /^::1$/,\n /^fe80:/i,\n /^fc00:/i,\n /^fd00:/i,\n ];\n\n // Allow localhost only in development with explicit flag\n const isPrivate = blockedPatterns.some((pattern) => pattern.test(hostname));\n if (isPrivate && !allowInsecure) {\n throw new Error(\n 'Private/internal URLs are blocked. Set allowInsecure=true for local development.'\n );\n }\n\n return parsed;\n } catch (error) {\n if (error instanceof Error && error.message.includes('Invalid URL')) {\n throw new MirrorNodeError(`Invalid URL format: ${url}`, 400);\n }\n throw error;\n }\n}\n\n/**\n * Validate Hedera topic ID format\n */\nfunction validateTopicId(topicId: string): void {\n // Format: shard.realm.num (e.g., 0.0.123456)\n if (!/^\\d+\\.\\d+\\.\\d+$/.test(topicId)) {\n throw new MirrorNodeError(\n `Invalid topic ID format: ${topicId}. Expected format: 0.0.123456`,\n 400\n );\n }\n}\n\n/**\n * HCS topic message from mirror node API\n */\nexport interface TopicMessage {\n /** Consensus timestamp */\n consensus_timestamp: string;\n /** Message content (base64 encoded) */\n message: string;\n /** Payer account ID */\n payer_account_id: string;\n /** Running hash */\n running_hash: string;\n /** Running hash version */\n running_hash_version: number;\n /** Sequence number */\n sequence_number: number;\n /** Topic ID */\n topic_id: string;\n}\n\n/**\n * Mirror node API response for topic messages\n */\nexport interface TopicMessagesResponse {\n messages: TopicMessage[];\n links: {\n next?: string;\n };\n}\n\n/**\n * Default mirror node URLs by network\n */\nexport const MIRROR_NODE_URLS: Record<string, string> = {\n mainnet: 'https://mainnet-public.mirrornode.hedera.com',\n testnet: 'https://testnet.mirrornode.hedera.com',\n previewnet: 'https://previewnet.mirrornode.hedera.com',\n};\n\n/**\n * Hedera Mirror Node Client\n *\n * Query HCS topic messages via REST API for validator discovery.\n */\nexport class MirrorNodeClient {\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n\n constructor(config: MirrorNodeConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n\n // Validate the base URL\n const validatedUrl = validateUrl(config.baseUrl, this.allowInsecure);\n this.baseUrl = validatedUrl.origin;\n this.timeout = config.timeout || 30000;\n }\n\n /**\n * Create client for a specific network\n */\n static forNetwork(network: 'mainnet' | 'testnet' | 'previewnet'): MirrorNodeClient {\n const baseUrl = MIRROR_NODE_URLS[network];\n if (!baseUrl) {\n throw new Error(`Unknown network: ${network}`);\n }\n return new MirrorNodeClient({ baseUrl });\n }\n\n /**\n * Get topic messages from mirror node\n *\n * @param topicId - HCS topic ID (e.g., '0.0.123456')\n * @param options - Query options\n * @returns Topic messages\n */\n async getTopicMessages(\n topicId: string,\n options?: {\n /** Limit number of messages */\n limit?: number;\n /** Order (asc or desc) */\n order?: 'asc' | 'desc';\n /** Timestamp to start from */\n timestampStart?: string;\n /** Timestamp to end at */\n timestampEnd?: string;\n /** Sequence number to start from */\n sequenceNumberStart?: number;\n }\n ): Promise<TopicMessage[]> {\n // Validate topic ID format to prevent injection\n validateTopicId(topicId);\n\n const params = new URLSearchParams();\n\n if (options?.limit) {\n params.set('limit', options.limit.toString());\n }\n if (options?.order) {\n params.set('order', options.order);\n }\n if (options?.timestampStart) {\n params.set('timestamp', `gte:${options.timestampStart}`);\n }\n if (options?.timestampEnd) {\n params.set('timestamp', `lte:${options.timestampEnd}`);\n }\n if (options?.sequenceNumberStart) {\n params.set('sequencenumber', `gte:${options.sequenceNumberStart}`);\n }\n\n const url = `${this.baseUrl}/api/v1/topics/${topicId}/messages?${params.toString()}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new MirrorNodeError(\n `Mirror node error: ${response.status} ${response.statusText}`,\n response.status\n );\n }\n\n const data = (await response.json()) as TopicMessagesResponse;\n return data.messages;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof MirrorNodeError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new MirrorNodeError('Mirror node request timeout', 408);\n }\n throw new MirrorNodeError(`Mirror node network error: ${err.message}`, 0);\n }\n }\n\n /**\n * Get all topic messages with pagination\n *\n * @param topicId - HCS topic ID\n * @param maxMessages - Maximum messages to fetch (default: 1000)\n * @returns All topic messages\n */\n async getAllTopicMessages(topicId: string, maxMessages: number = 1000): Promise<TopicMessage[]> {\n // Validate topic ID format\n validateTopicId(topicId);\n\n // Enforce reasonable limits to prevent DoS\n const safeMaxMessages = Math.min(maxMessages, 10000);\n\n const allMessages: TopicMessage[] = [];\n let nextPath: string | undefined = `/api/v1/topics/${topicId}/messages?limit=100&order=desc`;\n\n while (nextPath && allMessages.length < safeMaxMessages) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Construct full URL safely - only use path from pagination\n const fullUrl = `${this.baseUrl}${nextPath}`;\n\n const response = await fetch(fullUrl, {\n method: 'GET',\n headers: { Accept: 'application/json' },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new MirrorNodeError(\n `Mirror node error: ${response.status} ${response.statusText}`,\n response.status\n );\n }\n\n const data = (await response.json()) as TopicMessagesResponse;\n allMessages.push(...data.messages);\n\n // Validate and sanitize pagination link\n // Only accept relative paths starting with /api/v1/\n if (data.links.next) {\n const nextLink = data.links.next;\n if (nextLink.startsWith('/api/v1/topics/')) {\n nextPath = nextLink;\n } else {\n // Invalid pagination link - stop pagination\n nextPath = undefined;\n }\n } else {\n nextPath = undefined;\n }\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof MirrorNodeError) {\n throw error;\n }\n const err = error as Error;\n throw new MirrorNodeError(`Mirror node error: ${err.message}`, 0);\n }\n }\n\n return allMessages.slice(0, safeMaxMessages);\n }\n\n /**\n * Decode base64 message content\n */\n static decodeMessage(base64Message: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(base64Message, 'base64').toString('utf-8');\n }\n // Browser environment\n return atob(base64Message);\n }\n}\n\n/**\n * Mirror node error\n */\nexport class MirrorNodeError extends Error {\n constructor(\n message: string,\n public statusCode: number\n ) {\n super(message);\n this.name = 'MirrorNodeError';\n }\n}\n","/**\n * Validator Discovery Client\n *\n * Discover smart-engine validators by reading the HCS validator registry topic.\n * Provides methods to list validators and select random validators for connection.\n */\n\nimport { MirrorNodeClient, MIRROR_NODE_URLS } from './mirror-node';\n\n/**\n * Network endpoints for validator connectivity\n */\nexport interface ValidatorNetworkEndpoints {\n /** HTTP API endpoint (e.g., https://validator.example.com:3000) */\n apiEndpoint: string;\n /** NATS endpoint for peer-to-peer messaging */\n natsEndpoint?: string;\n /** Public IP for NAT traversal */\n publicIp?: string;\n /** NATS port if different from default */\n natsPort?: number;\n}\n\n/**\n * Validator metadata\n */\nexport interface ValidatorMetadata {\n /** Human-readable description */\n description?: string;\n /** Version string */\n version?: string;\n /** Tags for categorization */\n tags?: string[];\n /** Author/operator name */\n author?: string;\n}\n\n/**\n * Validator registry entry parsed from HCS\n */\nexport interface ValidatorInfo {\n /** Validator consensus timestamp (unique ID) */\n validatorTimestamp: string;\n /** Node ID (e.g., validator-1) */\n nodeId: string;\n /** Validator type */\n type: 'consensus' | 'tokens' | 'accounts' | 'network';\n /** Network endpoints for connectivity */\n networkEndpoints?: ValidatorNetworkEndpoints;\n /** Public key for peer authentication (Ed25519 hex) */\n publicKey?: string;\n /** Membership NFT serial number */\n membershipNftSerial?: number;\n /** Supported blockchain capabilities */\n capabilities?: string[];\n /** Validator metadata */\n metadata: ValidatorMetadata;\n /** When registered */\n registeredAt: string;\n /** Message type */\n messageType?: 'validator.join' | 'validator.leave' | 'validator.update';\n}\n\n/**\n * Validator discovery configuration\n */\nexport interface ValidatorDiscoveryConfig {\n /** Hedera network (mainnet, testnet, previewnet) */\n network: 'mainnet' | 'testnet' | 'previewnet';\n /** HCS topic ID for validator registry */\n registryTopicId: string;\n /** Cache TTL in milliseconds (default: 60000 = 1 minute) */\n cacheTtlMs?: number;\n /** Custom mirror node URL (optional) */\n mirrorNodeUrl?: string;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Cached validators data\n */\ninterface ValidatorCache {\n validators: ValidatorInfo[];\n lastUpdated: number;\n}\n\n/**\n * Validator Discovery Client\n *\n * Discovers validators by reading the HCS validator registry topic\n * via Hedera mirror node API.\n *\n * @example\n * ```typescript\n * const discovery = new ValidatorDiscoveryClient({\n * network: 'testnet',\n * registryTopicId: '0.0.123456',\n * });\n *\n * const validators = await discovery.getValidators();\n * const randomValidator = await discovery.getRandomValidator();\n * ```\n */\nexport class ValidatorDiscoveryClient {\n private readonly mirrorNode: MirrorNodeClient;\n private readonly registryTopicId: string;\n private readonly cacheTtlMs: number;\n private cache: ValidatorCache | null = null;\n\n constructor(config: ValidatorDiscoveryConfig) {\n const mirrorNodeUrl = config.mirrorNodeUrl || MIRROR_NODE_URLS[config.network];\n if (!mirrorNodeUrl) {\n throw new Error(`Unknown network: ${config.network}`);\n }\n\n this.mirrorNode = new MirrorNodeClient({\n baseUrl: mirrorNodeUrl,\n allowInsecure: config.allowInsecure,\n });\n this.registryTopicId = config.registryTopicId;\n this.cacheTtlMs = config.cacheTtlMs ?? 60000; // 1 minute default\n }\n\n /**\n * Get all active validators from the registry\n *\n * Results are cached for efficiency. Use `forceRefresh` to bypass cache.\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns List of active validators\n */\n async getValidators(forceRefresh = false): Promise<ValidatorInfo[]> {\n // Return cached data if valid\n if (!forceRefresh && this.cache && this.isCacheValid()) {\n return this.cache.validators;\n }\n\n // Fetch from mirror node\n const messages = await this.mirrorNode.getAllTopicMessages(\n this.registryTopicId,\n 500 // Max messages to fetch\n );\n\n // Parse and deduplicate validators\n const validatorMap = new Map<string, ValidatorInfo>();\n const leftValidators = new Set<string>();\n\n // Process messages (newest first since we fetch desc order)\n for (const msg of messages) {\n try {\n const content = MirrorNodeClient.decodeMessage(msg.message);\n const raw = JSON.parse(content) as Record<string, unknown>;\n const entry = normalizeRegistryEntry(raw);\n if (!entry) continue;\n\n // Track leave events\n if (entry.messageType === 'validator.leave') {\n leftValidators.add(entry.nodeId);\n continue;\n }\n\n // Skip if validator has left\n if (leftValidators.has(entry.nodeId)) {\n continue;\n }\n\n // Keep only the latest entry per nodeId\n if (!validatorMap.has(entry.nodeId)) {\n validatorMap.set(entry.nodeId, entry);\n }\n } catch {\n // Skip unparseable messages\n continue;\n }\n }\n\n const validators = Array.from(validatorMap.values());\n\n // Update cache\n this.cache = {\n validators,\n lastUpdated: Date.now(),\n };\n\n return validators;\n }\n\n /**\n * Get validators with API endpoints available\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validators with apiEndpoint configured\n */\n async getValidatorsWithEndpoints(forceRefresh = false): Promise<ValidatorInfo[]> {\n const validators = await this.getValidators(forceRefresh);\n return validators.filter((v) => v.networkEndpoints?.apiEndpoint);\n }\n\n /**\n * Get a random validator from the registry\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Random validator info or null if none available\n */\n async getRandomValidator(forceRefresh = false): Promise<ValidatorInfo | null> {\n const validators = await this.getValidatorsWithEndpoints(forceRefresh);\n\n if (validators.length === 0) {\n return null;\n }\n\n // Use crypto.getRandomValues for cryptographically secure random selection\n const randomBytes = new Uint32Array(1);\n crypto.getRandomValues(randomBytes);\n const randomIndex = randomBytes[0] % validators.length;\n return validators[randomIndex];\n }\n\n /**\n * Get a random validator API endpoint URL\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Random validator API URL or null if none available\n */\n async getRandomValidatorUrl(forceRefresh = false): Promise<string | null> {\n const validator = await this.getRandomValidator(forceRefresh);\n return validator?.networkEndpoints?.apiEndpoint ?? null;\n }\n\n /**\n * Get validator by node ID\n *\n * @param nodeId - Validator node ID (e.g., 'validator-1')\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validator info or null if not found\n */\n async getValidatorByNodeId(nodeId: string, forceRefresh = false): Promise<ValidatorInfo | null> {\n const validators = await this.getValidators(forceRefresh);\n return validators.find((v) => v.nodeId === nodeId) ?? null;\n }\n\n /**\n * Get validators by capability\n *\n * @param capability - Required capability (e.g., 'hedera', 'xrpl', 'dkg')\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validators with the specified capability\n */\n async getValidatorsByCapability(\n capability: string,\n forceRefresh = false\n ): Promise<ValidatorInfo[]> {\n const validators = await this.getValidatorsWithEndpoints(forceRefresh);\n return validators.filter((v) => v.capabilities?.includes(capability));\n }\n\n /**\n * Clear the validator cache\n */\n clearCache(): void {\n this.cache = null;\n }\n\n /**\n * Check if cache is still valid\n */\n private isCacheValid(): boolean {\n if (!this.cache) return false;\n return Date.now() - this.cache.lastUpdated < this.cacheTtlMs;\n }\n}\n\n/**\n * Normalize a raw registry message into a ValidatorInfo.\n *\n * Accepts two shapes observed on real HCS registry topics:\n *\n * 1. Canonical (emitted by chain-hedera ValidatorRegistryService):\n * { messageType: 'validator.join'|'validator.leave'|'validator.update',\n * nodeId, networkEndpoints: { apiEndpoint, ... }, ... }\n *\n * 2. Legacy / multisig-consensus (emitted by ops / genesis scripts):\n * { type: 'validator.register', validatorId, endpoint, capabilities,\n * publicKey, accountId, network, ... }\n *\n * Token-scoped validator registrations (validatorType === 'token') are ignored\n * — those are DAO token validators, not node validators. Returns null when the\n * entry doesn't represent a node validator.\n */\nfunction normalizeRegistryEntry(raw: Record<string, unknown>): ValidatorInfo | null {\n // Canonical shape: already a ValidatorInfo\n if (raw.messageType && typeof raw.nodeId === 'string') {\n return raw as unknown as ValidatorInfo;\n }\n\n // Legacy shape: { type: 'validator.register', validatorId, endpoint, ... }\n if (raw.type === 'validator.register') {\n // Skip token validator registrations - they aren't nodes\n if (raw.validatorType && raw.validatorType !== undefined && raw.validatorType !== null) {\n if (typeof raw.validatorType === 'string' && raw.validatorType !== 'node') {\n return null;\n }\n }\n\n const nodeId =\n (typeof raw.validatorId === 'string' && raw.validatorId) ||\n (typeof raw.nodeId === 'string' && raw.nodeId) ||\n null;\n if (!nodeId) return null;\n\n const endpoint = typeof raw.endpoint === 'string' ? raw.endpoint : undefined;\n if (!endpoint) return null;\n\n const capabilities = Array.isArray(raw.capabilities)\n ? (raw.capabilities as unknown[]).filter((c): c is string => typeof c === 'string')\n : undefined;\n\n return {\n validatorTimestamp: typeof raw.timestamp === 'string' ? raw.timestamp : '',\n nodeId,\n type: 'consensus',\n networkEndpoints: { apiEndpoint: endpoint },\n publicKey: typeof raw.publicKey === 'string' ? raw.publicKey : undefined,\n capabilities,\n metadata: {},\n registeredAt: typeof raw.timestamp === 'string' ? raw.timestamp : '',\n messageType: 'validator.join',\n };\n }\n\n // Unknown / unrelated message type (e.g., token validator registrations)\n return null;\n}\n","/**\n * Cluster Discovery Client.\n *\n * SDK-side consumer of the service-registry distribution layer\n * (validator `GET /api/v3/discovery/clusters`). Instead of pinning one\n * baseUrl, the caller supplies a bootstrap-seed list and the client\n * random-picks an active cluster per request, so SDK consumers automatically\n * follow permissionless cluster join/leave without code edits.\n *\n * Resolution chain:\n * 1. HTTP fetch of `/api/v3/discovery/clusters` from each bootstrap seed\n * in order; take the first successful response.\n * 2. (Optional) HCS trust-anchor membership cross-check — verify that\n * every returned nodeId appears in the HCS validator registry and\n * that the publicKey matches. A bootstrap seed cannot inject a rogue\n * cluster whose nodeIds aren't on-chain.\n * 3. Random-pick over the verified set.\n *\n * The {@link ValidatorDiscoveryClient} (HCS mirror-node read, per-validator\n * granularity) stays available as the HCS-direct fallback / trust anchor —\n * it is the only path that doesn't require any HTTP-reachable cluster.\n */\n\nimport { ValidatorDiscoveryClient, type ValidatorDiscoveryConfig } from './validator-discovery';\n\n/**\n * Cluster-level endpoint metadata as exposed by the validator's\n * `/api/v3/discovery/clusters` HTTP endpoint. Mirrors the on-wire shape\n * defined server-side by the service-registry cluster-endpoints payload.\n */\nexport interface ClusterEndpointsView {\n clusterId: string;\n gatewayUrl: string;\n harborUrl?: string;\n natsUrl?: string;\n publicIp?: string;\n region?: string;\n}\n\n/**\n * Cluster info as returned by `getClusters()`. `nodeIds` are the validator\n * nodeIds whose announcements contributed to this cluster's record —\n * useful for HCS trust-anchor cross-checking.\n */\nexport interface ClusterInfo {\n clusterId: string;\n endpoints: ClusterEndpointsView;\n nodeIds: string[];\n}\n\nexport interface ClusterDiscoveryConfig {\n /**\n * Bootstrap seeds — fully-qualified URLs that respond to\n * `GET /api/v3/discovery/clusters`. The SDK tries them in order on each\n * refresh; the first success wins. **Order is the operator's\n * preference signal** (e.g., list a Cloudflare-fronted hostname first,\n * then individual cluster ingress IPs as backstops).\n */\n bootstrap: string[];\n\n /** Cache TTL in milliseconds (default: 60_000 — same as HCS path). */\n cacheTtlMs?: number;\n\n /**\n * Per-bootstrap fetch timeout in milliseconds (default: 5_000). Keep\n * tight: when the first seed is unreachable, we want to fall through\n * to the next without blocking the SDK call for long.\n */\n fetchTimeoutMs?: number;\n\n /**\n * Optional HCS trust anchor. When supplied, the SDK lazily loads the\n * on-chain validator-registry set and verifies that:\n *\n * - every cluster's `nodeIds` appears in the HCS registry, and\n * - the on-chain `publicKey` for each nodeId matches the HTTP\n * response (when the discovery endpoint exposes it).\n *\n * Clusters that fail the cross-check are dropped silently. A logged\n * warning would normally accompany this, but the SDK is environment-\n * agnostic (browser, Node, edge) — surfacing via the returned set is\n * the conservative contract.\n *\n * The anchor performs membership cross-checking only; cryptographic\n * per-record signature verification of the DKG-signed payload is not\n * performed here.\n */\n trustAnchor?: ValidatorDiscoveryConfig;\n\n /** Allow HTTP (insecure) connections — only for local development. */\n allowInsecure?: boolean;\n}\n\ninterface ClusterCache {\n clusters: ClusterInfo[];\n lastUpdated: number;\n}\n\n/**\n * Cluster Discovery Client — HTTP-driven, random-pick across an active\n * cluster set with optional on-chain trust anchor.\n */\nexport class ClusterDiscoveryClient {\n private readonly bootstrap: string[];\n private readonly cacheTtlMs: number;\n private readonly fetchTimeoutMs: number;\n private readonly allowInsecure: boolean;\n private readonly trustAnchorClient: ValidatorDiscoveryClient | null;\n private cache: ClusterCache | null = null;\n\n constructor(config: ClusterDiscoveryConfig) {\n if (!config.bootstrap || config.bootstrap.length === 0) {\n throw new Error('ClusterDiscoveryClient: bootstrap must list at least one seed URL');\n }\n if (!config.allowInsecure) {\n for (const seed of config.bootstrap) {\n if (!seed.startsWith('https://')) {\n throw new Error(\n `ClusterDiscoveryClient: bootstrap seed \"${seed}\" is not HTTPS. ` +\n `Set allowInsecure=true for local development only.`,\n );\n }\n }\n }\n this.bootstrap = config.bootstrap;\n this.cacheTtlMs = config.cacheTtlMs ?? 60_000;\n this.fetchTimeoutMs = config.fetchTimeoutMs ?? 5_000;\n this.allowInsecure = config.allowInsecure ?? false;\n this.trustAnchorClient = config.trustAnchor\n ? new ValidatorDiscoveryClient(config.trustAnchor)\n : null;\n }\n\n /**\n * Fetch the active-cluster set, with caching.\n *\n * Tries each bootstrap seed in order until one returns HTTP 200 with a\n * parseable cluster list. If all seeds fail, throws — callers can\n * handle by falling back to a previously-cached value if they want,\n * or by initializing with multiple seeds.\n */\n async getClusters(forceRefresh = false): Promise<ClusterInfo[]> {\n if (!forceRefresh && this.cache && this.isCacheValid()) {\n return this.cache.clusters;\n }\n\n const fetched = await this.fetchFromFirstAvailableSeed();\n const verified = this.trustAnchorClient ? await this.verifyAgainstTrustAnchor(fetched) : fetched;\n\n this.cache = { clusters: verified, lastUpdated: Date.now() };\n return verified;\n }\n\n /**\n * Random pick over the active-cluster set. Returns `null` when no\n * cluster passes verification (empty registry / all-rejected anchor).\n *\n * Uses `crypto.getRandomValues` when available (browsers, Deno, modern\n * Node) for cryptographic-strength randomness; `Math.random` is a\n * fallback for older runtimes where `globalThis.crypto` is undefined.\n * Discovery isn't cryptographically sensitive — load distribution is\n * the goal here.\n */\n async getRandomCluster(forceRefresh = false): Promise<ClusterInfo | null> {\n const clusters = await this.getClusters(forceRefresh);\n if (clusters.length === 0) return null;\n return clusters[this.pickRandomIndex(clusters.length)];\n }\n\n /**\n * Convenience wrapper returning just the gateway URL of a random\n * active cluster. Feed this to `BaasClient` (the host BaaS tier) — e.g.\n * `new BaasClient({ hostUrl, pathPrefix: '/host' })` or\n * `BaasClient.connectToCluster({ network })`. Do NOT feed it to\n * `SmartEngineClient`: that client's raw `/api/v3/*` tier is un-ingressed at\n * the gateway and will 404 (it requires an explicit `validatorBaseUrl`).\n */\n async getRandomGatewayUrl(forceRefresh = false): Promise<string | null> {\n const cluster = await this.getRandomCluster(forceRefresh);\n return cluster?.endpoints.gatewayUrl ?? null;\n }\n\n /** Per-clusterId lookup, useful for \"stick the SDK to cluster X\" flows. */\n async getClusterById(clusterId: string, forceRefresh = false): Promise<ClusterInfo | null> {\n const clusters = await this.getClusters(forceRefresh);\n return clusters.find((c) => c.clusterId === clusterId) ?? null;\n }\n\n clearCache(): void {\n this.cache = null;\n }\n\n private isCacheValid(): boolean {\n if (!this.cache) return false;\n return Date.now() - this.cache.lastUpdated < this.cacheTtlMs;\n }\n\n private async fetchFromFirstAvailableSeed(): Promise<ClusterInfo[]> {\n const errors: string[] = [];\n for (const seed of this.bootstrap) {\n try {\n return await this.fetchClustersFromSeed(seed);\n } catch (err) {\n errors.push(`${seed}: ${(err as Error).message}`);\n }\n }\n throw new Error(\n `ClusterDiscoveryClient: no bootstrap seed reachable. Attempts:\\n ${errors.join('\\n ')}`,\n );\n }\n\n private async fetchClustersFromSeed(seed: string): Promise<ClusterInfo[]> {\n const url = `${seed.replace(/\\/$/, '')}/api/v3/discovery/clusters`;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.fetchTimeoutMs);\n try {\n const res = await fetch(url, { signal: ctrl.signal });\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`);\n }\n const body = (await res.json()) as {\n clusters?: Array<{\n clusterId?: unknown;\n endpoints?: Record<string, unknown>;\n nodeIds?: unknown;\n }>;\n };\n if (!Array.isArray(body.clusters)) {\n throw new Error('response missing clusters[]');\n }\n return body.clusters\n .map((c) => this.normalizeClusterEntry(c))\n .filter((c): c is ClusterInfo => c !== null);\n } finally {\n clearTimeout(timer);\n }\n }\n\n private normalizeClusterEntry(raw: {\n clusterId?: unknown;\n endpoints?: Record<string, unknown>;\n nodeIds?: unknown;\n }): ClusterInfo | null {\n if (typeof raw.clusterId !== 'string' || !raw.clusterId) return null;\n if (!raw.endpoints || typeof raw.endpoints !== 'object') return null;\n const ep = raw.endpoints as Record<string, unknown>;\n if (typeof ep.gatewayUrl !== 'string' || !ep.gatewayUrl) return null;\n if (!this.allowInsecure && !ep.gatewayUrl.startsWith('https://')) {\n // Drop non-HTTPS gateways in secure mode — never silently accept\n // a downgrade attack via a poisoned bootstrap response.\n return null;\n }\n const nodeIds = Array.isArray(raw.nodeIds)\n ? raw.nodeIds.filter((n): n is string => typeof n === 'string')\n : [];\n return {\n clusterId: raw.clusterId,\n endpoints: {\n clusterId: raw.clusterId,\n gatewayUrl: ep.gatewayUrl,\n harborUrl: typeof ep.harborUrl === 'string' ? ep.harborUrl : undefined,\n natsUrl: typeof ep.natsUrl === 'string' ? ep.natsUrl : undefined,\n publicIp: typeof ep.publicIp === 'string' ? ep.publicIp : undefined,\n region: typeof ep.region === 'string' ? ep.region : undefined,\n },\n nodeIds,\n };\n }\n\n /**\n * Cross-check the HTTP-fetched cluster set against the HCS validator\n * registry. Clusters whose nodeIds are not on-chain are dropped.\n *\n * Two failure modes are deliberately silent here:\n * - the HCS read itself throws → original list is returned\n * un-verified. Trust-anchor is advisory; a network partition\n * between SDK and Hedera mirror shouldn't strand the SDK.\n * - the HCS read returns empty (mirror node lag, wrong topicId)\n * → original list is returned. Better to keep working off\n * possibly-stale-but-real data than reject every cluster.\n *\n * Both behaviors are why this is called \"trust *anchor*\", not\n * \"trust gate\". Crypto-strong gating is a follow-up.\n */\n private async verifyAgainstTrustAnchor(clusters: ClusterInfo[]): Promise<ClusterInfo[]> {\n if (!this.trustAnchorClient || clusters.length === 0) return clusters;\n let onChainNodeIds: Set<string>;\n try {\n const validators = await this.trustAnchorClient.getValidators();\n if (validators.length === 0) return clusters;\n onChainNodeIds = new Set(validators.map((v) => v.nodeId));\n } catch {\n return clusters;\n }\n return clusters.filter((c) => {\n if (c.nodeIds.length === 0) {\n // The discovery endpoint surfaces nodeIds for verifiability.\n // An entry with none was either (a) emitted by an older\n // validator, or (b) crafted to evade the check. Either way,\n // drop it to keep the contract sharp.\n return false;\n }\n return c.nodeIds.some((id) => onChainNodeIds.has(id));\n });\n }\n\n private pickRandomIndex(n: number): number {\n if (n <= 1) return 0;\n const g = (globalThis as { crypto?: { getRandomValues?: (a: Uint32Array) => Uint32Array } }).crypto;\n if (g?.getRandomValues) {\n const buf = new Uint32Array(1);\n g.getRandomValues(buf);\n return buf[0] % n;\n }\n return Math.floor(Math.random() * n);\n }\n}\n","/**\n * Shared HTTP Client\n *\n * Unified HTTP layer used by all SDK clients (SmartEngineClient, SmartGatewayClient, BaasClient).\n * Handles authentication headers, timeouts, error handling, and multipart uploads.\n */\n\n/**\n * Per-call request options. Lets a single request carry extra context the\n * client-wide config can't express.\n *\n * The motivating case is multi-tenant BaaS: an app-as-proxy holds its OWN\n * Bearer auth (set once on the client), but each downstream request acts on\n * behalf of a specific END USER whose session token must reach the host for\n * per-user metering/quota. That token is per-call, not per-client — so it\n * rides here as `customerToken` and is attached as `X-Customer-Session-Token`\n * for this request only.\n */\nexport type HttpCallOptions = {\n /**\n * End-user customer-session token, forwarded to the host as\n * `X-Customer-Session-Token` for this request only. Used by app-as-proxy\n * flows so the host meters the end user, not the app.\n */\n customerToken?: string;\n /**\n * Act ON BEHALF OF an end user for OWNER-GATED routes (e.g. agents\n * fund/withdraw/execute). The value is that user's Mode-1 customer-session\n * JWT (the `token` from `baas.customerSession.verify()`). It is forwarded\n * verbatim as BOTH `Authorization: Bearer <jwt>` (so the host pins the caller\n * to that user) AND `X-Customer-Session-Claim` (the host's claim-resolution\n * header). No client-side signing: owner routes accept only this Mode-1 JWT —\n * the Mode-2 BLS claim is minted host-side and is rejected on owner routes.\n * Distinct from {@link customerToken} (metering-only `X-Customer-Session-Token`).\n */\n onBehalfOf?: string;\n /** Extra per-call headers (escape hatch); merged last, wins on conflict. */\n headers?: Record<string, string>;\n};\n\n/**\n * HTTP client interface consumed by all sub-clients.\n * Sub-clients only depend on this interface, never on fetch directly.\n *\n * Every method takes an optional trailing {@link HttpCallOptions} so a single\n * request can carry an end-user `customerToken` without mutating client state.\n */\nexport type HttpClient = {\n post<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n get<T = any>(path: string, opts?: HttpCallOptions): Promise<T>;\n put<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n patch<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n delete<T = any>(path: string, opts?: HttpCallOptions): Promise<T>;\n /**\n * GET a non-JSON body. Returns the raw response text without attempting\n * to parse it. Required for endpoints that emit Prometheus exposition,\n * plain logs, or any other `text/*` content-type — the default\n * {@link HttpClient.get} eagerly `JSON.parse`s and would corrupt those\n * payloads.\n */\n getText(path: string, opts?: HttpCallOptions): Promise<string>;\n /**\n * GET a binary body as raw bytes. Returns a {@link Uint8Array} without any\n * decoding — required for file downloads and any non-text content where the\n * default {@link HttpClient.get}'s `JSON.parse` would corrupt the payload.\n */\n getBinary(path: string, opts?: HttpCallOptions): Promise<Uint8Array>;\n /**\n * GET a binary body WITH its response metadata — the bytes plus the\n * `content-type` and (parsed) `content-disposition` filename. {@link getBinary}\n * discards the headers; this variant is for download endpoints whose caller\n * must echo the content-type back (the host derives it from the stored file's\n * metadata, so a bytes-only download can't recover it).\n */\n getBinaryWithMeta(\n path: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }>;\n /**\n * Upload a file with `multipart/form-data`.\n *\n * `fieldName` defaults to `'file'` for back-compat; callers whose\n * server-side handler uses a different multer field name (e.g.\n * `'bundle'` for SPA tarball uploads) MUST override.\n */\n upload<T = any>(\n path: string,\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n fieldName?: string,\n opts?: HttpCallOptions,\n ): Promise<T>;\n /**\n * Update the Bearer auth token used on subsequent requests. Pass\n * `undefined` to clear the Authorization header (e.g. on logout).\n *\n * Typed accessor — replaces the previous `(client as any).authToken`\n * peek that scattered across the SDK.\n */\n setAuthToken(token: string | undefined): void;\n /**\n * Return the currently configured Bearer auth token, or `undefined`\n * when no token is set.\n */\n getAuthToken(): string | undefined;\n};\n\n/**\n * Configuration for creating an HttpClient instance\n */\nexport type HttpClientConfig = {\n /** Base URL for all requests (e.g. https://validator.example.com/api/v3) */\n baseUrl: string;\n /** Bearer token for Authorization header */\n authToken?: string;\n /** API key for X-API-Key header */\n apiKey?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /**\n * Optional hook invoked when a request returns 401 Unauthorized. Lets the\n * client owner refresh the session (e.g. re-run the web3 challenge-response\n * and call {@link HttpClient.setAuthToken}); the failed request is then\n * retried once with the new token. Calls to `/api/v3/{,baas/}auth/*` are excluded so the\n * refresh flow itself can never recurse, and concurrent 401s share a single\n * in-flight refresh. Without this hook a 401 propagates unchanged.\n */\n onUnauthorized?: () => Promise<void>;\n};\n\n/**\n * SDK-level error class used across all clients\n */\nexport class SdkHttpError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: any\n ) {\n super(message);\n this.name = 'SdkHttpError';\n }\n\n /**\n * True for transient failures worth retrying: a 5xx, a 429 (rate limit), a 408\n * (timeout), or a 0 (network/abort). Deterministic 4xx client errors are not.\n */\n get isRetryable(): boolean {\n return (\n this.statusCode === 0 ||\n this.statusCode === 408 ||\n this.statusCode === 429 ||\n this.statusCode >= 500\n );\n }\n}\n\n/**\n * Create a concrete HttpClient from config.\n * This is the single place where `fetch` is called in the entire SDK.\n */\nexport function createHttpClient(config: HttpClientConfig): HttpClient {\n const timeout = config.timeout ?? 30000;\n\n function getHeaders(contentType?: string, opts?: HttpCallOptions): Record<string, string> {\n const headers: Record<string, string> = {};\n if (contentType) {\n headers['Content-Type'] = contentType;\n }\n if (config.authToken) {\n headers['Authorization'] = `Bearer ${config.authToken}`;\n }\n if (config.apiKey) {\n headers['X-API-Key'] = config.apiKey;\n }\n // Per-call end-user token for app-as-proxy metering. Distinct from the\n // app's own Authorization above — both can ride the same request.\n if (opts?.customerToken) {\n headers['X-Customer-Session-Token'] = opts.customerToken;\n }\n // Owner-acting: forward the end user's Mode-1 JWT as the Authorization\n // bearer (overriding the app token for this request) AND the host's\n // claim-resolution header. Verbatim pass-through — no signing.\n if (opts?.onBehalfOf) {\n headers['Authorization'] = `Bearer ${opts.onBehalfOf}`;\n headers['X-Customer-Session-Claim'] = opts.onBehalfOf;\n }\n if (opts?.headers) {\n Object.assign(headers, opts.headers);\n }\n return headers;\n }\n\n /** Update auth token (e.g. after authentication flow) */\n function setAuthToken(token: string | undefined): void {\n config.authToken = token;\n }\n\n /** Read the current auth token (or undefined when none is set). */\n function getAuthToken(): string | undefined {\n return config.authToken;\n }\n\n async function request<T>(method: string, path: string, body?: unknown, opts?: HttpCallOptions): Promise<T> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const init: RequestInit = {\n method,\n headers: getHeaders('application/json', opts),\n signal: controller.signal,\n };\n\n if (body !== undefined) {\n init.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, init);\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({})) as Record<string, unknown>;\n throw new SdkHttpError(\n (errorData.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n // Handle empty responses (204 No Content)\n const text = await response.text();\n if (!text) return undefined as T;\n return JSON.parse(text) as T;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getText(path: string, opts?: HttpCallOptions): Promise<string> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // The error path still tries JSON — server-side error responses\n // are JSON even when the success path is text/plain (e.g.\n // Prometheus metrics). Fall back to text if that fails.\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n return await response.text();\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getBinary(path: string, opts?: HttpCallOptions): Promise<Uint8Array> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // Error bodies stay JSON even when the success body is binary.\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n // Raw bytes — never JSON.parse / text-decode, which would corrupt a file.\n return new Uint8Array(await response.arrayBuffer());\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getBinaryWithMeta(\n path: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n const bytes = new Uint8Array(await response.arrayBuffer());\n const contentType = response.headers.get('content-type') ?? undefined;\n // Pull `filename` out of content-disposition (filename* RFC 5987 or plain).\n const disposition = response.headers.get('content-disposition') ?? '';\n const match = /filename\\*?=(?:UTF-8'')?\"?([^\"\\n;]+)\"?/i.exec(disposition);\n const filename = match ? decodeURIComponent(match[1].trim()) : undefined;\n return { bytes, contentType, filename };\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function upload<T>(\n path: string,\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n fieldName: string = 'file',\n opts?: HttpCallOptions,\n ): Promise<T> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n // Uploads get 2x timeout\n const timeoutId = setTimeout(() => controller.abort(), timeout * 2);\n\n try {\n const formData = new FormData();\n const blob = file instanceof Blob ? file : new Blob([new Uint8Array(file as Buffer)]);\n formData.append(fieldName, blob, filename);\n\n if (metadata) {\n for (const [key, value] of Object.entries(metadata)) {\n formData.append(key, value);\n }\n }\n\n // Don't set Content-Type — browser/node will set multipart boundary\n const headers: Record<string, string> = {};\n if (config.authToken) {\n headers['Authorization'] = `Bearer ${config.authToken}`;\n }\n if (config.apiKey) {\n headers['X-API-Key'] = config.apiKey;\n }\n if (opts?.customerToken) {\n headers['X-Customer-Session-Token'] = opts.customerToken;\n }\n if (opts?.onBehalfOf) {\n headers['Authorization'] = `Bearer ${opts.onBehalfOf}`;\n headers['X-Customer-Session-Claim'] = opts.onBehalfOf;\n }\n if (opts?.headers) {\n Object.assign(headers, opts.headers);\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: formData,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({})) as Record<string, unknown>;\n throw new SdkHttpError(\n (errorData.message as string) || `Upload error: ${response.status} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n return response.json() as Promise<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Upload timeout', 408);\n }\n throw new SdkHttpError(`Upload error: ${err.message}`, 0, error);\n }\n }\n\n // Transparent session refresh: when a request 401s, invoke `onUnauthorized`\n // (which re-authenticates and updates the token) and retry the request once.\n // Concurrent 401s share a single in-flight refresh; `/api/v3/{,baas/}auth/*` is excluded\n // so the refresh's own challenge/verify can never trigger another refresh.\n let reauthInFlight: Promise<void> | null = null;\n async function withAuthRetry<T>(path: string, op: () => Promise<T>): Promise<T> {\n try {\n return await op();\n } catch (error) {\n const refreshable =\n !!config.onUnauthorized &&\n !path.startsWith('/api/v3/baas/auth/') &&\n !path.startsWith('/api/v3/auth/') &&\n error instanceof SdkHttpError &&\n error.statusCode === 401;\n if (!refreshable) throw error;\n if (!reauthInFlight) {\n reauthInFlight = Promise.resolve(config.onUnauthorized!()).finally(() => {\n reauthInFlight = null;\n });\n }\n try {\n await reauthInFlight;\n } catch {\n throw error; // refresh failed → surface the original 401\n }\n return await op(); // retry once with the refreshed token\n }\n }\n\n const client: HttpClient = {\n post: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('POST', path, body, opts)),\n get: <T>(path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('GET', path, undefined, opts)),\n put: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('PUT', path, body, opts)),\n patch: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('PATCH', path, body, opts)),\n delete: <T>(path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('DELETE', path, undefined, opts)),\n getText: (path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => getText(path, opts)),\n getBinary: (path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => getBinary(path, opts)),\n getBinaryWithMeta: (path: string, opts?: HttpCallOptions) =>\n withAuthRetry(path, () => getBinaryWithMeta(path, opts)),\n upload: ((path: string, file: Blob | Buffer, filename: string, metadata?: Record<string, string>, fieldName?: string, opts?: HttpCallOptions) =>\n withAuthRetry(path, () => upload(path, file, filename, metadata, fieldName, opts))) as HttpClient['upload'],\n setAuthToken,\n getAuthToken,\n };\n\n return client;\n}\n\n/**\n * Encode a path parameter to prevent injection attacks.\n * Removes path traversal attempts and encodes special characters.\n */\nexport function encodePathParam(param: string): string {\n return encodeURIComponent(param).replace(/%2F/gi, '');\n}\n\n/**\n * Body shape of an HTTP 403 `rule_rejected` envelope raised by the validator's\n * rule-enforcement hooks (e.g. the NFT-transfer hook):\n *\n * ```json\n * { \"error\": \"rule_rejected\", \"reason\": \"<atom-reason>\", \"ruleAtoms\": [\"SoulboundNftAtom\"] }\n * ```\n */\nexport interface RuleRejectedDetails {\n /** Literal discriminator — always 'rule_rejected'. */\n error: 'rule_rejected';\n /** Atom-supplied reason string, e.g. 'soulbound_transfer_rejected'. */\n reason: string;\n /** Names of the rule atoms that fired the rejection. */\n ruleAtoms: string[];\n}\n\n/**\n * Type predicate: narrows an unknown error to a 403 `rule_rejected` envelope.\n *\n * Use in smart-app code to branch on rules-engine rejections without\n * inspecting raw HTTP details:\n *\n * ```typescript\n * try {\n * await sdk.transactions.prepareNftTransfer({ chain: 'hedera', ... });\n * } catch (err) {\n * if (isRuleRejected(err)) {\n * console.log(`Blocked by ${err.details.ruleAtoms.join(', ')}: ${err.details.reason}`);\n * return;\n * }\n * throw err;\n * }\n * ```\n *\n * Status-code AND shape are both checked — non-403 errors and 403s without\n * the rule_rejected envelope (e.g. plain auth failures) return false.\n *\n * @public SDK-SOULBOUND-1\n */\nexport function isRuleRejected(\n err: unknown,\n): err is SdkHttpError & { details: RuleRejectedDetails } {\n if (!(err instanceof SdkHttpError)) return false;\n if (err.statusCode !== 403) return false;\n const d = err.details as unknown;\n if (d === null || typeof d !== 'object') return false;\n const obj = d as Record<string, unknown>;\n if (obj.error !== 'rule_rejected') return false;\n if (typeof obj.reason !== 'string') return false;\n if (!Array.isArray(obj.ruleAtoms)) return false;\n return obj.ruleAtoms.every((a) => typeof a === 'string');\n}\n\n/**\n * Type predicate: narrows an unknown error to the SDK's {@link SdkHttpError}.\n * Lets consumers branch on SDK HTTP failures without importing the class purely\n * for an `instanceof` check.\n */\nexport function isSmartEngineSdkError(err: unknown): err is SdkHttpError {\n return err instanceof SdkHttpError;\n}\n\n/**\n * Normalize any thrown value into an HTTP-shaped record a server (e.g. a NestJS\n * exception filter) can re-emit. An {@link SdkHttpError} maps verbatim; a sub-400\n * status (0 network / unexpected) is clamped to 502 Bad Gateway (a failed\n * upstream call is a gateway error, not a success); a non-SDK error becomes 500.\n * `isRetryable` follows {@link SdkHttpError.isRetryable}.\n */\nexport function toHttpError(err: unknown): {\n statusCode: number;\n code: string;\n message: string;\n isRetryable: boolean;\n details?: unknown;\n} {\n if (isSmartEngineSdkError(err)) {\n return {\n statusCode: err.statusCode >= 400 ? err.statusCode : 502,\n code: 'SDK_HTTP_ERROR',\n message: err.message,\n isRetryable: err.isRetryable,\n details: err.details,\n };\n }\n const message = err instanceof Error ? err.message : 'Unknown error';\n return { statusCode: 500, code: 'INTERNAL_ERROR', message, isRetryable: false };\n}\n","/**\n * Discovery Sub-Client — `client.discovery.*`\n *\n * Thin typed wrapper over the validator's `/api/v3/discovery/*` HTTP\n * surface. Backs the cluster-registry browser endpoints (active set,\n * all-nodes debug view, per-nodeId lookup) **and** the platform-image\n * manifest discovery endpoints (list, per-image versions, single-version\n * fetch, verify gate, signed envelopes).\n *\n * Trust model — discovery endpoints are intentionally `@Public`\n * server-side:\n *\n * - Cluster registry rows are signed cluster-internal data; the\n * advertised `publicKey` is the SDK's verification anchor.\n * - Platform-image manifests are DKG-threshold signed at publish time;\n * pulling them by SHA-256 digest + content-addressed verification\n * keeps the read surface authentication-free.\n *\n * The {@link ClusterDiscoveryClient} in this same module already wraps\n * the active-set endpoint for the bootstrap → random-pick connect flow.\n * This client exists for callers that want the **typed** endpoints\n * directly (operator dashboards, supply-chain auditors, smart-apps\n * inspecting validator membership).\n *\n * Mounted at `client.discovery` over the `/api/v3`-rooted shared\n * `HttpClient` — every method here resolves to `/api/v3/discovery/...`.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\n\n/**\n * Cluster endpoints payload, mirrored from the server-side\n * `ClusterEndpointsPayload` shape.\n *\n * Re-declared here (not imported from `./cluster-discovery`) so this\n * client stays compileable in environments that tree-shake the\n * mirror-node / HCS path out.\n */\nexport type DiscoveryClusterEndpoints = {\n clusterId: string;\n gatewayUrl: string;\n harborUrl?: string;\n natsUrl?: string;\n publicIp?: string;\n region?: string;\n};\n\n/**\n * Active-set cluster row returned by `GET /api/v3/discovery/clusters`.\n *\n * `nodeIds` is the validator-pod identity set whose announcements\n * contributed to this cluster's record — the HCS trust-anchor uses\n * these for cross-checking against the on-chain validator registry.\n */\nexport type DiscoveryClusterRecord = {\n clusterId: string;\n endpoints: DiscoveryClusterEndpoints;\n nodeIds: string[];\n};\n\n/**\n * Per-node registry row returned by `GET /api/v3/discovery/clusters/all`\n * and `GET /api/v3/discovery/clusters/:nodeId`. Carries the publish-time\n * `publicKey` (SDK's verification anchor), the cluster-internal `status`,\n * and the content-addressed envelope CID.\n */\nexport type DiscoveryNodeRecord = {\n nodeId: string;\n publicKey?: string;\n status?: string;\n endpoints: DiscoveryClusterEndpoints;\n endpointsCid: string;\n /** ISO-8601 timestamp of the last cluster-registry event for this node. */\n lastEventTs: string;\n};\n\n/**\n * Platform image manifest — content-addressed kubelet-pull payload.\n * Mirrors `PlatformImageManifest` from `service-registry.events.ts`.\n * Re-declared as an `unknown`-leaning structural type so the SDK does\n * not pull the full server-side schema package into customer bundles.\n */\nexport type DiscoveryPlatformImageManifest = {\n imageName: string;\n version: string;\n sha256digest: string;\n publishedAt: string;\n publisherNodeId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Signed platform-image envelope — manifest + DKG-threshold signature +\n * the cluster's aggregated public key. Used by external re-verifiers\n * that want to independently confirm authenticity without trusting\n * the discovery endpoint.\n */\nexport type DiscoveryPlatformImageEnvelope = {\n manifest: DiscoveryPlatformImageManifest;\n signature: string;\n publicKey: string;\n};\n\n/**\n * Result of the `/verify` gate — whether the supplied `sha256digest`\n * matches the on-record manifest for `(imageName, version)`. The\n * server returns a structured `{ verified, reason? }` object even on\n * mismatch so callers don't have to disambiguate HTTP 200 + 404 + 400.\n */\nexport type DiscoveryVerifyResult = {\n verified: boolean;\n reason?: string;\n};\n\n/**\n * Top-level discovery client.\n *\n * Exposes two namespaces via the `client.discovery` surface:\n *\n * - `clusters` (default — flat methods on this instance):\n * `listClusters` / `listAllClusters` / `getClusterByNode`.\n * - `platformImages` (sub-object): manifest browsing, per-version\n * fetch, content-addressed verify, signed envelope retrieval.\n *\n * The two namespaces share the underlying `/api/v3/discovery` URL\n * prefix; splitting them at the SDK boundary mirrors the server-side\n * controller split (`ServiceRegistryController` + `ImageManifestController`)\n * and keeps the API discoverable in IDE autocomplete.\n *\n * @example List active clusters + drill into platform images\n * ```ts\n * const { clusters } = await client.discovery.listClusters();\n * console.log(`${clusters.length} active clusters in this validator's registry view`);\n *\n * const manifests = await client.discovery.platformImages.list();\n * ```\n */\nexport class DiscoveryClient {\n /** Platform-image manifest discovery endpoints. */\n public readonly platformImages: PlatformImagesClient;\n\n constructor(private readonly http: HttpClient) {\n this.platformImages = new PlatformImagesClient(http);\n }\n\n /**\n * `GET /api/v3/discovery/clusters` — active-set cluster registry,\n * grouped by `clusterId`. This is the same data the bootstrap-seed\n * flow consumes for random-pick connect.\n */\n async listClusters(): Promise<{ clusters: DiscoveryClusterRecord[] }> {\n return this.http.get('/discovery/clusters');\n }\n\n /**\n * `GET /api/v3/discovery/clusters/all` — every node-level record\n * (debug / audit view). Includes nodes that the active-set filter\n * dropped (e.g. recently-departed validators still in the registry's\n * eventual-consistency window).\n */\n async listAllClusters(): Promise<{ records: DiscoveryNodeRecord[] }> {\n return this.http.get('/discovery/clusters/all');\n }\n\n /**\n * `GET /api/v3/discovery/clusters/:nodeId` — per-nodeId registry row.\n * Returns `{ record: null }` (not 404) when the nodeId is unknown to\n * this validator's registry view, so callers can branch without\n * try/catch.\n */\n async getClusterByNode(nodeId: string): Promise<{ record: DiscoveryNodeRecord | null }> {\n return this.http.get(`/discovery/clusters/${encodePathParam(nodeId)}`);\n }\n}\n\n/**\n * Platform-image manifest browser. Mounted under\n * `client.discovery.platformImages`.\n *\n * The kubelet pulls platform images by their `sha256digest` (per-image\n * content-addressed pinning at the deploy boundary); this client lets\n * smart-app builders inspect WHICH digests the cluster has DKG-signed\n * as canonical for `(imageName, version)` pairs.\n */\nexport class PlatformImagesClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /api/v3/discovery/platform-images` — every signed manifest the\n * cluster has on record. One row per `(imageName, version)` pair.\n */\n async list(): Promise<{ manifests: DiscoveryPlatformImageManifest[] }> {\n return this.http.get('/discovery/platform-images');\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/envelopes` — full signed\n * envelopes (manifest + signature + publicKey). Heavier payload than\n * {@link list}; for external re-verifiers that want to independently\n * confirm authenticity.\n */\n async listEnvelopes(): Promise<{ envelopes: DiscoveryPlatformImageEnvelope[] }> {\n return this.http.get('/discovery/platform-images/envelopes');\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName` — every version\n * of a single image. Useful for \"which tags has the cluster\n * authorized?\" queries.\n */\n async get(imageName: string): Promise<{\n imageName: string;\n manifests: DiscoveryPlatformImageManifest[];\n }> {\n return this.http.get(`/discovery/platform-images/${encodePathParam(imageName)}`);\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName/:version` —\n * single signed manifest. Returns `{ manifest: null }` when the\n * `(imageName, version)` pair is unknown.\n */\n async getVersion(\n imageName: string,\n version: string,\n ): Promise<{ manifest: DiscoveryPlatformImageManifest | null }> {\n return this.http.get(\n `/discovery/platform-images/${encodePathParam(imageName)}/${encodePathParam(version)}`,\n );\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName/:version/verify?digest=...`\n * — content-addressed verify gate. Returns `{ verified: true }` only\n * when the supplied SHA-256 digest matches the on-record manifest.\n *\n * Use before pulling an image off a registry to make sure you're\n * about to run cluster-signed bits and not whatever drifted into\n * the registry namespace.\n */\n async verify(\n imageName: string,\n version: string,\n digest: string,\n ): Promise<DiscoveryVerifyResult> {\n return this.http.get(\n `/discovery/platform-images/${encodePathParam(imageName)}/${encodePathParam(\n version,\n )}/verify?digest=${encodeURIComponent(digest)}`,\n );\n }\n}\n","/**\n * Network presets for the Smart Engines SDK.\n *\n * Built so SDK consumers don't have to hand-roll a gateway URL or remember\n * which HCS topic ID is the validator-registry trust anchor. The \"zero-\n * config\" entrypoint flow:\n *\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * network: 'testnet',\n * appId: 'app_abc',\n * });\n * ```\n *\n * ↓ the SDK internally:\n * 1. Resolves `KNOWN_NETWORKS['testnet'].bootstrap` to the canonical\n * `https://gateway.<network>.hsuite.network` entrypoint.\n * 2. Fetches `GET /api/v3/discovery/clusters` from that gateway.\n * 3. Random-picks an active cluster's gatewayUrl.\n * 4. Returns a `BaasClient`/`SmartEngineClient` pointed at that cluster.\n *\n * The on-chain trust-anchor (validator-registry HCS topic) is **per\n * deployment** — the testnet that ships today, a customer-run private\n * testnet, or future mainnet all have different topic IDs. We deliberately\n * do NOT bake a registryTopicId in here; callers who want anchored discovery\n * pass `trustAnchor` explicitly. Callers who don't get the same security\n * guarantees as a plain HTTPS fetch of a public endpoint, which is the same\n * trust model as every other \"talk to gateway.testnet.X\" SDK in the wild.\n */\n\n/** Network identifiers the SDK knows about by name. */\nexport type NetworkName = 'testnet' | 'mainnet';\n\n/** Resolved network preset — what the SDK needs to bootstrap discovery. */\nexport interface NetworkPreset {\n /**\n * Bootstrap seeds for `ClusterDiscoveryClient`. Ordered: first reachable\n * wins. Operators can append fallback URLs locally; the SDK only ships\n * the canonical Cloudflare-fronted gateway here.\n */\n readonly bootstrap: readonly string[];\n}\n\n/**\n * Canonical entrypoints for each supported HSuite network.\n *\n * Update this map (and ship a SDK minor bump) when DNS for a network changes\n * or when a new network goes live. Customers who run their own validators\n * should NOT extend this map — they should pass `bootstrap: [...]` directly.\n */\nexport const KNOWN_NETWORKS: Readonly<Record<NetworkName, NetworkPreset>> = {\n testnet: {\n bootstrap: ['https://gateway.testnet.hsuite.network'],\n },\n mainnet: {\n // Mainnet entrypoint reserved. The SDK still resolves the name so\n // upgrade-by-flipping-NETWORK works; the bootstrap URL is the\n // pre-allocated DNS we own. If mainnet isn't deployed yet, the discovery\n // fetch will fail at runtime with the same \"no seed reachable\" error\n // any unreachable URL produces — the caller learns the network is not\n // live, rather than getting a baffling \"unknown network\" TypeScript\n // error at compile time.\n bootstrap: ['https://gateway.hsuite.network'],\n },\n} as const;\n\n/**\n * Resolve a network name to its preset. Throws on unknown name — this is the\n * one place a stringly-typed call (e.g. from a config file) gets validated.\n *\n * Callers passing a `NetworkName`-typed value compile-time-guarantee this\n * never throws.\n */\nexport function resolveNetwork(name: NetworkName): NetworkPreset {\n const preset = KNOWN_NETWORKS[name];\n if (!preset) {\n // Defensive guard for the runtime string case. NetworkName is a closed\n // union, but JS callers can pass anything.\n throw new Error(\n `Unknown network: \"${name}\". Known networks: ${Object.keys(KNOWN_NETWORKS).join(', ')}`,\n );\n }\n return preset;\n}\n\n/**\n * Type guard for `NetworkName`. Useful when accepting input from configs,\n * env vars, or CLI flags.\n */\nexport function isKnownNetwork(name: string): name is NetworkName {\n return Object.prototype.hasOwnProperty.call(KNOWN_NETWORKS, name);\n}\n","/**\n * Shared bootstrap → cluster resolution helper.\n *\n * `BaasClient.connectToCluster` (and, before SDK 4.0, the now-removed\n * `SmartEngineClient.connectToCluster`) had ~25 lines of identical scaffolding\n * (resolve `bootstrap | network` → `ClusterDiscoveryClient` → `getRandomCluster`\n * → throw if null). This helper collapses that duplication; the factory delegates\n * here and wraps the null-case in its own error class.\n */\n\nimport { ClusterDiscoveryClient, type ClusterInfo } from './cluster-discovery';\nimport { resolveNetwork, type NetworkName } from '../network-presets';\n\n/**\n * Discovery-seed half of every `connectToCluster` config — must supply\n * exactly one of `bootstrap` or `network` (the call-sites encode the\n * exactly-one constraint via a discriminated union; this type intersects\n * with the auth / config half).\n */\nexport type ResolveClusterSeed = {\n /** Bootstrap seeds: URLs that serve `GET /api/v3/discovery/clusters`. */\n bootstrap?: string[];\n /** Named network — resolves the canonical gateway entrypoint. */\n network?: NetworkName;\n};\n\n/**\n * Optional HCS trust-anchor (cross-checks the bootstrap response against\n * the on-chain validator-registry topic so a compromised bootstrap seed\n * can't inject rogue clusters).\n */\nexport type ResolveClusterTrustAnchor = {\n network: 'mainnet' | 'testnet' | 'previewnet';\n registryTopicId: string;\n mirrorNodeUrl?: string;\n};\n\n/**\n * Common config inputs for {@link resolveClusterEndpoint}.\n */\nexport type ResolveClusterConfig = ResolveClusterSeed & {\n allowInsecure?: boolean;\n trustAnchor?: ResolveClusterTrustAnchor;\n};\n\n/**\n * Outcomes from {@link resolveClusterEndpoint}.\n *\n * - `'no-seeds'` — neither a `bootstrap` list nor a known `network` was\n * supplied (caller passed an empty list explicitly, or the network\n * preset has no seeds).\n * - `'no-clusters'` — discovery completed but found no active cluster\n * via any seed (network reachability / bootstrap URLs are likely off).\n */\nexport type ResolveClusterFailure = 'no-seeds' | 'no-clusters';\n\nexport type ResolveClusterResult =\n | { ok: true; cluster: ClusterInfo }\n | { ok: false; reason: ResolveClusterFailure };\n\n/**\n * Resolve a cluster endpoint via bootstrap seeds or a named network.\n *\n * `BaasClient.connectToCluster` calls this. The factory handles wrapping\n * the failure cases in its error class (so callers keep getting `BaasError`\n * rather than a leaked helper-side type).\n */\nexport async function resolveClusterEndpoint(\n config: ResolveClusterConfig,\n): Promise<ResolveClusterResult> {\n const allowInsecure = config.allowInsecure ?? false;\n\n // Resolve the seed half. `bootstrap` wins when both are set under\n // `any`-cast usage; the call-site types prevent that under normal TS.\n const bootstrap: string[] = config.bootstrap\n ? [...config.bootstrap]\n : config.network\n ? [...resolveNetwork(config.network).bootstrap]\n : [];\n\n if (bootstrap.length === 0) {\n return { ok: false, reason: 'no-seeds' };\n }\n\n const discovery = new ClusterDiscoveryClient({\n bootstrap,\n allowInsecure,\n trustAnchor: config.trustAnchor\n ? {\n network: config.trustAnchor.network,\n registryTopicId: config.trustAnchor.registryTopicId,\n mirrorNodeUrl: config.trustAnchor.mirrorNodeUrl,\n allowInsecure,\n }\n : undefined,\n });\n\n const cluster = await discovery.getRandomCluster();\n if (!cluster) {\n return { ok: false, reason: 'no-clusters' };\n }\n\n return { ok: true, cluster };\n}\n","/**\n * Validator Authentication Client\n *\n * Web3-style authentication for connecting to smart-engine validators.\n * Supports challenge-response authentication with Hedera, XRPL, Polkadot,\n * Stellar, or Solana wallets.\n */\n\n/**\n * Supported blockchain types for authentication.\n *\n * All five are verified end-to-end server-side by {@link Web3AuthService}\n * (Hedera ed25519, XRPL secp256k1/ed25519, Polkadot sr25519/ed25519,\n * Stellar ed25519, Solana ed25519). The partial-mode prepare guards\n * enforce `session.chain === request.chain`, so a caller who wants to\n * prepare sovereignty on chain X must authenticate with chain X's wallet.\n */\nexport type AuthChain = 'hedera' | 'xrpl' | 'polkadot' | 'stellar' | 'solana';\n\nconst SUPPORTED_AUTH_CHAINS: readonly AuthChain[] = [\n 'hedera',\n 'xrpl',\n 'polkadot',\n 'stellar',\n 'solana',\n];\n\n/**\n * Security configuration for auth client\n */\nexport interface SecurityConfig {\n /** Allow HTTP (insecure) connections - default false, use only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Structural type of a Hedera-style signer — matches the `PrivateKey`\n * surface in `@hashgraph/sdk` without importing it. Accepts any of the\n * three return shapes the SDK has historically used: a raw `Uint8Array`,\n * a Node `Buffer`, or an object with `toBytes()`.\n *\n * Defined here rather than imported to keep `@hashgraph/sdk` out of the\n * SDK's runtime — it stays a peer/optional dep of the consumer.\n */\nexport type HederaSigner = {\n sign(message: Uint8Array): Uint8Array | Buffer | { toBytes(): Uint8Array };\n};\n\n/**\n * Structural type of an XRPL-style signer — matches the `Wallet.sign`\n * surface in the `xrpl` library without importing it. Returns either a\n * bare hex/base58 string or a `{ signedTransaction }` envelope.\n */\nexport type XrplSigner = {\n sign(message: string): string | { signedTransaction: string };\n};\n\n/**\n * Normalize the three Hedera-signer return shapes into a `Uint8Array`.\n */\nfunction toBytes(value: Uint8Array | Buffer | { toBytes(): Uint8Array }): Uint8Array {\n // Buffer extends Uint8Array, so this branch catches both.\n if (value instanceof Uint8Array) return value;\n return value.toBytes();\n}\n\n/**\n * Validate and sanitize a validator URL\n */\nfunction validateValidatorUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n\n // Only allow http/https protocols\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new ValidatorAuthError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n\n // Enforce HTTPS unless explicitly allowed for development\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new ValidatorAuthError(\n 'HTTPS is required for validator connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n\n // Block private IP ranges in production to prevent SSRF\n const hostname = parsed.hostname.toLowerCase();\n const isLocalhost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';\n\n if (isLocalhost && !allowInsecure) {\n throw new ValidatorAuthError(\n 'Localhost connections blocked in secure mode. Set allowInsecure=true for local development.',\n 400\n );\n }\n\n return parsed.origin;\n } catch (error) {\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n throw new ValidatorAuthError(`Invalid validator URL: ${url}`, 400);\n }\n}\n\n/**\n * Sanitize input to prevent injection attacks\n */\nfunction sanitizeInput(input: string, fieldName: string, maxLength = 256): string {\n if (typeof input !== 'string') {\n throw new ValidatorAuthError(`${fieldName} must be a string`, 400);\n }\n\n if (input.length > maxLength) {\n throw new ValidatorAuthError(`${fieldName} exceeds maximum length of ${maxLength}`, 400);\n }\n\n // Remove any control characters\n return input.replace(/[\\x00-\\x1F\\x7F]/g, '');\n}\n\n/**\n * Challenge response from validator\n */\nexport interface ChallengeResponse {\n /** Whether the request was successful */\n success: boolean;\n /** Challenge string to sign */\n challenge: string;\n /** Informational message */\n message: string;\n /** Challenge expiration time */\n expiresIn: string;\n}\n\n/**\n * Authentication request payload\n */\nexport interface AuthenticateRequest {\n /** Blockchain type */\n chain: AuthChain;\n /** Wallet address (account ID for Hedera, address for XRPL) */\n address: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Signed challenge (hex encoded signature) */\n signature: string;\n /** Original challenge string */\n challenge: string;\n /** Optional metadata */\n metadata?: {\n nodeId?: string;\n endpoint?: string;\n capabilities?: string[];\n appId?: string;\n appName?: string;\n };\n}\n\n/**\n * Authentication response with session token\n */\nexport interface AuthenticateResponse {\n /** JWT session token */\n token: string;\n /** Session ID */\n sessionId: string;\n /** Assigned validator ID */\n validatorId: string;\n /** Token expiration timestamp */\n expiresAt: string;\n /** Informational message */\n message: string;\n}\n\n/**\n * Session information\n */\nexport interface SessionInfo {\n /** Session ID */\n sessionId: string;\n /** Validator ID */\n validatorId: string;\n /** Wallet address */\n address: string;\n /** Blockchain type */\n chain: AuthChain;\n /** Session creation time */\n createdAt: string;\n /** Session expiration time */\n expiresAt: string;\n /** Whether session is valid */\n isValid: boolean;\n}\n\n/**\n * Validator auth configuration\n */\nexport interface ValidatorAuthConfig {\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Security configuration */\n security?: SecurityConfig;\n}\n\n/**\n * Validator Authentication Client\n *\n * Implements Web3-style challenge-response authentication:\n * 1. Request challenge from validator\n * 2. Sign challenge with wallet private key\n * 3. Authenticate with signed challenge to get session token\n *\n * @example\n * ```typescript\n * const auth = new ValidatorAuthClient();\n *\n * // Request challenge\n * const challenge = await auth.requestChallenge(\n * 'https://validator.example.com',\n * 'hedera',\n * '0.0.123456'\n * );\n *\n * // Sign challenge (using @hashgraph/sdk)\n * const signature = auth.signChallengeHedera(challenge.challenge, privateKey);\n *\n * // Authenticate\n * const session = await auth.authenticate('https://validator.example.com', {\n * chain: 'hedera',\n * address: '0.0.123456',\n * publicKey: publicKeyHex,\n * signature,\n * challenge: challenge.challenge,\n * });\n *\n * console.log('Token:', session.token);\n * ```\n */\nexport class ValidatorAuthClient {\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n\n constructor(config?: ValidatorAuthConfig) {\n this.timeout = config?.timeout ?? 30000;\n this.allowInsecure = config?.security?.allowInsecure ?? false;\n }\n\n /**\n * Request authentication challenge from validator\n *\n * @param validatorUrl - Validator API base URL\n * @param chain - Blockchain type\n * @param address - Wallet address\n * @returns Challenge to sign\n */\n async requestChallenge(\n validatorUrl: string,\n chain: AuthChain,\n address: string\n ): Promise<ChallengeResponse> {\n // Validate and sanitize inputs\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n const safeAddress = sanitizeInput(address, 'address', 128);\n\n if (!SUPPORTED_AUTH_CHAINS.includes(chain)) {\n throw new ValidatorAuthError(`Invalid chain type: ${chain}`, 400);\n }\n\n const url = `${safeUrl}/auth/validator/challenge`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ chain, address: safeAddress }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Challenge request failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as ChallengeResponse;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Challenge request timeout', 408);\n }\n throw new ValidatorAuthError(`Challenge request failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Authenticate with signed challenge\n *\n * @param validatorUrl - Validator API base URL\n * @param request - Authentication request with signature\n * @returns Session token and info\n */\n async authenticate(\n validatorUrl: string,\n request: AuthenticateRequest\n ): Promise<AuthenticateResponse> {\n // Validate URL\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n\n // Validate and sanitize request fields\n const sanitizedRequest: AuthenticateRequest = {\n chain: request.chain,\n address: sanitizeInput(request.address, 'address', 128),\n publicKey: sanitizeInput(request.publicKey, 'publicKey', 512),\n signature: sanitizeInput(request.signature, 'signature', 1024),\n challenge: sanitizeInput(request.challenge, 'challenge', 512),\n metadata: request.metadata\n ? {\n nodeId: request.metadata.nodeId\n ? sanitizeInput(request.metadata.nodeId, 'nodeId', 64)\n : undefined,\n endpoint: request.metadata.endpoint\n ? sanitizeInput(request.metadata.endpoint, 'endpoint', 256)\n : undefined,\n capabilities: request.metadata.capabilities,\n appId: request.metadata.appId\n ? sanitizeInput(request.metadata.appId, 'appId', 64)\n : undefined,\n appName: request.metadata.appName\n ? sanitizeInput(request.metadata.appName, 'appName', 128)\n : undefined,\n }\n : undefined,\n };\n\n if (!SUPPORTED_AUTH_CHAINS.includes(sanitizedRequest.chain)) {\n throw new ValidatorAuthError(`Invalid chain type: ${sanitizedRequest.chain}`, 400);\n }\n\n // Validate signature is hex\n if (!/^[0-9a-fA-F]+$/.test(sanitizedRequest.signature.replace(/_.*$/, ''))) {\n throw new ValidatorAuthError('Invalid signature format: must be hex encoded', 400);\n }\n\n const url = `${safeUrl}/auth/validator/authenticate`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(sanitizedRequest),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Authentication failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as AuthenticateResponse;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Authentication request timeout', 408);\n }\n throw new ValidatorAuthError(`Authentication failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Get current session info\n *\n * @param validatorUrl - Validator API base URL\n * @param token - Session token\n * @returns Session information\n */\n async getSession(validatorUrl: string, token: string): Promise<SessionInfo> {\n // Validate URL and token\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n const safeToken = sanitizeInput(token, 'token', 2048);\n\n const url = `${safeUrl}/auth/validator/session`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${safeToken}`,\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Session request failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as SessionInfo;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Session request timeout', 408);\n }\n throw new ValidatorAuthError(`Session request failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Sign challenge with Hedera private key.\n *\n * Structurally typed against the surface of `@hashgraph/sdk`'s\n * `PrivateKey`. We don't `import` the SDK directly — pulling it into\n * the smart-engine SDK's runtime would bloat browser bundles and bring\n * peer-dep churn — but any object with a compatible `sign(...)` method\n * works.\n *\n * @param challenge - Challenge string from validator\n * @param privateKey - Hedera PrivateKey instance (or compatible signer)\n * @returns Hex-encoded signature\n */\n signChallengeHedera(challenge: string, privateKey: HederaSigner): string {\n const messageBytes = new Uint8Array(Buffer.from(challenge, 'utf-8'));\n const signature = privateKey.sign(messageBytes);\n return Buffer.from(toBytes(signature)).toString('hex');\n }\n\n /**\n * Sign challenge with XRPL wallet.\n *\n * Structurally typed against the surface of xrpl's `Wallet` — see the\n * comment on {@link HederaSigner} for the \"no direct import\" rationale.\n * Accepts both the `{ signedTransaction }` envelope and the bare-string\n * return shapes that xrpl signer libraries expose.\n *\n * @param challenge - Challenge string from validator\n * @param wallet - XRPL Wallet instance (or compatible signer)\n * @returns Hex-encoded signature\n */\n signChallengeXRPL(challenge: string, wallet: XrplSigner): string {\n const signature = wallet.sign(challenge);\n // XRPL libs expose two return shapes: a bare hex/base58 string, or a\n // `{ signedTransaction }` envelope. Normalize to hex.\n if (typeof signature === 'string') {\n if (/^[0-9A-Fa-f]+$/.test(signature)) return signature;\n return Buffer.from(signature).toString('hex');\n }\n return signature.signedTransaction;\n }\n\n /**\n * Complete authentication flow in one call\n *\n * @param validatorUrl - Validator API base URL\n * @param chain - Blockchain type\n * @param address - Wallet address\n * @param publicKey - Public key (hex)\n * @param signFn - Function to sign the challenge\n * @param metadata - Optional metadata\n * @returns Session token and info\n */\n async authenticateWithSigner(\n validatorUrl: string,\n chain: AuthChain,\n address: string,\n publicKey: string,\n signFn: (challenge: string) => string | Promise<string>,\n metadata?: AuthenticateRequest['metadata']\n ): Promise<AuthenticateResponse> {\n // Step 1: Request challenge\n const challengeResponse = await this.requestChallenge(validatorUrl, chain, address);\n\n // Step 2: Sign challenge\n const signature = await signFn(challengeResponse.challenge);\n\n // Step 3: Authenticate\n return this.authenticate(validatorUrl, {\n chain,\n address,\n publicKey,\n signature,\n challenge: challengeResponse.challenge,\n metadata,\n });\n }\n}\n\n/**\n * Authentication error\n */\nexport class ValidatorAuthError extends Error {\n constructor(\n message: string,\n public statusCode: number,\n public details?: any\n ) {\n super(message);\n this.name = 'ValidatorAuthError';\n }\n}\n","/**\n * Subscription Sub-Client\n *\n * Manages application subscriptions for using the validator network.\n */\n\n/**\n * Subscription tier names.\n *\n * The ladder is `builder → growth → scale → enterprise`. Every tier is paid;\n * the previous free_testnet/starter/professional names were retired.\n *\n * - builder: Entry-level paid tier\n * - growth: Mid-tier with usage analytics\n * - scale: High-volume tier with advanced features\n * - enterprise: Full-featured enterprise tier (custom / unlimited)\n *\n * BREAKING: this union changed from `free_testnet | starter | professional |\n * enterprise`. Consumers pinning the old names must migrate.\n */\nexport type SubscriptionTierName = 'builder' | 'growth' | 'scale' | 'enterprise';\n\n/**\n * Subscription statuses.\n *\n * NOTE: `'deposit_confirmed'` is the mint-ready status — the validator's\n * `activateSubscription` refuses to mint the subscription NFT unless the\n * subscription is in `deposit_confirmed` (there is no `'pending_mint'` status).\n * After a successful mint the status advances to `'active'`.\n */\nexport type SubscriptionStatus =\n | 'pending_deposit'\n | 'deposit_confirmed'\n | 'active'\n | 'expired'\n | 'cancelled';\n\n/**\n * Deposit wallet statuses\n */\nexport type DepositWalletStatus = 'pending' | 'locked' | 'expired' | 'slashed' | 'released';\n\n/**\n * Subscription tier information for API responses\n */\nexport type SubscriptionTierInfo = {\n /** Tier name identifier */\n name: SubscriptionTierName;\n /** Display name for UI */\n displayName: string;\n /** Tier description */\n description: string;\n /** Monthly price in USD */\n priceUsd: number;\n /** Deposit amount in HSUITE tokens */\n depositAmount: string;\n /** API calls per day limit */\n apiCallsPerDay: number;\n /** Supported networks for this tier */\n supportedNetworks: ('hedera' | 'xrpl')[];\n /** Additional features included in this tier */\n features: string[];\n};\n\n/**\n * Subscription request\n */\nexport type SubscriptionRequest = {\n /** Application ID */\n appId: string;\n /** Application name */\n appName: string;\n /** Developer's account ID on the chosen chain */\n developerAccountId: string;\n /** Chain for deposit */\n chain: 'hedera' | 'xrpl';\n /** Selected subscription tier */\n selectedTier: SubscriptionTierName;\n /** Selected networks to support */\n selectedNetworks: ('hedera' | 'xrpl')[];\n /** App logo URL (optional) */\n logoUrl?: string;\n /** App description (optional) */\n appDescription?: string;\n /** Additional metadata (optional) */\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Subscription response\n */\nexport type SubscriptionResponse = {\n success: boolean;\n subscriptionId?: string;\n status?: SubscriptionStatus;\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n message: string;\n};\n\n/**\n * Subscription status response\n */\nexport type SubscriptionStatusResponse = {\n appId: string;\n hasSubscription: boolean;\n subscriptionId?: string;\n appName?: string;\n status: SubscriptionStatus | 'not_found';\n depositWallet?: {\n walletAddress: string;\n chain: string;\n depositAmount: string;\n actualDepositAmount?: string;\n status: DepositWalletStatus;\n lockedUntil?: string;\n };\n subscriptionNftSerial?: number;\n /**\n * Per-chain minted-NFT coordinates exposed by the validator once the\n * subscription NFT is minted. For XRPL this carries the NFTokenID, the\n * issuing account (the cluster SignerList issuer), and the brokered\n * sell-offer tx id — enough for a client to resolve + accept the sell offer\n * so the NFT lands on the developer wallet (`NFTokenAcceptOffer`).\n */\n chainNfts?: {\n xrpl?: {\n nftId?: string;\n issuerAddress?: string;\n offerTxId?: string;\n };\n } & Record<string, unknown>;\n expiresAt?: string;\n remainingBalance?: string;\n createdAt?: string;\n /** Current subscription tier */\n tier?: SubscriptionTierName;\n /** Networks selected for this subscription */\n selectedNetworks?: string[];\n /** API calls made today */\n apiCallsToday?: number;\n /** Daily API call limit based on tier */\n apiCallsLimit?: number;\n};\n\n/**\n * Mint NFT response\n */\nexport type MintNftResponse = {\n success: boolean;\n subscriptionId?: string;\n appId?: string;\n expiresAt?: string;\n message: string;\n};\n\n/**\n * Subscription renewal request\n */\nexport type SubscriptionRenewalRequest = {\n appId: string;\n additionalDays?: number;\n};\n\n/**\n * Subscription renewal response\n */\nexport type SubscriptionRenewalResponse = {\n success: boolean;\n appId: string;\n status?: string;\n newExpiresAt?: string;\n message: string;\n};\n\n/**\n * Subscription configuration\n */\nexport type SubscriptionConfig = {\n subscriptionDepositAmount: string;\n lockDurationDays: number;\n renewalWindowDays: number;\n hsuiteTokenIds: Record<string, string>;\n /** Available subscription tiers */\n availableTiers: SubscriptionTierInfo[];\n};\n\n/**\n * Subscription list response\n */\nexport type SubscriptionListResponse = {\n count: number;\n subscriptions: Array<{\n subscriptionId: string;\n appId: string;\n appName: string;\n status: SubscriptionStatus;\n expiresAt?: string;\n createdAt: string;\n }>;\n};\n\n/**\n * Pending tier change envelope returned by downgrade/upgrade endpoints.\n * The validator records the change without applying it until the next\n * renewal (downgrade) or until the on-chain top-up is confirmed (upgrade).\n */\nexport type PendingTierChange = {\n fromTier?: SubscriptionTierName;\n toTier?: SubscriptionTierName;\n direction?: 'upgrade' | 'downgrade';\n effectiveAt?: string;\n /** Top-up deposit (upgrade only). */\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n};\n\n/** Response shape for `POST /subscription/downgrade`. */\nexport type DowngradeSubscriptionRequest = {\n appId: string;\n toTier: SubscriptionTierName;\n};\n\nexport type DowngradeSubscriptionResponse = {\n success: boolean;\n appId: string;\n pendingTierChange?: PendingTierChange;\n message: string;\n};\n\n/** Response shape for `POST /subscription/upgrade`. */\nexport type UpgradeSubscriptionRequest = {\n appId: string;\n toTier: SubscriptionTierName;\n};\n\nexport type UpgradeSubscriptionResponse = {\n success: boolean;\n appId: string;\n pendingTierChange?: PendingTierChange;\n /** Top-up deposit instructions; flip activates once on-chain. */\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n message: string;\n};\n\nexport type CancelTierChangeRequest = {\n appId: string;\n};\n\nexport type CancelTierChangeResponse = {\n success: boolean;\n appId: string;\n message: string;\n};\n\n/**\n * Response shape for `GET /subscription/active-for/:walletAddress`.\n *\n * **Internal-by-design.** Server-side this is allowlisted under\n * `ApiKeyGuard.INTERNAL_SERVICE_MESH_ROUTES` — smart-host pods call it via\n * `X-API-Key`. Smart-app callers SHOULD NOT use this endpoint; it is\n * exposed for completeness and for in-cluster tooling.\n */\nexport type ActiveSubscriptionForWalletResponse = {\n active: boolean;\n};\n\n/**\n * Response shape for `GET /subscription/usage/:appId`. Mirrors the\n * server-side `UsageBreakdown` projection.\n */\nexport type SubscriptionUsageSummaryResponse = {\n appId: string;\n total: number;\n byCategory: {\n database: number;\n functions: number;\n messaging: number;\n storage: number;\n ipfs: number;\n snapshots: number;\n other: number;\n };\n recordCount: number;\n lastUpdated: string;\n};\n\n/** Response shape for `GET /subscription/usage/status/:appId`. */\nexport type SubscriptionUsageStatusResponse = {\n appId: string;\n usagePercent: number;\n currentUsage: number;\n dailyLimit: number;\n overagePercent: number;\n inGracePeriod: boolean;\n graceExpiresAt: string | null;\n blocked: boolean;\n suggestUpgrade: boolean;\n nextTier: {\n tier: SubscriptionTierName;\n name: string;\n apiCallsPerDay: number;\n monthlyPriceHsuite: number;\n } | null;\n projectedDaysUntilLimit: number | null;\n};\n\n/** Response shape for `GET /subscription/billing/:appId`. */\nexport type SubscriptionBillingLedgerEntry = {\n id: string;\n subscriptionId: string;\n operation: string;\n amount: string;\n balanceAfter: string;\n timestamp: string;\n metadata?: Record<string, unknown>;\n};\n\nexport type SubscriptionBillingResponse = {\n appId: string;\n entries: SubscriptionBillingLedgerEntry[];\n total: number;\n hasMore: boolean;\n};\n\nexport type GetBillingOptions = {\n limit?: number;\n offset?: number;\n /** ISO-8601 lower bound. */\n from?: string;\n /** ISO-8601 upper bound. */\n to?: string;\n};\n\n/** Response shape for `POST /subscription/customer/mint`. */\nexport type MintCustomerSubscriptionRequest = {\n appId: string;\n customerAddress: string;\n /** v1 is XRPL-only — Hedera/Solana/Polkadot not supported server-side. */\n customerChain: 'xrpl';\n metadataCid: string;\n};\n\nexport type MintCustomerSubscriptionResponse = {\n success: true;\n nftSerial: number;\n txHash: string;\n};\n\n/**\n * Balance response\n */\nexport type BalanceResponse = {\n appId: string;\n subscriptionId: string;\n status: SubscriptionStatus;\n remainingBalance: string;\n expiresAt?: string;\n};\n\nimport { encodePathParam, type HttpClient } from '../http';\n\n/**\n * Subscription Sub-Client\n *\n * Manages application subscriptions including:\n * - Subscription requests with deposit wallets\n * - Deposit verification and NFT minting\n * - Subscription renewal\n * - Balance checking\n */\nexport class SubscriptionClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Request a new subscription.\n * Creates a deposit wallet and returns deposit instructions.\n */\n async request(request: SubscriptionRequest): Promise<SubscriptionResponse> {\n return this.http.post('/subscription/request', request);\n }\n\n /**\n * Get subscription status by app ID\n */\n async getStatus(appId: string): Promise<SubscriptionStatusResponse> {\n return this.http.get(`/subscription/status/${encodePathParam(appId)}`);\n }\n\n /**\n * Mint subscription NFT after deposit is confirmed\n */\n async mintNft(appId: string): Promise<MintNftResponse> {\n return this.http.post(`/subscription/mint/${encodePathParam(appId)}`, {});\n }\n\n /**\n * Renew subscription by extending period\n */\n async renew(request: SubscriptionRenewalRequest): Promise<SubscriptionRenewalResponse> {\n return this.http.post('/subscription/renew', request);\n }\n\n /**\n * Fetch available subscription tiers from the network.\n *\n * Use this instead of hard-coding tier names -- the validator returns the\n * canonical list of tiers together with pricing, limits, and features.\n *\n * @returns Array of {@link SubscriptionTierInfo} objects.\n *\n * @example\n * ```typescript\n * const tiers = await subscription.getTiers();\n * console.log(tiers.map(t => `${t.name}: $${t.priceUsd}/mo`));\n * ```\n */\n async getTiers(): Promise<SubscriptionTierInfo[]> {\n try {\n return await this.http.get<SubscriptionTierInfo[]>('/subscription/tiers');\n } catch (err) {\n // Backwards compatibility: older validator builds don't have the\n // dedicated /tiers endpoint yet. Fall back to /config, which\n // returns the same tiers under `availableTiers` (though in the\n // raw pricing-core shape rather than SubscriptionTierInfo).\n const isNotFound =\n err != null &&\n typeof err === 'object' &&\n 'statusCode' in err &&\n (err as { statusCode?: number }).statusCode === 404;\n if (!isNotFound) throw err;\n const cfg = await this.http.get<{\n availableTiers: Array<Record<string, unknown>>;\n }>('/subscription/config');\n // Normalize: pricing-core's SubscriptionTierConfig uses\n // { tier, name, monthlyPriceHsuite, allowedNetworks, ... } — map\n // to the SDK contract so callers see a stable shape across\n // server versions.\n return (cfg.availableTiers || []).map((raw) => {\n const tier = (raw.tier ?? raw.name) as SubscriptionTierName;\n const displayName = (raw.name ?? raw.displayName ?? String(tier)) as string;\n const monthlyPriceHsuite = Number(\n raw.monthlyPriceHsuite ?? raw.depositAmount ?? 0\n );\n const apiCallsPerDay = Number(raw.apiCallsPerDay ?? 0);\n const rawNetworks = (raw.allowedNetworks ?? raw.supportedNetworks ?? []) as string[];\n const supportedNetworks: ('hedera' | 'xrpl')[] = rawNetworks.some(\n (n) => n === 'mainnet'\n )\n ? ['hedera', 'xrpl']\n : ['hedera'];\n return {\n name: tier,\n displayName,\n description:\n (raw.description as string | undefined) ??\n `${displayName} tier`,\n priceUsd: Number(raw.priceUsd ?? 0),\n depositAmount: String(monthlyPriceHsuite),\n apiCallsPerDay: Number.isFinite(apiCallsPerDay)\n ? apiCallsPerDay\n : Number.MAX_SAFE_INTEGER,\n supportedNetworks,\n features: (raw.features as string[]) ?? [],\n };\n });\n }\n }\n\n /**\n * Get subscription configuration\n */\n async getConfig(): Promise<SubscriptionConfig> {\n return this.http.get('/subscription/config');\n }\n\n /**\n * List all subscriptions\n */\n async list(): Promise<SubscriptionListResponse> {\n return this.http.get('/subscription/list');\n }\n\n /**\n * List subscriptions by status\n */\n async listByStatus(status: SubscriptionStatus): Promise<SubscriptionListResponse> {\n return this.http.get(`/subscription/list/status/${encodePathParam(status)}`);\n }\n\n /**\n * Get subscription balance\n */\n async getBalance(appId: string): Promise<BalanceResponse> {\n return this.http.get(`/subscription/balance/${encodePathParam(appId)}`);\n }\n\n // ─── Tier-Change Endpoints ────────────────────────────────────────────────\n\n /**\n * Schedule a tier downgrade. The downgrade takes effect at the next\n * renewal — the deposit is NOT partially refunded mid-lock. Excess\n * collateral returns on eventual cancel.\n */\n async downgrade(\n request: DowngradeSubscriptionRequest,\n ): Promise<DowngradeSubscriptionResponse> {\n return this.http.post('/subscription/downgrade', request);\n }\n\n /**\n * Request a tier upgrade. The server records the upgrade and returns\n * top-up deposit instructions for the price delta. The new tier flips\n * only once the on-chain top-up is confirmed by the deposit monitor.\n */\n async upgrade(\n request: UpgradeSubscriptionRequest,\n ): Promise<UpgradeSubscriptionResponse> {\n return this.http.post('/subscription/upgrade', request);\n }\n\n /** Cancel a pending (not-yet-applied) tier change. */\n async cancelTierChange(\n request: CancelTierChangeRequest,\n ): Promise<CancelTierChangeResponse> {\n return this.http.post('/subscription/tier-change/cancel', request);\n }\n\n // ─── Internal / Usage / Billing ───────────────────────────────────────────\n\n /**\n * Check whether a developer wallet has any active subscription. Used by\n * smart-host's deploy gate via the cluster-internal API-key path; smart-app\n * callers should not rely on this endpoint (server-side it requires the\n * `INTERNAL_SERVICE_MESH_ROUTES` allowlist + an `X-API-Key` header).\n */\n async getActiveFor(walletAddress: string): Promise<ActiveSubscriptionForWalletResponse> {\n return this.http.get(\n `/subscription/active-for/${encodePathParam(walletAddress)}`,\n );\n }\n\n /** Today's consumption breakdown by category for an app. Owner-only. */\n async getUsage(appId: string): Promise<SubscriptionUsageSummaryResponse> {\n return this.http.get(`/subscription/usage/${encodePathParam(appId)}`);\n }\n\n /**\n * Current usage with overage info: usage percent, grace status,\n * upgrade suggestion, projected days until limit. Owner-only.\n */\n async getUsageStatus(appId: string): Promise<SubscriptionUsageStatusResponse> {\n return this.http.get(`/subscription/usage/status/${encodePathParam(appId)}`);\n }\n\n /**\n * Subscription balance deduction history. Pagination + ISO-8601 range\n * filtering supported. Owner-only.\n */\n async getBilling(\n appId: string,\n options?: GetBillingOptions,\n ): Promise<SubscriptionBillingResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n if (options?.from) params.append('from', options.from);\n if (options?.to) params.append('to', options.to);\n const qs = params.toString();\n return this.http.get(\n `/subscription/billing/${encodePathParam(appId)}${qs ? `?${qs}` : ''}`,\n );\n }\n\n /**\n * Mint a customer-subscription NFT on behalf of a smart-app.\n *\n * Distinct from `mintNft(appId)`, which mints the smart-app's own\n * developer-level subscription NFT. This endpoint mints a *customer*\n * NFT held by an end-user wallet — used by smart-host's\n * `XrplCustomerNftIssuerAdapter` when an app calls\n * `SubscriptionService.issueCustomerSubscription()` from the sandbox.\n *\n * v1 is XRPL-only (the `customerChain` field is a literal `'xrpl'`).\n * Internal-by-design — server-side gated by `X-API-Key`.\n */\n async mintCustomer(\n request: MintCustomerSubscriptionRequest,\n ): Promise<MintCustomerSubscriptionResponse> {\n return this.http.post('/subscription/customer/mint', request);\n }\n}\n","/**\n * Faucet Sub-Client\n *\n * Public bootstrap surface for dispensing testnet HSUITE (HST) to a recipient\n * address via a challenge/response signature flow.\n */\n\nimport { type HttpClient } from '../http';\n\n/**\n * Challenge envelope returned by `POST /faucet/hsuite/challenge`.\n *\n * The caller signs `message` with the key controlling `recipientAddress` and\n * echoes the `challengeId` back on the dispense call.\n */\nexport type FaucetChallenge = {\n /** Opaque challenge identifier; echo on the dispense call. */\n challengeId: string;\n /** The exact string to sign with the recipient's key. */\n message: string;\n /** Seconds until the challenge expires and must be re-requested. */\n expiresInSeconds: number;\n};\n\n/**\n * Request body for `POST /faucet/hsuite`.\n */\nexport type FaucetDispenseRequest = {\n /** Chain the recipient address lives on (e.g. `'xrpl'`). */\n chain: string;\n /** Address to receive the dispensed HST. */\n recipientAddress: string;\n /** `challengeId` from the prior {@link FaucetChallenge}. */\n challengeId: string;\n /** Signature over the challenge `message`, hex-encoded. */\n signature: string;\n /** Public key (hex) that produced `signature`; optional when derivable. */\n publicKey?: string;\n};\n\n/**\n * Successful dispense — HST was sent on-chain.\n */\nexport type FaucetDispensed = {\n status: 'dispensed';\n /** Amount of HST dispensed. */\n amount: string;\n /** On-chain transaction hash of the dispense. */\n txHash: string;\n /** Remaining HST the recipient may still claim today. */\n remainingDailyAllowance: string;\n};\n\n/**\n * The recipient must establish a trust line for the HST issued-currency\n * before it can receive any. Set the returned trust line, then re-dispense\n * with a fresh challenge.\n */\nexport type FaucetTrustlineRequired = {\n status: 'trustline_required';\n /** Trust line the recipient must set before re-dispensing. */\n trustLine: {\n /** Issued-currency code (e.g. `'HST'`). */\n currency: string;\n /** Issuer address of the currency. */\n issuer: string;\n /** Trust line limit to set. */\n limit: string;\n };\n};\n\n/**\n * The recipient hit the daily rate limit; retry after the given delay.\n */\nexport type FaucetRateLimited = {\n status: 'rate_limited';\n /** Seconds to wait before the next dispense attempt is allowed. */\n retryAfterSeconds: number;\n};\n\n/**\n * Discriminated union over `status` returned by `POST /faucet/hsuite`.\n */\nexport type FaucetDispenseResult =\n | FaucetDispensed\n | FaucetTrustlineRequired\n | FaucetRateLimited;\n\n/**\n * Response shape for `GET /faucet/hsuite/status`.\n */\nexport type FaucetStatusResponse = {\n /** HST already dispensed to the recipient today. */\n dispensedToday: string;\n /** Forward-compatible: server may add allowance/reset fields. */\n [key: string]: unknown;\n};\n\n/**\n * Faucet Sub-Client\n *\n * Dispenses testnet HSUITE (HST) through a Web3-style challenge/response.\n * These are `@Public` bootstrap routes — no bearer token is required (a token\n * on the shared HTTP client is harmless).\n *\n * Lifecycle:\n * 1. {@link FaucetClient.requestChallenge} — get a {@link FaucetChallenge}.\n * 2. Sign `challenge.message` with the key controlling `recipientAddress`.\n * 3. {@link FaucetClient.dispense} — submit `{challengeId, signature, publicKey?}`.\n * 4. If the result is `status: 'trustline_required'`, the signer MUST set the\n * returned `trustLine` on `recipientAddress`, then request a NEW challenge\n * and re-dispense (the consumed challenge can't be reused).\n * 5. If the result is `status: 'rate_limited'`, wait `retryAfterSeconds` and retry.\n * 6. On `status: 'dispensed'`, the HST `txHash` confirms the on-chain transfer.\n *\n * @example\n * ```typescript\n * const challenge = await faucet.requestChallenge('xrpl', wallet.address);\n * const signature = await sign(challenge.message);\n * let result = await faucet.dispense({\n * chain: 'xrpl',\n * recipientAddress: wallet.address,\n * challengeId: challenge.challengeId,\n * signature,\n * publicKey: wallet.publicKey,\n * });\n * if (result.status === 'trustline_required') {\n * await setTrustLine(result.trustLine); // set on recipientAddress, then retry\n * }\n * ```\n */\nexport class FaucetClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Request a signing challenge for a recipient address. The returned\n * `message` must be signed by the key controlling `recipientAddress`.\n */\n async requestChallenge(\n chain: string,\n recipientAddress: string,\n ): Promise<FaucetChallenge> {\n return this.http.post('/faucet/hsuite/challenge', { chain, recipientAddress });\n }\n\n /**\n * Submit a signed challenge to dispense HST. The result is a discriminated\n * union on `status` — branch on `'dispensed' | 'trustline_required' |\n * 'rate_limited'`. On `'trustline_required'`, set the returned trust line on\n * the recipient and re-dispense with a fresh challenge.\n */\n async dispense(req: FaucetDispenseRequest): Promise<FaucetDispenseResult> {\n return this.http.post('/faucet/hsuite', req);\n }\n\n /**\n * Get today's dispense status for a recipient (e.g. amount already\n * dispensed today).\n */\n async getStatus(\n chain: string,\n recipientAddress: string,\n ): Promise<FaucetStatusResponse> {\n const params = new URLSearchParams();\n params.append('chain', chain);\n params.append('recipientAddress', recipientAddress);\n return this.http.get(`/faucet/hsuite/status?${params.toString()}`);\n }\n}\n","/**\n * TSS (Threshold Signature Scheme) Sub-Client\n *\n * Provides access to TSS/MPC operations for multi-sig entity management.\n * All operations are chain-agnostic — pass `chain` as a parameter.\n */\nimport type {\n EntityCreationOptions,\n EntityCreationResponse,\n ReshareRequest,\n ReshareResponse,\n EntityDetails,\n MPCSigningRequest,\n MPCSigningResponse,\n ValidatorListResponse,\n TSSStats,\n EntityListResponse,\n TSSHealthResponse,\n CeremonyListResponse,\n MultiSigStatusResponse,\n TssJobAccepted,\n TssJobResponse,\n SignForAppRequest,\n SignForAppResponse,\n} from './types';\nimport { encodePathParam, type HttpClient } from '../http';\n\nexport * from './types';\n\n/**\n * TSS Sub-Client\n *\n * Manages Threshold Signature Scheme operations including:\n * - Multi-sig entity creation (chain-agnostic)\n * - Key resharing for membership changes\n * - MPC transaction signing for any supported chain\n * - DKG ceremony monitoring\n *\n * @example\n * ```typescript\n * // Sign a transaction on any chain\n * const result = await client.tss.signMPC({\n * chain: 'hedera',\n * entityId: 'entity-123',\n * transactionBytes: '0x...',\n * });\n * ```\n */\nexport class TSSClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a multi-sig entity via a synchronous DKG ceremony.\n *\n * @param options Entity-creation parameters (chain, threshold, participants).\n * @returns The created entity's identity (ids + group public keys).\n */\n async createEntity(options: EntityCreationOptions): Promise<EntityCreationResponse> {\n return this.http.post('/tss/entity/create', options);\n }\n\n /**\n * Reshare keys when cluster membership changes. Redistributes secret shares\n * WITHOUT changing public keys.\n *\n * @param request The new membership / threshold to reshare to.\n * @returns The reshare outcome.\n */\n async reshareCluster(request: ReshareRequest): Promise<ReshareResponse> {\n return this.http.post('/tss/cluster/reshare', request);\n }\n\n /**\n * Get entity details by id.\n *\n * @param entityId The entity id to look up.\n * @returns The entity's details.\n */\n async getEntity(entityId: string): Promise<EntityDetails> {\n return this.http.get(`/tss/entity/${encodePathParam(entityId)}`);\n }\n\n /**\n * Sign a transaction using MPC.\n *\n * Routes to `POST /api/v3/tss/hedera/sign-mpc`. Only `'hedera'` is wired\n * server-side; other chain signing paths run via their own controllers (XRPL\n * multisig, Polkadot MPC) and are not exposed through this sub-client. The\n * `chain` field is carried into the request body so the validator can log +\n * route, but any non-`'hedera'` value will 404.\n *\n * @param request The MPC signing request; `chain` is forced to `'hedera'`.\n * @returns The MPC signing result.\n */\n async signMPC(\n request: MPCSigningRequest & { chain?: 'hedera' },\n ): Promise<MPCSigningResponse> {\n const chain = 'hedera' as const;\n return this.http.post(`/tss/${chain}/sign-mpc`, { ...request, chain });\n }\n\n /**\n * Get known validators and their public keys.\n *\n * @returns The validator list with public keys.\n */\n async getValidators(): Promise<ValidatorListResponse> {\n return this.http.get('/tss/validators');\n }\n\n /**\n * Force announcement of this node's public key.\n *\n * @returns Whether the announcement was accepted, plus a status message.\n */\n async announceKey(): Promise<{ success: boolean; message: string }> {\n return this.http.post('/tss/announce', {});\n }\n\n /**\n * Get TSS statistics.\n *\n * @returns Aggregate TSS statistics.\n */\n async getStats(): Promise<TSSStats> {\n return this.http.get('/tss/stats');\n }\n\n /**\n * List all TSS entities.\n *\n * @returns The full entity list.\n */\n async listEntities(): Promise<EntityListResponse> {\n return this.http.get('/tss/entities');\n }\n\n /**\n * TSS health check.\n *\n * @returns The TSS subsystem health report.\n */\n async getHealth(): Promise<TSSHealthResponse> {\n return this.http.get('/tss/health');\n }\n\n /**\n * List DKG ceremonies and their statistics.\n *\n * @returns The ceremony list.\n */\n async listCeremonies(): Promise<CeremonyListResponse> {\n return this.http.get('/tss/multisig/ceremonies');\n }\n\n /**\n * Get multi-sig transaction status by transaction id.\n *\n * @param txId The multi-sig transaction id.\n * @returns The current status of that transaction.\n */\n async getMultiSigStatus(txId: string): Promise<MultiSigStatusResponse> {\n return this.http.get(`/tss/multisig/transactions/${encodePathParam(txId)}`);\n }\n\n /**\n * Async-job variant of {@link createEntity}.\n *\n * Server returns 202 + `{ jobId, statusUrl, status: 'pending' }` immediately;\n * the DKG ceremony runs in the background. Poll {@link getJob} until the\n * status reaches `'success'` or `'failed'`.\n *\n * @param options Entity-creation parameters.\n * @returns A job descriptor (`jobId`, `statusUrl`, initial status).\n */\n async createEntityAsync(options: EntityCreationOptions): Promise<TssJobAccepted> {\n return this.http.post('/tss/entity/create/async', options);\n }\n\n /**\n * Async-job variant of {@link reshareCluster}. Returns 202 + a polling\n * descriptor; resharing runs in the background.\n *\n * @param request The new membership / threshold to reshare to.\n * @returns A job descriptor to poll via {@link getJob}.\n */\n async reshareClusterAsync(request: ReshareRequest): Promise<TssJobAccepted> {\n return this.http.post('/tss/cluster/reshare/async', request);\n }\n\n /**\n * Poll the status of an async TSS-ceremony job kicked off via\n * {@link createEntityAsync} or {@link reshareClusterAsync}.\n *\n * @param jobId The job id returned by the async kickoff call.\n * @returns The job's current status (and result once terminal).\n */\n async getJob(jobId: string): Promise<TssJobResponse> {\n return this.http.get(`/tss/jobs/${encodePathParam(jobId)}`);\n }\n\n /**\n * Sign a hex payload as smart-app entity `appId` via the cluster's TSS\n * quorum. Used by smart-deployer for per-entity BLS12-381 signatures over\n * deployment-context payloads (trustless APP_TOKEN replacement).\n *\n * Payload constraints (enforced server-side):\n * - even-length lowercase hex\n * - ≥32 bytes, ≤8KB\n *\n * @param appId The smart-app entity id to sign as.\n * @param request The hex payload to sign.\n * @returns The aggregate signature over the payload.\n */\n async signForApp(appId: string, request: SignForAppRequest): Promise<SignForAppResponse> {\n return this.http.post(`/tss/entity/${encodePathParam(appId)}/sign`, request);\n }\n}\n","/**\n * IPFS Sub-Client\n *\n * Provides access to IPFS operations for decentralized file storage.\n *\n * @example\n * ```typescript\n * // Upload a file\n * const result = await client.ipfs.upload(fileBuffer, 'document.pdf');\n *\n * // Pin content\n * await client.ipfs.pin(result.cid);\n *\n * // Get file\n * const file = await client.ipfs.getFile(result.cid);\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n IpfsUploadResult,\n IpfsPinResult,\n IpfsFileMetadata,\n IpfsPinListResponse,\n IpfsStatusResponse,\n IpfsStorageUsageResponse,\n} from './types';\n\nexport * from './types';\n\n/**\n * IPFS Sub-Client\n *\n * Manages IPFS operations including:\n * - File upload and retrieval\n * - Content pinning and unpinning\n * - Metadata queries\n * - Storage usage monitoring\n */\nexport class IPFSClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Upload a file to IPFS\n *\n * @param file - File data as Blob or Buffer\n * @param filename - Name of the file\n * @param metadata - Optional metadata key-value pairs\n * @returns Upload result with CID\n */\n async upload(\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>\n ): Promise<IpfsUploadResult> {\n return this.http.upload('/ipfs/upload', file, filename, metadata);\n }\n\n /**\n * Pin content by CID to ensure it persists\n */\n async pin(cid: string): Promise<IpfsPinResult> {\n return this.http.post(`/ipfs/pin/${encodePathParam(cid)}`, {});\n }\n\n /**\n * Unpin content by CID\n */\n async unpin(cid: string): Promise<IpfsPinResult> {\n return this.http.delete(`/ipfs/unpin/${encodePathParam(cid)}`);\n }\n\n /**\n * Get a file by CID\n */\n async getFile(cid: string): Promise<any> {\n return this.http.get(`/ipfs/file/${encodePathParam(cid)}`);\n }\n\n /**\n * Get raw content by CID\n */\n async getContent(cid: string): Promise<any> {\n return this.http.get(`/ipfs/${encodePathParam(cid)}`);\n }\n\n /**\n * Get file metadata by CID\n */\n async getMetadata(cid: string): Promise<IpfsFileMetadata> {\n return this.http.get(`/ipfs/metadata/${encodePathParam(cid)}`);\n }\n\n /**\n * List all pinned content\n */\n async listPins(): Promise<IpfsPinListResponse> {\n return this.http.get('/ipfs/pins');\n }\n\n /**\n * Get IPFS node status\n */\n async getStatus(): Promise<IpfsStatusResponse> {\n return this.http.get('/ipfs/status');\n }\n\n /**\n * Get storage usage information\n */\n async getStorageUsage(): Promise<IpfsStorageUsageResponse> {\n return this.http.get('/ipfs/storage');\n }\n}\n","/**\n * Hedera TSS Sub-Client\n *\n * Server-side controller: the server\n * (route prefix `/api/v3/hedera/tss`).\n *\n * These endpoints are **TSS-signed immediate-execute** — the cluster signs AND\n * submits in one call, distinct from:\n * - `client.hedera.*` (prepare-only, the caller signs + submits)\n * - `client.tss.signMPC(...)` (signs an externally-built tx, doesn't submit)\n *\n * Mounted on the main client as `client.hedera.tss`.\n *\n * Wire format: every request goes to `/api/v3/hedera/tss/<op>`. The injected\n * `HttpClient` must be rooted at `${baseUrl}/api/v3` (the same one\n * `TSSClient`/`SubscriptionClient`/etc. use).\n */\n\nimport type { HttpClient } from '../http';\n\n/** Sovereignty security mode for TSS-controlled Hedera accounts. */\nexport type HederaTssSecurityMode = 'full' | 'partial';\n\n/** Common validator-binding fields required to anchor an op to on-chain rules. */\ntype ValidatorBoundRequest = {\n /** TSS entity id (already created via `client.tss.createEntity*`). */\n entityId: string;\n /** HCS timestamp of the rules message (`SECONDS.NANOS`). */\n validatorTimestamp: string;\n /** HCS topic that holds the rules message. */\n validatorTopicId: string;\n /** Payer for the on-chain fee. Validator operator pays when omitted. */\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-account` request body. */\nexport type CreateHederaAccountRequest = ValidatorBoundRequest & {\n /** Initial HBAR balance for the new account. */\n initialBalance?: number;\n /** Defaults to `full` server-side. `partial` requires `appOwnerPublicKey`. */\n securityMode?: HederaTssSecurityMode;\n /** Required when `securityMode === 'partial'`. */\n appOwnerPublicKey?: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-account` response body. */\nexport type CreateHederaAccountResponse = {\n success: boolean;\n accountId: string;\n transactionId: string;\n hashscanUrl: string;\n securityMode: HederaTssSecurityMode;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/** POST `/api/v3/hedera/tss/update-memo` request body. */\nexport type UpdateHederaMemoRequest = {\n entityId: string;\n accountId: string;\n newMemo: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/update-memo` response body. */\nexport type UpdateHederaMemoResponse = {\n success: boolean;\n transactionId: string;\n hashscanUrl: string;\n status: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-topic` request body. */\nexport type CreateHederaTopicRequest = ValidatorBoundRequest;\n\n/** POST `/api/v3/hedera/tss/create-topic` response body. */\nexport type CreateHederaTopicResponse = {\n success: boolean;\n topicId: string;\n transactionId: string;\n hashscanUrl: string;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/** POST `/api/v3/hedera/tss/submit-message` request body. */\nexport type SubmitHederaMessageRequest = {\n entityId: string;\n topicId: string;\n message: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/submit-message` response body. */\nexport type SubmitHederaMessageResponse = {\n success: boolean;\n sequenceNumber: string | number;\n transactionId: string;\n hashscanUrl: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-token` request body. */\nexport type CreateHederaTokenRequest = ValidatorBoundRequest & {\n name: string;\n symbol: string;\n decimals: number;\n initialSupply: number;\n maxSupply?: number;\n treasuryAccountId: string;\n enableAdminKey?: boolean;\n enableSupplyKey?: boolean;\n enableFreezeKey?: boolean;\n enablePauseKey?: boolean;\n enableWipeKey?: boolean;\n};\n\n/** POST `/api/v3/hedera/tss/create-token` response body. */\nexport type CreateHederaTokenResponse = {\n success: boolean;\n tokenId: string;\n transactionId: string;\n hashscanUrl: string;\n tokenUrl: string;\n keys: Record<string, string>;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/**\n * POST `/api/v3/hedera/tss/mint-token` request body.\n *\n * `validatorTopicId` is OPTIONAL here (unlike the create-* ops) — when\n * supplied + the validator has TokenValidationService wired, the cluster\n * enforces the rules-message mint policy. When omitted, mint runs unchecked.\n */\nexport type MintHederaTokenRequest = {\n entityId: string;\n tokenId: string;\n amount: number;\n decimals?: number;\n validatorTopicId?: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/mint-token` response body. */\nexport type MintHederaTokenResponse = {\n success: boolean;\n transactionId: string;\n hashscanUrl: string;\n newTotalSupply: string;\n mintedAmount: string | number;\n tokenId: string;\n decimals: number;\n};\n\n/**\n * Hedera TSS sub-client — immediate-execute paths where the cluster's TSS\n * quorum signs AND submits the transaction in one HTTP call.\n *\n * Distinct from `client.hedera` (prepare-only) and from\n * `client.tss.signMPC(...)` (sign-only, no submission).\n *\n * @example Mint an HTS token created by the TSS cluster\n * ```ts\n * const minted = await client.hedera.tss.mintToken({\n * entityId: 'tss-entity-1',\n * validatorTimestamp: '1700000000.000000001',\n * validatorTopicId: '0.0.98765',\n * tokenId: '0.0.123456',\n * amount: '1000',\n * });\n * console.log(`Minted tx ${minted.transactionId}, new supply ${minted.newTotalSupply}`);\n * ```\n */\nexport class HederaTssClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a Hedera account whose keys are controlled by the TSS cluster. */\n async createAccount(request: CreateHederaAccountRequest): Promise<CreateHederaAccountResponse> {\n return this.http.post('/hedera/tss/create-account', request);\n }\n\n /** Update an existing account's memo via TSS-signed transaction. */\n async updateMemo(request: UpdateHederaMemoRequest): Promise<UpdateHederaMemoResponse> {\n return this.http.post('/hedera/tss/update-memo', request);\n }\n\n /** Create a TSS-controlled HCS topic. */\n async createTopic(request: CreateHederaTopicRequest): Promise<CreateHederaTopicResponse> {\n return this.http.post('/hedera/tss/create-topic', request);\n }\n\n /** Submit a message to an HCS topic via TSS signing. */\n async submitMessage(request: SubmitHederaMessageRequest): Promise<SubmitHederaMessageResponse> {\n return this.http.post('/hedera/tss/submit-message', request);\n }\n\n /** Create an HTS token with TSS-controlled admin/supply/freeze/pause/wipe keys. */\n async createToken(request: CreateHederaTokenRequest): Promise<CreateHederaTokenResponse> {\n return this.http.post('/hedera/tss/create-token', request);\n }\n\n /** Mint tokens via TSS signing — optionally rule-validated via `validatorTopicId`. */\n async mintToken(request: MintHederaTokenRequest): Promise<MintHederaTokenResponse> {\n return this.http.post('/hedera/tss/mint-token', request);\n }\n}\n","/**\n * Hedera-Specific Transaction Preparation Sub-Client\n *\n * Hedera-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.hedera.*`\n *\n * Operations exposed here:\n * - HCS topic create + topic message (Hedera Consensus Service — no analog on\n * other chains. Most app developers will not need these.)\n * - HTS compliance enable/disable (KYC grant/revoke — server hard-dispatches\n * to the Hedera capability; even though the request schema accepts other\n * chains, the handler always treats it as Hedera).\n * - HTS wipe (force-remove tokens from an account — Hedera-only by schema).\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, etc.), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\nimport { HederaTssClient } from '../../hedera-tss';\n\n/** Topic creation preparation request (Hedera HCS only). */\nexport type PrepareTopicCreateRequest = {\n payerAccountId?: string;\n memo?: string;\n adminKeyRequired?: boolean;\n submitKeyRequired?: boolean;\n entityId: string;\n};\n\n/** Topic message preparation request (Hedera HCS only). */\nexport type PrepareTopicMessageRequest = {\n payerAccountId?: string;\n topicId: string;\n message: string | Record<string, unknown>;\n entityId: string;\n};\n\n/** Token compliance-enable (grant KYC) — Hedera-only by handler dispatch. */\nexport type PrepareTokenComplianceEnableRequest = {\n payerAccountId?: string;\n tokenId: string;\n accountId: string;\n entityId: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n memo?: string;\n};\n\n/** Token compliance-disable (revoke KYC) — Hedera-only by handler dispatch. */\nexport type PrepareTokenComplianceDisableRequest = PrepareTokenComplianceEnableRequest;\n\n/** Token wipe — Hedera-only (literal schema). Force-removes tokens from an account. */\nexport type PrepareTokenWipeRequest = {\n payerAccountId?: string;\n tokenId: string;\n accountId: string;\n amount: string;\n entityId: string;\n memo?: string;\n};\n\n/**\n * Hedera-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'hedera'` before\n * POSTing — callers never write the chain literal themselves.\n *\n * Nested sub-client:\n * - `client.hedera.tss` — TSS-signed immediate-execute paths\n * (HCS topic + HTS token, account create + memo update, all submitted by\n * the cluster in one round-trip). Routes under `/api/v3/hedera/tss/*` —\n * distinct base path from the prepare-only routes on this class.\n */\nexport class HederaTransactionsClient {\n /**\n * TSS-signed Hedera operations (`/api/v3/hedera/tss/*`).\n *\n * Distinct from the prepare-only routes on this class:\n * - `client.hedera.prepareTopicCreate(...)` returns bytes for local sign+submit.\n * - `client.hedera.tss.createTopic(...)` makes the cluster sign+submit in one call.\n *\n * `tssHttp` is the validator's `/api/v3`-rooted HTTP client (different from\n * the `/api/v3/transactions` one this class uses for prepare paths). Both\n * clients are required — the previous single-arg fallback to `http` was\n * unreachable through `SmartEngineClient` (the only call site always\n * passes both).\n */\n public readonly tss: HederaTssClient;\n\n constructor(private readonly http: HttpClient, tssHttp: HttpClient) {\n this.tss = new HederaTssClient(tssHttp);\n }\n\n /** Prepare an HCS topic creation transaction. */\n async prepareTopicCreate(request: PrepareTopicCreateRequest): Promise<PreparedTransaction> {\n return this.http.post('/topic/create/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare an HCS topic message submission. */\n async prepareTopicMessage(request: PrepareTopicMessageRequest): Promise<PreparedTransaction> {\n return this.http.post('/topic/message/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token compliance-enable (KYC grant) transaction. */\n async prepareTokenComplianceEnable(\n request: PrepareTokenComplianceEnableRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/compliance/enable/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token compliance-disable (KYC revoke) transaction. */\n async prepareTokenComplianceDisable(\n request: PrepareTokenComplianceDisableRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/compliance/disable/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token wipe transaction (force-remove tokens from an account). */\n async prepareTokenWipe(request: PrepareTokenWipeRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/wipe/prepare', { ...request, chain: 'hedera' });\n }\n}\n","/**\n * XRPL-Specific Transaction Preparation Sub-Client\n *\n * XRPL-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.xrpl.*`\n *\n * Operations exposed here:\n * - Trust line setup (XRPL TrustSet — XRPL's account-to-issuer authorization\n * for an issued currency. The chain-agnostic analog `associateToken` does\n * not yet exist on the validator; once added, callers should prefer that.)\n *\n * For multi-chain operations (transfer, mint, burn, NFT ops), use the\n * chain-agnostic top-level `client.transactions.*` or top-level `client.*`\n * methods with `chain: 'xrpl'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Trust line preparation request (XRPL TrustSet). */\nexport type PrepareTrustLineRequest = {\n /**\n * XRPL account authorising the trust line. Falls back to `payerAccountId`\n * and ultimately the authenticated session wallet.\n */\n accountAddress?: string;\n payerAccountId?: string;\n /** ISO-4217-like currency code (e.g. \"USD\") or 40-char hex. */\n currency: string;\n /** Classic-address of the issuer. */\n issuerAddress: string;\n /** Decimal-string trust-line limit. Defaults to validator policy when omitted. */\n limit?: string;\n entityId: string;\n};\n\n/**\n * XRPL account-setup preparation request (SignerList + DisableMaster).\n *\n * Builds the ordered transaction set required to flip an XRPL account into\n * sovereignty mode: install the validator-derived SignerList, then disable\n * the master key. Two-step response — caller signs + submits in order.\n *\n * Server schema (the server):\n * - `accountAddress` 25–34 chars (XRPL classic address).\n * - `validatorTimestamp` + `validatorTopicId` required for rule anchoring.\n * - `securityMode='partial'` requires `appOwnerPublicKey` + `entityId`.\n */\nexport type PrepareXrplAccountSetupRequest = {\n payerAccountId?: string;\n /** XRPL classic address whose authorization we're configuring. */\n accountAddress: string;\n validatorTimestamp: string;\n validatorTopicId: string;\n /** Sovereignty mode — `partial` requires `appOwnerPublicKey`. */\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n /** Required in `partial`/`full` modes to identify the TSS entity. */\n entityId?: string;\n};\n\n/**\n * Sovereignty descriptor attached to a prepared XRPL account-setup response.\n * Field shape mirrors the server's `PreparedTransactionSovereignty`.\n */\nexport type PreparedTransactionSovereignty = {\n mode: SecurityMode | 'none';\n appOwnerPublicKey?: string;\n signerListEntries?: Array<{ account: string; weight: number }>;\n signerQuorum?: number;\n};\n\n/**\n * Two-step response from `POST /xrpl/account-setup/prepare`. The caller must\n * sign + submit each step in order — step 0 installs the SignerList, step 1\n * disables the master key.\n */\nexport type XrplAccountSetupSteps = {\n steps: Array<{\n step: number;\n description?: string;\n transactionBytes: string;\n transactionId?: string;\n [k: string]: unknown;\n }>;\n sovereignty: PreparedTransactionSovereignty;\n};\n\n/**\n * XRPL-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'xrpl'` before\n * POSTing — callers never write the chain literal themselves.\n */\nexport class XrplTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare an XRPL TrustSet (trust line) transaction. */\n async prepareTrustLine(request: PrepareTrustLineRequest): Promise<PreparedTransaction> {\n return this.http.post('/trustline/prepare', { ...request, chain: 'xrpl' });\n }\n\n /**\n * Prepare the ordered XRPL account-setup transaction set\n * (SignerListSet + AccountSet DisableMaster) for sovereignty mode.\n *\n * Returns `{ steps, sovereignty }`. Caller signs + submits each step in\n * order; the master key remains usable until the final AccountSet lands.\n */\n async prepareAccountSetup(\n request: PrepareXrplAccountSetupRequest,\n ): Promise<XrplAccountSetupSteps> {\n return this.http.post('/xrpl/account-setup/prepare', { ...request, chain: 'xrpl' });\n }\n}\n","/**\n * Solana-Specific Transaction Preparation Sub-Client\n *\n * Solana-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.solana.*`\n *\n * Operations exposed here:\n * - Token close-account (SPL Token CloseAccount — closes an empty ATA and\n * recovers the SOL rent. No analog on Hedera/XRPL/Polkadot/Cardano.)\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, NFT ops), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods with `chain: 'solana'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Token close-account preparation request (Solana SPL Token). */\nexport type PrepareTokenCloseAccountRequest = {\n payerAccountId?: string;\n /** ATA address to close. Must have zero token balance. */\n account: string;\n /** Recipient of recovered SOL rent lamports. */\n destination: string;\n /** ATA owner — required when not using TSS multisig; vault PDA used for partial/full. */\n owner?: string;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n memo?: string;\n};\n\n/**\n * Solana-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'solana'` before\n * POSTing — callers never write the chain literal themselves.\n */\nexport class SolanaTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare an SPL Token close-account transaction. */\n async prepareTokenCloseAccount(\n request: PrepareTokenCloseAccountRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/close-account/prepare', { ...request, chain: 'solana' });\n }\n}\n","/**\n * Polkadot-Specific Transaction Preparation Sub-Client\n *\n * Polkadot Asset Hub-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.polkadot.*`\n *\n * Operations exposed here:\n * - assets.setTeam — transfer issuer/admin/freezer roles of a pallet-assets\n * asset to new SS58 addresses. No analog on Hedera/XRPL.\n * - assets.setMetadata — update on-chain name/symbol/decimals of a pallet-\n * assets asset post-creation.\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, NFT ops), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods with `chain: 'polkadot'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Asset setTeam preparation request (Polkadot Asset Hub). */\nexport type PrepareAssetSetTeamRequest = {\n payerAccountId?: string;\n /** pallet-assets asset id (u32). */\n assetId: number;\n /** SS58 address — new issuer. */\n issuer: string;\n /** SS58 address — new admin. */\n admin: string;\n /** SS58 address — new freezer. */\n freezer: string;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n ss58Format?: number;\n};\n\n/** Asset setMetadata preparation request (Polkadot Asset Hub). */\nexport type PrepareAssetSetMetadataRequest = {\n payerAccountId?: string;\n /** pallet-assets asset id (u32). */\n assetId: number;\n /** Human-readable asset name (max 64 chars). */\n name: string;\n /** Asset symbol (max 16 chars). */\n symbol: string;\n /** Decimal precision (0..18). */\n decimals: number;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n ss58Format?: number;\n};\n\n/**\n * Polkadot-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'polkadot'`\n * before POSTing — callers never write the chain literal themselves.\n */\nexport class PolkadotTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare a pallet-assets.setTeam transaction. */\n async prepareAssetSetTeam(request: PrepareAssetSetTeamRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/set-team/prepare', { ...request, chain: 'polkadot' });\n }\n\n /** Prepare a pallet-assets.setMetadata transaction. */\n async prepareAssetSetMetadata(\n request: PrepareAssetSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/set-metadata/prepare', { ...request, chain: 'polkadot' });\n }\n}\n","/**\n * Transactions Sub-Client — Chain-Agnostic\n *\n * Provides transaction preparation for the sovereignty model:\n * transactions are prepared on the validator but signed locally by the user.\n *\n * **Every method here accepts the `ChainType` union — never a chain literal.**\n * Chain-specific escape hatches (Hedera HCS topics, XRPL trust lines, Solana\n * close-account, Polkadot setTeam/setMetadata) are exposed via namespaced\n * sub-clients on the main client: `client.hedera`, `client.xrpl`,\n * `client.solana`, `client.polkadot`.\n *\n * @example\n * ```typescript\n * // Multi-chain transfer\n * const prepared = await client.transactions.prepareTransfer({\n * chain: 'xrpl',\n * from: 'rXXX',\n * to: 'rYYY',\n * amount: '100',\n * });\n *\n * // Multi-chain token mint\n * const prepared = await client.transactions.prepareTokenMint({\n * chain: 'solana',\n * tokenId: '<mint-pubkey>',\n * amount: '1000',\n * });\n * ```\n */\n\nimport type { HttpClient } from '../http';\nimport type {\n PreparedTransaction,\n PrepareTransferRequest,\n PrepareNftMintRequest,\n PrepareNftBurnRequest,\n PrepareNftTransferRequest,\n PrepareNftCollectionCreateRequest,\n PrepareNftSetMetadataRequest,\n PrepareNftCollectionSetMetadataRequest,\n PrepareNftCollectionLockRequest,\n PrepareTokenCreateRequest,\n PrepareTokenMintRequest,\n PrepareTokenBurnRequest,\n PrepareTokenAssociateRequest,\n PrepareTokenPauseRequest,\n PrepareTokenUnpauseRequest,\n PrepareTokenRestrictRequest,\n PrepareTokenUnrestrictRequest,\n TransactionInfoResponse,\n} from './types';\n\nexport * from './types';\nexport * from './chains';\n\n/**\n * Chain-agnostic transactions sub-client.\n *\n * NOTE: This client targets `/api/v3/transactions`.\n * The injected `HttpClient` must be configured with that base URL.\n */\nexport class TransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Get transaction preparation service info. */\n async getInfo(): Promise<TransactionInfoResponse> {\n return this.http.get('/info');\n }\n\n /** Prepare a transfer transaction (any supported chain). */\n async prepareTransfer(request: PrepareTransferRequest): Promise<PreparedTransaction> {\n return this.http.post('/transfer/prepare', request);\n }\n\n /** Prepare an NFT mint transaction (any supported chain). */\n async prepareNftMint(request: PrepareNftMintRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/mint/prepare', request);\n }\n\n /** Prepare an NFT burn transaction (any supported chain). */\n async prepareNftBurn(request: PrepareNftBurnRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/burn/prepare', request);\n }\n\n /** Prepare an NFT transfer transaction (any supported chain). */\n async prepareNftTransfer(request: PrepareNftTransferRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/transfer/prepare', request);\n }\n\n /**\n * Prepare an NFT collection-create transaction (Polkadot pallet-nfts /\n * Solana Metaplex master-edition).\n */\n async prepareNftCollectionCreate(\n request: PrepareNftCollectionCreateRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/create/prepare', request);\n }\n\n /** Prepare an NFT item set-metadata transaction (Polkadot pallet-nfts/uniques). */\n async prepareNftSetMetadata(\n request: PrepareNftSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/set-metadata/prepare', request);\n }\n\n /** Prepare an NFT collection set-metadata transaction (Polkadot pallet-nfts/uniques). */\n async prepareNftCollectionSetMetadata(\n request: PrepareNftCollectionSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/set-metadata/prepare', request);\n }\n\n /**\n * Prepare an NFT collection-lock transaction (Polkadot pallet-nfts only).\n * Asset Hub runtimes on pallet-uniques fallback will reject with a 4xx.\n */\n async prepareNftCollectionLock(\n request: PrepareNftCollectionLockRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/lock/prepare', request);\n }\n\n /** Prepare a token creation transaction (Hedera, Solana, Polkadot, Cardano). */\n async prepareTokenCreate(request: PrepareTokenCreateRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/create/prepare', request);\n }\n\n /** Prepare a token mint transaction (any supported chain). */\n async prepareTokenMint(request: PrepareTokenMintRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/mint/prepare', request);\n }\n\n /**\n * Prepare a fungible token burn transaction (Hedera, Solana, Polkadot,\n * Cardano). For NFT burn use `prepareNftBurn` with a `serialNumber`.\n */\n async prepareTokenBurn(request: PrepareTokenBurnRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/burn/prepare', request);\n }\n\n /**\n * Prepare a token association transaction (Hedera HTS associate / Solana\n * ATA create). On chains that don't need explicit association (XRPL uses\n * trustlines — see `client.xrpl.prepareTrustLine`), the server returns 400.\n */\n async prepareTokenAssociate(\n request: PrepareTokenAssociateRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/associate/prepare', request);\n }\n\n /** Prepare a token pause transaction (Hedera, Polkadot, Solana). */\n async prepareTokenPause(request: PrepareTokenPauseRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/pause/prepare', request);\n }\n\n /** Prepare a token unpause transaction (Hedera, Polkadot, Solana). */\n async prepareTokenUnpause(request: PrepareTokenUnpauseRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/unpause/prepare', request);\n }\n\n /**\n * Prepare a token restrict (freeze account) transaction (Hedera, Polkadot,\n * Solana). Freezes `accountId`/`who`/`account` from transacting the token.\n */\n async prepareTokenRestrict(request: PrepareTokenRestrictRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/restrict/prepare', request);\n }\n\n /** Prepare a token unrestrict (unfreeze account) transaction. */\n async prepareTokenUnrestrict(\n request: PrepareTokenUnrestrictRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/unrestrict/prepare', request);\n }\n}\n","/**\n * Snapshots Sub-Client\n *\n * Provides token holder snapshot generation and retrieval.\n *\n * @example\n * ```typescript\n * // Generate a snapshot\n * const { snapshotId } = await client.snapshots.generate('0.0.12345');\n *\n * // Check status\n * const info = await client.snapshots.get(snapshotId);\n *\n * // Download when ready\n * const data = await client.snapshots.download(snapshotId, 'csv');\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n SnapshotInfo,\n SnapshotGenerateOptions,\n SnapshotGenerateResponse,\n SnapshotListResponse,\n SnapshotFormat,\n PaginationOptions,\n} from './types';\n\nexport * from './types';\n\n/**\n * Snapshots Sub-Client\n *\n * Manages token holder snapshots:\n * - Generate point-in-time snapshots of token holders\n * - Query snapshot status and metadata\n * - Download snapshot data in JSON or CSV\n */\nexport class SnapshotsClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate a new snapshot for a token\n *\n * @param tokenId - Token identifier\n * @param options - Generation options (format, filters)\n */\n async generate(\n tokenId: string,\n options?: SnapshotGenerateOptions\n ): Promise<SnapshotGenerateResponse> {\n return this.http.post(\n `/snapshots/generate/${encodePathParam(tokenId)}`,\n options || {}\n );\n }\n\n /**\n * Get snapshot details by ID\n */\n async get(snapshotId: string): Promise<SnapshotInfo> {\n return this.http.get(`/snapshots/${encodePathParam(snapshotId)}`);\n }\n\n /**\n * List snapshots for a token\n */\n async listByToken(\n tokenId: string,\n pagination?: PaginationOptions\n ): Promise<SnapshotListResponse> {\n const params = new URLSearchParams();\n if (pagination?.page !== undefined) params.set('page', String(pagination.page));\n if (pagination?.limit !== undefined) params.set('limit', String(pagination.limit));\n const qs = params.toString();\n return this.http.get(\n `/snapshots/token/${encodePathParam(tokenId)}${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Download snapshot data\n *\n * @param snapshotId - Snapshot ID\n * @param format - Output format (json or csv)\n */\n async download(snapshotId: string, format?: SnapshotFormat): Promise<any> {\n const params = format ? `?format=${encodeURIComponent(format)}` : '';\n return this.http.get(\n `/snapshots/${encodePathParam(snapshotId)}/download${params}`\n );\n }\n}\n","/**\n * HistoricalBalanceClient — thin HTTP wrapper around\n * `POST /api/v3/historical-balance/query`.\n *\n * Two construction modes:\n * 1. **Standalone (CLI):** `new HistoricalBalanceClient({ baseUrl, ... })`.\n * The client builds its own `fetch` URL + headers + timeout.\n * 2. **As a sub-client of `SmartEngineClient`:** the parent passes its\n * shared `HttpClient` via the static `HistoricalBalanceClient.fromHttp`\n * factory so that auth, timeouts, and base-URL resolution stay in one\n * place. See `client.ts`.\n *\n * Zero internal `@hsuite/*` imports — wire types are locally declared in\n * `./historical-balance-types` so the published SDK has no workspace\n * dependency.\n */\n\nimport type { HttpClient } from '../http';\nimport type {\n HistoricalBalanceClientConfig,\n HistoricalBalanceQueryParams,\n HistoricalBalanceResult,\n} from './historical-balance-types';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst ENDPOINT_PATH = '/api/v3/historical-balance/query';\n\n/**\n * Error thrown by `HistoricalBalanceClient` on non-2xx responses or transport\n * failures. Surfaces `statusCode` so callers can map specific codes (400 →\n * input error / unsupported chain, 502 → upstream archive issue) without\n * string-matching messages.\n */\nexport class HistoricalBalanceClientError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'HistoricalBalanceClientError';\n }\n}\n\nexport class HistoricalBalanceClient {\n // Standalone-mode fields (set when the client builds its own fetch).\n private readonly baseUrl?: string;\n private readonly authToken?: string;\n private readonly apiKey?: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl?: typeof fetch;\n\n // Sub-client-mode field (set when wired via SmartEngineClient).\n private readonly http?: HttpClient;\n\n constructor(config: HistoricalBalanceClientConfig | { http: HttpClient }) {\n if ('http' in config) {\n this.http = config.http;\n this.timeoutMs = DEFAULT_TIMEOUT_MS;\n return;\n }\n if (!config.baseUrl) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient: baseUrl is required for standalone construction',\n 400\n );\n }\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.authToken = config.authToken;\n this.apiKey = config.apiKey;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl;\n }\n\n /**\n * Factory used by `SmartEngineClient` to wire this sub-client onto the\n * parent's shared `HttpClient` (which already carries auth + baseUrl + a\n * `/api/v3` prefix). Routes through `/historical-balance/query` since the\n * parent's HttpClient is rooted at `/api/v3`.\n */\n static fromHttp(http: HttpClient): HistoricalBalanceClient {\n return new HistoricalBalanceClient({ http });\n }\n\n /**\n * Query a point-in-time balance.\n *\n * The validator returns the on-chain bigint as a base-10 decimal string.\n * Callers needing arithmetic precision should wrap the result:\n *\n * ```ts\n * const { balance } = await client.historicalBalance.getBalance({ ... });\n * const value = BigInt(balance);\n * ```\n */\n async getBalance(params: HistoricalBalanceQueryParams): Promise<HistoricalBalanceResult> {\n this.validateParams(params);\n\n if (this.http) {\n // Sub-client mode: delegate to the shared HttpClient. The path is\n // relative because the parent client roots at `/api/v3`.\n return this.http.post<HistoricalBalanceResult>('/historical-balance/query', params);\n }\n return this.standaloneFetch(params);\n }\n\n private validateParams(params: HistoricalBalanceQueryParams): void {\n if (!params || typeof params !== 'object') {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: params object is required',\n 400\n );\n }\n const { chain, entityId, account, atTimestamp } = params;\n if (chain !== 'hedera' && chain !== 'xrpl' && chain !== 'polkadot') {\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient.getBalance: unsupported chain \"${String(chain)}\" (expected hedera | xrpl | polkadot)`,\n 400\n );\n }\n if (typeof entityId !== 'string' || entityId.length === 0) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: entityId must be a non-empty string',\n 400\n );\n }\n if (typeof account !== 'string' || account.length === 0) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: account must be a non-empty string',\n 400\n );\n }\n if (\n typeof atTimestamp !== 'number' ||\n !Number.isInteger(atTimestamp) ||\n atTimestamp <= 0\n ) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: atTimestamp must be a positive integer (unix seconds)',\n 400\n );\n }\n }\n\n private async standaloneFetch(\n params: HistoricalBalanceQueryParams\n ): Promise<HistoricalBalanceResult> {\n const url = `${this.baseUrl}${ENDPOINT_PATH}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n if (this.authToken) headers.Authorization = `Bearer ${this.authToken}`;\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n const fetchFn = this.fetchImpl ?? (typeof fetch !== 'undefined' ? fetch : undefined);\n if (!fetchFn) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient: no fetch implementation available (provide fetchImpl)',\n 500\n );\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetchFn(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(params),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const message = err instanceof Error ? err.message : String(err);\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: transport error: ${message}`,\n 0,\n err\n );\n }\n clearTimeout(timer);\n\n let body: unknown;\n const text = await response.text();\n if (text.length > 0) {\n try {\n body = JSON.parse(text);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: non-JSON response (status=${response.status}): ${message}`,\n response.status,\n { raw: text }\n );\n }\n }\n\n if (!response.ok) {\n const detail =\n body && typeof body === 'object' && 'message' in (body as any)\n ? String((body as any).message)\n : `HTTP ${response.status}`;\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: ${detail}`,\n response.status,\n body\n );\n }\n\n return body as HistoricalBalanceResult;\n }\n}\n","/**\n * Settlement Sub-Client\n *\n * Manages cross-chain settlement operations including initiation,\n * status tracking, XRP landing confirmation, and history retrieval.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\n\nexport type {\n SettlementPurpose,\n SettlementAsset,\n SettlementInitiateRequest,\n SettlementStatusResponse,\n SettlementHistoryEntry,\n} from './types';\n\nimport type {\n SettlementInitiateRequest,\n SettlementStatusResponse,\n SettlementHistoryEntry,\n} from './types';\n\nexport class SettlementClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a new settlement operation.\n * Submits source-chain payment details and begins the conversion pipeline.\n */\n async initiate(request: SettlementInitiateRequest): Promise<SettlementStatusResponse> {\n return this.http.post('/settlement/initiate', request);\n }\n\n /**\n * Get the current status of a settlement by ID.\n */\n async getStatus(settlementId: string): Promise<SettlementStatusResponse> {\n return this.http.get(`/settlement/${encodePathParam(settlementId)}/status`);\n }\n\n /**\n * Confirm that XRP has landed on the destination address.\n * Advances the settlement to the next processing step.\n */\n async confirmXrpLanded(settlementId: string): Promise<SettlementStatusResponse> {\n return this.http.post(`/settlement/${encodePathParam(settlementId)}/confirm-xrp`, {});\n }\n\n /**\n * Get settlement history for a given entity.\n */\n async getHistory(entityId: string): Promise<SettlementHistoryEntry[]> {\n return this.http.get(`/settlement/history/${encodePathParam(entityId)}`);\n }\n}\n","/**\n * Governance Sub-Client.\n *\n * Thin HTTP wrapper around `POST /api/v3/governance/simulate`. Lets\n * smart-app authors dry-run governance-rule validation against fixture data\n * without depending on the rules-engine package.\n *\n * Zero internal-lib coupling: types are declared locally in\n * `./governance-types`; the only runtime dependency is the SDK's own\n * `HttpClient` abstraction.\n */\nimport type { HttpClient } from '../http';\nimport type {\n GovernanceSimulateRequest,\n GovernanceValidationResult,\n} from './governance-types';\n\n/**\n * Governance Sub-Client.\n *\n * Exposed as `client.governance` on `SmartEngineClient`.\n *\n * @example\n * ```typescript\n * const result = await client.governance.simulate({\n * config: { governanceTokenId: '0.0.123', proposalThreshold: '100', votingPeriodMs: 604800000 },\n * context: { callerAccountId: '0.0.111', action: 'create_proposal', tokenBalance: '500' },\n * });\n * if (!result.isValid) {\n * console.error('proposal rejected:', result.reason);\n * }\n * ```\n */\nexport class GovernanceClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Dry-run a governance proposal/vote/etc. against `GovernanceMolecule.validate(...)`.\n *\n * Returns whatever `ValidationResult` the molecule produced. A `false`\n * `isValid` is **not** an error — it is a successful \"this proposal is\n * invalid\" outcome and is surfaced via the normal return value.\n *\n * HTTP errors (400 malformed body, 500 unexpected) bubble up as\n * `SdkHttpError` via the shared `HttpClient` layer.\n */\n async simulate(params: GovernanceSimulateRequest): Promise<GovernanceValidationResult> {\n return this.http.post<GovernanceValidationResult>('/governance/simulate', params);\n }\n}\n","/**\n * DAO Dashboard Sub-Client.\n *\n * Read-only rollups indexed by user wallet address — backs the smart-app\n * \"your governance\" home screen. Maps 1:1 to `dao.controller.ts`'s\n * `dashboard/*` route group.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n DaoActiveProposalForUser,\n DaoActivityEntry,\n DaoDashboardStats,\n DaoGovernanceImpact,\n DaoPendingAction,\n DaoVote,\n DashboardActivityOptions,\n DashboardListOptions,\n} from './types';\n\nfunction buildQuery(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, String(value));\n }\n const qs = search.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport class DaoDashboardClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Aggregated dashboard counters for a user's governance home screen. */\n async getStats(userAddress: string): Promise<DaoDashboardStats> {\n return this.http.get(\n `/dao/dashboard/stats/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Active proposals across every DAO the user belongs to, with vote state. */\n async getActiveProposals(\n userAddress: string,\n ): Promise<DaoActiveProposalForUser[]> {\n return this.http.get(\n `/dao/dashboard/active-proposals/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Paginated vote history across DAOs. */\n async getVoteHistory(\n userAddress: string,\n opts: DashboardListOptions = {},\n ): Promise<{ count: number; votes: DaoVote[] }> {\n const qs = buildQuery({ limit: opts.limit, offset: opts.offset });\n return this.http.get(\n `/dao/dashboard/vote-history/${encodePathParam(userAddress)}${qs}`,\n );\n }\n\n /** Activity feed (proposal-created/vote-cast/etc.) across user's DAOs. */\n async getActivity(\n userAddress: string,\n opts: DashboardActivityOptions = {},\n ): Promise<DaoActivityEntry[]> {\n const qs = buildQuery({ limit: opts.limit, daoId: opts.daoId });\n return this.http.get(\n `/dao/dashboard/activity/${encodePathParam(userAddress)}${qs}`,\n );\n }\n\n /** Items the user must act on (sign prepared messages, claim NFTs, …). */\n async getPendingActions(userAddress: string): Promise<DaoPendingAction[]> {\n return this.http.get(\n `/dao/dashboard/pending-actions/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Governance impact metrics — weight delivered, success rate, streak. */\n async getImpact(userAddress: string): Promise<DaoGovernanceImpact> {\n return this.http.get(\n `/dao/dashboard/impact/${encodePathParam(userAddress)}`,\n );\n }\n}\n","/**\n * DAO Sub-Client.\n *\n * Wraps every public DAO endpoint (mounted under `/api/v3/dao`).\n *\n * Why a dedicated sub-client:\n * - The controller exposes ~30 endpoints across 5 surfaces (DAOs,\n * proposals, votes, treasury, members) plus a dashboard rollup. Before\n * this client there was no SDK entrypoint at all — smart-apps were\n * hand-rolling fetch calls.\n * - Types mirror `multi-chain-core`'s `dao.types.ts` over the wire (see\n * `./types`) so smart-app bundles don't drag NestJS / Mongoose.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\nimport { DaoDashboardClient } from './dashboard-client';\nimport type {\n AddDaoMemberRequest,\n AddMemberResponse,\n CastVoteRequest,\n CastVoteResponse,\n ClaimDaoMemberNftRequest,\n ClaimNftResponse,\n CreateDaoProposalRequest,\n CreateDaoRequest,\n CreateDaoResponse,\n CreateProposalResponse,\n DaoConfig,\n DaoProposalConfig,\n DaoVote,\n DaoWithProposalsResponse,\n ExecuteProposalResponse,\n ListDaosOptions,\n ListDaosResponse,\n ListMembersOptions,\n ListMembersResponse,\n ListProposalsOptions,\n ListProposalsResponse,\n MemberNftResponse,\n PrepareDaoProposalRequest,\n PrepareProposalResponse,\n PrepareVoteRequest,\n PrepareVoteResponse,\n ProposalResultsResponse,\n RemoveMemberResponse,\n SubmitSignedProposalRequest,\n SubmitSignedProposalResponse,\n SubmitSignedVoteRequest,\n TreasuryBalancesResponse,\n TreasuryHistoryOptions,\n TreasuryHistoryResponse,\n VoteListOptions,\n VotesListResponse,\n} from './types';\n\nfunction buildQuery(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, String(value));\n }\n const qs = search.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction encodeDaoId(daoId: string): string {\n return encodePathParam(daoId);\n}\n\nfunction encodeProposalId(proposalId: string): string {\n return encodePathParam(proposalId);\n}\n\nfunction encodeAddress(address: string): string {\n return encodePathParam(address);\n}\n\n/**\n * DAO Sub-Client — exposed as `client.dao` on `SmartEngineClient`.\n *\n * @example Create a DAO and submit a proposal\n * ```typescript\n * const { dao } = await client.dao.create({\n * name: 'Foo DAO',\n * description: '...',\n * membershipModel: 'token-only',\n * governanceToken: { symbol: 'FOO', chains: [{ chain: 'xrpl', tokenId: 'FOO.rISSUER', decimals: 8 }] },\n * votingRules: { ... },\n * treasuryChains: ['xrpl'],\n * createdBy: 'rUserAddress',\n * });\n * const { proposal } = await client.dao.createProposal(dao.daoId, {\n * type: 'dao_treasury_transfer',\n * title: 'Pay grant',\n * description: '...',\n * proposer: 'rUserAddress',\n * actions: [...],\n * });\n * ```\n */\nexport class DaoClient {\n /** Per-user rollups for the smart-app's governance home screen. */\n public readonly dashboard: DaoDashboardClient;\n\n constructor(private readonly http: HttpClient) {\n this.dashboard = new DaoDashboardClient(http);\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n /** Create a new DAO. */\n async create(request: CreateDaoRequest): Promise<CreateDaoResponse> {\n return this.http.post('/dao/create', request);\n }\n\n /** List DAOs with optional status / creator filters. */\n async list(opts: ListDaosOptions = {}): Promise<ListDaosResponse> {\n const qs = buildQuery({ status: opts.status, createdBy: opts.createdBy });\n return this.http.get(`/dao/list${qs}`);\n }\n\n /** Fetch a single DAO by ID. */\n async get(daoId: string): Promise<DaoConfig> {\n return this.http.get(`/dao/${encodeDaoId(daoId)}`);\n }\n\n /** Fetch a DAO together with its proposals (single round-trip). */\n async getWithProposals(daoId: string): Promise<DaoWithProposalsResponse> {\n return this.http.get(`/dao/${encodeDaoId(daoId)}/with-proposals`);\n }\n\n // ─── Proposals ────────────────────────────────────────────────────────────\n\n /** List proposals for a DAO, optionally filtered by status / proposer. */\n async listProposals(\n daoId: string,\n opts: ListProposalsOptions = {},\n ): Promise<ListProposalsResponse> {\n const qs = buildQuery({ status: opts.status, proposer: opts.proposer });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/proposals${qs}`);\n }\n\n /** Create a proposal (server activates the proposal immediately). */\n async createProposal(\n daoId: string,\n request: CreateDaoProposalRequest,\n ): Promise<CreateProposalResponse> {\n return this.http.post(`/dao/${encodeDaoId(daoId)}/proposals`, request);\n }\n\n /**\n * Prepare a proposal for off-chain signing (returns the message to sign).\n * Use {@link signProposal} to submit the signature once captured.\n */\n async prepareProposal(\n daoId: string,\n request: PrepareDaoProposalRequest,\n ): Promise<PrepareProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/prepare`,\n request,\n );\n }\n\n /** Submit the signed prepared-proposal payload. */\n async signProposal(\n daoId: string,\n proposalId: string,\n request: SubmitSignedProposalRequest,\n ): Promise<SubmitSignedProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/sign`,\n request,\n );\n }\n\n /** Prepare a vote message for off-chain signing. */\n async prepareVote(\n daoId: string,\n proposalId: string,\n request: PrepareVoteRequest,\n ): Promise<PrepareVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/prepare-vote`,\n request,\n );\n }\n\n /** Submit the signed prepared-vote payload. */\n async submitVote(\n daoId: string,\n proposalId: string,\n request: SubmitSignedVoteRequest,\n ): Promise<CastVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/submit-vote`,\n request,\n );\n }\n\n /**\n * Cast a vote directly (no separate prepare/sign hop — server records the\n * vote on the caller's behalf). Use {@link prepareVote} + {@link submitVote}\n * when the smart-app's signing model requires client-side signing.\n */\n async vote(\n daoId: string,\n proposalId: string,\n request: CastVoteRequest,\n ): Promise<CastVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/vote`,\n request,\n );\n }\n\n /**\n * Manually execute a passed proposal via TSS. Proposals auto-execute after\n * the execution delay; this endpoint is for the governance-admin override\n * path.\n */\n async execute(\n daoId: string,\n proposalId: string,\n ): Promise<ExecuteProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/execute`,\n {},\n );\n }\n\n /** Paginated vote list for a proposal. */\n async getVotes(\n daoId: string,\n proposalId: string,\n opts: VoteListOptions = {},\n ): Promise<VotesListResponse> {\n const qs = buildQuery({ limit: opts.limit, offset: opts.offset });\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/votes${qs}`,\n );\n }\n\n /** Resolved tally / quorum / pass-fail for a proposal. */\n async getResults(\n daoId: string,\n proposalId: string,\n ): Promise<ProposalResultsResponse> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/results`,\n );\n }\n\n /** Raw vote counts by option ID (no quorum / pass logic). */\n async getVoteCounts(\n daoId: string,\n proposalId: string,\n ): Promise<Record<string, number>> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/vote-counts`,\n );\n }\n\n /** Fetch a single voter's vote on a proposal. */\n async getVoterRecord(\n daoId: string,\n proposalId: string,\n voterAddress: string,\n ): Promise<DaoVote> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/voter/${encodeAddress(voterAddress)}`,\n );\n }\n\n /** Fetch a single proposal by ID. */\n async getProposal(\n daoId: string,\n proposalId: string,\n ): Promise<DaoProposalConfig> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}`,\n );\n }\n\n // ─── Treasury ─────────────────────────────────────────────────────────────\n\n /** Per-chain treasury balances for a DAO. */\n async getTreasury(\n daoId: string,\n chain?: string,\n ): Promise<TreasuryBalancesResponse> {\n const qs = buildQuery({ chain });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/treasury${qs}`);\n }\n\n /** Paginated treasury transaction history (in/out/swap). */\n async getTreasuryHistory(\n daoId: string,\n opts: TreasuryHistoryOptions = {},\n ): Promise<TreasuryHistoryResponse> {\n const qs = buildQuery({\n chain: opts.chain,\n limit: opts.limit,\n offset: opts.offset,\n });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/treasury/history${qs}`);\n }\n\n // ─── Members ──────────────────────────────────────────────────────────────\n\n /** List a DAO's members, optionally filtered by status. */\n async listMembers(\n daoId: string,\n opts: ListMembersOptions = {},\n ): Promise<ListMembersResponse> {\n const qs = buildQuery({ status: opts.status });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/members${qs}`);\n }\n\n /** Add a member to a DAO. */\n async addMember(\n daoId: string,\n request: AddDaoMemberRequest,\n ): Promise<AddMemberResponse> {\n return this.http.post(`/dao/${encodeDaoId(daoId)}/members`, request);\n }\n\n /** Remove a member from a DAO. */\n async removeMember(\n daoId: string,\n address: string,\n ): Promise<RemoveMemberResponse> {\n return this.http.delete(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}`,\n );\n }\n\n /** Bind a held membership NFT serial to a member record. */\n async claimMemberNft(\n daoId: string,\n address: string,\n request: ClaimDaoMemberNftRequest,\n ): Promise<ClaimNftResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}/claim-nft`,\n request,\n );\n }\n\n /** Fetch the NFT serials + status for a member. */\n async getMemberNft(\n daoId: string,\n address: string,\n ): Promise<MemberNftResponse> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}/nft`,\n );\n }\n}\n","/**\n * Personhood Sub-Client\n *\n * Thin HTTP wrapper around `POST /api/v3/personhood/verify`. Pure HTTP —\n * never imports a server-side personhood module or the baas-core types.\n * The locally-declared types in `./personhood-types` mirror the server's\n * wire shape; see that file for the source-of-truth annotation.\n *\n * @example\n * ```typescript\n * const cert = await client.personhood.verify({\n * candidate: '0.0.12345',\n * proof: {\n * attestationMethod: 'web-of-trust',\n * payload: { vouchers: ['0.0.111', '0.0.222'] },\n * },\n * });\n * if (!cert) {\n * console.log('verification rejected');\n * return;\n * }\n * console.log('cert expires at', cert.expiresAt);\n * ```\n */\nimport type { HttpClient } from '../http';\nimport { SdkHttpError } from '../http';\nimport type {\n PersonhoodCert,\n PersonhoodVerifyParams,\n} from './personhood-types';\n\n/**\n * Error envelope emitted by the validator when the hub has no\n * `IPersonhoodVerifier` wired. Exposed as a constant so callers can\n * branch on the `error` discriminator without re-typing the string.\n */\nexport const PERSONHOOD_VERIFIER_NOT_CONFIGURED = 'personhood_verifier_not_configured' as const;\n\n/**\n * Thin HTTP client for the personhood endpoint.\n *\n * Method outcomes:\n * - HTTP 200 with a cert object → resolves to `PersonhoodCert`.\n * - HTTP 200 with `null` body → resolves to `null` (clean rejection).\n * - HTTP 400 → throws `SdkHttpError(400)`.\n * - HTTP 503 → throws `SdkHttpError(503)` whose\n * `.details.error === 'personhood_verifier_not_configured'`.\n * - HTTP 5xx → throws `SdkHttpError` with the upstream status.\n * - Network / timeout → throws `SdkHttpError(0|408)`.\n */\nexport class PersonhoodClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Verify a personhood proof for `candidate`.\n *\n * Returns the issued cert on accept, `null` on clean rejection. All\n * other failure modes (validation, transport, 5xx) propagate as\n * `SdkHttpError`.\n */\n async verify(params: PersonhoodVerifyParams): Promise<PersonhoodCert | null> {\n const result = await this.http.post<PersonhoodCert | null>(\n '/personhood/verify',\n {\n candidate: params.candidate,\n proof: params.proof,\n },\n );\n // The validator returns `null` literally on clean rejection, and the\n // HTTP layer surfaces empty `204 No Content` bodies as `undefined`.\n // Treat both as the same \"no cert\" outcome so callers only branch on\n // `=== null`.\n if (result === undefined) return null;\n return result;\n }\n}\n\nexport type { PersonhoodCert, PersonhoodVerifyParams } from './personhood-types';\n\n/**\n * Predicate: narrows an unknown error to a 503\n * `personhood_verifier_not_configured` envelope. Use in smart-app code to\n * treat unconfigured hubs as a graceful downgrade.\n */\nexport function isPersonhoodVerifierNotConfigured(\n err: unknown,\n): err is SdkHttpError & { details: { error: typeof PERSONHOOD_VERIFIER_NOT_CONFIGURED } } {\n if (!(err instanceof SdkHttpError)) return false;\n if (err.statusCode !== 503) return false;\n const d = err.details as unknown;\n if (d === null || typeof d !== 'object') return false;\n return (d as Record<string, unknown>).error === PERSONHOOD_VERIFIER_NOT_CONFIGURED;\n}\n","/**\n * Agents Sub-Client\n *\n * Manages autonomous smart agents on the host platform.\n *\n * @example\n * ```typescript\n * // Register an agent\n * const agent = await baas.agents.register({\n * name: 'Trading Bot',\n * capabilities: ['trade', 'withdraw'],\n * rules: { maxTradeAmount: '1000', allowedPairs: ['HBAR/USDC'] },\n * });\n *\n * // Fund and trade\n * await baas.agents.fund(agent.agentId, { chain: 'hedera', amount: '500' });\n * await baas.agents.trade(agent.agentId, { chain: 'hedera', pair: 'HBAR/USDC', side: 'buy', amount: '100' });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type { PreparedTransactionResponse } from '../../_vendor';\nimport type {\n AgentRegisterRequest,\n AgentInfo,\n AgentCertification,\n AgentRules,\n AgentEvent,\n AgentBalance,\n AgentFundRequest,\n AgentTradeRequest,\n AgentWithdrawRequest,\n AgentExecuteRequest,\n AgentExecuteResponse,\n} from './types';\n\nexport * from './types';\nexport { validateAgentRules } from './types';\nexport type { PreparedTransactionResponse } from '../../_vendor';\n\n/**\n * Envelope returned by `fund` / `trade` / `withdraw` on the host. The\n * server wraps the underlying `PreparedTransactionResponse` with a\n * `success: true` flag so the caller can distinguish the\n * lifecycle-success path from a 400/404 error response.\n */\nexport type AgentPreparedTransactionResponse = PreparedTransactionResponse & {\n success: true;\n};\n\n/**\n * Envelope returned by `fund` when the requested amount trips an\n * approval-required rule: instead of prepared transaction bytes the host\n * records a pending operation and returns its id for later approve/reject.\n * Discriminate from {@link AgentPreparedTransactionResponse} with\n * {@link isAgentFundPending}.\n */\nexport type AgentPendingApprovalResponse = {\n success: true;\n pendingOpId: string;\n agentId: string;\n action: string;\n status: 'awaiting_approval';\n description: string;\n};\n\n/**\n * Type guard distinguishing the pending-approval envelope from the\n * prepared-transaction envelope returned by {@link AgentsClient.fund}.\n */\nexport function isAgentFundPending(\n r: AgentPreparedTransactionResponse | AgentPendingApprovalResponse,\n): r is AgentPendingApprovalResponse {\n return 'pendingOpId' in r;\n}\n\nexport class AgentsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Register a new agent */\n async register(request: AgentRegisterRequest, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.post('/api/v3/baas/agents/register', request, opts);\n }\n\n /** Get agent details */\n async get(agentId: string, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}`, opts);\n }\n\n /** List all agents */\n async list(opts?: HttpCallOptions): Promise<{ agents: AgentInfo[]; total: number }> {\n return this.http.get('/api/v3/baas/agents', opts);\n }\n\n /**\n * Fund agent treasury (owner-only). Normally returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope —\n * the caller is expected to sign and submit the prepared bytes. When the\n * amount trips an approval-required rule the host instead returns an\n * {@link AgentPendingApprovalResponse}; discriminate with\n * {@link isAgentFundPending}.\n */\n async fund(\n agentId: string,\n request: AgentFundRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse | AgentPendingApprovalResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/fund`, request, opts);\n }\n\n /**\n * Execute a trade (agent-wallet OR owner). Returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope.\n */\n async trade(\n agentId: string,\n request: AgentTradeRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/trade`, request, opts);\n }\n\n /**\n * Withdraw from agent treasury (owner-only). Returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope.\n */\n async withdraw(\n agentId: string,\n request: AgentWithdrawRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/withdraw`, request, opts);\n }\n\n /**\n * Execute a generic, declared capability (agent-wallet OR owner). The\n * chain-agnostic general form of an agent action: the capability may settle\n * on-chain, act off-chain, or both. Returns the ordered step results.\n */\n async execute(\n agentId: string,\n request: AgentExecuteRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentExecuteResponse & { success: true }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/execute`, request, opts);\n }\n\n /** Pause an agent */\n async pause(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/pause`, {}, opts);\n }\n\n /** Resume a paused agent */\n async resume(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/resume`, {}, opts);\n }\n\n /** Revoke an agent (permanent) */\n async revoke(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/revoke`, {}, opts);\n }\n\n /**\n * Get an agent's certification snapshot (identity, rule refs, BLS group key,\n * and recent on-chain activity). A 404 throws `SdkHttpError` via `http.get`\n * — parity with {@link get}.\n */\n async certification(agentId: string, opts?: HttpCallOptions): Promise<AgentCertification> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/certification`, opts);\n }\n\n /**\n * Update agent rules.\n *\n * Server route is PATCH `/api/v3/baas/agents/:agentId/rules`\n * (`agents.controller.ts:375`). The previous PUT variant 404'd because\n * Nest matched the dynamic `:agentId` GET/POST handlers and rejected\n * the verb mismatch.\n */\n async updateRules(agentId: string, rules: Partial<AgentRules>, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.patch(`/api/v3/baas/agents/${encodePathParam(agentId)}/rules`, rules, opts);\n }\n\n /** Get agent events */\n async getEvents(agentId: string, opts?: HttpCallOptions): Promise<{ events: AgentEvent[]; total: number }> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/events`, opts);\n }\n\n /** Get agent balances across chains */\n async getBalances(agentId: string, opts?: HttpCallOptions): Promise<{ balances: AgentBalance[] }> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/balances`, opts);\n }\n\n /** Approve a pending agent operation */\n async approve(agentId: string, operationId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/approve/${encodePathParam(operationId)}`, {}, opts);\n }\n\n /** Reject a pending agent operation */\n async reject(agentId: string, operationId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/reject/${encodePathParam(operationId)}`, {}, opts);\n }\n}\n","/**\n * Deployment Sub-Client — runtime orchestration.\n *\n * The four-step deploy flow:\n *\n * 1. `init` — server allocates appId + per-app Harbor project + ephemeral push robot creds.\n * 2. (out-of-band) — customer `docker login <registry.server>` then `docker push <registry.server>/<registry.repository>:<tag>`.\n * 3. `uploadFrontend` — (optional) tarball with the SPA bundle.\n * 4. `deploy` — server reconciles to k8s.\n *\n * @example\n * ```typescript\n * const init = await baas.deployment.init({ name: 'my-app', port: 3200, services: ['database'] });\n *\n * // Use the credentials returned in init.registry to push the backend image.\n * // init.registry.server → e.g. 'harbor.testnet.hsuite.network' (public round-robin)\n * // init.registry.repository → e.g. 'hsuite-customers-<appId>'\n * // init.registry.username → per-project robot account\n * // init.registry.password → per-app push secret (re-derivable, not persisted as plaintext)\n * //\n * // docker login <init.registry.server> -u <init.registry.username> -p <init.registry.password>\n * // docker push <init.registry.server>/<init.registry.repository>:v1\n *\n * await baas.deployment.deploy(init.appId, { tag: 'v1', replicas: 2 });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n BaasInitRequest,\n BaasInitResponse,\n BaasReissuePushCredentialsResponse,\n BaasDeployRequest,\n BaasDeployResponse,\n BaasUploadFrontendResponse,\n BaasRollbackRequest,\n BaasRuntimeStatus,\n BaasAppListResponse,\n BaasSetWebhookResponse,\n BaasRotateKekResponse,\n BaasRevokeKekResponse,\n DeployedAppInfo,\n} from '../types';\n\nexport class DeploymentClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Step 1 — allocate appId + receive ephemeral push credentials for\n * the cluster's per-tenant Harbor project.\n *\n * Each app gets its own Harbor project (`hsuite-customers-<appId>`)\n * isolated by Harbor's RBAC. The push robot returned in\n * `registry.{username, password}` is scoped to that project only —\n * it cannot read or write any other tenant's images.\n *\n * **Single-use secret discipline:** `registry.password` is returned\n * exactly once and is NOT persisted server-side. Store it locally\n * for the `docker push` and discard. To rotate, call `init` again\n * (issues a new robot under the same project).\n *\n * Use the credentials to `docker login` + `docker push`, then call\n * {@link deploy} with the pushed image tag.\n */\n async init(request: BaasInitRequest): Promise<BaasInitResponse> {\n return this.http.post('/api/v3/baas/deployment/apps/init', request);\n }\n\n /**\n * Issue ephemeral Harbor push credentials for a smart-app that ALREADY\n * EXISTS — the MINT-FIRST / DEPLOY-LAST credentials-push call.\n *\n * Unlike {@link init} (which historically allocated a fresh entity), this\n * takes the developer's pre-existing `appId` — the `SUBSCRIPTION_APP_ID`\n * minted by `hsuite subscribe` (`appId == DKG entityId`) — and ONLY\n * (re)provisions the per-app Harbor project + push robot. The server creates\n * no DKG entity and no subscription; it asserts the caller owns the app and\n * that its subscription is ACTIVE (402 otherwise) first.\n *\n * Returns the same `{ appId, registry }` shape as {@link init}. Single-use\n * secret discipline applies to `registry.password` exactly as in `init`.\n *\n * This is the credentials path the mint-first `hsuite deploy` uses to obtain\n * push creds for the developer's already-minted subscription app\n * (`POST /apps/:appId/credentials/push`). The `hsuite redeploy` re-push path\n * uses {@link reissuePushCredentials} instead, which targets a dedicated\n * `credentials/reissue` route with stricter SUSPENDED-app + Harbor-failure\n * handling.\n */\n async pushCredentials(appId: string): Promise<BaasInitResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/push`,\n {},\n );\n }\n\n /**\n * Reissue ephemeral Harbor push credentials for an EXISTING app, WITHOUT\n * allocating a new appId / entity. Unlike {@link init} — which historically\n * forked a fresh smart-app entity (and a fresh paid subscription) on every\n * call — this re-binds to an app the developer already owns: the `appId` is\n * echoed back unchanged and only a new single-use `registry.password` push\n * robot is minted. Same `{ appId, registry }` response shape as `init`.\n *\n * Owner-only + active-subscription gated server-side. This is the credential\n * path `hsuite redeploy` uses so a re-push does not cost a new entity +\n * subscription each run. Targets the dedicated\n * `POST /apps/:appId/credentials/reissue` route (distinct from\n * {@link pushCredentials}'s first-deploy `credentials/push`): the reissue\n * route additionally refuses SUSPENDED apps and surfaces Harbor failures\n * loudly rather than returning placeholder creds.\n */\n async reissuePushCredentials(\n appId: string,\n ): Promise<BaasReissuePushCredentialsResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/reissue`,\n {},\n );\n }\n\n /**\n * Step 3 (optional) — upload the SPA tarball.\n *\n * The tarball is content-addressed (SHA-256) and mounted read-only\n * into the customer's pod alongside the backend container. Returns\n * the hash + size so the caller can verify the upload.\n */\n async uploadFrontend(\n appId: string,\n bundle: Blob | Buffer,\n filename = 'bundle.tar.gz'\n ): Promise<BaasUploadFrontendResponse> {\n // The smart-host upload handler uses `FileInterceptor('bundle', ...)` —\n // the multipart field name MUST be `bundle`, not the SDK's default\n // `'file'`. Override explicitly.\n return this.http.upload(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/frontend`,\n bundle,\n filename,\n undefined,\n 'bundle',\n );\n }\n\n /**\n * Step 4 — reconcile the runtime to k8s.\n *\n * Returns immediately with `status: 'deploying'`. Poll {@link status}\n * until `runtime.runtimeState === 'RUNNING'` for the URL to be live.\n */\n async deploy(appId: string, request: BaasDeployRequest): Promise<BaasDeployResponse> {\n return this.http.post(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/deploy`, request);\n }\n\n /**\n * Roll back to a previously-deployed image tag (must exist in\n * `runtime.deploymentHistory[]`).\n */\n async rollback(appId: string, request: BaasRollbackRequest): Promise<BaasDeployResponse> {\n return this.http.post(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/rollback`, request);\n }\n\n /**\n * Live combined lifecycle + runtime status of an app.\n */\n async status(appId: string): Promise<BaasRuntimeStatus> {\n return this.http.get(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/status`);\n }\n\n /**\n * List all deployed apps for the authenticated developer.\n */\n async list(): Promise<BaasAppListResponse> {\n return this.http.get('/api/v3/smart-apps');\n }\n\n /**\n * Get app details.\n */\n async get(appId: string): Promise<DeployedAppInfo> {\n return this.http.get(`/api/v3/smart-apps/${encodePathParam(appId)}`);\n }\n\n /**\n * Update app configuration.\n *\n * @param appId - The app to update.\n * @param updates - Partial deploy-request fields to apply.\n * @returns The updated app info.\n */\n async update(appId: string, updates: Partial<BaasDeployRequest>): Promise<DeployedAppInfo> {\n return this.http.put(`/api/v3/smart-apps/${encodePathParam(appId)}`, updates);\n }\n\n /**\n * Delete an app (runtime effect: namespace teardown).\n */\n async delete(appId: string): Promise<{ success: boolean }> {\n return this.http.delete(`/api/v3/smart-apps/${encodePathParam(appId)}`);\n }\n\n /**\n * Suspend an app (runtime effect: scale to zero).\n */\n async suspend(appId: string): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/smart-apps/${encodePathParam(appId)}/suspend`, {});\n }\n\n /**\n * Resume a suspended app (runtime effect: scale back up).\n */\n async resume(appId: string): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/smart-apps/${encodePathParam(appId)}/resume`, {});\n }\n\n /**\n * Get deployment statistics.\n */\n async getStats(): Promise<{\n totalApps: number;\n activeApps: number;\n totalOwners: number;\n }> {\n return this.http.get('/api/v3/smart-apps/stats');\n }\n\n /**\n * Register or update the developer-facing webhook URL for runtime\n * lifecycle events (`runtime.deploying` / `running` / `failed` /\n * `suspended` / `resumed` / `retired`).\n *\n * The host's `DeployWebhookDispatcher` POSTs to this URL whenever the\n * smart-deployer reconciler emits a `runtime.*` NATS event, signed with\n * the returned `webhookSecret`:\n *\n * `X-HSuite-Signature: sha256=<hmac-sha256(secret, raw-body)>`\n *\n * Store `webhookSecret` server-side and re-compute the signature over\n * the raw delivery body to verify authenticity. The secret is surfaced\n * only on PUT — re-call this method to rotate.\n *\n * Server validates: HTTPS only, no loopback / RFC1918 / link-local /\n * CGNAT / cloud metadata destinations (SSRF guard).\n */\n async setWebhook(appId: string, webhookUrl: string): Promise<BaasSetWebhookResponse> {\n return this.http.put(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/webhook`, {\n webhookUrl,\n });\n }\n\n /**\n * Per-app Prometheus metrics in the standard exposition format\n * (text/plain; version=0.0.4). The server filters smart-deployer's\n * `/metrics` to lines that mention this app's `appId` label, while\n * preserving HELP / TYPE comment lines and cluster-wide metrics.\n *\n * Returned as a raw string so callers can pipe directly into a\n * Prometheus parser (`prom-client`, `parse-prometheus-text-format`,\n * etc.) without an intermediate JSON decode that would corrupt the\n * exposition format.\n */\n async getMetrics(appId: string): Promise<string> {\n return this.http.getText(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/metrics`);\n }\n\n /**\n * Rotate the smart-app's tenant-secret KEK.\n *\n * Re-encrypts every `runtime.env` envelope at the new KEK version\n * transparently. Previous versions remain valid until explicitly\n * revoked via {@link revokeKek}. Owner-only.\n */\n async rotateKek(appId: string): Promise<BaasRotateKekResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/rotate-kek`,\n {},\n );\n }\n\n /**\n * Revoke a tenant-secret KEK version (emergency burn).\n *\n * Envelopes at the revoked version become operationally dead —\n * decryption inside the smart-app pod fails. Owner-only and\n * **irreversible**. Returns the cumulative list of revoked versions\n * for this app.\n */\n async revokeKek(appId: string, version: number): Promise<BaasRevokeKekResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/revoke-kek`,\n { version },\n );\n }\n}\n","/**\n * Bridge Sub-Client.\n *\n * Mounted on `client.bridge`. Endpoints map 1:1 to the validator bridge routes:\n *\n * - POST `/bridge/create` → `create`\n * - GET `/bridge/list` → `list` (Public)\n * - GET `/bridge/:bridgeId` → `get` (Public)\n * - POST `/bridge/:bridgeId/port` → `port`\n * - POST `/bridge/:bridgeId/return` → `return`\n * - GET `/bridge/:bridgeId/status/:claimId` → `getStatus` (Public)\n * - GET `/bridge/:bridgeId/supply` → `getSupply` (Public)\n * - GET `/bridge/:bridgeId/claims` → `listClaims` (Public)\n *\n * Operator-only routes (PATCH `/rules`, POST `/pause`, POST `/close`) are\n * intentionally not surfaced — those flip the cross-cluster state of a\n * live bridge and belong in governance tooling, not SDK callers.\n *\n * @example List bridges then port tokens through one\n * ```ts\n * const { bridges } = await client.bridge.list();\n * const port = await client.bridge.port(bridges[0].bridgeId, {\n * fromChain: 'hedera',\n * toChain: 'xrpl',\n * amount: '100',\n * recipient: 'rRecipient...',\n * });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n CreateBridgeRequest,\n CreateBridgeResponse,\n BridgeConfig,\n ListBridgesOptions,\n ListBridgesResponse,\n PortRequest,\n ReturnRequest,\n PortResult,\n BridgeClaimRecord,\n BridgeSupply,\n ListClaimsOptions,\n ListClaimsResponse,\n} from './bridge-types';\n\nexport class BridgeClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new bridge instance — triggers DKG + TSS entity creation server-side. */\n async create(request: CreateBridgeRequest): Promise<CreateBridgeResponse> {\n return this.http.post('/bridge/create', request);\n }\n\n /** List bridges. Both filters are optional. */\n async list(options?: ListBridgesOptions): Promise<ListBridgesResponse> {\n const params = new URLSearchParams();\n if (options?.status) params.append('status', options.status);\n if (options?.sourceChain) params.append('sourceChain', options.sourceChain);\n const qs = params.toString();\n return this.http.get(`/bridge/list${qs ? `?${qs}` : ''}`);\n }\n\n /** Get bridge configuration. */\n async get(bridgeId: string): Promise<BridgeConfig> {\n return this.http.get(`/bridge/${encodePathParam(bridgeId)}`);\n }\n\n /** Port tokens from source → destination. */\n async port(bridgeId: string, request: PortRequest): Promise<PortResult> {\n return this.http.post(`/bridge/${encodePathParam(bridgeId)}/port`, request);\n }\n\n /**\n * Return tokens from destination → source. Only meaningful on two-way\n * bridges; the validator rejects the call on one-way bridges with a 400.\n *\n * Method name is `return_` to avoid colliding with the reserved JS\n * keyword in some downstream codegen. Prefer `client.bridge.return(...)`\n * via the named alias below.\n */\n async return(bridgeId: string, request: ReturnRequest): Promise<PortResult> {\n return this.http.post(`/bridge/${encodePathParam(bridgeId)}/return`, request);\n }\n\n /** Get claim status by claim ID under a given bridge. */\n async getStatus(bridgeId: string, claimId: string): Promise<BridgeClaimRecord> {\n return this.http.get(\n `/bridge/${encodePathParam(bridgeId)}/status/${encodePathParam(claimId)}`,\n );\n }\n\n /** Get aggregate supply view for a bridge. */\n async getSupply(bridgeId: string): Promise<BridgeSupply> {\n return this.http.get(`/bridge/${encodePathParam(bridgeId)}/supply`);\n }\n\n /** List bridge claims with optional pagination. */\n async listClaims(\n bridgeId: string,\n options?: ListClaimsOptions,\n ): Promise<ListClaimsResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n const qs = params.toString();\n return this.http.get(\n `/bridge/${encodePathParam(bridgeId)}/claims${qs ? `?${qs}` : ''}`,\n );\n }\n}\n","/**\n * Resources Sub-Client.\n *\n * Mounted on `client.resources`. Wraps the validator resources routes:\n *\n * - GET `/resources/summary` → `getSummary`\n * - GET `/resources/consumption/:appId` → `getConsumption`\n * - GET `/resources/consumption/:appId/history` → `getHistory`\n * - GET `/resources/consumption/:appId/ledger` → `getLedger`\n * - GET `/resources/consumption/:appId/status` → `getStatus`\n * - GET `/resources/consumption/:appId/breakdown` → `getBreakdown`\n * - GET `/resources/nodes` → `listNodes`\n * - GET `/resources/nodes/:nodeId` → `getNode`\n *\n * The two resource controllers (`ResourcesController` here +\n * `ResourceController` in `monitoring/`) are kept separate because they\n * serve different audiences; this wrapper exposes the smart-app facing\n * surface only.\n *\n * @example Inspect today's consumption for a smart-app\n * ```ts\n * const summary = await client.resources.getConsumption('app_abc');\n * console.log(`${summary.requests} requests, ${summary.storageMb} MB storage today`);\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n ResourceSummaryResponse,\n ResourceConsumptionResponse,\n ResourceHistoryResponse,\n ResourceLedgerResponse,\n ResourceStatusResponse,\n ResourceBreakdownResponse,\n ResourceNodesResponse,\n ResourceNodeResponse,\n ResourceLedgerOptions,\n ResourceBreakdownOptions,\n} from './resources-types';\n\nexport class ResourcesClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Network-wide consumption summary across all nodes. */\n async getSummary(): Promise<ResourceSummaryResponse> {\n return this.http.get('/resources/summary');\n }\n\n /** Current-day consumption breakdown for an app. */\n async getConsumption(appId: string): Promise<ResourceConsumptionResponse> {\n return this.http.get(`/resources/consumption/${encodePathParam(appId)}`);\n }\n\n /** Daily usage history from the persistent store. `days` defaults to 30 server-side. */\n async getHistory(appId: string, days?: number): Promise<ResourceHistoryResponse> {\n const qs = days !== undefined ? `?days=${days}` : '';\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/history${qs}`,\n );\n }\n\n /** Paginated billing ledger. All filters optional. */\n async getLedger(\n appId: string,\n options?: ResourceLedgerOptions,\n ): Promise<ResourceLedgerResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n if (options?.since) params.append('since', options.since);\n if (options?.until) params.append('until', options.until);\n if (options?.category) params.append('category', options.category);\n const qs = params.toString();\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/ledger${qs ? `?${qs}` : ''}`,\n );\n }\n\n /**\n * Current consumption status with threshold warnings and upgrade hints.\n * `dailyLimit` overrides the per-app tier default and is rare —\n * smart-app callers should leave it unset.\n */\n async getStatus(appId: string, dailyLimit?: number): Promise<ResourceStatusResponse> {\n const qs = dailyLimit !== undefined ? `?dailyLimit=${dailyLimit}` : '';\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/status${qs}`,\n );\n }\n\n /** Consumption aggregated by category over the supplied window. */\n async getBreakdown(\n appId: string,\n options?: ResourceBreakdownOptions,\n ): Promise<ResourceBreakdownResponse> {\n const params = new URLSearchParams();\n if (options?.since) params.append('since', options.since);\n if (options?.until) params.append('until', options.until);\n const qs = params.toString();\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/breakdown${qs ? `?${qs}` : ''}`,\n );\n }\n\n /** Per-node consumption reports. */\n async listNodes(): Promise<ResourceNodesResponse> {\n return this.http.get('/resources/nodes');\n }\n\n /** Single node's report. */\n async getNode(nodeId: string): Promise<ResourceNodeResponse> {\n return this.http.get(`/resources/nodes/${encodePathParam(nodeId)}`);\n }\n}\n","/**\n * Envelope Sub-Client.\n *\n * Mounted on `client.envelope`. Wraps the validator envelope routes:\n *\n * - POST `/envelope/encrypt` → `encrypt`\n * - POST `/envelope/decrypt` → `decrypt`\n *\n * The cluster master KEK and the derived per-app KEK NEVER cross the HTTP\n * boundary. Only the envelope (ciphertext + nonce + tag + metadata) is\n * persisted client-side; the validator handles all key material.\n *\n * @example Seal a tenant secret + recover it later\n * ```ts\n * const sealed = await client.envelope.encrypt({\n * appId: 'app_abc',\n * plaintext: 'super-secret-api-key',\n * });\n *\n * const opened = await client.envelope.decrypt({\n * appId: 'app_abc',\n * envelope: sealed.envelope,\n * });\n * ```\n */\nimport type { HttpClient } from '../http';\nimport type {\n EncryptRequest,\n EncryptResponse,\n DecryptRequest,\n DecryptResponse,\n} from './envelope-types';\n\nexport class EnvelopeClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Seal `plaintext` under the per-app KEK for `appId` at `kekVersion`.\n * Returns the canonical envelope shape suitable for persistence in\n * Mongo / NATS / on the EventBus.\n */\n async encrypt(request: EncryptRequest): Promise<EncryptResponse> {\n return this.http.post('/envelope/encrypt', request);\n }\n\n /**\n * Open `envelope` for `appId`. The plaintext is returned in the response\n * body — callers MUST treat it as ephemeral (no logs, no Mongo, no\n * NATS broadcast). The validator never persists or replays it.\n */\n async decrypt(request: DecryptRequest): Promise<DecryptResponse> {\n return this.http.post('/envelope/decrypt', request);\n }\n}\n","/**\n * Tokens (Migration) Sub-Client.\n *\n * Mounted on `client.tokens`. Wraps the validator's token-migration routes:\n *\n * - POST `/tokens/migrate` → `migrate`\n * - GET `/tokens/migrations` → `listMigrations`\n * - GET `/tokens/migrations/:id` → `getMigration`\n * - GET `/tokens/:tokenId/migrations` → `getMigrationsForToken`\n *\n * For per-token details, use `client.getTokenInfo(chain, tokenId)`.\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n TokenMigrationRequest,\n TokenMigrationResponse,\n TokenMigrationStatus,\n ListMigrationsResponse,\n TokenMigrationsForTokenResponse,\n} from './tokens-types';\n\nexport class TokensClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Initiate a token migration to TSS-controlled keys. */\n async migrate(request: TokenMigrationRequest): Promise<TokenMigrationResponse> {\n return this.http.post('/tokens/migrate', request);\n }\n\n /** List all known migrations on this validator. */\n async listMigrations(): Promise<ListMigrationsResponse> {\n return this.http.get('/tokens/migrations');\n }\n\n /**\n * Get one migration's status by id. The server returns\n * `{ error: string }` (NOT a 404) when the migration is unknown, so the\n * union type makes the failure mode explicit.\n */\n async getMigration(\n migrationId: string,\n ): Promise<TokenMigrationStatus | { error: string }> {\n return this.http.get(`/tokens/migrations/${encodePathParam(migrationId)}`);\n }\n\n /** All migrations recorded against a specific token id. */\n async getMigrationsForToken(\n tokenId: string,\n ): Promise<TokenMigrationsForTokenResponse> {\n return this.http.get(`/tokens/${encodePathParam(tokenId)}/migrations`);\n }\n}\n","/**\n * Operator Funding Sub-Client.\n *\n * Mounted on `client.operator`. Wraps the validator operator-funding routes:\n *\n * - GET `/operator/balance/:chain/:accountId` → `getBalance`\n * - GET `/operator/topup/:chain/:accountId` → `getTopup`\n *\n * Both endpoints are `@Public()` server-side — no auth required.\n *\n * @example Check operator funding before submitting a chain op\n * ```ts\n * const balance = await client.operator.getBalance('hedera', '0.0.12345');\n * const topup = await client.operator.getTopup('hedera', '0.0.12345');\n * if (topup.status !== 'healthy') {\n * console.warn(`Operator needs top-up: recommended=${topup.recommendedBalance}`);\n * }\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n OperatorChain,\n OperatorBalanceResponse,\n OperatorTopUpResponse,\n} from './operator-types';\n\nexport class OperatorClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Get the on-chain HBAR + token balance of an operator account. */\n async getBalance(\n chain: OperatorChain,\n accountId: string,\n ): Promise<OperatorBalanceResponse> {\n return this.http.get(\n `/operator/balance/${encodePathParam(chain)}/${encodePathParam(accountId)}`,\n );\n }\n\n /** Get top-up guidance for an operator account (recommended balance + status). */\n async getTopup(\n chain: OperatorChain,\n accountId: string,\n ): Promise<OperatorTopUpResponse> {\n return this.http.get(\n `/operator/topup/${encodePathParam(chain)}/${encodePathParam(accountId)}`,\n );\n }\n}\n","import {\n CreateAccountRequestSchema,\n CreateAccountRequest,\n CreateAccountResponse,\n TransferRequestSchema,\n TransferRequest,\n TransferResponse,\n CreateTokenRequestSchema,\n CreateTokenRequest,\n CreateTokenResponse,\n MintTokenRequestSchema,\n MintTokenRequest,\n BurnTokenRequestSchema,\n BurnTokenRequest,\n TokenActionRequestSchema,\n TokenActionRequest,\n ActionResult,\n AccountBalance,\n AccountInfo,\n Transaction,\n TokenInfo,\n ChainType,\n} from './_vendor';\nimport { type CircuitBreakerSnapshot } from './_vendor';\nimport {\n ValidatorDiscoveryClient,\n ValidatorInfo,\n DiscoveryClient,\n} from './discovery';\nimport { ValidatorAuthClient, AuthChain, AuthenticateResponse } from './auth';\nimport { createHttpClient, encodePathParam, type HttpClient } from './http';\n\n// Sub-client imports — public API only (for third-party smart-app developers)\nimport { SubscriptionClient } from './subscription';\nimport { FaucetClient } from './faucet';\nimport { TSSClient } from './tss';\nimport { IPFSClient } from './ipfs';\nimport {\n TransactionsClient,\n HederaTransactionsClient,\n XrplTransactionsClient,\n SolanaTransactionsClient,\n PolkadotTransactionsClient,\n} from './transactions';\nimport { SnapshotsClient } from './snapshots';\nimport { HistoricalBalanceClient } from './historical-balance';\nimport { SettlementClient } from './settlement';\nimport { GovernanceClient } from './governance';\nimport { DaoClient } from './dao';\nimport { PersonhoodClient } from './personhood';\nimport { AgentsClient } from './baas/agents';\nimport { DeploymentClient } from './baas/deployment';\nimport { BridgeClient } from './bridge';\nimport { ResourcesClient } from './resources';\nimport { EnvelopeClient } from './envelope';\nimport { TokensClient } from './tokens';\nimport { OperatorClient } from './operator';\n\n/**\n * Smart Engine Client Configuration.\n *\n * TYPE-FENCE (SDK 4.0): `SmartEngineClient` is the IN-CLUSTER / VALIDATOR-DIRECT\n * profile. It targets the validator's RAW tier (`/api/v3/{transactions,tss,\n * faucet,tokens,...}`), which is un-ingressed at the public gateway — calling it\n * with a gateway origin 404s. To make that footgun structurally impossible the\n * config requires an EXPLICIT `validatorBaseUrl` (not a generic `baseUrl`): the\n * caller must consciously hand over a validator origin, never a gateway URL that\n * happened to flow out of cluster discovery. App-as-proxy / external consumers\n * must use {@link BaasClient} instead (host BaaS tier).\n */\nexport interface SmartEngineClientConfig {\n /**\n * VALIDATOR API base URL (the in-cluster validator origin — NOT a gateway).\n * The raw `/api/v3/*` tier is reachable only here; a gateway URL will 404.\n */\n validatorBaseUrl: string;\n /** API key for authenticated requests */\n apiKey?: string;\n /** Session token from validator auth */\n authToken?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Network connection configuration for auto-discovery\n */\nexport interface NetworkConnectionConfig {\n /** Hedera network (mainnet, testnet, previewnet) */\n network: 'mainnet' | 'testnet' | 'previewnet';\n /** HCS topic ID for validator registry */\n registryTopicId: string;\n /** Blockchain type for authentication */\n chain: AuthChain;\n /** Wallet address for authentication */\n address: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Function to sign the challenge */\n signFn: (challenge: string) => string | Promise<string>;\n /** Optional metadata for authentication */\n metadata?: {\n appId?: string;\n appName?: string;\n };\n /** Custom mirror node URL */\n mirrorNodeUrl?: string;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Connection result from connectToNetwork\n */\nexport interface NetworkConnectionResult {\n /** Configured client ready to use */\n client: SmartEngineClient;\n /** Validator that was connected to */\n validator: ValidatorInfo;\n /** Authentication session */\n session: AuthenticateResponse;\n}\n\n/**\n * Smart Engine Client — IN-CLUSTER / VALIDATOR-DIRECT profile.\n *\n * Unified, type-safe client for interacting with Smart Engines validators over\n * the RAW tier (`/api/v3/{transactions,tss,faucet,tokens,...}`).\n *\n * **TYPE-FENCE (SDK 4.0):** this client is constructible ONLY with an explicit\n * validator origin ({@link SmartEngineClientConfig.validatorBaseUrl}). The raw\n * `/api/v3/*` tier is un-ingressed at the public gateway, so pointing this\n * client at a gateway URL 404s — that footgun is removed by requiring a\n * conscious validator origin and by NOT shipping a gateway-discovery factory on\n * this client. External / app-as-proxy consumers must use `BaasClient` (the\n * host BaaS tier at `{gateway}/host/api/v3/baas/*`) instead. The only\n * auto-discovery path here ({@link connectToNetwork}) resolves a real validator\n * `apiEndpoint` from the HCS registry, never a gateway URL.\n *\n * Supports direct connection or HCS-registry auto-discovery.\n *\n * Sub-clients for third-party app developers:\n * - `client.subscription` — Application subscription management\n * - `client.tss` — Threshold Signature Scheme (chain-agnostic MPC)\n * - `client.ipfs` — Decentralized file storage\n * - `client.transactions` — Transaction sovereignty (prepare-sign-submit) — **chain-agnostic**\n *\n * Chain-namespaced advanced sub-clients (escape hatches with no multi-chain analog):\n * - `client.hedera` — HCS topics, KYC compliance, HTS wipe\n * - `client.xrpl` — Trust lines\n * - `client.solana` — Token close-account\n * - `client.polkadot` — Asset setTeam/setMetadata\n *\n * @example Direct connection (explicit validator origin)\n * ```typescript\n * const client = new SmartEngineClient({\n * validatorBaseUrl: 'https://validator.example.com', // a VALIDATOR origin, never a gateway\n * apiKey: 'your-api-key',\n * });\n * ```\n *\n * @example Auto-discovery with authentication\n * ```typescript\n * const { client, validator, session } = await SmartEngineClient.connectToNetwork({\n * network: 'testnet',\n * registryTopicId: '0.0.123456',\n * chain: 'hedera',\n * address: '0.0.789',\n * publicKey: 'your-public-key-hex',\n * signFn: (challenge) => privateKey.sign(Buffer.from(challenge)).toString('hex'),\n * });\n *\n * // Use sub-clients\n * const result = await client.tss.signMPC({\n * chain: 'hedera',\n * entityId: 'entity-123',\n * transactionBytes: '0x...',\n * });\n * ```\n */\nexport class SmartEngineClient {\n private baseUrl: string;\n private allowInsecure: boolean;\n private readonly http: HttpClient;\n /** Separate HTTP client for /api/v3/transactions */\n private readonly txHttp: HttpClient;\n /** Last HTTP error (for getHttpHealth) */\n private lastHttpError?: Error;\n\n // ========== Sub-Clients ==========\n\n /** Application subscription management */\n public readonly subscription: SubscriptionClient;\n /** Testnet HST faucet (challenge -> sign -> dispense) */\n public readonly faucet: FaucetClient;\n /** Threshold Signature Scheme — chain-agnostic MPC operations */\n public readonly tss: TSSClient;\n /** IPFS decentralized file storage */\n public readonly ipfs: IPFSClient;\n /** Transaction preparation for local signing (sovereignty model) — chain-agnostic */\n public readonly transactions: TransactionsClient;\n /** Hedera-specific transaction preparation (HCS topics, KYC, wipe) */\n public readonly hedera: HederaTransactionsClient;\n /** XRPL-specific transaction preparation (trust lines) */\n public readonly xrpl: XrplTransactionsClient;\n /** Solana-specific transaction preparation (close-account) */\n public readonly solana: SolanaTransactionsClient;\n /** Polkadot-specific transaction preparation (asset setTeam/setMetadata) */\n public readonly polkadot: PolkadotTransactionsClient;\n /** Token holder snapshot generation and retrieval */\n public readonly snapshots: SnapshotsClient;\n /** Historical balance archive reads (chain-native bigint, returned as decimal string) */\n public readonly historicalBalance: HistoricalBalanceClient;\n /** Cross-chain settlement operations */\n public readonly settlement: SettlementClient;\n /** Governance proposal dry-run (simulate-only) */\n public readonly governance: GovernanceClient;\n /** DAO governance — DAOs, proposals, votes, treasury, members, dashboard */\n public readonly dao: DaoClient;\n /** Personhood verification (HPP one-human-one-member) */\n public readonly personhood: PersonhoodClient;\n /** BaaS smart-agent lifecycle (register/fund/trade/withdraw/pause/resume/revoke/...) */\n public readonly agents: AgentsClient;\n /** BaaS smart-app deployment lifecycle (init/uploadFrontend/deploy/rollback/status/...) */\n public readonly deployments: DeploymentClient;\n /** Universal Token Bridge — port/return/claim across chains */\n public readonly bridge: BridgeClient;\n /** Network + per-app resource consumption (summary, history, ledger, nodes) */\n public readonly resources: ResourcesClient;\n /** AES-256-GCM envelope encrypt/decrypt under the TSS-backed master KEK */\n public readonly envelope: EnvelopeClient;\n /** Token migration — move existing tokens to TSS-controlled keys */\n public readonly tokens: TokensClient;\n /** Operator account funding helpers (balance + top-up guidance) */\n public readonly operator: OperatorClient;\n /** Discovery endpoints — cluster registry + platform-image manifests */\n public readonly discovery: DiscoveryClient;\n\n constructor(config: SmartEngineClientConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n this.baseUrl = validateClientUrl(config.validatorBaseUrl, this.allowInsecure);\n\n // Create shared HTTP client for /api/v3 endpoints\n this.http = createHttpClient({\n baseUrl: `${this.baseUrl}/api/v3`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n // Create separate HTTP client for /api/v3/transactions\n this.txHttp = createHttpClient({\n baseUrl: `${this.baseUrl}/api/v3/transactions`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n // Initialize sub-clients\n this.subscription = new SubscriptionClient(this.http);\n this.faucet = new FaucetClient(this.http);\n this.tss = new TSSClient(this.http);\n this.ipfs = new IPFSClient(this.http);\n this.transactions = new TransactionsClient(this.txHttp);\n // Pass `this.http` (rooted at `/api/v3`) as the second arg so\n // `client.hedera.tss.*` reaches `/api/v3/hedera/tss/*` — the prepare paths\n // continue to use `this.txHttp` (rooted at `/api/v3/transactions`).\n this.hedera = new HederaTransactionsClient(this.txHttp, this.http);\n this.xrpl = new XrplTransactionsClient(this.txHttp);\n this.solana = new SolanaTransactionsClient(this.txHttp);\n this.polkadot = new PolkadotTransactionsClient(this.txHttp);\n this.snapshots = new SnapshotsClient(this.http);\n this.historicalBalance = HistoricalBalanceClient.fromHttp(this.http);\n this.settlement = new SettlementClient(this.http);\n this.governance = new GovernanceClient(this.http);\n this.dao = new DaoClient(this.http);\n this.personhood = new PersonhoodClient(this.http);\n // BaaS sub-clients — they call fully-qualified `/api/v3/baas/<x>` (host) and\n // `/api/v3/smart-apps/<x>` (validator) paths directly, so they need an HTTP\n // client rooted at the bare `baseUrl` (NO `/api/v3` suffix — the suffix is\n // already baked into each method's path). Reuse of `txHttp` is wrong because\n // its base is `${baseUrl}/api/v3/transactions`. Build a fresh, root-scoped\n // client just for these.\n const rootHttp = createHttpClient({\n baseUrl: this.baseUrl,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n this.agents = new AgentsClient(rootHttp);\n this.deployments = new DeploymentClient(rootHttp);\n this.bridge = new BridgeClient(this.http);\n this.resources = new ResourcesClient(this.http);\n this.envelope = new EnvelopeClient(this.http);\n this.tokens = new TokensClient(this.http);\n this.operator = new OperatorClient(this.http);\n this.discovery = new DiscoveryClient(this.http);\n }\n\n /**\n * Build a `SmartEngineClient` from a plain env object. Reads:\n * - `VALIDATOR_URL` (required) — gateway/validator base URL\n * - `VALIDATOR_API_KEY` (optional) — API key for authenticated calls\n * - `APP_TOKEN` (optional) — session JWT from prior auth\n * - `ALLOW_INSECURE` (optional, `'true'`) — only for local dev\n * - `REQUEST_TIMEOUT` (optional, ms)\n *\n * Throws if `VALIDATOR_URL` is missing or invalid. Designed for BaaS\n * scheduled functions: `const client = SmartEngineClient.fromEnv(ctx.env)`.\n */\n static fromEnv(env: Record<string, string | undefined>): SmartEngineClient {\n const baseUrl = env['VALIDATOR_URL'];\n if (!baseUrl) {\n throw new SmartEngineError('VALIDATOR_URL is required to build a SmartEngineClient', 500);\n }\n const timeoutRaw = env['REQUEST_TIMEOUT'];\n const timeout = timeoutRaw ? Number.parseInt(timeoutRaw, 10) : undefined;\n return new SmartEngineClient({\n validatorBaseUrl: baseUrl,\n apiKey: env['VALIDATOR_API_KEY'],\n authToken: env['APP_TOKEN'],\n allowInsecure: env['ALLOW_INSECURE'] === 'true',\n timeout: Number.isFinite(timeout) ? timeout : undefined,\n });\n }\n\n /**\n * Connect to the smart-engines network with auto-discovery and authentication.\n *\n * Steps:\n * 1. Discovers validators via the HCS registry topic.\n * 2. Selects a random validator with an API endpoint.\n * 3. Authenticates with Web3-style challenge-response.\n * 4. Returns a configured client ready to use.\n *\n * @param config - Network, registry topic, and auth signer config.\n * @returns The configured client, the chosen validator, and the auth session.\n * @throws SmartEngineError 503 if no validator with an API endpoint is found.\n */\n static async connectToNetwork(config: NetworkConnectionConfig): Promise<NetworkConnectionResult> {\n const allowInsecure = config.allowInsecure ?? false;\n\n // Step 1: Discover validators\n const discovery = new ValidatorDiscoveryClient({\n network: config.network,\n registryTopicId: config.registryTopicId,\n mirrorNodeUrl: config.mirrorNodeUrl,\n });\n\n const validator = await discovery.getRandomValidator();\n\n if (!validator || !validator.networkEndpoints?.apiEndpoint) {\n throw new SmartEngineError(\n 'No validators available. Check registry topic and network configuration.',\n 503\n );\n }\n\n const validatorUrl = validator.networkEndpoints.apiEndpoint;\n validateClientUrl(validatorUrl, allowInsecure);\n\n // Step 2: Authenticate\n const auth = new ValidatorAuthClient({\n security: { allowInsecure },\n });\n const session = await auth.authenticateWithSigner(\n validatorUrl,\n config.chain,\n config.address,\n config.publicKey,\n config.signFn,\n config.metadata\n );\n\n // Step 3: Create client with auth token. `validatorUrl` is the validator's\n // own `apiEndpoint` resolved from the HCS registry — a validator origin, NOT\n // a gateway URL — so it satisfies the validator-origin type-fence.\n const client = new SmartEngineClient({\n validatorBaseUrl: validatorUrl,\n authToken: session.token,\n allowInsecure,\n });\n\n return { client, validator, session };\n }\n\n // NOTE (SDK 4.0 type-fence): the former `SmartEngineClient.connectToCluster`\n // was REMOVED. It resolved a cluster's `gatewayUrl` and fed it into\n // `new SmartEngineClient({ baseUrl: gatewayUrl })` — a gateway-pointed\n // validator-direct client whose raw `/api/v3/*` calls 404 (the raw tier is\n // un-ingressed at the gateway). That was the footgun. To reach web3 through a\n // cluster use `BaasClient.connectToCluster({ network })` (the host BaaS tier);\n // for an explicit in-cluster validator origin use `new SmartEngineClient({\n // validatorBaseUrl })` or `connectToNetwork` (which resolves a real validator\n // `apiEndpoint` from the HCS registry, never a gateway URL).\n\n /** Get the current validator URL */\n getBaseUrl(): string {\n return this.baseUrl;\n }\n\n /** Check if client has an auth token */\n isAuthenticated(): boolean {\n return this.http.getAuthToken() !== undefined;\n }\n\n /**\n * Get HTTP resilience health information\n * @returns Object with circuit breaker state and last error (if any)\n */\n getHttpHealth(): { breaker: CircuitBreakerSnapshot | null; lastError?: Error } {\n // Note: In a real implementation, we would get the circuit breaker state\n // from the resilient HTTP layer. For now, return null since the base\n // HTTP client doesn't expose it yet.\n return {\n breaker: null,\n lastError: this.lastHttpError,\n };\n }\n\n // ========== Health & Info ==========\n\n /** Get health status of the validator */\n async getHealth(): Promise<{ status: string; timestamp: string; chains: any[] }> {\n return this.http.get('/health');\n }\n\n /** Get list of supported chains */\n async getSupportedChains(): Promise<{ chains: string[] }> {\n return this.http.get('/chains');\n }\n\n // ========== Account Operations ==========\n\n /** Create a new account on the specified chain */\n async createAccount(request: CreateAccountRequest): Promise<CreateAccountResponse> {\n const validated = CreateAccountRequestSchema.parse(request);\n return this.http.post('/accounts', validated);\n }\n\n /** Get account information */\n async getAccountInfo(chain: string, accountId: string): Promise<AccountInfo> {\n return this.http.get(`/accounts/${encodePathParam(chain)}/${encodePathParam(accountId)}`);\n }\n\n /** Get account balance */\n async getBalance(chain: string, accountId: string): Promise<AccountBalance> {\n return this.http.get(`/accounts/${encodePathParam(chain)}/${encodePathParam(accountId)}/balance`);\n }\n\n // ========== Transaction Operations ==========\n\n /** Execute a transfer transaction */\n async transfer(request: TransferRequest): Promise<TransferResponse> {\n const validated = TransferRequestSchema.parse(request);\n return this.http.post('/transfer', validated);\n }\n\n /** Get transaction details */\n async getTransaction(chain: string, txId: string): Promise<Transaction> {\n return this.http.get(`/transactions/${encodePathParam(chain)}/${encodePathParam(txId)}`);\n }\n\n /** Get transaction receipt */\n async getTransactionReceipt(chain: string, txId: string): Promise<any> {\n return this.http.get(`/transactions/${encodePathParam(chain)}/${encodePathParam(txId)}/receipt`);\n }\n\n // ========== Token Operations ==========\n\n /** Create a new token */\n async createToken(request: CreateTokenRequest): Promise<CreateTokenResponse> {\n const validated = CreateTokenRequestSchema.parse(request);\n return this.http.post('/tokens', validated);\n }\n\n /** Mint tokens */\n async mintToken(request: MintTokenRequest): Promise<any> {\n const validated = MintTokenRequestSchema.parse(request);\n return this.http.post('/tokens/mint', validated);\n }\n\n /**\n * Get token information for a token on the given chain.\n *\n * @param chain - Chain identifier (e.g. `'hedera'`, `'xrpl'`).\n * @param tokenId - Chain-native token identifier.\n * @returns Token metadata and supply information.\n */\n async getTokenInfo(chain: string, tokenId: string): Promise<TokenInfo> {\n return this.http.get(`/tokens/${encodePathParam(chain)}/${encodePathParam(tokenId)}`);\n }\n\n /** Burn tokens to reduce supply */\n async burnToken(request: BurnTokenRequest): Promise<ActionResult> {\n const validated = BurnTokenRequestSchema.parse(request);\n return this.http.post('/tokens/burn', validated);\n }\n\n /** Pause all token operations globally */\n async pauseToken(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n return this.http.post('/tokens/pause', validated);\n }\n\n /** Unpause token operations */\n async unpauseToken(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n return this.http.post('/tokens/unpause', validated);\n }\n\n /** Freeze/restrict an account from transacting the token */\n async restrictAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for restrictAccount', 400);\n }\n return this.http.post('/tokens/restrict', validated);\n }\n\n /** Unfreeze an account */\n async unrestrictAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for unrestrictAccount', 400);\n }\n return this.http.post('/tokens/unrestrict', validated);\n }\n\n /** Grant KYC/compliance approval to an account */\n async enableCompliance(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for enableCompliance', 400);\n }\n return this.http.post('/tokens/compliance/enable', validated);\n }\n\n /** Revoke KYC/compliance approval from an account */\n async disableCompliance(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for disableCompliance', 400);\n }\n return this.http.post('/tokens/compliance/disable', validated);\n }\n\n /** Force remove tokens from an account (compliance action) */\n async wipeFromAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for wipeFromAccount', 400);\n }\n if (!validated.amount) {\n throw new SmartEngineError('amount is required for wipeFromAccount', 400);\n }\n return this.http.post('/tokens/wipe', validated);\n }\n\n // ========== Capabilities Discovery ==========\n\n /** Get capability support matrix for all chains */\n async getAllCapabilities(): Promise<any> {\n return this.http.get('/capabilities');\n }\n\n /** Get capability support for a specific chain */\n async getChainCapabilities(chain: ChainType): Promise<any> {\n return this.http.get(`/capabilities/${encodePathParam(chain)}`);\n }\n\n /** Get comprehensive system status */\n async getSystemStatus(): Promise<any> {\n return this.http.get('/status');\n }\n\n // ========== Messaging Operations ==========\n\n /**\n * Submit a message to consensus.\n *\n * @deprecated Operator-funded message submission is RETIRED on the validator\n * under transaction sovereignty — `POST /api/v3/messages/:chain/:topicId`\n * now returns `403 Forbidden` (the operator must never front the chain fee\n * for a customer-supplied message). Use the payer-funded prepare path\n * instead: prepare a topic-message transaction via\n * `POST /api/transactions/topic/message/prepare`, then have the payer sign\n * and submit the returned bytes.\n */\n async submitMessage(chain: string, topicId: string, message: string): Promise<any> {\n if (message.length > 1024 * 1024) {\n throw new SmartEngineError('Message too large (max 1MB)', 400);\n }\n return this.http.post(`/messages/${encodePathParam(chain)}/${encodePathParam(topicId)}`, {\n message,\n });\n }\n\n // ========== Cluster Operations ==========\n\n /** Get cluster health status */\n async getClusterHealth(): Promise<{\n status: string;\n nodes: number;\n healthy: number;\n unhealthy: number;\n }> {\n return this.http.get('/cluster/health');\n }\n\n /** Get cluster status including node details */\n async getClusterStatus(): Promise<{\n status: string;\n nodeId: string;\n nodes: Array<{\n nodeId: string;\n endpoint: string;\n status: string;\n lastSeen?: string;\n }>;\n quorum: {\n required: number;\n current: number;\n reached: boolean;\n };\n }> {\n return this.http.get('/cluster/status');\n }\n\n // ========== Metrics & Monitoring ==========\n\n /** Get Prometheus-format metrics */\n async getMetrics(): Promise<string> {\n return this.http.get('/metrics');\n }\n\n /** Get queue statistics for monitoring */\n async getQueueStats(): Promise<{\n queues: Record<\n string,\n { pending: number; processing: number; completed: number; failed: number }\n >;\n timestamp: string;\n }> {\n return this.http.get('/monitoring/queue');\n }\n\n /** Get circuit breaker status for all services */\n async getCircuitBreakerStatus(): Promise<{\n breakers: Record<\n string,\n {\n state: 'closed' | 'open' | 'half-open';\n failures: number;\n successes: number;\n lastFailure?: string;\n nextRetry?: string;\n }\n >;\n timestamp: string;\n }> {\n return this.http.get('/monitoring/circuit-breakers');\n }\n\n // ========== Signature Verification ==========\n\n /** Verify an arbitrary signature */\n async verifySignature(request: {\n chain: ChainType;\n message: string;\n signature: string;\n publicKey: string;\n }): Promise<{ valid: boolean; chain: ChainType }> {\n return this.http.post('/auth/verify-signature', request);\n }\n}\n\n/**\n * Custom error class for Smart Engine client\n */\nexport class SmartEngineError extends Error {\n constructor(\n message: string,\n public statusCode: number,\n public details?: any\n ) {\n super(message);\n this.name = 'SmartEngineError';\n }\n}\n\n/**\n * Validate URL and enforce security requirements\n */\nfunction validateClientUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new SmartEngineError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new SmartEngineError(\n 'HTTPS is required for secure connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n return parsed.origin;\n } catch (error) {\n if (error instanceof SmartEngineError) throw error;\n throw new SmartEngineError(`Invalid URL: ${url}`, 400);\n }\n}\n","/**\n * Routing Sub-Client\n *\n * Manages host registration, routing configuration, and request proxying.\n * Wire shapes mirror the server.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n RegisterHostRequest,\n RegisterHostResponse,\n HostInfo,\n HostListResponse,\n RoutingConfig,\n ProxyRequest,\n ProxyResponse,\n RoutingStatsResponse,\n MapDomainToAppResponse,\n} from '../types';\n\n/**\n * Routing Sub-Client\n *\n * @example\n * ```typescript\n * await gateway.routing.registerHost({\n * appId: 'my-app',\n * address: '10.0.0.5',\n * port: 3000,\n * });\n *\n * const stats = await gateway.routing.getStats();\n * ```\n */\nexport class RoutingClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Register a new host. The server validates the payload via Zod (appId\n * pattern, IP/hostname format, port range) and kicks off async\n * verification. Response includes the registered host plus a status\n * message about verification.\n */\n async registerHost(request: RegisterHostRequest): Promise<RegisterHostResponse> {\n return this.http.post('/routing/hosts', request);\n }\n\n /** Unregister a host. */\n async unregisterHost(hostId: string): Promise<{ success: boolean; message: string }> {\n return this.http.delete(`/routing/hosts/${encodePathParam(hostId)}`);\n }\n\n /** Get all registered hosts. */\n async getAllHosts(): Promise<HostListResponse> {\n return this.http.get('/routing/hosts');\n }\n\n /** Get only verified hosts. */\n async getVerifiedHosts(): Promise<HostListResponse> {\n return this.http.get('/routing/hosts/verified');\n }\n\n /** Get a specific host by ID. */\n async getHost(hostId: string): Promise<HostInfo> {\n return this.http.get(`/routing/hosts/${encodePathParam(hostId)}`);\n }\n\n /** Trigger host re-verification. */\n async verifyHost(\n hostId: string,\n ): Promise<{\n success: boolean;\n hostId: string;\n verified: boolean;\n attestationScore?: number;\n message: string;\n }> {\n return this.http.post(`/routing/hosts/${encodePathParam(hostId)}/verify`, {});\n }\n\n /** Set routing configuration for an app. */\n async setRoutingConfig(\n appId: string,\n config: RoutingConfig,\n ): Promise<{ success: boolean; appId: string; message: string }> {\n return this.http.put(`/routing/config/${encodePathParam(appId)}`, config);\n }\n\n /** Get routing configuration for an app. */\n async getRoutingConfig(appId: string): Promise<RoutingConfig> {\n return this.http.get(`/routing/config/${encodePathParam(appId)}`);\n }\n\n /** Proxy a request through the gateway. */\n async proxyRequest(request: ProxyRequest): Promise<ProxyResponse> {\n return this.http.post('/routing/proxy', request);\n }\n\n /** Get routing statistics. */\n async getStats(): Promise<RoutingStatsResponse> {\n return this.http.get('/routing/stats');\n }\n\n /**\n * Map a domain/subdomain to an application for hostname-based routing.\n * The server returns `{ domain, appId, message }` — there is no `success`\n * field; treat `appId` as the success signal.\n */\n async mapDomainToApp(domain: string, appId: string): Promise<MapDomainToAppResponse> {\n return this.http.post(`/routing/domains/${encodePathParam(domain)}/map`, { appId });\n }\n}\n","/**\n * Domains Sub-Client\n *\n * Manages domain registration, verification, DNS configuration, and transfers.\n * Wire shapes mirror the server.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n DomainRegistrationRequest,\n DomainInfo,\n DomainListResponse,\n DomainAvailabilityResponse,\n VerificationMethod,\n VerificationTokenResponse,\n VerificationResult,\n DnsRecord,\n DomainTransferRequest,\n} from '../types';\n\n/**\n * Domains Sub-Client\n *\n * @example\n * ```typescript\n * const domain = await gateway.domains.register({ domain: 'myapp.example.com', owner: '0.0.123' });\n *\n * const token = await gateway.domains.generateVerificationToken('myapp.example.com', 'dns-txt');\n * const result = await gateway.domains.verifyOwnership('myapp.example.com', token.token);\n * ```\n */\nexport class DomainsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Register a new domain */\n async register(request: DomainRegistrationRequest): Promise<DomainInfo> {\n return this.http.post('/domains', request);\n }\n\n /** Check domain availability */\n async checkAvailability(domain: string): Promise<DomainAvailabilityResponse> {\n return this.http.get(`/domains/check/${encodePathParam(domain)}`);\n }\n\n /** Get domain information */\n async getInfo(domain: string): Promise<DomainInfo> {\n return this.http.get(`/domains/${encodePathParam(domain)}`);\n }\n\n /** List domains, optionally filtered by owner */\n async list(owner?: string): Promise<DomainListResponse> {\n const params = owner ? `?owner=${encodeURIComponent(owner)}` : '';\n return this.http.get(`/domains${params}`);\n }\n\n /**\n * Generate a verification token. Server accepts one of `dns-txt`,\n * `dns-cname`, `http-file`, `email`.\n */\n async generateVerificationToken(\n domain: string,\n method: VerificationMethod,\n ): Promise<VerificationTokenResponse> {\n return this.http.post(`/domains/${encodePathParam(domain)}/verification`, { method });\n }\n\n /** Verify domain ownership */\n async verifyOwnership(domain: string, token: string): Promise<VerificationResult> {\n return this.http.post(`/domains/${encodePathParam(domain)}/verify`, { token });\n }\n\n /** Configure DNS records for a domain */\n async configureDns(\n domain: string,\n records: DnsRecord[],\n ): Promise<{ success: boolean; records: DnsRecord[] }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dns`, { records });\n }\n\n /** Enable DNSSEC for a domain */\n async enableDnssec(domain: string): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dnssec/enable`, {});\n }\n\n /** Disable DNSSEC for a domain */\n async disableDnssec(domain: string): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dnssec/disable`, {});\n }\n\n /** Renew a domain */\n async renew(domain: string, years?: number): Promise<DomainInfo> {\n return this.http.post(`/domains/${encodePathParam(domain)}/renew`, { years: years ?? 1 });\n }\n\n /** Initiate a domain transfer */\n async transfer(\n domain: string,\n request: DomainTransferRequest,\n ): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer`, request);\n }\n\n /** Approve a pending domain transfer */\n async approveTransfer(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer/approve`, {});\n }\n\n /** Reject a pending domain transfer */\n async rejectTransfer(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer/reject`, {});\n }\n\n /** Suspend a domain */\n async suspend(domain: string, reason: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/suspend`, { reason });\n }\n\n /** Unsuspend a domain */\n async unsuspend(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/unsuspend`, {});\n }\n}\n","/**\n * DNS Sub-Client\n *\n * Manages DNS resolution, zone management, and DNSSEC.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n DnsResolveResponse,\n DnsBatchQuery,\n DnsBatchResolveResponse,\n DnsZone,\n DnsZoneListResponse,\n DnsRecord,\n DnsRecordInfo,\n DnssecKey,\n DnssecDsRecord,\n} from '../types';\n\n/**\n * DNS Sub-Client\n *\n * @example\n * ```typescript\n * // Resolve a name\n * const result = await gateway.dns.resolve('myapp.example.com', 'A');\n *\n * // Manage zones\n * const zones = await gateway.dns.listZones();\n * ```\n */\nexport class DnsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Resolve a DNS name */\n async resolve(name: string, type?: string, dnssec?: boolean): Promise<DnsResolveResponse> {\n const params = new URLSearchParams({ name });\n if (type) params.set('type', type);\n if (dnssec !== undefined) params.set('dnssec', String(dnssec));\n return this.http.get(`/dns/resolve?${params.toString()}`);\n }\n\n /** Batch resolve multiple DNS queries */\n async resolveBatch(queries: DnsBatchQuery[]): Promise<DnsBatchResolveResponse> {\n return this.http.post('/dns/resolve/batch', { queries });\n }\n\n /** List all DNS zones */\n async listZones(): Promise<DnsZoneListResponse> {\n return this.http.get('/dns/zones');\n }\n\n /** Get a specific zone */\n async getZone(zoneName: string): Promise<DnsZone & { records: DnsRecordInfo[] }> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}`);\n }\n\n /** Create a new DNS zone */\n async createZone(request: { zoneName: string; description?: string }): Promise<DnsZone> {\n return this.http.post('/dns/zones', request);\n }\n\n /** Delete a DNS zone */\n async deleteZone(zoneName: string): Promise<{ success: boolean }> {\n return this.http.delete(`/dns/zones/${encodePathParam(zoneName)}`);\n }\n\n /** Add a record to a zone */\n async addRecord(zoneName: string, record: DnsRecord): Promise<DnsRecordInfo> {\n return this.http.post(`/dns/zones/${encodePathParam(zoneName)}/records`, record);\n }\n\n /** Update a record in a zone */\n async updateRecord(\n zoneName: string,\n recordId: string,\n updates: Partial<DnsRecord>\n ): Promise<DnsRecordInfo> {\n return this.http.put(\n `/dns/zones/${encodePathParam(zoneName)}/records/${encodePathParam(recordId)}`,\n updates\n );\n }\n\n /** Delete a record from a zone */\n async deleteRecord(zoneName: string, recordId: string): Promise<{ success: boolean }> {\n return this.http.delete(\n `/dns/zones/${encodePathParam(zoneName)}/records/${encodePathParam(recordId)}`\n );\n }\n\n /** Generate DNSSEC keys for a zone */\n async generateDnssecKeys(\n zoneName: string,\n algorithm?: string\n ): Promise<{ keys: DnssecKey[] }> {\n return this.http.post(`/dns/zones/${encodePathParam(zoneName)}/dnssec/keys`, {\n algorithm,\n });\n }\n\n /** Get DNSSEC keys for a zone */\n async getDnssecKeys(zoneName: string): Promise<{ keys: DnssecKey[] }> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}/dnssec/keys`);\n }\n\n /** Get DS record for a zone (for registrar configuration) */\n async getDsRecord(zoneName: string): Promise<DnssecDsRecord> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}/dnssec/ds`);\n }\n\n /** Clear DNS cache */\n async clearCache(): Promise<{ success: boolean; entriesCleared: number }> {\n return this.http.post('/dns/cache/clear', {});\n }\n}\n","/**\n * Health Sub-Client\n *\n * Wraps the gateway's health endpoints, including the per-cluster\n * `GET /cluster/health` aggregate that merges local validator + host +\n * genesis state (used by the cross-cluster metrics aggregator and any SDK\n * caller probing a single cluster). All endpoints are `@Public()` on the\n * server — no auth required.\n */\nimport type { HttpClient } from '../../http';\nimport type { ClusterHealthAggregate } from '../types';\n\nexport class HealthClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Per-cluster aggregate health probe. Wraps `GET /api/v3/cluster/health`.\n * Returns local validator + host + genesis state in a single payload.\n */\n async getCluster(): Promise<ClusterHealthAggregate> {\n return this.http.get('/cluster/health');\n }\n}\n","/**\n * Smart Gateway Client\n *\n * Top-level client for interacting with Smart Engines Gateway.\n * Manages host routing, domain registration, and DNS resolution.\n *\n * @example\n * ```typescript\n * import { SmartGatewayClient } from '@hsuite/smart-engines-sdk';\n *\n * const gateway = new SmartGatewayClient({\n * baseUrl: 'https://gateway.smartengines.io',\n * apiKey: 'your-api-key',\n * });\n *\n * // Routing\n * const hosts = await gateway.routing.getAllHosts();\n *\n * // Domains\n * const available = await gateway.domains.checkAvailability('myapp.example.com');\n *\n * // DNS\n * const resolved = await gateway.dns.resolve('myapp.example.com', 'A');\n *\n * // Health\n * const health = await gateway.getHealth();\n * const cluster = await gateway.health.getCluster();\n * ```\n */\nimport { createHttpClient, SdkHttpError, type HttpClient } from '../http';\nimport { RoutingClient } from './routing';\nimport { DomainsClient } from './domains';\nimport { DnsClient } from './dns';\nimport { HealthClient } from './health';\nimport type {\n GatewayHealthResponse,\n GatewayStatusResponse,\n GatewayReadinessResponse,\n GatewayLivenessResponse,\n GatewayMetricsResponse,\n GatewayMetricsSummaryResponse,\n} from './types';\n\n/**\n * Configuration for SmartGatewayClient\n */\nexport type SmartGatewayClientConfig = {\n /** Gateway API base URL */\n baseUrl: string;\n /** API key for authenticated requests */\n apiKey?: string;\n /** Bearer token from authentication */\n authToken?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Allow HTTP connections (only for local development) */\n allowInsecure?: boolean;\n};\n\n/**\n * Smart Gateway Client\n *\n * Primary client for gateway operations: routing, domains, DNS, and\n * cluster-aggregate health.\n */\nexport class SmartGatewayClient {\n private readonly http: HttpClient;\n\n /** Host routing and proxy management */\n public readonly routing: RoutingClient;\n /** Domain registration and management */\n public readonly domains: DomainsClient;\n /** DNS resolution and zone management */\n public readonly dns: DnsClient;\n /** Per-cluster aggregate health probe (validator + host + genesis state) */\n public readonly health: HealthClient;\n\n constructor(config: SmartGatewayClientConfig) {\n const baseUrl = config.baseUrl.replace(/\\/+$/, '');\n\n this.http = createHttpClient({\n baseUrl: `${baseUrl}/api/v3`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n this.routing = new RoutingClient(this.http);\n this.domains = new DomainsClient(this.http);\n this.dns = new DnsClient(this.http);\n this.health = new HealthClient(this.http);\n }\n\n // ========== Health & Metrics ==========\n\n /** Get gateway-only health status (binary `status: 'ok'` snapshot). */\n async getHealth(): Promise<GatewayHealthResponse> {\n return this.http.get('/health');\n }\n\n /**\n * Get detailed gateway status — `subsystems` tree (dns/routing/verification)\n * plus the operating `mode` snapshot. Aggregated counts live on `getMetrics()`.\n */\n async getStatus(): Promise<GatewayStatusResponse> {\n return this.http.get('/status');\n }\n\n /**\n * Check gateway readiness. Resolves to either `{ status: 'ready', ... }`\n * with a verified host count or `{ status: 'not_ready', reason, ... }`.\n *\n * NOTE: `/api/v3/ready` returns **HTTP 503** when not ready (so load\n * balancers / k8s probes drain the origin). This method unwraps that 503's\n * body and still RESOLVES to a `GatewayReadinessResponse` — it does not\n * throw for a not-ready gateway. Genuine errors (non-readiness 503s, 5xx,\n * network) still throw.\n */\n async getReadiness(): Promise<GatewayReadinessResponse> {\n try {\n return await this.http.get<GatewayReadinessResponse>('/ready');\n } catch (err) {\n // The not-ready 503 carries the `{status:'not_ready', ...}` body. The\n // gateway's global exception filter wraps it as\n // {statusCode,error,message,context:{...}} — payload under `context` —\n // while a non-filtered server would return it top-level. Accept either\n // and surface the inner body instead of throwing.\n if (err instanceof SdkHttpError && err.statusCode === 503) {\n const d = err.details as\n | { status?: string; context?: GatewayReadinessResponse }\n | undefined;\n const body = (d?.context ?? d) as\n | (GatewayReadinessResponse & { status?: string })\n | undefined;\n if (body?.status === 'not_ready') {\n return body as GatewayReadinessResponse;\n }\n }\n throw err;\n }\n }\n\n /** Check gateway liveness. */\n async getLiveness(): Promise<GatewayLivenessResponse> {\n return this.http.get('/live');\n }\n\n /**\n * Get aggregated network metrics across all clusters — per-cluster health,\n * chain connectivity, gateway counts, and genesis state. Server caches the\n * payload (default 30s); pass `refresh=true` to force a fresh fetch.\n */\n async getMetrics(refresh?: boolean): Promise<GatewayMetricsResponse> {\n const params = refresh ? '?refresh=true' : '';\n return this.http.get(`/metrics${params}`);\n }\n\n /** Get lightweight network summary (status-badge-friendly). */\n async getMetricsSummary(): Promise<GatewayMetricsSummaryResponse> {\n return this.http.get('/metrics/summary');\n }\n}\n","/**\n * Database Sub-Client\n *\n * Trustless database with state proofs and Merkle verification.\n *\n * @example\n * ```typescript\n * // CRUD operations\n * const result = await baas.db.insert('users', { name: 'Alice' });\n * const users = await baas.db.find('users', { name: 'Alice' });\n *\n * // State proofs\n * const root = await baas.db.getStateRoot();\n * const proof = await baas.db.getDocumentProof('doc-123');\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n BaasInsertResult,\n BaasUpdateResult,\n BaasDeleteResult,\n BaasFindResult,\n BaasQueryOptions,\n BaasMerkleProof,\n BaasStateTransition,\n} from '../types';\n\n/** State root response */\nexport type StateRootResponse = {\n appId: string;\n stateRoot: string;\n blockHeight: number;\n timestamp: string;\n};\n\n/** Document proof response */\nexport type DocumentProofResponse = {\n documentId: string;\n exists: boolean;\n proof: BaasMerkleProof;\n stateRoot: string;\n};\n\n/** State transitions response */\nexport type StateTransitionsResponse = {\n transitions: BaasStateTransition[];\n total: number;\n fromBlock: number;\n toBlock: number;\n};\n\n/** Database stats response */\nexport type DatabaseStatsResponse = {\n collections: number;\n documents: number;\n storageSize: number;\n stateRoot: string;\n blockHeight: number;\n};\n\nexport class DatabaseClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Insert a document into a collection\n */\n async insert(collection: string, document: Record<string, unknown>): Promise<BaasInsertResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}`,\n document\n );\n }\n\n /**\n * Find documents in a collection\n */\n async find(\n collection: string,\n query?: Record<string, unknown>,\n options?: BaasQueryOptions\n ): Promise<BaasFindResult> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (query && Object.keys(query).length > 0) {\n params.set('query', JSON.stringify(query));\n }\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.skip !== undefined) params.set('skip', String(options.skip));\n if (options?.sort) params.set('sort', options.sort);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Update a document in a collection\n */\n async update(\n collection: string,\n documentId: string,\n updates: Record<string, unknown>\n ): Promise<BaasUpdateResult> {\n const appId = this.getAppId();\n return this.http.put(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}/${encodePathParam(documentId)}`,\n updates\n );\n }\n\n /**\n * Delete a document from a collection\n */\n async delete(collection: string, documentId: string): Promise<BaasDeleteResult> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}/${encodePathParam(documentId)}`\n );\n }\n\n /**\n * List collections for the app.\n *\n * Server route is `/api/v3/baas/db/:appId/collections`\n * (`database.controller.ts:106`). The previous bare-`:appId` GET 404'd\n * — Nest reserves that pattern for the document-find router below.\n */\n async listCollections(): Promise<{ collections: string[] }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/collections`);\n }\n\n /**\n * Create a new collection in the database.\n *\n * Server returns `{ success: true; collection: string }`\n * (`database.controller.ts:96`).\n */\n async createCollection(name: string): Promise<{ success: boolean; collection: string }> {\n const appId = this.getAppId();\n return this.http.post(`/api/v3/baas/db/${encodePathParam(appId)}/collections`, { name });\n }\n\n /**\n * Drop a collection and all its documents.\n *\n * Server returns `{ success: true }`\n * (`database.controller.ts:133`).\n */\n async dropCollection(name: string): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/db/${encodePathParam(appId)}/collections/${encodePathParam(name)}`\n );\n }\n\n // ========== State Proofs ==========\n\n /**\n * Get the current state root for the app\n */\n async getStateRoot(): Promise<StateRootResponse> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/state/root`);\n }\n\n /**\n * Get a Merkle proof for a specific document\n */\n async getDocumentProof(documentId: string): Promise<DocumentProofResponse> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(documentId)}/proof`\n );\n }\n\n /**\n * Get state transitions (audit log)\n */\n async getStateTransitions(options?: {\n fromBlock?: number;\n toBlock?: number;\n limit?: number;\n }): Promise<StateTransitionsResponse> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.fromBlock !== undefined) params.set('fromBlock', String(options.fromBlock));\n if (options?.toBlock !== undefined) params.set('toBlock', String(options.toBlock));\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/state/transitions${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Get database statistics\n */\n async getDbStats(): Promise<DatabaseStatsResponse> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/stats`);\n }\n}\n","/**\n * Storage Sub-Client\n *\n * Manages decentralized file storage on the host.\n *\n * @example\n * ```typescript\n * const result = await baas.storage.upload(fileBuffer, 'report.pdf');\n * const exists = await baas.storage.exists(result.cid);\n * const file = await baas.storage.download(result.cid);\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasUploadResult,\n BaasFileInfo,\n BaasFileMetadata,\n BaasStorageUsage,\n} from '../types';\n\nexport class StorageClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Upload a file to storage\n */\n async upload(\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n opts?: HttpCallOptions\n ): Promise<BaasUploadResult> {\n const appId = this.getAppId();\n return this.http.upload(`/api/v3/baas/storage/${encodePathParam(appId)}/upload`, file, filename, metadata, undefined, opts);\n }\n\n /**\n * Download a file by CID. Returns the raw file bytes as a `Uint8Array`\n * (binary-safe — never JSON-parsed or text-decoded).\n */\n async download(cid: string, opts?: HttpCallOptions): Promise<Uint8Array> {\n const appId = this.getAppId();\n return this.http.getBinary(`/api/v3/baas/storage/${encodePathParam(appId)}/download/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * Download a file by CID WITH its response metadata — the raw bytes plus the\n * host-supplied `contentType` (derived from the stored file's metadata) and,\n * when present, the `filename`. Use this instead of {@link download} when the\n * caller must echo the content-type back to its own client; a bytes-only\n * download cannot recover it.\n */\n async downloadWithMeta(\n cid: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }> {\n const appId = this.getAppId();\n return this.http.getBinaryWithMeta(\n `/api/v3/baas/storage/${encodePathParam(appId)}/download/${encodePathParam(cid)}`,\n opts,\n );\n }\n\n /**\n * Get file metadata\n */\n async getMetadata(cid: string, opts?: HttpCallOptions): Promise<BaasFileMetadata> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/metadata/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * Delete a file\n */\n async delete(cid: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(`/api/v3/baas/storage/${encodePathParam(appId)}/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * List all files for the app.\n *\n * @param pagination - Optional `limit` and `offset` (the server reads\n * `offset` for pagination).\n * @returns The file list and total count.\n */\n async listFiles(pagination?: { limit?: number; offset?: number }, opts?: HttpCallOptions): Promise<{ files: BaasFileInfo[]; total: number }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (pagination?.limit !== undefined) params.set('limit', String(pagination.limit));\n if (pagination?.offset !== undefined) params.set('offset', String(pagination.offset));\n const qs = params.toString();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/files${qs ? `?${qs}` : ''}`, opts);\n }\n\n /**\n * Get storage usage for the current app\n */\n async getUsage(opts?: HttpCallOptions): Promise<BaasStorageUsage> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/usage`, opts);\n }\n\n /**\n * Check if a file exists\n */\n async exists(cid: string, opts?: HttpCallOptions): Promise<{ exists: boolean; cid: string }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/exists/${encodePathParam(cid)}`, opts);\n }\n}\n","/**\n * Functions Sub-Client\n *\n * Manages serverless function deployment, invocation, and monitoring.\n *\n * @example\n * ```typescript\n * // Deploy a function\n * const fn = await baas.functions.deploy({\n * name: 'process-order',\n * runtime: 'nodejs18',\n * handler: 'index.handler',\n * code: functionCode,\n * });\n *\n * // Invoke it\n * const result = await baas.functions.invoke(fn.functionId, { orderId: '123' });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasFunctionDeployRequest,\n BaasFunctionEvalRequest,\n BaasFunctionDeployResult,\n BaasFunctionResult,\n BaasFunctionInfo,\n BaasFunctionCode,\n BaasFunctionLog,\n BaasFunctionLogOptions,\n BaasSignedCode,\n} from '../types';\n\nexport class FunctionsClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Build the Ed25519 signed-code envelope the host mandates for every deploy\n * and eval. A fresh ephemeral keypair is generated per call, so no long-lived\n * signing key is held anywhere — each artifact carries its own signature.\n *\n * Scheme (must match the host verifier): `hash = sha256(code)` (hex),\n * `message = \"<hash>:<timestamp>\"`, signed Ed25519; `publicKey` is SPKI-DER\n * (base64). `crypto` is imported lazily so this never pulls Node built-ins\n * into a browser bundle that doesn't sign code.\n */\n async signCode(code: string): Promise<BaasSignedCode> {\n const { generateKeyPairSync, createHash, sign } = await import('crypto');\n const { publicKey, privateKey } = generateKeyPairSync('ed25519');\n const hash = createHash('sha256').update(code, 'utf8').digest('hex');\n const timestamp = new Date().toISOString();\n const signature = sign(null, Buffer.from(`${hash}:${timestamp}`, 'utf8'), privateKey).toString('base64');\n const publicKeyDer = publicKey.export({ format: 'der', type: 'spki' }).toString('base64');\n return { code, hash, timestamp, signature, publicKey: publicKeyDer };\n }\n\n /**\n * Deploy a new function. If `signedCode` is omitted it is auto-built from\n * `request.code` via {@link signCode} — the host requires it, so the default\n * is to sign rather than 400. Pass your own envelope to override.\n */\n async deploy(request: BaasFunctionDeployRequest, opts?: HttpCallOptions): Promise<BaasFunctionDeployResult> {\n const appId = this.getAppId();\n const signedCode = request.signedCode ?? (await this.signCode(request.code));\n return this.http.post(`/api/v3/baas/functions/${encodePathParam(appId)}`, { ...request, signedCode }, opts);\n }\n\n /**\n * Invoke a function\n */\n async invoke(functionId: string, payload?: unknown, opts?: HttpCallOptions): Promise<BaasFunctionResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/invoke`,\n payload ?? {},\n opts\n );\n }\n\n /**\n * Evaluate signed code once (ephemeral) — no persistent deploy.\n *\n * For throwaway / AI-generated snippets. The host runs it in the same hardened\n * isolate and discards it; metered + quota'd like a normal invocation. As with\n * {@link deploy}, `signedCode` is auto-built from `request.code` when omitted.\n */\n async eval(request: BaasFunctionEvalRequest, opts?: HttpCallOptions): Promise<BaasFunctionResult> {\n const appId = this.getAppId();\n const signedCode = request.signedCode ?? (await this.signCode(request.code));\n return this.http.post(`/api/v3/baas/functions/${encodePathParam(appId)}/eval`, { ...request, signedCode }, opts);\n }\n\n /**\n * List all functions for the current app\n */\n async list(opts?: HttpCallOptions): Promise<{ functions: BaasFunctionInfo[]; total: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/functions/${encodePathParam(appId)}`, opts);\n }\n\n /**\n * Get function details\n */\n async get(functionId: string, opts?: HttpCallOptions): Promise<BaasFunctionInfo> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n opts\n );\n }\n\n /**\n * Get a function's source code\n */\n async getCode(functionId: string, opts?: HttpCallOptions): Promise<BaasFunctionCode> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/code`,\n opts\n );\n }\n\n /**\n * Update a function\n */\n async update(functionId: string, updates: Partial<BaasFunctionDeployRequest>, opts?: HttpCallOptions): Promise<BaasFunctionInfo> {\n const appId = this.getAppId();\n return this.http.put(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n updates,\n opts\n );\n }\n\n /**\n * Delete a function\n */\n async delete(functionId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n opts\n );\n }\n\n /**\n * Get function execution logs\n */\n async getLogs(functionId: string, options?: BaasFunctionLogOptions, opts?: HttpCallOptions): Promise<{ logs: BaasFunctionLog[]; total: number }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.startTime) params.set('startTime', options.startTime);\n if (options?.level) params.set('level', options.level);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/logs${qs ? `?${qs}` : ''}`,\n opts\n );\n }\n\n /**\n * Get function statistics for an app\n */\n async getStats(opts?: HttpCallOptions): Promise<any> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/functions/${encodePathParam(appId)}/stats`, opts);\n }\n}\n","/**\n * Messaging Sub-Client\n *\n * Full pub/sub messaging with channels, history, and presence.\n *\n * @example\n * ```typescript\n * // Create a channel\n * await baas.messaging.createChannel({ name: 'events', persistent: true });\n *\n * // Publish a message\n * await baas.messaging.publish('events', { type: 'order.created', orderId: '123' });\n *\n * // Get history\n * const history = await baas.messaging.getHistory('events', { limit: 50 });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasChannelConfig,\n BaasPublishResult,\n BaasPresenceMember,\n BaasPresenceInfo,\n BaasHistoryOptions,\n BaasMessage,\n} from '../types';\n\nexport class MessagingClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Create a new channel\n */\n async createChannel(config: BaasChannelConfig, opts?: HttpCallOptions): Promise<BaasChannelConfig & { channelId: string }> {\n const appId = this.getAppId();\n return this.http.post(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels`, config, opts);\n }\n\n /**\n * Delete a channel\n */\n async deleteChannel(channelId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channelId)}`, opts);\n }\n\n /**\n * Get a channel by ID\n */\n async getChannel(channelId: string, opts?: HttpCallOptions): Promise<BaasChannelConfig & { channelId: string; messageCount: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channelId)}`, opts);\n }\n\n /**\n * List all channels for the app\n */\n async listChannels(opts?: HttpCallOptions): Promise<{ channels: Array<BaasChannelConfig & { channelId: string }>; total: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels`, opts);\n }\n\n /**\n * Publish a message to a channel\n */\n async publish(\n channel: string,\n message: Record<string, unknown>,\n metadata?: Record<string, unknown>,\n opts?: HttpCallOptions\n ): Promise<BaasPublishResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/publish`,\n { data: message, metadata },\n opts\n );\n }\n\n /**\n * Get message history for a channel\n */\n async getHistory(\n channel: string,\n options?: BaasHistoryOptions,\n opts?: HttpCallOptions\n ): Promise<{ messages: BaasMessage[]; total: number; hasMore: boolean }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.before) params.set('before', options.before);\n if (options?.after) params.set('after', options.after);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/history${qs ? `?${qs}` : ''}`,\n opts\n );\n }\n\n /**\n * Set presence for a member in a channel.\n *\n * BREAKING CHANGE (SDK 3.3.0): presence is channel-scoped on the server\n * (`messaging.controller.ts:312`). Previous signature\n * `setPresence(member)` hit a non-existent appId-scoped route and 404'd\n * in production. The channel is now the first argument.\n */\n async setPresence(channel: string, member: BaasPresenceMember, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence`,\n member,\n opts\n );\n }\n\n /**\n * Remove a member's presence from a channel.\n *\n * BREAKING CHANGE (SDK 3.3.0): server route is\n * `/api/v3/baas/messaging/:appId/channels/:channel/presence/:clientId`\n * (`messaging.controller.ts:352`). `channel` is now the first arg and\n * `clientId` (not `memberId`) the second — they're the same identifier\n * but renamed to match the server param.\n */\n async removePresence(channel: string, clientId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence/${encodePathParam(clientId)}`,\n opts\n );\n }\n\n /**\n * Get presence info for a channel\n */\n async getPresence(channel: string, opts?: HttpCallOptions): Promise<BaasPresenceInfo> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence`,\n opts\n );\n }\n\n /**\n * Get messaging statistics\n */\n async getStats(opts?: HttpCallOptions): Promise<any> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/stats`, opts);\n }\n}\n","/**\n * Customer-Session Sub-Client (TokenGate Face B).\n *\n * Wraps the smart-host's customer→smart-app session bridge:\n * POST /api/v3/baas/customer-session/challenge (public)\n * POST /api/v3/baas/customer-session/verify (public)\n * GET /api/v3/baas/customer-session/validate (Bearer)\n * POST /api/v3/baas/customer-session/end (Bearer)\n *\n * Used by smart-apps to authenticate their customers without API keys: the\n * customer signs a chain-X challenge with their wallet, the host verifies the\n * signature against the chosen chain (and optionally a TokenGate NFT for\n * paid tiers), and returns a short-lived JWT (≤15 min by default).\n *\n * Free_testnet smart-apps gracefully skip the NFT step — customers only need\n * to prove wallet ownership via signature.\n */\n\nexport type CustomerSessionChallenge = {\n challenge: string;\n};\n\nexport type CustomerSessionVerifyRequest = {\n appId: string;\n chain: string;\n address: string;\n /** Public key (chain-dependent, e.g. ED25519 for Hedera, secp256k1 for XRPL). */\n publicKey?: string;\n signature: string;\n challenge: string;\n};\n\nexport type CustomerSessionToken = {\n /** Short-lived JWT to attach as `Authorization: Bearer ...` on subsequent calls. */\n token: string;\n sessionId: string;\n validatorId: string;\n expiresAt: string;\n sessionSecret: string;\n};\n\nexport type CustomerSessionInfo = {\n sessionId: string;\n appId: string;\n customerChain: string;\n customerAddress: string;\n /** Optional — present only when the customer holds a TokenGate-recognised NFT. */\n subscriptionContext?: {\n nftSerial: number;\n // Subscription tier ladder: builder | growth | scale | enterprise.\n tier: 'builder' | 'growth' | 'scale' | 'enterprise';\n expiresAt: string;\n allowedAutomations?: string[];\n };\n createdAt: string;\n expiresAt: string;\n lastActivityAt: string;\n};\n\nexport class CustomerSessionClient {\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number = 30_000,\n ) {}\n\n /**\n * Step 1: ask the host to issue a fresh challenge for the customer to sign.\n */\n async challenge(input: { chain: string; address: string }): Promise<CustomerSessionChallenge> {\n return this.fetch<CustomerSessionChallenge>('POST', '/api/v3/baas/customer-session/challenge', input);\n }\n\n /**\n * Step 2: submit the customer's signed challenge. On success returns a\n * short-lived bearer JWT scoped to {appId, chain, address}.\n */\n async verify(req: CustomerSessionVerifyRequest): Promise<CustomerSessionToken> {\n return this.fetch<CustomerSessionToken>('POST', '/api/v3/baas/customer-session/verify', req);\n }\n\n /**\n * Validate a customer bearer + return the decoded session info. Used by\n * smart-app backends to authorise incoming customer requests.\n */\n async validate(bearer: string): Promise<CustomerSessionInfo> {\n return this.fetch<CustomerSessionInfo>('GET', '/api/v3/baas/customer-session/validate', undefined, bearer);\n }\n\n /**\n * Revoke a customer session. Idempotent.\n */\n async end(bearer: string): Promise<{ revoked: boolean; sessionId: string }> {\n return this.fetch<{ revoked: boolean; sessionId: string }>(\n 'POST',\n '/api/v3/baas/customer-session/end',\n undefined,\n bearer,\n );\n }\n\n private async fetch<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: unknown,\n bearer?: string,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (bearer) headers['Authorization'] = `Bearer ${bearer}`;\n const init: RequestInit = { method, headers, signal: controller.signal };\n if (body !== undefined) init.body = JSON.stringify(body);\n const response = await fetch(url, init);\n clearTimeout(timeoutId);\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as { message?: string };\n const err = new Error(\n errBody.message ?? `customer-session ${path} failed: ${response.status} ${response.statusText}`,\n ) as Error & { status: number };\n err.status = response.status;\n throw err;\n }\n const text = await response.text();\n if (!text) return undefined as T;\n return JSON.parse(text) as T;\n } catch (error) {\n clearTimeout(timeoutId);\n const e = error as Error;\n if (e.name === 'AbortError') {\n throw new Error(`customer-session ${path} timeout`);\n }\n throw error;\n }\n }\n}\n","/**\n * Rules Sub-Client\n *\n * Smart-app authoring surface for canonical validator rules: publish a\n * `ValidatorRules` document to HCS, fetch a published rule by consensus\n * timestamp, list rules owned by the authenticated entity, simulate\n * cluster-side evaluation, and walk version history.\n *\n * @example\n * ```typescript\n * import { Rules } from '@hsuite/smart-engines-sdk';\n *\n * const rule = Rules.forToken()\n * .withSecurity('full')\n * .withOperations({ mint: { enabled: true, limits: { dailyLimit: '1000000' } } })\n * .build();\n *\n * const { ruleRef } = await baas.rules.publish(rule);\n * const sim = await baas.rules.simulate({ ruleRef, action: 'mint', context: { amount: '500' } });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type { PublishedRule, RuleRef, ValidatorRules } from '../../rules';\nimport type {\n DeprecateRuleResponse,\n ListRulesFilter,\n ListRulesResponse,\n PublishRuleResponse,\n SimulateRuleRequest,\n ValidationResult,\n VersionHistoryResponse,\n} from './types';\n\nexport class RulesClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Publish a canonical ValidatorRules document to HCS. */\n async publish(rule: ValidatorRules): Promise<PublishRuleResponse> {\n return this.http.post('/api/v3/baas/rules/publish', rule);\n }\n\n /** Fetch a published rule by its HCS consensus timestamp. */\n async get(consensusTimestamp: string): Promise<PublishedRule> {\n return this.http.get(`/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}`);\n }\n\n /** List rules owned by the authenticated entity, optionally filtered by type. */\n async listByOwner(filter?: ListRulesFilter): Promise<ListRulesResponse> {\n const path = filter?.type\n ? `/api/v3/baas/rules?type=${encodeURIComponent(filter.type)}`\n : '/api/v3/baas/rules';\n return this.http.get(path);\n }\n\n /**\n * Simulate cluster-side evaluation of an action against a rule. Either\n * `ruleRef` (published) or `rule` (inline) must be supplied by the caller.\n */\n async simulate(params: SimulateRuleRequest): Promise<ValidationResult> {\n return this.http.post('/api/v3/baas/rules/simulate', params);\n }\n\n /** Walk the version history of a published rule. */\n async getVersionHistory(consensusTimestamp: string): Promise<VersionHistoryResponse> {\n return this.http.get(\n `/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}/versions`,\n );\n }\n\n /** Deprecate a published rule (owner-only). */\n async deprecate(consensusTimestamp: string): Promise<DeprecateRuleResponse> {\n return this.http.post(\n `/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}/deprecate`,\n {},\n );\n }\n}\n\nexport type { RuleRef };\n","/**\n * Entities Sub-Client\n *\n * Smart-app authoring surface for canonical chain-bound entities. Each entity\n * arm (token / account / topic / agent) has a per-arm typed creator that\n * requires a published `ruleRef` — the cluster resolves the rule and stamps\n * it on the entity binding. A `launchpad(...)` mega-helper publishes a token\n * rule with an attached launchpad ModuleEntry and creates the token in one\n * call.\n *\n * @example\n * ```typescript\n * import { Rules } from '@hsuite/smart-engines-sdk';\n *\n * const rule = Rules.forToken().withSecurity('full').build();\n * const { ruleRef } = await baas.rules.publish(rule);\n *\n * const token = await baas.entities.createToken({\n * chain: 'hedera',\n * name: 'My Token',\n * symbol: 'MYT',\n * decimals: 6,\n * ruleRef,\n * });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type { ChainType } from '../..';\nimport type {\n BurnEntityRequest,\n ComplianceEntityRequest,\n CreateAccountRequest,\n CreateAgentRequest,\n CreateTokenRequest,\n CreateTopicRequest,\n EntityCreationResult,\n EntityInfo,\n EntitySecurityMode,\n LaunchpadEntityRequest,\n LaunchpadEntityResult,\n ListEntitiesFilter,\n ListEntitiesResponse,\n MintEntityRequest,\n PreparedEntityCreation,\n PreparedEntityTransactionResult,\n TransferEntityRequest,\n TrustlineEntityRequest,\n WithdrawEntityRequest,\n} from './types';\n\nexport class EntitiesClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Chains whose token-create routes through the payer-funded 3-step (prepare →\n * fund → execute), mirroring `createAccount`. Hedera = real HTS TokenCreate\n * (admin/supply = the per-entity DKG slot-pubkey KeyList; treasury = the\n * entity's own account; `0.0.X` token id is network-assigned, resolved from the\n * receipt via the threaded `createTxId`). Cardano/Solana/Polkadot = the\n * AUTHORITY entity (the entity IS the policy/mint/Assets-admin multisig — same\n * address as an account; the asset MINT itself is a later operate-tab payer\n * call). XRPL/Stellar token = an ISSUER ACCOUNT (reuses the account preparer) +\n * issuer flags set at finalize: XRPL relays the funding Payment then finalizes\n * (issuer-flag AccountSets + SignerListSet + disable-master); Stellar relays the\n * CreateAccount then finalizes (SetOptions install incl. issuer setFlags +\n * master lock). Every OTHER chain (EVM) stays on the legacy synchronous path.\n */\n private static readonly PAYER_FUNDED_TOKEN_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>([\n 'hedera',\n 'cardano',\n 'solana',\n 'polkadot',\n 'xrpl',\n 'stellar',\n ]);\n\n /**\n * PREPARE half of the payer-funded token-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'token'`. The cluster\n * runs the per-entity DKG, builds the payer-funded create (Hedera: TokenCreate\n * keyed by the slot-pubkey KeyList with the entity account as treasury;\n * Cardano/Solana/Polkadot: funds/provisions the authority multisig), and returns\n * the prepared blob. The prepared `transactionId` is the `createTxId` for\n * execute (Hedera).\n */\n async prepareCreateToken(\n req: Omit<CreateTokenRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'token',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded token-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'token'`. For Hedera,\n * pass `createTxId` (the prepared create's `transactionId`) so the validator\n * resolves the network-assigned `0.0.X` token id from the receipt and stamps\n * `chainAccounts.hedera`. For the authority-entity chains (cardano/solana/\n * polkadot) execute just verifies the binding and echoes the stamped authority\n * address (no `createTxId` needed).\n */\n async executeCreateToken(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n /** Hedera only: the prepared create's TransactionId (resolves the token id from the receipt). */\n createTxId?: string;\n /**\n * XRPL/Stellar issuer-account only: the payer's signed funding blob for the\n * validator to submit before finalizing the issuer-flag install. Omitted for\n * the other chains (their execute-create rejects a non-undefined blob).\n */\n signedFundingBlob?: string;\n }): Promise<EntityCreationResult> {\n const { createTxId, signedFundingBlob, ...rest } = req;\n return this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n ...(signedFundingBlob !== undefined ? { signedFundingBlob } : {}),\n entityType: 'token',\n });\n }\n\n /**\n * Create a canonical token entity bound to a published rule.\n *\n * Dispatches by `chain` (mirrors `createAccount`):\n * - **Hedera / Cardano / Solana / Polkadot** = payer-funded 3-step (prepare →\n * caller funds via `fundWith` → execute). Hedera resolves the network-assigned\n * `0.0.X` token id from the receipt (threads `createTxId`); the authority-\n * entity chains verify/echo the stamped authority address. `fundWith` is\n * REQUIRED; to drive the steps manually call `prepareCreateToken` /\n * `executeCreateToken` directly.\n * - **XRPL / Stellar** = payer-funded too (account-model issuer): `fundWith`\n * REQUIRED; the caller's signed funding blob is RELAYED to the validator,\n * which submits it then finalizes the issuer multisig (master-locked). NO\n * issuer flags are set at create — issuer auth flags / DefaultRipple / clawback\n * are an operate-tab, rules-validated concern.\n * - **EVM / other** = legacy synchronous `POST /api/v3/baas/entities/createToken`\n * (payer-funded-only fields ignored) until it migrates.\n */\n async createToken(req: CreateTokenRequest): Promise<EntityCreationResult> {\n if (EntitiesClient.PAYER_FUNDED_TOKEN_CHAINS.has(req.chain)) {\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateToken(prepReq);\n if (!fundWith) {\n throw new Error(\n `createToken(${req.chain}): pass fundWith (sign+submit the prepared create tx), or call prepareCreateToken/executeCreateToken directly`,\n );\n }\n // The caller signs the fee + submits the create tx with their OWN wallet.\n // XRPL/Stellar issuer accounts return a signed funding blob for the validator\n // to RELAY (then finalize on-chain); the other chains submit directly.\n const funded = await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n // Hedera threads the prepared create's TransactionId (network-assigned token\n // id is resolved from the receipt at execute); the authority-entity chains\n // need no createTxId (their address is deterministic / already stamped).\n // XRPL/Stellar (account-model issuer) RELAY the signed funding blob so the\n // validator submits it before finalizing the issuer-flag install.\n return this.executeCreateToken({\n entityId: prep.entityId,\n chain: req.chain,\n securityMode: req.securityMode,\n signedFundingBlob: EntitiesClient.FUNDING_BLOB_RELAY_CHAINS.has(req.chain)\n ? funded?.signedFundingBlob\n : undefined,\n createTxId:\n req.chain === 'hedera' ? prep.prepared?.[0]?.transactionId : undefined,\n });\n }\n // legacy synchronous create (unchanged) — only EVM remains on this path until\n // it migrates to the payer-funded flow.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n return this.http.post('/api/v3/baas/entities/createToken', legacyReq);\n }\n\n /**\n * PREPARE half of the payer-funded account-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create`. The cluster runs the per-entity DKG\n * (persists the binding, submits nothing on-chain) and returns the unsigned\n * payer-funding `Payment`(s) the caller signs + submits with their own wallet.\n */\n async prepareCreateAccount(\n req: Omit<CreateAccountRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'account',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded account-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create`. The entity already exists (its DKG\n * ran during prepare); pass `signedFundingBlob` for the validator to submit\n * the payer's signed funding `Payment` (XRPL only), or omit it when the caller\n * already submitted the funding tx themselves (then execute just finalizes /\n * verifies).\n *\n * `createTxId` is the HEDERA thread: a Hedera AccountCreate gets its\n * network-assigned `0.0.X` id only from the on-chain receipt after the payer\n * submits. The caller threads the prepared create's `transactionId` (from\n * `prepared[0].transactionId`) back here so the validator resolves the id from\n * the receipt server-side. Ignored for non-Hedera chains.\n */\n async executeCreateAccount(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n /** Hedera only: the prepared create's TransactionId (resolves the id from the receipt). */\n createTxId?: string;\n }): Promise<EntityCreationResult> {\n // Build a clean body: `createTxId` is the Hedera-only receipt thread, so it\n // is included ONLY when actually defined — non-Hedera bodies stay\n // `{ entityId, chain, securityMode?, signedFundingBlob? }` with no spurious\n // `createTxId: undefined`. `entityType` is omitted for accounts: the\n // execute-create DTO defaults a missing `entityType` to `account`, so the\n // receipt resolver reads `accountId` without the field being relayed.\n const { createTxId, ...rest } = req;\n return this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n });\n }\n\n /**\n * Chains whose account-create routes through the payer-funded 3-step\n * (prepare → fund → execute). All are ledgers where the validators never pay:\n * XRPL funds a reserve; Bitcoin funds a P2WSH UTXO; Cardano funds a\n * native-script enterprise address above min-UTXO; Polkadot funds a\n * pallet_multisig SS58 above the existential deposit; Solana funds a Squads\n * multisig PDA (deterministic from the createKey) via a payer-paid\n * `multisigCreateV2` — the payer's submission IS the create (no separate\n * finalizer). Hedera is create-WITH-KEY: the payer submits an AccountCreate\n * whose controlling key is the per-entity DKG slot-pubkey KeyList, so the\n * payer's submit IS the create; its `0.0.X` id is network-assigned (resolved\n * from the receipt at execute-create via the threaded `createTxId`). Stellar is\n * account-MODEL (like XRPL): the payer funds the entity's slot-0 `G...` master\n * via a CreateAccount, the validator RELAYS the signed funding blob, then\n * execute-create finalizes on-chain (threshold-signs a SetOptions installing\n * the validator chain-key multisig + locking the master). EVM stays on the\n * legacy synchronous create until it migrates.\n */\n private static readonly PAYER_FUNDED_CREATE_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>([\n 'xrpl',\n 'bitcoin',\n 'cardano',\n 'polkadot',\n 'solana',\n 'hedera',\n 'stellar',\n ]);\n\n /**\n * Chains whose execute-create RELAYS the payer's signed funding blob for the\n * validator to submit (then finalizes on-chain). Both are account-model ledgers\n * with a validator-side finalize step: XRPL (SignerListSet + disable-master),\n * Stellar (SetOptions install + master lock). Every OTHER payer-funded chain\n * has the PAYER submit the funding tx directly with their own wallet — their\n * execute-create REJECTS a non-undefined `signedFundingBlob` (400), so the blob\n * is omitted for them.\n */\n private static readonly FUNDING_BLOB_RELAY_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>(['xrpl', 'stellar']);\n\n /**\n * Create a canonical account entity bound to a published rule.\n *\n * Dispatches by `chain`:\n * - **XRPL / Stellar / Bitcoin / Cardano / Polkadot / Solana / Hedera** =\n * payer-funded 3-step (prepare → fund → execute). The cluster runs the\n * per-entity DKG and returns the unsigned payer-funding tx(s); the\n * caller-supplied `fundWith` callback signs + submits (or just signs) the\n * funding tx with their OWN wallet — the SDK never holds the customer's chain\n * key nor opens a network connection — then `executeCreateAccount` finalizes\n * (XRPL + Stellar finalize on-chain after relaying the funding blob; the\n * deterministic ledgers + Solana verify/stamp the binding; Hedera resolves\n * the network-assigned id from the receipt). `fundWith` is REQUIRED on these\n * chains; to drive the steps manually call `prepareCreateAccount` /\n * `executeCreateAccount` directly.\n * - **other chains** (EVM) = legacy synchronous create — a single\n * `POST /api/v3/baas/entities/createAccount`, unchanged from pre-3.9.0. These chains\n * migrate to the payer-funded flow in a later phase; until then the\n * payer-funded-only fields (`fundWith` / `payerAccountId` / `securityMode`)\n * are ignored.\n */\n async createAccount(req: CreateAccountRequest): Promise<EntityCreationResult> {\n if (EntitiesClient.PAYER_FUNDED_CREATE_CHAINS.has(req.chain)) {\n // payer-funded 3-step (the 3.9.0 logic, now multi-chain) — requires fundWith\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateAccount(prepReq);\n if (!fundWith) {\n throw new Error(\n `createAccount(${req.chain}): pass fundWith (sign+submit the prepared funding tx), or call prepareCreateAccount/executeCreateAccount directly`,\n );\n }\n const funded = await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n // Only the account-model finalize chains (XRPL, Stellar) relay the payer's\n // signed blob for the validator to submit (their execute-create finalizes\n // on-chain after the funding lands). The deterministic ledgers\n // (bitcoin/cardano/polkadot), Solana AND Hedera have the PAYER submit the tx\n // directly with their own wallet; their execute-create REJECTS a\n // non-undefined `signedFundingBlob` with a 400 (the payer is the submitter,\n // not the validator). So omit the blob for every non-relay chain.\n //\n // Hedera additionally threads `createTxId`: its create-with-key id is\n // network-assigned, so execute-create needs the prepared create's\n // TransactionId (on prepared[0].transactionId, the same tx the payer just\n // submitted via fundWith) to resolve the 0.0.X id from the receipt.\n return this.executeCreateAccount({\n entityId: prep.entityId,\n chain: req.chain,\n securityMode: req.securityMode,\n signedFundingBlob: EntitiesClient.FUNDING_BLOB_RELAY_CHAINS.has(req.chain)\n ? funded?.signedFundingBlob\n : undefined,\n createTxId:\n req.chain === 'hedera' ? prep.prepared?.[0]?.transactionId : undefined,\n });\n }\n // legacy synchronous create (unchanged from pre-3.9.0) — only EVM remains on\n // this path; it migrates to payer-funded in a later phase.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n return this.http.post('/api/v3/baas/entities/createAccount', legacyReq);\n }\n\n /**\n * PREPARE half of the payer-funded topic-create flow (Hedera).\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'topic'`. The cluster\n * runs the per-entity DKG (persists the binding), builds the payer-funded\n * TopicCreate keyed by the slot-pubkey KeyList, attaches the validator admin\n * threshold sig, and returns the prepared blob for the caller to add the fee\n * sig + submit. The prepared `transactionId` is the `createTxId` for execute.\n */\n async prepareCreateTopic(\n req: Omit<CreateTopicRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'topic',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded topic-create flow (Hedera).\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'topic'`. The topic\n * already exists once the payer submitted the create tx; pass `createTxId` (the\n * prepared create's `transactionId`) so the validator resolves the network-\n * assigned `0.0.X` topic id from the receipt and stamps `chainAccounts.hedera`.\n */\n async executeCreateTopic(req: {\n entityId: string;\n chain: ChainType;\n createTxId: string;\n securityMode?: EntitySecurityMode;\n }): Promise<EntityCreationResult> {\n return this.http.post('/api/v3/baas/entities/execute-create', {\n ...req,\n entityType: 'topic',\n });\n }\n\n /**\n * Create a canonical topic entity bound to a published rule.\n *\n * Dispatches by `chain`:\n * - **Hedera** = payer-funded 3-step (prepare → caller submits the TopicCreate\n * via `fundWith` → execute resolves the `0.0.X` topic id from the receipt).\n * `fundWith` is REQUIRED; to drive the steps manually call\n * `prepareCreateTopic` / `executeCreateTopic` directly.\n * - **other chains** = legacy synchronous `POST /api/v3/baas/entities/createTopic`\n * (topics are a Hedera primitive; the legacy path is unchanged).\n */\n async createTopic(req: CreateTopicRequest): Promise<EntityCreationResult> {\n if (req.chain === 'hedera') {\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateTopic(prepReq);\n if (!fundWith) {\n throw new Error(\n 'createTopic(hedera): pass fundWith (sign+submit the prepared TopicCreate), or call prepareCreateTopic/executeCreateTopic directly',\n );\n }\n // The caller signs the fee + submits the create tx with their OWN wallet.\n // Hedera topics have no reserve/address at prepare (the id is receipt-only).\n await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n const createTxId = prep.prepared?.[0]?.transactionId;\n if (!createTxId) {\n throw new Error(\n 'createTopic(hedera): prepared TopicCreate carries no transactionId — cannot resolve the topic id from the receipt',\n );\n }\n return this.executeCreateTopic({\n entityId: prep.entityId,\n chain: req.chain,\n createTxId,\n securityMode: req.securityMode,\n });\n }\n // legacy synchronous create (unchanged) — topics are a Hedera primitive.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n return this.http.post('/api/v3/baas/entities/createTopic', legacyReq);\n }\n\n /** Create a canonical agent entity bound to a published rule. */\n async createAgent(req: CreateAgentRequest): Promise<EntityCreationResult> {\n return this.http.post('/api/v3/baas/entities/createAgent', req);\n }\n\n /**\n * PREPARE half of the payer-funded agent-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'agent'`. The cluster\n * runs the per-entity DKG (persists the binding, submits nothing on-chain) and\n * returns the unsigned payer-funding `Payment`(s) the caller signs + submits with\n * their own wallet — mirroring `prepareCreateAccount`. The agent's primary chain\n * is relayed as `chain` (the generic prepare/execute DTO key) so the host's\n * chain-bound preparer runs; `name` / `agentType` / `ruleRef` ride along.\n */\n async prepareCreateAgent(\n req: Omit<CreateAgentRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n const { primaryChain, ...rest } = req;\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'agent',\n chain: primaryChain,\n ...rest,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded agent-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'agent'`. The entity\n * already exists (its DKG ran during prepare); pass `signedFundingBlob` for the\n * validator to submit the payer's signed funding tx (XRPL/Stellar account-model\n * relay), or omit it when the caller already submitted the funding tx themselves.\n * `createTxId` is the Hedera receipt thread (the prepared create's\n * `transactionId`); ignored for non-Hedera chains. Mirrors\n * `executeCreateAccount` but tags `entityType: 'agent'`.\n */\n async executeCreateAgent(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n /** Hedera only: the prepared create's TransactionId (resolves the id from the receipt). */\n createTxId?: string;\n }): Promise<EntityCreationResult> {\n // Build a clean body: `createTxId` / `signedFundingBlob` are included ONLY when\n // actually defined (mirrors executeCreateAccount), so non-relay / non-Hedera\n // bodies stay `{ entityId, chain, securityMode?, entityType: 'agent' }`.\n const { createTxId, signedFundingBlob, ...rest } = req;\n return this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n ...(signedFundingBlob !== undefined ? { signedFundingBlob } : {}),\n entityType: 'agent',\n });\n }\n\n /**\n * Mega-helper: build a token rule with a launchpad ModuleEntry attached,\n * publish it, create the token, and return the combined result in one HTTP\n * round-trip.\n */\n async launchpad(req: LaunchpadEntityRequest): Promise<LaunchpadEntityResult> {\n return this.http.post('/api/v3/baas/entities/launchpad', req);\n }\n\n /** Fetch an entity by its canonical `entityId`. */\n async get(entityId: string): Promise<EntityInfo> {\n return this.http.get(`/api/v3/baas/entities/${encodePathParam(entityId)}`);\n }\n\n /** List entities owned by the authenticated wallet, optionally filtered by type. */\n async listByOwner(filter?: ListEntitiesFilter): Promise<ListEntitiesResponse> {\n const path = filter?.type\n ? `/api/v3/baas/entities?type=${encodeURIComponent(filter.type)}`\n : '/api/v3/baas/entities';\n return this.http.get(path);\n }\n\n // ─── Value-movement (prepare-bytes only) ──────────────────────────────────\n //\n // Each method POSTs the host's entity-scoped value-movement route. The entity\n // is the source / treasury / authority + fee-payer (resolved server-side from\n // the entity record — never the body), so a caller can never name a foreign\n // payer or drain another account. The host authorises the call (session\n // caller identity + `loadOwnedEntity` ownership), delegates to the validator\n // preparer, and returns prepared bytes for the caller to sign + submit; the\n // host never submits and never pays. A rule-deny surfaces as an HTTP 403\n // `rule_rejected` (use `isRuleRejected`), never as signed bytes.\n //\n // `opts` threads {@link HttpCallOptions} (`onBehalfOf` / `customerToken` /\n // `headers`) so an app-as-proxy can act on behalf of an owner — the owner's\n // Mode-1 customer-session JWT rides as both `Authorization: Bearer` and\n // `X-Customer-Session-Claim`, exactly as `agents.execute` does.\n\n /**\n * Prepare a native or token transfer FROM an account entity.\n *\n * `POST /api/v3/baas/entities/:entityId/transfer`.\n */\n async transfer(\n entityId: string,\n body: TransferEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/transfer`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a withdrawal FROM an account entity to a destination.\n *\n * `POST /api/v3/baas/entities/:entityId/withdraw`.\n */\n async withdraw(\n entityId: string,\n body: WithdrawEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/withdraw`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a token/NFT mint whose supply authority is the account entity.\n *\n * `POST /api/v3/baas/entities/:entityId/mint`.\n */\n async mint(\n entityId: string,\n body: MintEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/mint`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a token/NFT burn from the account entity's treasury.\n *\n * `POST /api/v3/baas/entities/:entityId/burn`.\n */\n async burn(\n entityId: string,\n body: BurnEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/burn`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a compliance action (pause / restrict / wipe) on a token whose\n * compliance authority is the account entity. The body `account` is the\n * per-account subject for restrict/wipe — never the payer.\n *\n * `POST /api/v3/baas/entities/:entityId/compliance`.\n */\n async compliance(\n entityId: string,\n body: ComplianceEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/compliance`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare an XRPL TrustSet authorising the account entity to hold a currency\n * from an issuer.\n *\n * `POST /api/v3/baas/entities/:entityId/trustline`.\n */\n async trustline(\n entityId: string,\n body: TrustlineEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/trustline`,\n body,\n opts,\n );\n }\n}\n","/**\n * BaaS Client\n *\n * SDK client for interacting with Smart Engines Backend-as-a-Service.\n *\n * Provides:\n * - Wallet-based authentication (challenge-response)\n * - App registration and management\n * - Trustless database operations with state transitions and Merkle proofs\n * - Decentralized file storage\n * - Serverless function deployment and invocation\n * - Real-time pub/sub messaging with channels, history, and presence\n * - App deployment lifecycle management\n * - Autonomous smart agent management\n *\n * @example\n * ```typescript\n * import { BaasClient } from '@hsuite/smart-engines-sdk';\n *\n * const baas = new BaasClient({\n * hostUrl: 'https://host.smartengines.io',\n * appId: 'my-app',\n * });\n *\n * await baas.authenticate({\n * chain: 'hedera',\n * walletAddress: '0.0.12345',\n * publicKey: 'your-public-key',\n * signFn: async (message) => wallet.sign(message),\n * });\n *\n * // Database with state proofs\n * const result = await baas.db.insert('users', { name: 'Alice' });\n * const proof = await baas.db.getDocumentProof(result.document._id);\n *\n * // File storage\n * const upload = await baas.storage.upload(fileBuffer, 'document.pdf');\n *\n * // Messaging\n * await baas.messaging.publish('events', { type: 'user.created' });\n *\n * // Functions\n * const fn = await baas.functions.deploy({ name: 'handler', runtime: 'nodejs20', code: '...', codeType: 'inline' });\n *\n * // Agents\n * const agent = await baas.agents.register({ name: 'Bot', capabilities: ['trade'], rules: {} });\n * ```\n */\n\nimport type {\n BaasClientConfig,\n BaasSupportedChain,\n BaasChallengeResponse,\n BaasAuthResult,\n BaasSessionInfo,\n BaasErrorDetails,\n} from './types';\nimport { type CircuitBreakerSnapshot } from '../_vendor';\nimport { createHttpClient, SdkHttpError, type HttpClient } from '../http';\nimport { resolveClusterEndpoint } from '../discovery';\nimport { type NetworkName } from '../network-presets';\nimport { DatabaseClient } from './database';\nimport { StorageClient } from './storage';\nimport { FunctionsClient } from './functions';\nimport { MessagingClient } from './messaging';\nimport { DeploymentClient } from './deployment';\nimport { AgentsClient } from './agents';\nimport { CustomerSessionClient } from './customer-session';\nimport { RulesClient } from './rules';\nimport { EntitiesClient } from './entities';\n\n/**\n * Authentication options for wallet-based auth\n */\nexport type AuthenticateOptions = {\n /** Blockchain chain */\n chain: BaasSupportedChain;\n /** Wallet address on the chain */\n walletAddress: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Function to sign the challenge message */\n signFn: (message: string) => string | Promise<string>;\n};\n\n/**\n * Fields shared across both arms of {@link BaasConnectToClusterConfig}.\n * Pulled out so the discriminated-union arms below stay focused on the\n * \"where to discover from\" decision.\n */\ninterface BaasConnectToClusterShared {\n /** Application ID (for existing apps) */\n appId?: string;\n /** Application name (for registration) */\n appName?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP connections (for local development only) */\n allowInsecure?: boolean;\n /**\n * Path prefix prepended to every request to the chosen host. Defaults to\n * `/host` because cluster discovery returns the gateway URL, and the\n * gateway routes BaaS traffic at `/host/*`. Override to `''` if you are\n * pointing the SDK directly at a host that doesn't sit behind the\n * gateway path rewrite.\n */\n pathPrefix?: string;\n /**\n * Optional HCS trust anchor — cross-checks the bootstrap response\n * against the on-chain validator-registry topic so a compromised\n * bootstrap seed can't inject rogue clusters. Per deployment.\n */\n trustAnchor?: {\n network: 'mainnet' | 'testnet' | 'previewnet';\n registryTopicId: string;\n mirrorNodeUrl?: string;\n };\n}\n\n/**\n * Config for {@link BaasClient.connectToCluster}. Exactly ONE of\n * `network` or `bootstrap` must be supplied — encoded as a discriminated\n * union so passing both is a compile-time error.\n *\n * `network` is the recommended default for smart-app callers; the SDK\n * resolves the canonical gateway entrypoint from {@link KNOWN_NETWORKS}.\n * `bootstrap` is the manual escape hatch for private deployments.\n */\nexport type BaasConnectToClusterConfig =\n | ({\n /** Named network — SDK resolves the canonical gateway entrypoint. */\n network: NetworkName;\n bootstrap?: never;\n } & BaasConnectToClusterShared)\n | ({\n /** Bootstrap seeds: URLs that serve `GET /api/v3/discovery/clusters`. */\n bootstrap: string[];\n network?: never;\n } & BaasConnectToClusterShared);\n\nexport class BaasClient {\n private readonly hostUrl: string;\n private readonly pathPrefix: string;\n private appId: string | undefined;\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n private readonly http: HttpClient;\n /** Last HTTP error (for getHttpHealth) */\n private lastHttpError?: Error;\n /**\n * Auth options from the last {@link authenticate} call, retained so the\n * client can transparently re-authenticate when the session token expires\n * (the http client invokes {@link reauthenticate} on a 401). Undefined until\n * the first successful authenticate.\n */\n private authContext?: AuthenticateOptions;\n\n // ========== Sub-Clients ==========\n\n /** Trustless database with state proofs and Merkle verification */\n public readonly db: DatabaseClient;\n /** Decentralized file storage */\n public readonly storage: StorageClient;\n /** Serverless function deployment and invocation */\n public readonly functions: FunctionsClient;\n /** Real-time pub/sub messaging with channels, history, and presence */\n public readonly messaging: MessagingClient;\n /** App deployment lifecycle management */\n public readonly deployment: DeploymentClient;\n /** Autonomous smart agent management */\n public readonly agents: AgentsClient;\n /** Customer→smart-app session bridge (TokenGate Face B). */\n public readonly customerSession: CustomerSessionClient;\n /** Canonical validator-rules authoring surface (publish/get/list/simulate). */\n public readonly rules: RulesClient;\n /** Canonical entity authoring surface (token/account/topic/agent + launchpad). */\n public readonly entities: EntitiesClient;\n\n constructor(config: BaasClientConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n this.hostUrl = validateUrl(config.hostUrl, this.allowInsecure);\n this.appId = config.appId;\n this.timeout = config.timeout ?? 30000;\n\n // Strip trailing slash from pathPrefix and ensure leading slash; empty if none.\n const prefix = (config.pathPrefix ?? '').replace(/\\/$/, '');\n this.pathPrefix = prefix ? (prefix.startsWith('/') ? prefix : `/${prefix}`) : '';\n const baseUrlWithPrefix = this.pathPrefix\n ? this.hostUrl.replace(/\\/$/, '') + this.pathPrefix\n : this.hostUrl;\n\n // Create shared HTTP client. baseUrl includes optional pathPrefix so all\n // /api/v3/baas/* paths get routed to the host even when consumed via a gateway.\n this.http = createHttpClient({\n baseUrl: baseUrlWithPrefix,\n timeout: this.timeout,\n // Transparent session refresh: on a 401, re-run the challenge-response\n // with the retained signer and retry once. No-op until authenticate() has\n // been called (authContext set). Excludes /api/v3/{,baas/}auth/* (see http client).\n onUnauthorized: () => this.reauthenticate(),\n });\n\n // Helper to get appId with validation\n const getAppId = () => this.requireAppId();\n\n // Initialize sub-clients\n this.db = new DatabaseClient(this.http, getAppId);\n this.storage = new StorageClient(this.http, getAppId);\n this.functions = new FunctionsClient(this.http, getAppId);\n this.messaging = new MessagingClient(this.http, getAppId);\n this.deployment = new DeploymentClient(this.http);\n this.agents = new AgentsClient(this.http);\n this.customerSession = new CustomerSessionClient(baseUrlWithPrefix, this.timeout);\n this.rules = new RulesClient(this.http);\n this.entities = new EntitiesClient(this.http);\n }\n\n /**\n * Connect to the Smart Engines BaaS via cluster auto-discovery.\n *\n * Zero-config entrypoint flow:\n *\n * 1. Resolves the bootstrap seed list:\n * - `network: 'testnet' | 'mainnet'` → canonical Cloudflare-fronted\n * gateway via {@link KNOWN_NETWORKS}.\n * - `bootstrap: string[]` → explicit seed list (private deployments).\n * 2. Fetches `GET /api/v3/discovery/clusters` from the first reachable\n * seed; the response carries every active cluster's gateway URL.\n * 3. Random-picks one active cluster.\n * 4. Returns a `BaasClient` pointed at that cluster's gatewayUrl, with\n * `pathPrefix: '/host'` so all BaaS sub-clients (db / storage /\n * functions / messaging / agents / rules / entities) route through\n * the gateway's `/host/*` rewrite.\n *\n * @example Zero-config (recommended)\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * network: 'testnet',\n * appId: 'app_abc',\n * });\n *\n * await baas.db.insert('users', { name: 'Alice' });\n * ```\n *\n * @example Custom seeds (private deployments)\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * bootstrap: ['https://gateway.my-private-net.example'],\n * appId: 'app_abc',\n * });\n * ```\n *\n * @throws {BaasError} `503` when no cluster is reachable via any seed.\n * @throws {BaasError} `400` when bootstrap resolution yields an empty list\n * (only possible when the caller passes an empty array explicitly).\n */\n static async connectToCluster(config: BaasConnectToClusterConfig): Promise<BaasClient> {\n const allowInsecure = config.allowInsecure ?? false;\n\n const resolved = await resolveClusterEndpoint({\n bootstrap: config.bootstrap,\n network: config.network,\n allowInsecure,\n trustAnchor: config.trustAnchor,\n });\n\n if (!resolved.ok) {\n if (resolved.reason === 'no-seeds') {\n throw new BaasError(\n 'connectToCluster requires either a non-empty `bootstrap` list or a known `network` name.',\n 400,\n );\n }\n throw new BaasError(\n 'No active clusters available via bootstrap seeds. Check network reachability or bootstrap URLs.',\n 503,\n );\n }\n\n const cluster = resolved.cluster;\n return new BaasClient({\n hostUrl: cluster.endpoints.gatewayUrl,\n appId: config.appId,\n appName: config.appName,\n timeout: config.timeout,\n allowInsecure,\n // BaaS traffic is gateway-routed at `/host/*` by default. Callers\n // pointing at a bare host can override with `pathPrefix: ''`.\n pathPrefix: config.pathPrefix ?? '/host',\n });\n }\n\n /** Set the app ID (for newly registered apps) */\n setAppId(appId: string): void {\n this.appId = appId;\n }\n\n /** Check if the client is authenticated */\n isAuthenticated(): boolean {\n return this.http.getAuthToken() !== undefined;\n }\n\n /** Get the current app ID */\n getAppId(): string | undefined {\n return this.appId;\n }\n\n /**\n * Get the configured host URL. After\n * {@link BaasClient.connectToCluster} this is the gateway URL of the\n * cluster the SDK landed on after random-pick — useful for logging,\n * \"behind the curtain\" UIs, or debugging which cluster is serving a\n * given request.\n */\n getHostUrl(): string {\n return this.hostUrl;\n }\n\n /**\n * Get HTTP resilience health information\n * @returns Object with circuit breaker state and last error (if any)\n */\n getHttpHealth(): { breaker: CircuitBreakerSnapshot | null; lastError?: Error } {\n // Note: In a real implementation, we would get the circuit breaker state\n // from the resilient HTTP layer. For now, return null since the base\n // HTTP client doesn't expose it yet.\n return {\n breaker: null,\n lastError: this.lastHttpError,\n };\n }\n\n private requireAppId(): string {\n if (!this.appId) {\n throw new BaasError(\n 'App ID required. Provide appId in config (e.g. from a prior deployment.init() call).',\n 400\n );\n }\n return this.appId;\n }\n\n // ========== Authentication ==========\n\n /**\n * Authenticate with the BaaS host using wallet challenge-response\n *\n * 1. Requests a challenge message from the host\n * 2. Signs the challenge with the provided signing function\n * 3. Submits the signature for verification\n * 4. Stores the JWT token for subsequent requests\n */\n async authenticate(options: AuthenticateOptions): Promise<BaasAuthResult> {\n const { chain, walletAddress, publicKey, signFn } = options;\n // Retain for transparent re-authentication when the token later expires.\n this.authContext = options;\n\n // Step 1: Request challenge — `this.http` already includes the\n // pathPrefix in its baseUrl, so we use the same /api/v3/baas/* path the\n // server route exposes.\n let challenge: BaasChallengeResponse;\n try {\n challenge = await this.http.post<BaasChallengeResponse>('/api/v3/baas/auth/challenge', {\n chain,\n walletAddress,\n appId: this.appId,\n });\n } catch (err) {\n throw asBaasError(err);\n }\n\n // Step 2: Sign the challenge\n const signature = await signFn(challenge.message);\n\n // Step 3: Verify and get token\n let result: BaasAuthResult;\n try {\n result = await this.http.post<BaasAuthResult>('/api/v3/baas/auth/verify', {\n challengeId: challenge.challengeId,\n signature,\n publicKey,\n });\n } catch (err) {\n throw asBaasError(err);\n }\n\n // Persist the token on the shared HTTP client so every subsequent\n // sub-client request automatically carries Authorization: Bearer ...\n this.http.setAuthToken(result.token);\n\n return result;\n }\n\n /**\n * Re-run the challenge-response with the retained signer to mint a fresh\n * session token. Invoked by the http client's `onUnauthorized` hook when a\n * request 401s because the token expired — so long-lived clients keep working\n * without the caller re-implementing refresh. No-op if {@link authenticate}\n * was never called. The `/api/v3/baas/auth/*` calls below are excluded from the http\n * client's 401-retry path, so this can never recurse.\n */\n private async reauthenticate(): Promise<void> {\n const ctx = this.authContext;\n if (!ctx) return; // never authenticated — nothing to refresh\n const challenge = await this.http.post<BaasChallengeResponse>('/api/v3/baas/auth/challenge', {\n chain: ctx.chain,\n walletAddress: ctx.walletAddress,\n appId: this.appId,\n });\n const signature = await ctx.signFn(challenge.message);\n const result = await this.http.post<BaasAuthResult>('/api/v3/baas/auth/verify', {\n challengeId: challenge.challengeId,\n signature,\n publicKey: ctx.publicKey,\n });\n this.http.setAuthToken(result.token);\n }\n\n /** Validate the current session */\n async validateSession(): Promise<BaasSessionInfo> {\n this.requireAuth();\n try {\n return await this.http.get<BaasSessionInfo>('/api/v3/baas/auth/session');\n } catch (err) {\n throw asBaasError(err);\n }\n }\n\n /** Destroy the current session on server and clear local token */\n async logout(): Promise<void> {\n if (this.http.getAuthToken()) {\n try {\n await this.http.post('/api/v3/baas/auth/logout', {});\n } catch {\n // Best effort — clear locally even if server request fails\n }\n }\n this.http.setAuthToken(undefined);\n }\n\n // ========== HTTP Helpers ==========\n\n private requireAuth(): void {\n if (!this.http.getAuthToken()) {\n throw new BaasError('Authentication required. Call authenticate() first.', 401);\n }\n }\n}\n\n/**\n * BaaS Error\n */\nexport class BaasError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: BaasErrorDetails\n ) {\n super(message);\n this.name = 'BaasError';\n }\n}\n\n/**\n * Convert a thrown `SdkHttpError` (raised by the shared HTTP client) into\n * a `BaasError` so BaaS callers continue to see the historically expected\n * error type, with a uniform `statusCode` field and the raw server-side\n * `details` payload preserved.\n */\nfunction asBaasError(err: unknown): BaasError {\n if (err instanceof BaasError) return err;\n if (err instanceof SdkHttpError) {\n const details = (err.details ?? undefined) as BaasErrorDetails | undefined;\n return new BaasError(err.message, err.statusCode, details);\n }\n const e = err as Error;\n return new BaasError(`Network error: ${e?.message ?? String(err)}`, 0, {\n originalError: e?.message ?? String(err),\n });\n}\n\nfunction validateUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new BaasError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new BaasError(\n 'HTTPS is required for secure connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n return parsed.origin;\n } catch (error) {\n if (error instanceof BaasError) throw error;\n throw new BaasError(`Invalid URL: ${url}`, 400);\n }\n}\n","import {\n Injectable,\n Logger,\n OnModuleInit,\n OnModuleDestroy,\n Inject,\n Optional,\n} from '@nestjs/common';\nimport { SmartEngineClient, SmartEngineClientConfig, SmartEngineError } from '../client';\nimport { SmartGatewayClient } from '../gateway';\nimport { BaasClient as SdkBaasClient } from '../baas';\n\n/**\n * Configuration for SmartEngineService\n */\nexport interface SmartEngineServiceConfig extends SmartEngineClientConfig {\n /** Enable automatic connection test on module init */\n testConnection?: boolean;\n /** Enable auto-reconnect on connection failure */\n autoReconnect?: boolean;\n /** Reconnection interval in milliseconds */\n reconnectInterval?: number;\n /** Maximum reconnection attempts (0 = infinite) */\n maxReconnectAttempts?: number;\n}\n\n/**\n * Configuration token for dependency injection\n */\nexport const SMART_ENGINE_CONFIG = 'SMART_ENGINE_CONFIG';\n\n/**\n * Injection token for the full SDK `BaasClient` (with `.rules`, `.entities`,\n * `.db`, `.storage`, etc. as sub-clients). Use this when a consumer wants the\n * parent BaaS surface.\n */\nexport const SDK_BAAS_CLIENT = 'SDK_BAAS_CLIENT';\n\n/**\n * Injection token for the BaaS `RulesClient` sub-client (publish/get/list/\n * simulate/deprecate canonical validator rules).\n */\nexport const RULES_CLIENT = 'RULES_CLIENT';\n\n/**\n * Injection token for the BaaS `EntitiesClient` sub-client (create\n * token/account/topic/agent + launchpad).\n */\nexport const ENTITIES_CLIENT = 'ENTITIES_CLIENT';\n\n/**\n * BaaS (Blockchain-as-a-Service) client interface\n *\n * Provides simplified access to blockchain operations for BaaS scenarios\n * where applications need managed blockchain infrastructure without\n * direct validator management.\n */\nexport interface BaasClient {\n /** The underlying SmartEngineClient */\n readonly client: SmartEngineClient;\n /** Check if the client is connected and healthy */\n isHealthy(): Promise<boolean>;\n /** Get the validator base URL */\n getBaseUrl(): string;\n}\n\n/**\n * SmartEngineService - NestJS injectable service for Smart Engines SDK\n *\n * Provides lifecycle-managed access to SmartEngineClient with:\n * - Automatic connection testing on module init\n * - Graceful shutdown on module destroy\n * - BaaS client wrapper for simplified access\n * - Optional auto-reconnect functionality\n *\n * @example Module configuration with forRoot\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRoot({\n * validatorBaseUrl: 'https://validator.example.com',\n * apiKey: process.env.SMART_ENGINE_API_KEY,\n * testConnection: true,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Direct service injection\n * ```typescript\n * import { Injectable } from '@nestjs/common';\n * import { SmartEngineService } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Injectable()\n * export class MyService {\n * constructor(private readonly smartEngine: SmartEngineService) {}\n *\n * async doSomething() {\n * const client = this.smartEngine.getClient();\n * const health = await client.getHealth();\n * }\n * }\n * ```\n */\n@Injectable()\nexport class SmartEngineService implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(SmartEngineService.name);\n private client: SmartEngineClient | null = null;\n private baasClient: BaasClient | null = null;\n private connected = false;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private reconnectAttempts = 0;\n\n constructor(\n @Optional()\n @Inject(SMART_ENGINE_CONFIG)\n private readonly config?: SmartEngineServiceConfig\n ) {}\n\n /**\n * Initialize the service when the module starts\n */\n async onModuleInit(): Promise<void> {\n if (!this.config) {\n this.logger.warn(\n 'SmartEngineService initialized without configuration. Call configure() before using.'\n );\n return;\n }\n\n await this.initialize(this.config);\n }\n\n /**\n * Clean up resources when the module is destroyed\n */\n async onModuleDestroy(): Promise<void> {\n await this.shutdown();\n }\n\n /**\n * Initialize the service with configuration\n *\n * Can be called manually if not using DI configuration\n */\n async initialize(config: SmartEngineServiceConfig): Promise<void> {\n this.logger.log(`Initializing SmartEngineService for ${config.validatorBaseUrl}`);\n\n try {\n this.client = new SmartEngineClient({\n // SDK 4.0 validator-origin type-fence: the service config extends\n // SmartEngineClientConfig, so it carries `validatorBaseUrl` directly.\n validatorBaseUrl: config.validatorBaseUrl,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n allowInsecure: config.allowInsecure,\n });\n\n // Create BaaS client wrapper\n this.baasClient = this.createBaasClient(this.client);\n\n // Test connection if enabled\n if (config.testConnection !== false) {\n await this.testConnection();\n }\n\n this.connected = true;\n this.reconnectAttempts = 0;\n this.logger.log('SmartEngineService initialized successfully');\n } catch (error) {\n const err = error as Error;\n this.logger.error(`Failed to initialize SmartEngineService: ${err.message}`);\n\n if (config.autoReconnect) {\n this.scheduleReconnect(config);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Gracefully shutdown the service\n */\n async shutdown(): Promise<void> {\n this.logger.log('Shutting down SmartEngineService');\n\n // Clear reconnect timer\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Clear client references\n this.client = null;\n this.baasClient = null;\n this.connected = false;\n\n this.logger.log('SmartEngineService shutdown complete');\n }\n\n /**\n * Get the SmartEngineClient instance\n *\n * @throws SmartEngineError if client is not initialized\n */\n getClient(): SmartEngineClient {\n if (!this.client) {\n throw new SmartEngineError(\n 'SmartEngineClient not initialized. Ensure SmartEngineService is configured properly.',\n 500\n );\n }\n return this.client;\n }\n\n /**\n * Get the BaaS client for simplified blockchain access\n *\n * The BaaS client provides a simplified interface for applications\n * that need managed blockchain infrastructure access.\n *\n * @throws SmartEngineError if client is not initialized\n */\n getBaasClient(): BaasClient {\n if (!this.baasClient) {\n throw new SmartEngineError(\n 'BaasClient not initialized. Ensure SmartEngineService is configured properly.',\n 500\n );\n }\n return this.baasClient;\n }\n\n /**\n * Check if the service is connected and healthy\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Test the connection to the validator\n */\n async testConnection(): Promise<boolean> {\n if (!this.client) {\n return false;\n }\n\n try {\n const health = await this.client.getHealth();\n this.connected = health.status === 'healthy' || health.status === 'ok';\n return this.connected;\n } catch (error) {\n const err = error as Error;\n this.logger.warn(`Connection test failed: ${err.message}`);\n this.connected = false;\n return false;\n }\n }\n\n /**\n * Get the current connection status\n */\n getStatus(): {\n connected: boolean;\n baseUrl: string | null;\n authenticated: boolean;\n reconnectAttempts: number;\n } {\n return {\n connected: this.connected,\n baseUrl: this.client?.getBaseUrl() ?? null,\n authenticated: this.client?.isAuthenticated() ?? false,\n reconnectAttempts: this.reconnectAttempts,\n };\n }\n\n /**\n * Create a SmartGatewayClient for gateway operations\n */\n createGatewayClient(config: {\n baseUrl: string;\n apiKey?: string;\n authToken?: string;\n timeout?: number;\n allowInsecure?: boolean;\n }): SmartGatewayClient {\n return new SmartGatewayClient(config);\n }\n\n /**\n * Create a BaaS client for host operations\n */\n createHostClient(config: {\n hostUrl: string;\n appId?: string;\n timeout?: number;\n allowInsecure?: boolean;\n }): SdkBaasClient {\n return new SdkBaasClient(config);\n }\n\n /**\n * Create a BaaS client wrapper around the SmartEngineClient\n */\n private createBaasClient(client: SmartEngineClient): BaasClient {\n return {\n client,\n isHealthy: async () => {\n try {\n const health = await client.getHealth();\n return health.status === 'healthy' || health.status === 'ok';\n } catch {\n return false;\n }\n },\n getBaseUrl: () => client.getBaseUrl(),\n };\n }\n\n /**\n * Schedule a reconnection attempt\n */\n private scheduleReconnect(config: SmartEngineServiceConfig): void {\n const maxAttempts = config.maxReconnectAttempts ?? 0;\n const interval = config.reconnectInterval ?? 5000;\n\n if (maxAttempts > 0 && this.reconnectAttempts >= maxAttempts) {\n this.logger.error(`Max reconnection attempts (${maxAttempts}) reached. Giving up.`);\n return;\n }\n\n this.reconnectAttempts++;\n this.logger.log(`Scheduling reconnection attempt ${this.reconnectAttempts} in ${interval}ms`);\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.initialize(config);\n } catch {\n // Error already logged in initialize\n }\n }, interval);\n }\n}\n","import { DynamicModule, Module, Provider, Type } from '@nestjs/common';\nimport {\n SmartEngineService,\n SmartEngineServiceConfig,\n SMART_ENGINE_CONFIG,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n} from './smart-engine.service';\nimport { BaasClient as SdkBaasClient } from '../baas';\n\n/**\n * Options for async module configuration\n */\nexport interface SmartEngineModuleAsyncOptions {\n /** Imports required for the factory */\n imports?: any[];\n /** Factory function to create configuration */\n useFactory?: (...args: any[]) => Promise<SmartEngineServiceConfig> | SmartEngineServiceConfig;\n /** Dependencies to inject into the factory */\n inject?: any[];\n /** Class to use for configuration */\n useClass?: Type<SmartEngineOptionsFactory>;\n /** Existing provider to use for configuration */\n useExisting?: Type<SmartEngineOptionsFactory>;\n /** Make the module global */\n isGlobal?: boolean;\n}\n\n/**\n * Factory interface for creating SmartEngine configuration\n */\nexport interface SmartEngineOptionsFactory {\n createSmartEngineOptions(): Promise<SmartEngineServiceConfig> | SmartEngineServiceConfig;\n}\n\n/**\n * SmartEngineModule - NestJS module for Smart Engines SDK integration\n *\n * Provides dependency injection for SmartEngineService with support for\n * both synchronous and asynchronous configuration.\n *\n * @example Synchronous configuration with forRoot\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRoot({\n * validatorBaseUrl: 'https://validator.example.com',\n * apiKey: 'your-api-key',\n * testConnection: true,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Async configuration with forRootAsync\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { ConfigService, ConfigModule } from '@nestjs/config';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRootAsync({\n * imports: [ConfigModule],\n * useFactory: (configService: ConfigService) => ({\n * validatorBaseUrl: configService.get('SMART_ENGINE_URL'),\n * apiKey: configService.get('SMART_ENGINE_API_KEY'),\n * testConnection: true,\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Using a configuration class\n * ```typescript\n * import { Injectable } from '@nestjs/common';\n * import { SmartEngineModule, SmartEngineOptionsFactory } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Injectable()\n * class SmartEngineConfigService implements SmartEngineOptionsFactory {\n * createSmartEngineOptions() {\n * return {\n * validatorBaseUrl: process.env.SMART_ENGINE_URL,\n * apiKey: process.env.SMART_ENGINE_API_KEY,\n * };\n * }\n * }\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRootAsync({\n * useClass: SmartEngineConfigService,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class SmartEngineModule {\n /**\n * Configure the module with static configuration.\n *\n * @param config - SmartEngine service configuration.\n * @param isGlobal - Whether to make the module global. @defaultValue true\n * @returns A `DynamicModule` exporting {@link SmartEngineService} plus the\n * BaaS / rules / entities clients.\n */\n static forRoot(config: SmartEngineServiceConfig, isGlobal = true): DynamicModule {\n return {\n module: SmartEngineModule,\n global: isGlobal,\n providers: [\n {\n provide: SMART_ENGINE_CONFIG,\n useValue: config,\n },\n SmartEngineService,\n ...this.createBaasProviders(),\n ],\n exports: [\n SmartEngineService,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n ],\n };\n }\n\n /**\n * Configure the module with async configuration.\n *\n * Supports factory functions, configuration classes, and existing providers.\n *\n * @param options - Async configuration options.\n * @returns A `DynamicModule` exporting {@link SmartEngineService} plus the\n * BaaS / rules / entities clients.\n * @throws Error if `options` provides none of `useFactory`, `useClass`, or\n * `useExisting`.\n */\n static forRootAsync(options: SmartEngineModuleAsyncOptions): DynamicModule {\n const asyncProviders = this.createAsyncProviders(options);\n\n return {\n module: SmartEngineModule,\n global: options.isGlobal ?? true,\n imports: options.imports || [],\n providers: [\n ...asyncProviders,\n SmartEngineService,\n ...this.createBaasProviders(),\n ],\n exports: [\n SmartEngineService,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n ],\n };\n }\n\n /**\n * Build the BaaS SDK providers — the full `BaasClient` and its `rules` /\n * `entities` sub-clients — all bound to dedicated injection tokens. Wired\n * into both `forRoot` and `forRootAsync` so consumers can\n * `@Inject(RULES_CLIENT) rules: RulesClient` directly.\n */\n private static createBaasProviders(): Provider[] {\n return [\n {\n provide: SDK_BAAS_CLIENT,\n useFactory: (config: SmartEngineServiceConfig) =>\n new SdkBaasClient({\n // SDK 4.0: the service config carries a single origin field\n // (`validatorBaseUrl`); the BaaS client uses it as its `hostUrl`,\n // preserving the prior single-URL wiring.\n hostUrl: config.validatorBaseUrl,\n timeout: config.timeout,\n allowInsecure: config.allowInsecure,\n }),\n inject: [SMART_ENGINE_CONFIG],\n },\n {\n provide: RULES_CLIENT,\n useFactory: (baas: SdkBaasClient) => baas.rules,\n inject: [SDK_BAAS_CLIENT],\n },\n {\n provide: ENTITIES_CLIENT,\n useFactory: (baas: SdkBaasClient) => baas.entities,\n inject: [SDK_BAAS_CLIENT],\n },\n ];\n }\n\n /**\n * Create async providers based on configuration options\n */\n private static createAsyncProviders(options: SmartEngineModuleAsyncOptions): Provider[] {\n if (options.useFactory) {\n return [\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: options.useFactory,\n inject: options.inject || [],\n },\n ];\n }\n\n if (options.useClass) {\n return [\n {\n provide: options.useClass,\n useClass: options.useClass,\n },\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: async (optionsFactory: SmartEngineOptionsFactory) =>\n optionsFactory.createSmartEngineOptions(),\n inject: [options.useClass],\n },\n ];\n }\n\n if (options.useExisting) {\n return [\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: async (optionsFactory: SmartEngineOptionsFactory) =>\n optionsFactory.createSmartEngineOptions(),\n inject: [options.useExisting],\n },\n ];\n }\n\n throw new Error(\n 'Invalid SmartEngineModuleAsyncOptions: must provide useFactory, useClass, or useExisting'\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/_vendor/chain.schema.ts","../../src/_vendor/capabilities.schema.ts","../../src/_vendor/account.schema.ts","../../src/_vendor/sovereignty.schema.ts","../../src/_vendor/api.schema.ts","../../src/discovery/mirror-node.ts","../../src/discovery/validator-discovery.ts","../../src/discovery/cluster-discovery.ts","../../src/http/index.ts","../../src/discovery/discovery-client.ts","../../src/network-presets.ts","../../src/discovery/resolve-cluster.ts","../../src/auth/validator-auth.ts","../../src/subscription/index.ts","../../src/faucet/index.ts","../../src/tss/index.ts","../../src/ipfs/index.ts","../../src/hedera-tss/index.ts","../../src/transactions/chains/hedera.ts","../../src/transactions/chains/xrpl.ts","../../src/transactions/chains/solana.ts","../../src/transactions/chains/polkadot.ts","../../src/transactions/index.ts","../../src/snapshots/index.ts","../../src/historical-balance/historical-balance-client.ts","../../src/settlement/index.ts","../../src/governance/governance-client.ts","../../src/dao/dashboard-client.ts","../../src/dao/dao-client.ts","../../src/personhood/personhood-client.ts","../../src/baas/agents/index.ts","../../src/baas/deployment/index.ts","../../src/bridge/bridge-client.ts","../../src/resources/resources-client.ts","../../src/envelope/envelope-client.ts","../../src/tokens/tokens-client.ts","../../src/operator/operator-client.ts","../../src/client.ts","../../src/gateway/routing/index.ts","../../src/gateway/domains/index.ts","../../src/gateway/dns/index.ts","../../src/gateway/health/index.ts","../../src/gateway/client.ts","../../src/baas/database/index.ts","../../src/baas/storage/index.ts","../../src/baas/functions/index.ts","../../src/baas/messaging/index.ts","../../src/baas/customer-session/index.ts","../../src/baas/rules/client.ts","../../src/baas/entities/client.ts","../../src/baas/client.ts","../../src/nestjs/smart-engine.service.ts","../../src/nestjs/smart-engine.module.ts"],"names":["z","buildQuery","validateUrl","SmartEngineService","Logger","Injectable","Optional","SmartEngineModule","Module"],"mappings":";;;;;;;;;;;;;;AAKO,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK;AAAA,EACpC,QAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC,CAAA;AAOM,IAAM,iBAAA,GAAoBA,MAAE,IAAA,CAAK,CAAC,WAAW,SAAA,EAAW,QAAA,EAAU,OAAO,CAAC,CAAA;AAO9CA,MAAE,MAAA,CAAO;AAAA,EAC1C,KAAA,EAAO,eAAA;AAAA,EACP,OAAA,EAAS,iBAAA;AAAA,EACT,cAAA,EAAgBA,MAAE,MAAA,CAAO;AAAA,IACvB,IAAA,EAAMA,MAAE,MAAA,EAAO;AAAA,IACf,MAAA,EAAQA,MAAE,MAAA,EAAO;AAAA,IACjB,UAAUA,KAAA,CAAE,MAAA,GAAS,GAAA,EAAI,CAAE,IAAI,CAAC;AAAA,GACjC,CAAA;AAAA,EACD,SAAA,EAAWA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC/B,aAAaA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA;AAChC,CAAC;ACzBM,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA;AAAA;AAA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I,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACF;AA5IaI,yBAAA,GAAN,eAAA,CAAA;AAAA,EADNC,aAAA,CAAO,EAAE;AAAA,CAAA,EACGD,yBAAA,CAAA","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n/**\n * Supported blockchain types\n */\nexport const ChainTypeSchema = z.enum([\n 'hedera',\n 'xrpl',\n 'polkadot',\n 'solana',\n 'stellar',\n 'ethereum',\n 'polygon',\n 'bitcoin',\n 'cardano',\n]);\n\nexport type ChainType = z.infer<typeof ChainTypeSchema>;\n\n/**\n * Network environment types\n */\nexport const NetworkTypeSchema = z.enum(['mainnet', 'testnet', 'devnet', 'local']);\n\nexport type NetworkType = z.infer<typeof NetworkTypeSchema>;\n\n/**\n * Chain metadata schema\n */\nexport const ChainMetadataSchema = z.object({\n chain: ChainTypeSchema,\n network: NetworkTypeSchema,\n nativeCurrency: z.object({\n name: z.string(),\n symbol: z.string(),\n decimals: z.number().int().min(0),\n }),\n blockTime: z.number().optional(),\n rpcEndpoint: z.string().url().optional(),\n});\n\nexport type ChainMetadata = z.infer<typeof ChainMetadataSchema>;\n","/**\n * Token Capabilities Schema\n *\n * Defines universal token capabilities that are chain-agnostic.\n * Each capability maps to chain-specific implementations.\n */\nimport { z } from 'zod';\n\n/**\n * Token Capabilities Schema\n *\n * These capabilities define what operations a token supports.\n * The validator layer translates these to chain-specific implementations.\n */\nexport const TokenCapabilitiesSchema = z.object({\n /**\n * Pause all token operations globally\n * - Hedera: Adds pauseKey to token\n * - XRPL: Enables GlobalFreeze flag on issuer account\n */\n pausable: z.boolean().default(false),\n\n /**\n * Freeze/restrict specific accounts from transacting\n * - Hedera: Adds freezeKey to token\n * - XRPL: Enables trust line freeze capability\n */\n restrictable: z.boolean().default(false),\n\n /**\n * KYC/compliance controls for accounts\n * - Hedera: Adds kycKey to token\n * - XRPL: Requires authorized trust lines (RequireAuth)\n */\n compliant: z.boolean().default(false),\n\n /**\n * Force remove tokens from accounts (compliance wipe)\n * - Hedera: Adds wipeKey to token\n * - XRPL: Enables clawback (lsfAllowTrustLineClawback)\n */\n wipeable: z.boolean().default(false),\n\n /**\n * Mint additional supply after creation\n * - Hedera: Adds supplyKey to token\n * - XRPL: Issuer can always issue more via Payment\n */\n mintable: z.boolean().default(true),\n\n /**\n * Burn tokens (reduce supply)\n * - Hedera: Requires supplyKey\n * - XRPL: Send back to issuer (reduces supply)\n */\n burnable: z.boolean().default(true),\n\n /**\n * Allow transfers between accounts\n * - All chains: Generally always supported\n */\n transferable: z.boolean().default(true),\n});\n\nexport type TokenCapabilities = z.infer<typeof TokenCapabilitiesSchema>;\n\n/**\n * Capability names as a type\n */\nexport type CapabilityName = keyof TokenCapabilities;\n\n/**\n * List of all capability names\n */\nexport const CAPABILITY_NAMES: CapabilityName[] = [\n 'pausable',\n 'restrictable',\n 'compliant',\n 'wipeable',\n 'mintable',\n 'burnable',\n 'transferable',\n];\n","import { z } from 'zod';\nimport { ChainTypeSchema } from './chain.schema';\n\n/**\n * Account identifier schema - generic string that works across chains\n */\nexport const AccountIdSchema = z.string().min(1);\n\n// Note: Export as AccountIdString to avoid collision with AccountId value object\nexport type AccountIdString = z.infer<typeof AccountIdSchema>;\n\n/**\n * Account information schema\n */\nexport const AccountInfoSchema = z.object({\n accountId: AccountIdSchema,\n balance: z.string(), // String to handle large numbers and decimals\n chain: ChainTypeSchema,\n publicKey: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n});\n\nexport type AccountInfo = z.infer<typeof AccountInfoSchema>;\n\n/**\n * Account balance schema with token details\n */\nexport const AccountBalanceSchema = z.object({\n accountId: AccountIdSchema,\n chain: ChainTypeSchema,\n nativeBalance: z.string(),\n tokens: z\n .array(\n z.object({\n tokenId: z.string(),\n balance: z.string(),\n decimals: z.number().int().min(0),\n symbol: z.string().optional(),\n })\n )\n .optional(),\n timestamp: z.date(),\n});\n\nexport type AccountBalance = z.infer<typeof AccountBalanceSchema>;\n","import { z } from 'zod';\n\n/**\n * Sovereignty mode for entity creation.\n * - 'partial': user + validator both sign; on-chain = nested KeyList/SignerList\n * - 'full': validator-only signs; on-chain = validator multisig alone\n *\n * \"partial\" is product-facing \"mixed\".\n *\n * The schema accepts only 'partial' and 'full'. There is no owner-only mode\n * (no validator in the signing path); any payload carrying an unrecognized\n * `securityMode` fails safeParse at the schema boundary.\n */\nexport const SecurityModeSchema = z.enum(['partial', 'full']);\nexport type SecurityMode = z.infer<typeof SecurityModeSchema>;\n\n/**\n * Single source of truth for the sovereignty field invariant.\n *\n * - partial: requires BOTH entityId and appOwnerPublicKey\n * - full: requires entityId (appOwnerPublicKey is ignored, not an error)\n *\n * Exported so merged schemas in api.schema.ts can delegate here\n * instead of duplicating the predicate logic.\n */\nexport const sovereigntyRefinePredicate = (v: {\n securityMode: SecurityMode;\n entityId?: string;\n appOwnerPublicKey?: string;\n}): boolean => {\n if (v.securityMode === 'partial') {\n return !!v.entityId && !!v.appOwnerPublicKey;\n }\n // 'full': requires entityId\n return !!v.entityId;\n};\n\nexport const SOVEREIGNTY_REFINE_MESSAGE =\n \"securityMode='partial' requires entityId+appOwnerPublicKey; 'full' requires entityId\";\n\n/**\n * Shared fragment for every entity-creation prepare schema.\n *\n * Invariants enforced via refine:\n * - partial mode requires BOTH entityId and appOwnerPublicKey\n * - full mode requires entityId (appOwnerPublicKey ignored)\n */\n// Internal: the raw object so callers can `.merge()` it without needing\n// Zod-version-specific `.innerType()` unwrapping (v3 vs v4 API drift).\nexport const SovereigntyFieldsRawSchema = z.object({\n securityMode: SecurityModeSchema.default('full'),\n entityId: z.string().optional(),\n appOwnerPublicKey: z.string().optional(),\n});\n\nexport const SovereigntyFieldsSchema = SovereigntyFieldsRawSchema\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type SovereigntyFields = z.infer<typeof SovereigntyFieldsSchema>;\n\n/**\n * ---------------------------------------------------------------------------\n * Response-side metadata: the `sovereignty` block on PreparedTransaction\n * ---------------------------------------------------------------------------\n *\n * Every `PreparedTransactionResponse` carries a `sovereignty` block so smart-\n * apps and tests can inspect the on-chain authorization topology the\n * validator is building, without decoding raw chain-native bytes.\n *\n * - `mode: 'partial'|'full'` carries the entity id, the raw BLS hex pubkeys\n * from the entity's DKG binding, and a chain-native authorization-set\n * descriptor (KeyList for Hedera, SignerList for XRPL, weighted signer set\n * for Stellar).\n */\n\n/**\n * Recursive JSON shape for a Hedera authorization key.\n *\n * A Hedera `adminKey` / `supplyKey` / capability-key value is either a single\n * ed25519 public key or a threshold KeyList whose members are themselves\n * keys. Kept JSON-serializable (ed25519 keys as hex strings) so callers can\n * walk the structure without a `@hashgraph/sdk` dep.\n */\nexport type HederaKeyShape =\n | { type: 'ed25519'; key: string }\n | { type: 'keyList'; threshold: number; keys: HederaKeyShape[] };\n\nexport const HederaKeyShapeSchema: z.ZodType<HederaKeyShape> = z.lazy(() =>\n z.union([\n z.object({ type: z.literal('ed25519'), key: z.string() }),\n z.object({\n type: z.literal('keyList'),\n threshold: z.number().int().nonnegative(),\n keys: z.array(HederaKeyShapeSchema),\n }),\n ]),\n);\n\nexport const HederaAuthorizationSetShapeSchema = z.object({\n chain: z.literal('hedera'),\n adminKey: HederaKeyShapeSchema,\n supplyKey: HederaKeyShapeSchema.optional(),\n freezeKey: HederaKeyShapeSchema.optional(),\n wipeKey: HederaKeyShapeSchema.optional(),\n pauseKey: HederaKeyShapeSchema.optional(),\n kycKey: HederaKeyShapeSchema.optional(),\n});\n\nexport const XrplAuthorizationSetShapeSchema = z.object({\n chain: z.literal('xrpl'),\n signerEntries: z.array(\n z.object({\n account: z.string(),\n weight: z.number().int().nonnegative(),\n }),\n ),\n signerQuorum: z.number().int().nonnegative(),\n masterDisabled: z.boolean(),\n});\n\nexport const StellarAuthorizationSetShapeSchema = z.object({\n chain: z.literal('stellar'),\n signers: z.array(\n z.object({\n key: z.string(),\n weight: z.number().int().nonnegative(),\n }),\n ),\n thresholds: z.object({\n low: z.number().int().nonnegative(),\n med: z.number().int().nonnegative(),\n high: z.number().int().nonnegative(),\n }),\n masterWeight: z.number().int().nonnegative(),\n});\n\n/**\n * Recursive JSON shape for a Polkadot authorization signatory.\n *\n * A Polkadot sovereignty set resolves to a single on-chain controlling\n * `address`. That address is either a native `pallet_multisig` address\n * whose signatories may themselves be multisig accounts (`'full'` = flat\n * validator multisig; `'partial'` = nested outer multisig\n * `[userAddress, innerValidatorMultisig]`).\n *\n * Kept JSON-serializable (SS58 addresses as strings) so callers can walk the\n * structure without a `@polkadot/*` dep.\n */\nexport type PolkadotSignatoryShape =\n | { type: 'account'; address: string }\n | {\n type: 'multisig';\n address: string;\n threshold: number;\n signatories: PolkadotSignatoryShape[];\n };\n\nexport const PolkadotSignatoryShapeSchema: z.ZodType<PolkadotSignatoryShape> = z.lazy(() =>\n z.union([\n z.object({ type: z.literal('account'), address: z.string() }),\n z.object({\n type: z.literal('multisig'),\n address: z.string(),\n threshold: z.number().int().positive(),\n signatories: z.array(PolkadotSignatoryShapeSchema),\n }),\n ]),\n);\n\nexport const PolkadotAuthorizationSetShapeSchema = z.object({\n chain: z.literal('polkadot'),\n address: z.string(),\n signatory: PolkadotSignatoryShapeSchema,\n ss58Format: z.number().int().nonnegative(),\n});\n\nexport const PreparedTransactionAuthorizationSetSchema = z.discriminatedUnion('chain', [\n HederaAuthorizationSetShapeSchema,\n XrplAuthorizationSetShapeSchema,\n StellarAuthorizationSetShapeSchema,\n PolkadotAuthorizationSetShapeSchema,\n]);\n\nexport type HederaAuthorizationSetShape = z.infer<typeof HederaAuthorizationSetShapeSchema>;\nexport type XrplAuthorizationSetShape = z.infer<typeof XrplAuthorizationSetShapeSchema>;\nexport type StellarAuthorizationSetShape = z.infer<typeof StellarAuthorizationSetShapeSchema>;\nexport type PolkadotAuthorizationSetShape = z.infer<typeof PolkadotAuthorizationSetShapeSchema>;\nexport type PreparedTransactionAuthorizationSet = z.infer<\n typeof PreparedTransactionAuthorizationSetSchema\n>;\n\n/**\n * `authorizationSet` is REQUIRED for prepare endpoints that build the on-chain\n * authorization at create time (token create, account create, account setup)\n * and OPTIONAL for prepare endpoints that invoke an already-configured\n * authorization (mint, burn, transfer, payment). In the latter case the\n * authorization set lives on-chain from a prior create and smart-apps already\n * have its shape from the original create response.\n *\n * The union has two arms: `'partial'` and `'full'`. There is no owner-only\n * `'none'` arm.\n */\nexport const PreparedTransactionSovereigntySchema = z.discriminatedUnion('mode', [\n z.object({\n mode: z.literal('partial'),\n entityId: z.string(),\n validatorPublicKeys: z.array(z.string()),\n authorizationSet: PreparedTransactionAuthorizationSetSchema.optional(),\n }),\n z.object({\n mode: z.literal('full'),\n entityId: z.string(),\n validatorPublicKeys: z.array(z.string()),\n authorizationSet: PreparedTransactionAuthorizationSetSchema.optional(),\n }),\n]);\n\nexport type PreparedTransactionSovereignty = z.infer<typeof PreparedTransactionSovereigntySchema>;\n","import { z } from 'zod';\nimport { ChainTypeSchema } from './chain.schema';\nimport { AccountIdSchema } from './account.schema';\nimport { TokenCapabilitiesSchema } from './capabilities.schema';\nimport {\n SovereigntyFieldsRawSchema,\n sovereigntyRefinePredicate,\n SOVEREIGNTY_REFINE_MESSAGE,\n PreparedTransactionSovereigntySchema,\n} from './sovereignty.schema';\n\n/**\n * Vendored mirror of `RuleRefSchema` from\n * `libs/shared/src/schemas/api.schema.ts`. An HCS pointer to a published\n * `ValidatorRules`: the chain whose HCS carries it, the topic id, and the\n * rule message's consensus timestamp. Supplied on a create request so the\n * chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) instead of the degraded\n * `rule:bootstrap:<entityType>` marker (RFC 2026-06-15-onchain-rule-anchor §6.1).\n * Keep byte-identical with the shared definition when that schema changes.\n */\nexport const RuleRefSchema = z.object({\n /** Chain whose HCS the rule was published on (canonically 'hedera'). */\n chain: ChainTypeSchema,\n /** HCS topic ID the rule message was published to. */\n topicId: z.string().min(1),\n /** HCS consensus timestamp of the rule message. */\n consensusTimestamp: z.string().min(1),\n});\n\nexport type RuleRefInput = z.infer<typeof RuleRefSchema>;\n\n/**\n * Create account request schema\n *\n * @important validatorTimestamp is REQUIRED - all entities must be bound to a validator.\n * The validator rules are stored on HCS and referenced by consensus timestamp.\n */\nexport const CreateAccountRequestSchema = z.object({\n chain: ChainTypeSchema,\n initialBalance: z.string(),\n publicKey: z.string().optional(),\n memo: z.string().optional(),\n /**\n * Who pays the chain fee for this transaction. Resolution happens in the\n * controller layer (`resolvePayerAccountId`): explicit `payerAccountId`\n * wins, else the JWT-authenticated smart-app's wallet address, else the\n * request is rejected with 400. The validator **never** silently falls\n * back to its own operator account.\n */\n payerAccountId: z.string().optional(),\n /**\n * HCS consensus timestamp of the validator rules (REQUIRED).\n * Format: \"1766490325.123456789\"\n */\n validatorTimestamp: z.string().min(1, 'validatorTimestamp is required'),\n /**\n * HCS topic ID where validator rules are stored (REQUIRED).\n */\n validatorTopicId: z.string().min(1, 'validatorTopicId is required'),\n /**\n * Whether to remove admin key after creation (makes entity immutable).\n * Default: true for production-grade immutability.\n */\n immutable: z.boolean().default(true),\n /**\n * Smart node security mode for the account key structure.\n * - 'partial': threshold(2, [appOwnerKey, tssKeyList]) — co-control\n * - 'full': TSS KeyList only — full validator network control\n * @defaultValue 'full'\n */\n securityMode: z.enum(['partial', 'full']).default('full'),\n /**\n * App owner's public key (required for 'partial' security mode).\n * The owner key + TSS network key form a threshold-2 multi-sig.\n */\n appOwnerPublicKey: z.string().optional(),\n /**\n * The entity's canonical `ruleRef` (HCS pointer to its `ValidatorRules`). When\n * present, the chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) — distinct from the\n * mutable validator-binding memo — so the sign-gate resolves the rule on-chain\n * (kind:'ref') rather than trusting the replicated binding\n * (RFC 2026-06-15-onchain-rule-anchor §6.1). Absent ⇒ the degraded\n * `rule:bootstrap:<entityType>` marker when `entityType` is supplied.\n */\n ruleRef: RuleRefSchema.optional(),\n /**\n * Entity-type tag stamped into the rule anchor (e.g. 'wallet', 'account').\n * Supply it to enable the on-chain anchor; omit for the prior memo-less\n * (legacy) behaviour.\n */\n entityType: z.string().min(1).optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type ValidatorCreateAccountRequest = z.infer<typeof CreateAccountRequestSchema>;\n\n/**\n * Create account response schema\n */\nexport const CreateAccountResponseSchema = z.object({\n accountId: AccountIdSchema,\n publicKey: z.string().optional(),\n privateKey: z.string().optional(), // Only returned on creation, store securely!\n transactionId: z.string(),\n chain: ChainTypeSchema,\n timestamp: z.date().optional(),\n});\n\nexport type CreateAccountResponse = z.infer<typeof CreateAccountResponseSchema>;\n\n/**\n * Transfer request schema\n */\nexport const TransferRequestSchema = z.object({\n chain: ChainTypeSchema,\n from: AccountIdSchema,\n to: AccountIdSchema,\n amount: z.string(),\n tokenId: z.string().optional(), // undefined = native token\n memo: z.string().optional(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type TransferRequest = z.infer<typeof TransferRequestSchema>;\n\n/**\n * Transfer response schema\n */\nexport const TransferResponseSchema = z.object({\n transactionId: z.string(),\n status: z.enum(['pending', 'success', 'failed']),\n chain: ChainTypeSchema,\n fee: z.string().optional(),\n timestamp: z.date().optional(),\n});\n\nexport type TransferResponse = z.infer<typeof TransferResponseSchema>;\n\n/**\n * Query balance request schema\n */\nexport const QueryBalanceRequestSchema = z.object({\n chain: ChainTypeSchema,\n accountId: AccountIdSchema,\n});\n\nexport type QueryBalanceRequest = z.infer<typeof QueryBalanceRequestSchema>;\n\n/**\n * Query transaction request schema\n */\nexport const QueryTransactionRequestSchema = z.object({\n chain: ChainTypeSchema,\n transactionId: z.string(),\n});\n\nexport type QueryTransactionRequest = z.infer<typeof QueryTransactionRequestSchema>;\n\n/**\n * Create token request schema (v2 with capabilities)\n *\n * Supports universal token capabilities that are validated against chain support.\n * If a capability is requested but not supported on the target chain, an error is thrown.\n */\nexport const CreateTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n name: z.string().min(1).max(100),\n symbol: z.string().min(1).max(10),\n decimals: z.number().int().min(0).max(18),\n initialSupply: z.string(),\n type: z.enum(['fungible', 'nft']),\n treasury: AccountIdSchema.optional(),\n /**\n * Token capabilities define what operations the token supports.\n * These are validated against chain support and translated to native implementations.\n *\n * @example\n * ```typescript\n * capabilities: {\n * pausable: true, // Hedera: pauseKey, XRPL: GlobalFreeze\n * restrictable: true, // Hedera: freezeKey, XRPL: TrustLineFreeze\n * compliant: true, // Hedera: kycKey, XRPL: RequireAuth\n * wipeable: true, // Hedera: wipeKey, XRPL: Clawback\n * mintable: true, // Allow additional minting\n * burnable: true, // Allow burning\n * }\n * ```\n */\n capabilities: TokenCapabilitiesSchema.optional().default({\n pausable: false,\n restrictable: false,\n compliant: false,\n wipeable: false,\n mintable: true,\n burnable: true,\n transferable: true,\n }),\n /**\n * HCS consensus timestamp of the validator rules (REQUIRED).\n * Format: \"1766490325.123456789\"\n */\n validatorTimestamp: z.string().min(1, 'validatorTimestamp is required'),\n /**\n * HCS topic ID where validator rules are stored (REQUIRED).\n */\n validatorTopicId: z.string().min(1, 'validatorTopicId is required'),\n /**\n * Whether to remove admin key after creation (makes entity immutable).\n * Default: true for production-grade immutability.\n */\n immutable: z.boolean().default(true),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n /**\n * The entity's canonical `ruleRef` (HCS pointer to its `ValidatorRules`). When\n * present, the chain adapter stamps the IMMUTABLE creation-tx rule anchor\n * (`rule:<topicId>@<consensusTimestamp>:<entityType>`) — distinct from the\n * mutable validator-binding token memo — so the sign-gate resolves the rule\n * on-chain (kind:'ref') rather than trusting the replicated binding\n * (RFC 2026-06-15-onchain-rule-anchor §6.1). Absent ⇒ the degraded\n * `rule:bootstrap:<entityType>` marker when `entityType` is supplied.\n */\n ruleRef: RuleRefSchema.optional(),\n /**\n * Entity-type tag stamped into the rule anchor (e.g. 'token'). Supply it to\n * enable the on-chain anchor; omit for the prior memo-less behaviour.\n */\n entityType: z.string().min(1).optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type ValidatorCreateTokenRequest = z.infer<typeof CreateTokenRequestSchema>;\n\n/**\n * Create token response schema\n */\nexport const CreateTokenResponseSchema = z.object({\n tokenId: z.string(),\n transactionId: z.string(),\n chain: ChainTypeSchema,\n timestamp: z.date().optional(),\n});\n\nexport type CreateTokenResponse = z.infer<typeof CreateTokenResponseSchema>;\n\n/**\n * Mint token request schema\n */\n/**\n * Mint token request schema\n *\n * Supports both fungible and non-fungible token minting:\n * - Fungible: requires `amount` (e.g. \"1000\")\n * - NFT: requires `nftMetadata` (array of byte-encodable entries, one per NFT to mint)\n *\n * The chain adapter determines the appropriate native operation based on the token type.\n */\nexport const MintTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n\n /** Amount to mint (fungible tokens). Ignored for NFTs. */\n amount: z.string().optional(),\n\n /** Recipient account (fungible: transfer after mint; NFT: Hedera mints to treasury). */\n recipient: AccountIdSchema.optional(),\n\n /**\n * NFT metadata entries — one per NFT to mint.\n * Each entry becomes on-chain metadata (e.g. IPFS CID, encoded memo).\n * On Hedera: passed to TokenMintTransaction.setMetadata().\n * On XRPL: used as URI in NFTokenMint.\n */\n nftMetadata: z.array(z.string()).optional(),\n\n /** Additional chain-specific options. */\n metadata: z.record(z.any()).optional(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n});\n\nexport type MintTokenRequest = z.infer<typeof MintTokenRequestSchema>;\n\n/**\n * Burn token request schema\n */\nexport const BurnTokenRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n amount: z.string(),\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type BurnTokenRequest = z.infer<typeof BurnTokenRequestSchema>;\n\n/**\n * Token action request schema (for pause, restrict, etc.)\n */\nexport const TokenActionRequestSchema = z.object({\n chain: ChainTypeSchema,\n tokenId: z.string(),\n accountId: AccountIdSchema.optional(), // Required for account-specific actions\n amount: z.string().optional(), // Required for wipe action\n /** See CreateAccountRequestSchema.payerAccountId — same resolution rules. */\n payerAccountId: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport type TokenActionRequest = z.infer<typeof TokenActionRequestSchema>;\n\n/**\n * Action result schema - unified response for all token actions\n */\nexport const ActionResultSchema = z.object({\n success: z.boolean(),\n transactionId: z.string(),\n chain: ChainTypeSchema,\n /** The native chain operation that was executed */\n chainOperation: z.string(),\n /** Additional context or notes about the operation */\n notes: z.array(z.string()).optional(),\n /** Timestamp of the operation */\n timestamp: z.date().optional(),\n});\n\nexport type ActionResult = z.infer<typeof ActionResultSchema>;\n\n/**\n * Create token result schema - extends ActionResult with token info\n */\nexport const CreateTokenResultSchema = ActionResultSchema.extend({\n tokenId: z.string(),\n /** The capabilities that were enabled for this token */\n enabledCapabilities: z.array(z.string()),\n});\n\nexport type CreateTokenResult = z.infer<typeof CreateTokenResultSchema>;\n\n// =============================================================================\n// PREPARED TRANSACTION RESPONSE TYPES (v3 API - Transaction Sovereignty)\n// =============================================================================\n\n/**\n * Validator signature for a prepared transaction\n */\nexport const ValidatorSignatureSchema = z.object({\n /** Validator's node ID */\n validatorId: z.string(),\n /** Validator's public key (hex-encoded) */\n publicKey: z.string(),\n /** Signature over the transaction bytes (hex-encoded) */\n signature: z.string(),\n /** When this signature was created */\n signedAt: z.date(),\n /** Signature algorithm used */\n algorithm: z.enum(['ed25519', 'ecdsa-secp256k1', 'bls12-381']).optional(),\n});\n\nexport type ValidatorSignature = z.infer<typeof ValidatorSignatureSchema>;\n\n/**\n * Hedera-specific metadata for prepared transactions\n */\nexport const HederaPreparedMetadataSchema = z.object({\n /** Hedera node account IDs that will process this transaction */\n nodeAccountIds: z.array(z.string()).optional(),\n /** Maximum transaction fee in tinybars */\n maxTransactionFee: z.string().optional(),\n /** Transaction memo */\n memo: z.string().optional(),\n /** Schedule info if this is a scheduled transaction */\n scheduleInfo: z\n .object({\n scheduleId: z.string(),\n adminKey: z.string().optional(),\n })\n .optional(),\n});\n\nexport type HederaPreparedMetadata = z.infer<typeof HederaPreparedMetadataSchema>;\n\n/**\n * XRPL-specific metadata for prepared transactions\n */\nexport const XRPLPreparedMetadataSchema = z.object({\n /** Sequence number for this transaction */\n sequence: z.number().optional(),\n /** Last ledger sequence for expiration */\n lastLedgerSequence: z.number().optional(),\n /** Signer list info for multi-sig */\n signerList: z\n .array(\n z.object({\n account: z.string(),\n signerWeight: z.number(),\n })\n )\n .optional(),\n /** Quorum weight required */\n signerQuorum: z.number().optional(),\n});\n\nexport type XRPLPreparedMetadata = z.infer<typeof XRPLPreparedMetadataSchema>;\n\n/**\n * Solana-specific metadata for prepared transactions\n */\nexport const SolanaPreparedMetadataSchema = z.object({\n /** Recent blockhash for transaction validity */\n recentBlockhash: z.string().optional(),\n /** Fee payer account */\n feePayer: z.string().optional(),\n /** Program IDs involved */\n programIds: z.array(z.string()).optional(),\n /** Squads v4 multisig PDA address (partial/full modes) */\n squadsMultisigPda: z.string().optional(),\n /** Squads v4 vault PDA address (partial/full modes) */\n squadsVaultPda: z.string().optional(),\n /** Index of the vault transaction proposal */\n squadsTransactionIndex: z.number().optional(),\n /** Proposal PDA address */\n squadsProposalAddress: z.string().optional(),\n /** Whether the multisig was created in this call (vs already existed) */\n multisigCreated: z.boolean().optional(),\n /** Security mode used to prepare this transaction */\n securityMode: z.enum(['partial', 'full']).optional(),\n /** SPL Token mint address (token-create and all SPL operations) */\n splMint: z.string().optional(),\n});\n\nexport type SolanaPreparedMetadata = z.infer<typeof SolanaPreparedMetadataSchema>;\n\n/**\n * Polkadot-specific metadata for prepared transactions\n */\nexport const PolkadotPreparedMetadataSchema = z.object({\n /** Era for transaction mortality */\n era: z.string().optional(),\n /** Nonce for the sender */\n nonce: z.number().optional(),\n /** Tip for priority */\n tip: z.string().optional(),\n /** Spec version for runtime */\n specVersion: z.number().optional(),\n});\n\nexport type PolkadotPreparedMetadata = z.infer<typeof PolkadotPreparedMetadataSchema>;\n\n/**\n * Union of all chain-specific metadata types\n */\nexport const ChainPreparedMetadataSchema = z.union([\n HederaPreparedMetadataSchema,\n XRPLPreparedMetadataSchema,\n SolanaPreparedMetadataSchema,\n PolkadotPreparedMetadataSchema,\n z.record(z.any()), // Allow extension for future chains\n]);\n\nexport type ChainPreparedMetadata = z.infer<typeof ChainPreparedMetadataSchema>;\n\n/**\n * Prepared transaction response - the core type for v3 API\n *\n * IMPORTANT: This is the unified response type for all transaction operations.\n * The transaction is frozen/prepared but NOT submitted. The caller is responsible\n * for submitting the transaction to the network.\n *\n * SECURITY PRINCIPLES:\n * 1. Validators NEVER pay fees - caller provides payerAccountId\n * 2. Validators NEVER submit transactions - they return signed bytes\n * 3. All operations use multi-sig - no single-key fallbacks\n * 4. Transaction ID is pre-assigned for deterministic tracking\n */\nexport const PreparedTransactionResponseSchema = z.object({\n /** The blockchain this transaction is for */\n chain: ChainTypeSchema,\n /** Type of transaction (e.g., 'TokenCreate', 'Payment', 'NFTMint') */\n transactionType: z.string(),\n /** Pre-assigned transaction ID for tracking */\n transactionId: z.string(),\n /** Base64-encoded frozen transaction bytes ready for submission */\n transactionBytes: z.string(),\n /** When this prepared transaction expires */\n expiresAt: z.date(),\n /** Validator signatures collected for this transaction */\n validatorSignatures: z.array(ValidatorSignatureSchema),\n /** Required payer account ID (caller must fund this account) */\n payerAccountId: z.string().optional(),\n /** Estimated network fee */\n estimatedFee: z.string().optional(),\n /** Number of signatures required for submission */\n requiredSignatures: z.number().optional(),\n /** Whether the transaction has enough signatures to submit */\n readyToSubmit: z.boolean().default(false),\n /** Chain-specific metadata */\n metadata: ChainPreparedMetadataSchema.optional(),\n /**\n * Sovereignty metadata: the mode and (for partial/full) the on-chain\n * authorization set the validator is binding to. Lets smart-apps and tests\n * inspect the authorization topology without decoding chain-native bytes.\n */\n sovereignty: PreparedTransactionSovereigntySchema.optional(),\n});\n\nexport type PreparedTransactionResponse = z.infer<typeof PreparedTransactionResponseSchema>;\n\n/**\n * Generic prepared transaction response with typed metadata\n */\nexport type PreparedTransactionResponseWithMetadata<T extends ChainPreparedMetadata> = Omit<\n PreparedTransactionResponse,\n 'metadata'\n> & {\n metadata?: T;\n};\n\n/**\n * Type-safe prepared transaction responses for each chain\n */\nexport type HederaPreparedTransaction =\n PreparedTransactionResponseWithMetadata<HederaPreparedMetadata>;\n/**\n * XRPL prepared transaction response.\n *\n * Includes `transactionJson` alongside `transactionBytes` so xrpl.js-native\n * clients can sign the autofilled transaction object directly without having\n * to decode the binary blob. See Transaction Sovereignty Parity Part A.4.\n *\n * `transactionJson` is typed as the structural minimum — the fields every\n * autofilled XRPL tx carries — so `@hsuite/smart-engines-shared` stays\n * decoupled from the xrpl.js package. Callers that need the full\n * `SubmittableTransaction` union (see xrpl.js) should consume the stronger\n * local type exported from `@hsuite/smart-engines-chain-xrpl`, which is\n * typed against xrpl.js directly.\n */\nexport type XRPLPreparedTransactionJson = {\n TransactionType: string;\n Account: string;\n Fee?: string;\n Sequence?: number;\n LastLedgerSequence?: number;\n [extra: string]: unknown;\n};\n\nexport type XRPLPreparedTransaction = PreparedTransactionResponseWithMetadata<XRPLPreparedMetadata> & {\n /** Autofilled XRPL transaction object (post-autofill, pre-sign) for xrpl.js-native callers */\n transactionJson: XRPLPreparedTransactionJson;\n};\nexport type SolanaPreparedTransaction =\n PreparedTransactionResponseWithMetadata<SolanaPreparedMetadata>;\nexport type PolkadotPreparedTransaction =\n PreparedTransactionResponseWithMetadata<PolkadotPreparedMetadata>;\n\n/**\n * Submission result after caller submits the prepared transaction\n */\nexport const TransactionSubmissionResultSchema = z.object({\n /** The original transaction ID */\n transactionId: z.string(),\n /** The blockchain */\n chain: ChainTypeSchema,\n /** Whether submission was successful */\n success: z.boolean(),\n /** Consensus timestamp (Hedera) or ledger/block info */\n consensusTimestamp: z.string().optional(),\n /** Block or ledger number */\n blockNumber: z.number().optional(),\n /** Actual fee paid */\n actualFee: z.string().optional(),\n /** Receipt or confirmation data */\n receipt: z.record(z.any()).optional(),\n /** Error message if submission failed */\n error: z.string().optional(),\n});\n\nexport type TransactionSubmissionResult = z.infer<typeof TransactionSubmissionResultSchema>;\n\n// =============================================================================\n// PREPARE REQUEST SCHEMAS (v3 API - Transaction Sovereignty Mixed Layer)\n// =============================================================================\n\n/**\n * Prepare token-create request schema (Hedera HTS).\n *\n * Merges SovereigntyFieldsSchema so securityMode, entityId, and\n * appOwnerPublicKey carry the same cross-chain invariants.\n */\nexport const PrepareTokenCreateRequestSchema = z\n .object({\n chain: z.literal('hedera'),\n payerAccountId: z.string().optional(),\n name: z.string().min(1).max(100),\n symbol: z.string().min(1).max(10),\n decimals: z.number().int().min(0).max(18),\n initialSupply: z.string(),\n treasuryAccountId: z.string().min(1, 'treasuryAccountId is required'),\n memo: z.string().optional(),\n tokenType: z.enum(['FUNGIBLE_COMMON', 'NON_FUNGIBLE_UNIQUE']).default('FUNGIBLE_COMMON'),\n supplyKey: z.string().optional(),\n adminKey: z.string().optional(),\n pauseKey: z.string().optional(),\n freezeKey: z.string().optional(),\n kycKey: z.string().optional(),\n wipeKey: z.string().optional(),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n // SovereigntyFieldsRawSchema is the unrefined object (no .refine wrapping)\n // the sovereignty invariant is re-applied by the .refine() below.\n .merge(SovereigntyFieldsRawSchema)\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type PrepareTokenCreateRequest = z.infer<typeof PrepareTokenCreateRequestSchema>;\n\n/**\n * Prepare XRPL account-setup request schema.\n *\n * Used to configure the authorization (signer list / AccountSet flags) on an\n * existing XRPL account as part of the sovereignty key setup.\n */\nexport const PrepareXrplAccountSetupRequestSchema = z\n .object({\n chain: z.literal('xrpl'),\n payerAccountId: z.string().optional(),\n // User's XRPL account whose authorization we're configuring.\n accountAddress: z.string().min(25).max(34),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n .merge(SovereigntyFieldsRawSchema)\n .refine(sovereigntyRefinePredicate, { message: SOVEREIGNTY_REFINE_MESSAGE });\n\nexport type PrepareXrplAccountSetupRequest = z.infer<typeof PrepareXrplAccountSetupRequestSchema>;\n\n/**\n * Prepare Stellar account-create request schema.\n *\n * Creates a new Stellar account and optionally configures sovereignty signers.\n */\nexport const PrepareStellarAccountCreateRequestSchema = z\n .object({\n chain: z.literal('stellar'),\n payerAccountId: z.string().optional(),\n // The master public key of the new Stellar account.\n publicKey: z.string().min(56).max(56),\n startingBalance: z.string().regex(/^\\d+(\\.\\d+)?$/),\n validatorTimestamp: z.string().min(1),\n validatorTopicId: z.string().min(1),\n })\n .merge(SovereigntyFieldsRawSchema)\n // Stellar's partial mode uses the new account's OWN master key as the\n // \"user\" signer (via SetOptions(masterWeight=2)) — there is NO separate\n // appOwnerPublicKey because Stellar allows the master key to satisfy\n // authorization directly. Only entityId is required for partial/full.\n .refine(\n (v) => !!v.entityId,\n { message: \"securityMode='partial'/'full' requires entityId\" },\n );\n\nexport type PrepareStellarAccountCreateRequest = z.infer<\n typeof PrepareStellarAccountCreateRequestSchema\n>;\n","/**\n * Hedera Mirror Node Client\n *\n * Lightweight client for querying Hedera mirror node REST API.\n * Used for validator discovery by reading HCS topic messages.\n */\n\n/**\n * Mirror node configuration\n */\nexport interface MirrorNodeConfig {\n /** Mirror node base URL (e.g., https://testnet.mirrornode.hedera.com) */\n baseUrl: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP (insecure) connections - default false */\n allowInsecure?: boolean;\n}\n\n/**\n * Validate and sanitize a URL\n * Prevents SSRF and ensures HTTPS for security\n */\nfunction validateUrl(url: string, allowInsecure = false): URL {\n try {\n const parsed = new URL(url);\n\n // Only allow http/https protocols\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new Error(`Invalid protocol: ${parsed.protocol}`);\n }\n\n // Enforce HTTPS unless explicitly allowed\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new Error(\n 'HTTPS is required for secure connections. Set allowInsecure=true to override.'\n );\n }\n\n // Block private/internal IP ranges to prevent SSRF\n const hostname = parsed.hostname.toLowerCase();\n const blockedPatterns = [\n /^localhost$/i,\n /^127\\./,\n /^10\\./,\n /^172\\.(1[6-9]|2[0-9]|3[01])\\./,\n /^192\\.168\\./,\n /^169\\.254\\./,\n /^::1$/,\n /^fe80:/i,\n /^fc00:/i,\n /^fd00:/i,\n ];\n\n // Allow localhost only in development with explicit flag\n const isPrivate = blockedPatterns.some((pattern) => pattern.test(hostname));\n if (isPrivate && !allowInsecure) {\n throw new Error(\n 'Private/internal URLs are blocked. Set allowInsecure=true for local development.'\n );\n }\n\n return parsed;\n } catch (error) {\n if (error instanceof Error && error.message.includes('Invalid URL')) {\n throw new MirrorNodeError(`Invalid URL format: ${url}`, 400);\n }\n throw error;\n }\n}\n\n/**\n * Validate Hedera topic ID format\n */\nfunction validateTopicId(topicId: string): void {\n // Format: shard.realm.num (e.g., 0.0.123456)\n if (!/^\\d+\\.\\d+\\.\\d+$/.test(topicId)) {\n throw new MirrorNodeError(\n `Invalid topic ID format: ${topicId}. Expected format: 0.0.123456`,\n 400\n );\n }\n}\n\n/**\n * HCS topic message from mirror node API\n */\nexport interface TopicMessage {\n /** Consensus timestamp */\n consensus_timestamp: string;\n /** Message content (base64 encoded) */\n message: string;\n /** Payer account ID */\n payer_account_id: string;\n /** Running hash */\n running_hash: string;\n /** Running hash version */\n running_hash_version: number;\n /** Sequence number */\n sequence_number: number;\n /** Topic ID */\n topic_id: string;\n}\n\n/**\n * Mirror node API response for topic messages\n */\nexport interface TopicMessagesResponse {\n messages: TopicMessage[];\n links: {\n next?: string;\n };\n}\n\n/**\n * Default mirror node URLs by network\n */\nexport const MIRROR_NODE_URLS: Record<string, string> = {\n mainnet: 'https://mainnet-public.mirrornode.hedera.com',\n testnet: 'https://testnet.mirrornode.hedera.com',\n previewnet: 'https://previewnet.mirrornode.hedera.com',\n};\n\n/**\n * Hedera Mirror Node Client\n *\n * Query HCS topic messages via REST API for validator discovery.\n */\nexport class MirrorNodeClient {\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n\n constructor(config: MirrorNodeConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n\n // Validate the base URL\n const validatedUrl = validateUrl(config.baseUrl, this.allowInsecure);\n this.baseUrl = validatedUrl.origin;\n this.timeout = config.timeout || 30000;\n }\n\n /**\n * Create client for a specific network\n */\n static forNetwork(network: 'mainnet' | 'testnet' | 'previewnet'): MirrorNodeClient {\n const baseUrl = MIRROR_NODE_URLS[network];\n if (!baseUrl) {\n throw new Error(`Unknown network: ${network}`);\n }\n return new MirrorNodeClient({ baseUrl });\n }\n\n /**\n * Get topic messages from mirror node\n *\n * @param topicId - HCS topic ID (e.g., '0.0.123456')\n * @param options - Query options\n * @returns Topic messages\n */\n async getTopicMessages(\n topicId: string,\n options?: {\n /** Limit number of messages */\n limit?: number;\n /** Order (asc or desc) */\n order?: 'asc' | 'desc';\n /** Timestamp to start from */\n timestampStart?: string;\n /** Timestamp to end at */\n timestampEnd?: string;\n /** Sequence number to start from */\n sequenceNumberStart?: number;\n }\n ): Promise<TopicMessage[]> {\n // Validate topic ID format to prevent injection\n validateTopicId(topicId);\n\n const params = new URLSearchParams();\n\n if (options?.limit) {\n params.set('limit', options.limit.toString());\n }\n if (options?.order) {\n params.set('order', options.order);\n }\n if (options?.timestampStart) {\n params.set('timestamp', `gte:${options.timestampStart}`);\n }\n if (options?.timestampEnd) {\n params.set('timestamp', `lte:${options.timestampEnd}`);\n }\n if (options?.sequenceNumberStart) {\n params.set('sequencenumber', `gte:${options.sequenceNumberStart}`);\n }\n\n const url = `${this.baseUrl}/api/v1/topics/${topicId}/messages?${params.toString()}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new MirrorNodeError(\n `Mirror node error: ${response.status} ${response.statusText}`,\n response.status\n );\n }\n\n const data = (await response.json()) as TopicMessagesResponse;\n return data.messages;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof MirrorNodeError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new MirrorNodeError('Mirror node request timeout', 408);\n }\n throw new MirrorNodeError(`Mirror node network error: ${err.message}`, 0);\n }\n }\n\n /**\n * Get all topic messages with pagination\n *\n * @param topicId - HCS topic ID\n * @param maxMessages - Maximum messages to fetch (default: 1000)\n * @returns All topic messages\n */\n async getAllTopicMessages(topicId: string, maxMessages: number = 1000): Promise<TopicMessage[]> {\n // Validate topic ID format\n validateTopicId(topicId);\n\n // Enforce reasonable limits to prevent DoS\n const safeMaxMessages = Math.min(maxMessages, 10000);\n\n const allMessages: TopicMessage[] = [];\n let nextPath: string | undefined = `/api/v1/topics/${topicId}/messages?limit=100&order=desc`;\n\n while (nextPath && allMessages.length < safeMaxMessages) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Construct full URL safely - only use path from pagination\n const fullUrl = `${this.baseUrl}${nextPath}`;\n\n const response = await fetch(fullUrl, {\n method: 'GET',\n headers: { Accept: 'application/json' },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new MirrorNodeError(\n `Mirror node error: ${response.status} ${response.statusText}`,\n response.status\n );\n }\n\n const data = (await response.json()) as TopicMessagesResponse;\n allMessages.push(...data.messages);\n\n // Validate and sanitize pagination link\n // Only accept relative paths starting with /api/v1/\n if (data.links.next) {\n const nextLink = data.links.next;\n if (nextLink.startsWith('/api/v1/topics/')) {\n nextPath = nextLink;\n } else {\n // Invalid pagination link - stop pagination\n nextPath = undefined;\n }\n } else {\n nextPath = undefined;\n }\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof MirrorNodeError) {\n throw error;\n }\n const err = error as Error;\n throw new MirrorNodeError(`Mirror node error: ${err.message}`, 0);\n }\n }\n\n return allMessages.slice(0, safeMaxMessages);\n }\n\n /**\n * Decode base64 message content\n */\n static decodeMessage(base64Message: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(base64Message, 'base64').toString('utf-8');\n }\n // Browser environment\n return atob(base64Message);\n }\n}\n\n/**\n * Mirror node error\n */\nexport class MirrorNodeError extends Error {\n constructor(\n message: string,\n public statusCode: number\n ) {\n super(message);\n this.name = 'MirrorNodeError';\n }\n}\n","/**\n * Validator Discovery Client\n *\n * Discover smart-engine validators by reading the HCS validator registry topic.\n * Provides methods to list validators and select random validators for connection.\n */\n\nimport { MirrorNodeClient, MIRROR_NODE_URLS } from './mirror-node';\n\n/**\n * Network endpoints for validator connectivity\n */\nexport interface ValidatorNetworkEndpoints {\n /** HTTP API endpoint (e.g., https://validator.example.com:3000) */\n apiEndpoint: string;\n /** NATS endpoint for peer-to-peer messaging */\n natsEndpoint?: string;\n /** Public IP for NAT traversal */\n publicIp?: string;\n /** NATS port if different from default */\n natsPort?: number;\n}\n\n/**\n * Validator metadata\n */\nexport interface ValidatorMetadata {\n /** Human-readable description */\n description?: string;\n /** Version string */\n version?: string;\n /** Tags for categorization */\n tags?: string[];\n /** Author/operator name */\n author?: string;\n}\n\n/**\n * Validator registry entry parsed from HCS\n */\nexport interface ValidatorInfo {\n /** Validator consensus timestamp (unique ID) */\n validatorTimestamp: string;\n /** Node ID (e.g., validator-1) */\n nodeId: string;\n /** Validator type */\n type: 'consensus' | 'tokens' | 'accounts' | 'network';\n /** Network endpoints for connectivity */\n networkEndpoints?: ValidatorNetworkEndpoints;\n /** Public key for peer authentication (Ed25519 hex) */\n publicKey?: string;\n /** Membership NFT serial number */\n membershipNftSerial?: number;\n /** Supported blockchain capabilities */\n capabilities?: string[];\n /** Validator metadata */\n metadata: ValidatorMetadata;\n /** When registered */\n registeredAt: string;\n /** Message type */\n messageType?: 'validator.join' | 'validator.leave' | 'validator.update';\n}\n\n/**\n * Validator discovery configuration\n */\nexport interface ValidatorDiscoveryConfig {\n /** Hedera network (mainnet, testnet, previewnet) */\n network: 'mainnet' | 'testnet' | 'previewnet';\n /** HCS topic ID for validator registry */\n registryTopicId: string;\n /** Cache TTL in milliseconds (default: 60000 = 1 minute) */\n cacheTtlMs?: number;\n /** Custom mirror node URL (optional) */\n mirrorNodeUrl?: string;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Cached validators data\n */\ninterface ValidatorCache {\n validators: ValidatorInfo[];\n lastUpdated: number;\n}\n\n/**\n * Validator Discovery Client\n *\n * Discovers validators by reading the HCS validator registry topic\n * via Hedera mirror node API.\n *\n * @example\n * ```typescript\n * const discovery = new ValidatorDiscoveryClient({\n * network: 'testnet',\n * registryTopicId: '0.0.123456',\n * });\n *\n * const validators = await discovery.getValidators();\n * const randomValidator = await discovery.getRandomValidator();\n * ```\n */\nexport class ValidatorDiscoveryClient {\n private readonly mirrorNode: MirrorNodeClient;\n private readonly registryTopicId: string;\n private readonly cacheTtlMs: number;\n private cache: ValidatorCache | null = null;\n\n constructor(config: ValidatorDiscoveryConfig) {\n const mirrorNodeUrl = config.mirrorNodeUrl || MIRROR_NODE_URLS[config.network];\n if (!mirrorNodeUrl) {\n throw new Error(`Unknown network: ${config.network}`);\n }\n\n this.mirrorNode = new MirrorNodeClient({\n baseUrl: mirrorNodeUrl,\n allowInsecure: config.allowInsecure,\n });\n this.registryTopicId = config.registryTopicId;\n this.cacheTtlMs = config.cacheTtlMs ?? 60000; // 1 minute default\n }\n\n /**\n * Get all active validators from the registry\n *\n * Results are cached for efficiency. Use `forceRefresh` to bypass cache.\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns List of active validators\n */\n async getValidators(forceRefresh = false): Promise<ValidatorInfo[]> {\n // Return cached data if valid\n if (!forceRefresh && this.cache && this.isCacheValid()) {\n return this.cache.validators;\n }\n\n // Fetch from mirror node\n const messages = await this.mirrorNode.getAllTopicMessages(\n this.registryTopicId,\n 500 // Max messages to fetch\n );\n\n // Parse and deduplicate validators\n const validatorMap = new Map<string, ValidatorInfo>();\n const leftValidators = new Set<string>();\n\n // Process messages (newest first since we fetch desc order)\n for (const msg of messages) {\n try {\n const content = MirrorNodeClient.decodeMessage(msg.message);\n const raw = JSON.parse(content) as Record<string, unknown>;\n const entry = normalizeRegistryEntry(raw);\n if (!entry) continue;\n\n // Track leave events\n if (entry.messageType === 'validator.leave') {\n leftValidators.add(entry.nodeId);\n continue;\n }\n\n // Skip if validator has left\n if (leftValidators.has(entry.nodeId)) {\n continue;\n }\n\n // Keep only the latest entry per nodeId\n if (!validatorMap.has(entry.nodeId)) {\n validatorMap.set(entry.nodeId, entry);\n }\n } catch {\n // Skip unparseable messages\n continue;\n }\n }\n\n const validators = Array.from(validatorMap.values());\n\n // Update cache\n this.cache = {\n validators,\n lastUpdated: Date.now(),\n };\n\n return validators;\n }\n\n /**\n * Get validators with API endpoints available\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validators with apiEndpoint configured\n */\n async getValidatorsWithEndpoints(forceRefresh = false): Promise<ValidatorInfo[]> {\n const validators = await this.getValidators(forceRefresh);\n return validators.filter((v) => v.networkEndpoints?.apiEndpoint);\n }\n\n /**\n * Get a random validator from the registry\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Random validator info or null if none available\n */\n async getRandomValidator(forceRefresh = false): Promise<ValidatorInfo | null> {\n const validators = await this.getValidatorsWithEndpoints(forceRefresh);\n\n if (validators.length === 0) {\n return null;\n }\n\n // Use crypto.getRandomValues for cryptographically secure random selection\n const randomBytes = new Uint32Array(1);\n crypto.getRandomValues(randomBytes);\n const randomIndex = randomBytes[0] % validators.length;\n return validators[randomIndex];\n }\n\n /**\n * Get a random validator API endpoint URL\n *\n * @param forceRefresh - Force refresh from mirror node\n * @returns Random validator API URL or null if none available\n */\n async getRandomValidatorUrl(forceRefresh = false): Promise<string | null> {\n const validator = await this.getRandomValidator(forceRefresh);\n return validator?.networkEndpoints?.apiEndpoint ?? null;\n }\n\n /**\n * Get validator by node ID\n *\n * @param nodeId - Validator node ID (e.g., 'validator-1')\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validator info or null if not found\n */\n async getValidatorByNodeId(nodeId: string, forceRefresh = false): Promise<ValidatorInfo | null> {\n const validators = await this.getValidators(forceRefresh);\n return validators.find((v) => v.nodeId === nodeId) ?? null;\n }\n\n /**\n * Get validators by capability\n *\n * @param capability - Required capability (e.g., 'hedera', 'xrpl', 'dkg')\n * @param forceRefresh - Force refresh from mirror node\n * @returns Validators with the specified capability\n */\n async getValidatorsByCapability(\n capability: string,\n forceRefresh = false\n ): Promise<ValidatorInfo[]> {\n const validators = await this.getValidatorsWithEndpoints(forceRefresh);\n return validators.filter((v) => v.capabilities?.includes(capability));\n }\n\n /**\n * Clear the validator cache\n */\n clearCache(): void {\n this.cache = null;\n }\n\n /**\n * Check if cache is still valid\n */\n private isCacheValid(): boolean {\n if (!this.cache) return false;\n return Date.now() - this.cache.lastUpdated < this.cacheTtlMs;\n }\n}\n\n/**\n * Normalize a raw registry message into a ValidatorInfo.\n *\n * Accepts two shapes observed on real HCS registry topics:\n *\n * 1. Canonical (emitted by chain-hedera ValidatorRegistryService):\n * { messageType: 'validator.join'|'validator.leave'|'validator.update',\n * nodeId, networkEndpoints: { apiEndpoint, ... }, ... }\n *\n * 2. Legacy / multisig-consensus (emitted by ops / genesis scripts):\n * { type: 'validator.register', validatorId, endpoint, capabilities,\n * publicKey, accountId, network, ... }\n *\n * Token-scoped validator registrations (validatorType === 'token') are ignored\n * — those are DAO token validators, not node validators. Returns null when the\n * entry doesn't represent a node validator.\n */\nfunction normalizeRegistryEntry(raw: Record<string, unknown>): ValidatorInfo | null {\n // Canonical shape: already a ValidatorInfo\n if (raw.messageType && typeof raw.nodeId === 'string') {\n return raw as unknown as ValidatorInfo;\n }\n\n // Legacy shape: { type: 'validator.register', validatorId, endpoint, ... }\n if (raw.type === 'validator.register') {\n // Skip token validator registrations - they aren't nodes\n if (raw.validatorType && raw.validatorType !== undefined && raw.validatorType !== null) {\n if (typeof raw.validatorType === 'string' && raw.validatorType !== 'node') {\n return null;\n }\n }\n\n const nodeId =\n (typeof raw.validatorId === 'string' && raw.validatorId) ||\n (typeof raw.nodeId === 'string' && raw.nodeId) ||\n null;\n if (!nodeId) return null;\n\n const endpoint = typeof raw.endpoint === 'string' ? raw.endpoint : undefined;\n if (!endpoint) return null;\n\n const capabilities = Array.isArray(raw.capabilities)\n ? (raw.capabilities as unknown[]).filter((c): c is string => typeof c === 'string')\n : undefined;\n\n return {\n validatorTimestamp: typeof raw.timestamp === 'string' ? raw.timestamp : '',\n nodeId,\n type: 'consensus',\n networkEndpoints: { apiEndpoint: endpoint },\n publicKey: typeof raw.publicKey === 'string' ? raw.publicKey : undefined,\n capabilities,\n metadata: {},\n registeredAt: typeof raw.timestamp === 'string' ? raw.timestamp : '',\n messageType: 'validator.join',\n };\n }\n\n // Unknown / unrelated message type (e.g., token validator registrations)\n return null;\n}\n","/**\n * Cluster Discovery Client.\n *\n * SDK-side consumer of the service-registry distribution layer\n * (validator `GET /api/v3/discovery/clusters`). Instead of pinning one\n * baseUrl, the caller supplies a bootstrap-seed list and the client\n * random-picks an active cluster per request, so SDK consumers automatically\n * follow permissionless cluster join/leave without code edits.\n *\n * Resolution chain:\n * 1. HTTP fetch of `/api/v3/discovery/clusters` from each bootstrap seed\n * in order; take the first successful response.\n * 2. (Optional) HCS trust-anchor membership cross-check — verify that\n * every returned nodeId appears in the HCS validator registry and\n * that the publicKey matches. A bootstrap seed cannot inject a rogue\n * cluster whose nodeIds aren't on-chain.\n * 3. Random-pick over the verified set.\n *\n * The {@link ValidatorDiscoveryClient} (HCS mirror-node read, per-validator\n * granularity) stays available as the HCS-direct fallback / trust anchor —\n * it is the only path that doesn't require any HTTP-reachable cluster.\n */\n\nimport { ValidatorDiscoveryClient, type ValidatorDiscoveryConfig } from './validator-discovery';\n\n/**\n * Cluster-level endpoint metadata as exposed by the validator's\n * `/api/v3/discovery/clusters` HTTP endpoint. Mirrors the on-wire shape\n * defined server-side by the service-registry cluster-endpoints payload.\n */\nexport interface ClusterEndpointsView {\n clusterId: string;\n gatewayUrl: string;\n harborUrl?: string;\n natsUrl?: string;\n publicIp?: string;\n region?: string;\n}\n\n/**\n * Cluster info as returned by `getClusters()`. `nodeIds` are the validator\n * nodeIds whose announcements contributed to this cluster's record —\n * useful for HCS trust-anchor cross-checking.\n */\nexport interface ClusterInfo {\n clusterId: string;\n endpoints: ClusterEndpointsView;\n nodeIds: string[];\n}\n\nexport interface ClusterDiscoveryConfig {\n /**\n * Bootstrap seeds — fully-qualified URLs that respond to\n * `GET /api/v3/discovery/clusters`. The SDK tries them in order on each\n * refresh; the first success wins. **Order is the operator's\n * preference signal** (e.g., list a Cloudflare-fronted hostname first,\n * then individual cluster ingress IPs as backstops).\n */\n bootstrap: string[];\n\n /** Cache TTL in milliseconds (default: 60_000 — same as HCS path). */\n cacheTtlMs?: number;\n\n /**\n * Per-bootstrap fetch timeout in milliseconds (default: 5_000). Keep\n * tight: when the first seed is unreachable, we want to fall through\n * to the next without blocking the SDK call for long.\n */\n fetchTimeoutMs?: number;\n\n /**\n * Optional HCS trust anchor. When supplied, the SDK lazily loads the\n * on-chain validator-registry set and verifies that:\n *\n * - every cluster's `nodeIds` appears in the HCS registry, and\n * - the on-chain `publicKey` for each nodeId matches the HTTP\n * response (when the discovery endpoint exposes it).\n *\n * Clusters that fail the cross-check are dropped silently. A logged\n * warning would normally accompany this, but the SDK is environment-\n * agnostic (browser, Node, edge) — surfacing via the returned set is\n * the conservative contract.\n *\n * The anchor performs membership cross-checking only; cryptographic\n * per-record signature verification of the DKG-signed payload is not\n * performed here.\n */\n trustAnchor?: ValidatorDiscoveryConfig;\n\n /** Allow HTTP (insecure) connections — only for local development. */\n allowInsecure?: boolean;\n}\n\ninterface ClusterCache {\n clusters: ClusterInfo[];\n lastUpdated: number;\n}\n\n/**\n * Cluster Discovery Client — HTTP-driven, random-pick across an active\n * cluster set with optional on-chain trust anchor.\n */\nexport class ClusterDiscoveryClient {\n private readonly bootstrap: string[];\n private readonly cacheTtlMs: number;\n private readonly fetchTimeoutMs: number;\n private readonly allowInsecure: boolean;\n private readonly trustAnchorClient: ValidatorDiscoveryClient | null;\n private cache: ClusterCache | null = null;\n\n constructor(config: ClusterDiscoveryConfig) {\n if (!config.bootstrap || config.bootstrap.length === 0) {\n throw new Error('ClusterDiscoveryClient: bootstrap must list at least one seed URL');\n }\n if (!config.allowInsecure) {\n for (const seed of config.bootstrap) {\n if (!seed.startsWith('https://')) {\n throw new Error(\n `ClusterDiscoveryClient: bootstrap seed \"${seed}\" is not HTTPS. ` +\n `Set allowInsecure=true for local development only.`,\n );\n }\n }\n }\n this.bootstrap = config.bootstrap;\n this.cacheTtlMs = config.cacheTtlMs ?? 60_000;\n this.fetchTimeoutMs = config.fetchTimeoutMs ?? 5_000;\n this.allowInsecure = config.allowInsecure ?? false;\n this.trustAnchorClient = config.trustAnchor\n ? new ValidatorDiscoveryClient(config.trustAnchor)\n : null;\n }\n\n /**\n * Fetch the active-cluster set, with caching.\n *\n * Tries each bootstrap seed in order until one returns HTTP 200 with a\n * parseable cluster list. If all seeds fail, throws — callers can\n * handle by falling back to a previously-cached value if they want,\n * or by initializing with multiple seeds.\n */\n async getClusters(forceRefresh = false): Promise<ClusterInfo[]> {\n if (!forceRefresh && this.cache && this.isCacheValid()) {\n return this.cache.clusters;\n }\n\n const fetched = await this.fetchFromFirstAvailableSeed();\n const verified = this.trustAnchorClient ? await this.verifyAgainstTrustAnchor(fetched) : fetched;\n\n this.cache = { clusters: verified, lastUpdated: Date.now() };\n return verified;\n }\n\n /**\n * Random pick over the active-cluster set. Returns `null` when no\n * cluster passes verification (empty registry / all-rejected anchor).\n *\n * Uses `crypto.getRandomValues` when available (browsers, Deno, modern\n * Node) for cryptographic-strength randomness; `Math.random` is a\n * fallback for older runtimes where `globalThis.crypto` is undefined.\n * Discovery isn't cryptographically sensitive — load distribution is\n * the goal here.\n */\n async getRandomCluster(forceRefresh = false): Promise<ClusterInfo | null> {\n const clusters = await this.getClusters(forceRefresh);\n if (clusters.length === 0) return null;\n return clusters[this.pickRandomIndex(clusters.length)];\n }\n\n /**\n * Convenience wrapper returning just the gateway URL of a random\n * active cluster. Feed this to `BaasClient` (the host BaaS tier) — e.g.\n * `new BaasClient({ hostUrl, pathPrefix: '/host' })` or\n * `BaasClient.connectToCluster({ network })`. Do NOT feed it to\n * `SmartEngineClient`: that client's raw `/api/v3/*` tier is un-ingressed at\n * the gateway and will 404 (it requires an explicit `validatorBaseUrl`).\n */\n async getRandomGatewayUrl(forceRefresh = false): Promise<string | null> {\n const cluster = await this.getRandomCluster(forceRefresh);\n return cluster?.endpoints.gatewayUrl ?? null;\n }\n\n /** Per-clusterId lookup, useful for \"stick the SDK to cluster X\" flows. */\n async getClusterById(clusterId: string, forceRefresh = false): Promise<ClusterInfo | null> {\n const clusters = await this.getClusters(forceRefresh);\n return clusters.find((c) => c.clusterId === clusterId) ?? null;\n }\n\n clearCache(): void {\n this.cache = null;\n }\n\n private isCacheValid(): boolean {\n if (!this.cache) return false;\n return Date.now() - this.cache.lastUpdated < this.cacheTtlMs;\n }\n\n private async fetchFromFirstAvailableSeed(): Promise<ClusterInfo[]> {\n const errors: string[] = [];\n for (const seed of this.bootstrap) {\n try {\n return await this.fetchClustersFromSeed(seed);\n } catch (err) {\n errors.push(`${seed}: ${(err as Error).message}`);\n }\n }\n throw new Error(\n `ClusterDiscoveryClient: no bootstrap seed reachable. Attempts:\\n ${errors.join('\\n ')}`,\n );\n }\n\n private async fetchClustersFromSeed(seed: string): Promise<ClusterInfo[]> {\n const url = `${seed.replace(/\\/$/, '')}/api/v3/discovery/clusters`;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.fetchTimeoutMs);\n try {\n const res = await fetch(url, { signal: ctrl.signal });\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`);\n }\n const body = (await res.json()) as {\n clusters?: Array<{\n clusterId?: unknown;\n endpoints?: Record<string, unknown>;\n nodeIds?: unknown;\n }>;\n };\n if (!Array.isArray(body.clusters)) {\n throw new Error('response missing clusters[]');\n }\n return body.clusters\n .map((c) => this.normalizeClusterEntry(c))\n .filter((c): c is ClusterInfo => c !== null);\n } finally {\n clearTimeout(timer);\n }\n }\n\n private normalizeClusterEntry(raw: {\n clusterId?: unknown;\n endpoints?: Record<string, unknown>;\n nodeIds?: unknown;\n }): ClusterInfo | null {\n if (typeof raw.clusterId !== 'string' || !raw.clusterId) return null;\n if (!raw.endpoints || typeof raw.endpoints !== 'object') return null;\n const ep = raw.endpoints as Record<string, unknown>;\n if (typeof ep.gatewayUrl !== 'string' || !ep.gatewayUrl) return null;\n if (!this.allowInsecure && !ep.gatewayUrl.startsWith('https://')) {\n // Drop non-HTTPS gateways in secure mode — never silently accept\n // a downgrade attack via a poisoned bootstrap response.\n return null;\n }\n const nodeIds = Array.isArray(raw.nodeIds)\n ? raw.nodeIds.filter((n): n is string => typeof n === 'string')\n : [];\n return {\n clusterId: raw.clusterId,\n endpoints: {\n clusterId: raw.clusterId,\n gatewayUrl: ep.gatewayUrl,\n harborUrl: typeof ep.harborUrl === 'string' ? ep.harborUrl : undefined,\n natsUrl: typeof ep.natsUrl === 'string' ? ep.natsUrl : undefined,\n publicIp: typeof ep.publicIp === 'string' ? ep.publicIp : undefined,\n region: typeof ep.region === 'string' ? ep.region : undefined,\n },\n nodeIds,\n };\n }\n\n /**\n * Cross-check the HTTP-fetched cluster set against the HCS validator\n * registry. Clusters whose nodeIds are not on-chain are dropped.\n *\n * Two failure modes are deliberately silent here:\n * - the HCS read itself throws → original list is returned\n * un-verified. Trust-anchor is advisory; a network partition\n * between SDK and Hedera mirror shouldn't strand the SDK.\n * - the HCS read returns empty (mirror node lag, wrong topicId)\n * → original list is returned. Better to keep working off\n * possibly-stale-but-real data than reject every cluster.\n *\n * Both behaviors are why this is called \"trust *anchor*\", not\n * \"trust gate\". Crypto-strong gating is a follow-up.\n */\n private async verifyAgainstTrustAnchor(clusters: ClusterInfo[]): Promise<ClusterInfo[]> {\n if (!this.trustAnchorClient || clusters.length === 0) return clusters;\n let onChainNodeIds: Set<string>;\n try {\n const validators = await this.trustAnchorClient.getValidators();\n if (validators.length === 0) return clusters;\n onChainNodeIds = new Set(validators.map((v) => v.nodeId));\n } catch {\n return clusters;\n }\n return clusters.filter((c) => {\n if (c.nodeIds.length === 0) {\n // The discovery endpoint surfaces nodeIds for verifiability.\n // An entry with none was either (a) emitted by an older\n // validator, or (b) crafted to evade the check. Either way,\n // drop it to keep the contract sharp.\n return false;\n }\n return c.nodeIds.some((id) => onChainNodeIds.has(id));\n });\n }\n\n private pickRandomIndex(n: number): number {\n if (n <= 1) return 0;\n const g = (globalThis as { crypto?: { getRandomValues?: (a: Uint32Array) => Uint32Array } }).crypto;\n if (g?.getRandomValues) {\n const buf = new Uint32Array(1);\n g.getRandomValues(buf);\n return buf[0] % n;\n }\n return Math.floor(Math.random() * n);\n }\n}\n","/**\n * Shared HTTP Client\n *\n * Unified HTTP layer used by all SDK clients (SmartEngineClient, SmartGatewayClient, BaasClient).\n * Handles authentication headers, timeouts, error handling, and multipart uploads.\n */\n\n/**\n * Per-call request options. Lets a single request carry extra context the\n * client-wide config can't express.\n *\n * The motivating case is multi-tenant BaaS: an app-as-proxy holds its OWN\n * Bearer auth (set once on the client), but each downstream request acts on\n * behalf of a specific END USER whose session token must reach the host for\n * per-user metering/quota. That token is per-call, not per-client — so it\n * rides here as `customerToken` and is attached as `X-Customer-Session-Token`\n * for this request only.\n */\nexport type HttpCallOptions = {\n /**\n * End-user customer-session token, forwarded to the host as\n * `X-Customer-Session-Token` for this request only. Used by app-as-proxy\n * flows so the host meters the end user, not the app.\n */\n customerToken?: string;\n /**\n * Act ON BEHALF OF an end user for OWNER-GATED routes (e.g. agents\n * fund/withdraw/execute). The value is that user's Mode-1 customer-session\n * JWT (the `token` from `baas.customerSession.verify()`). It is forwarded\n * verbatim as BOTH `Authorization: Bearer <jwt>` (so the host pins the caller\n * to that user) AND `X-Customer-Session-Claim` (the host's claim-resolution\n * header). No client-side signing: owner routes accept only this Mode-1 JWT —\n * the Mode-2 BLS claim is minted host-side and is rejected on owner routes.\n * Distinct from {@link customerToken} (metering-only `X-Customer-Session-Token`).\n */\n onBehalfOf?: string;\n /** Extra per-call headers (escape hatch); merged last, wins on conflict. */\n headers?: Record<string, string>;\n};\n\n/**\n * HTTP client interface consumed by all sub-clients.\n * Sub-clients only depend on this interface, never on fetch directly.\n *\n * Every method takes an optional trailing {@link HttpCallOptions} so a single\n * request can carry an end-user `customerToken` without mutating client state.\n */\nexport type HttpClient = {\n post<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n get<T = any>(path: string, opts?: HttpCallOptions): Promise<T>;\n put<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n patch<T = any>(path: string, body: unknown, opts?: HttpCallOptions): Promise<T>;\n delete<T = any>(path: string, opts?: HttpCallOptions): Promise<T>;\n /**\n * GET a non-JSON body. Returns the raw response text without attempting\n * to parse it. Required for endpoints that emit Prometheus exposition,\n * plain logs, or any other `text/*` content-type — the default\n * {@link HttpClient.get} eagerly `JSON.parse`s and would corrupt those\n * payloads.\n */\n getText(path: string, opts?: HttpCallOptions): Promise<string>;\n /**\n * GET a binary body as raw bytes. Returns a {@link Uint8Array} without any\n * decoding — required for file downloads and any non-text content where the\n * default {@link HttpClient.get}'s `JSON.parse` would corrupt the payload.\n */\n getBinary(path: string, opts?: HttpCallOptions): Promise<Uint8Array>;\n /**\n * GET a binary body WITH its response metadata — the bytes plus the\n * `content-type` and (parsed) `content-disposition` filename. {@link getBinary}\n * discards the headers; this variant is for download endpoints whose caller\n * must echo the content-type back (the host derives it from the stored file's\n * metadata, so a bytes-only download can't recover it).\n */\n getBinaryWithMeta(\n path: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }>;\n /**\n * Upload a file with `multipart/form-data`.\n *\n * `fieldName` defaults to `'file'` for back-compat; callers whose\n * server-side handler uses a different multer field name (e.g.\n * `'bundle'` for SPA tarball uploads) MUST override.\n */\n upload<T = any>(\n path: string,\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n fieldName?: string,\n opts?: HttpCallOptions,\n ): Promise<T>;\n /**\n * Update the Bearer auth token used on subsequent requests. Pass\n * `undefined` to clear the Authorization header (e.g. on logout).\n *\n * Typed accessor — replaces the previous `(client as any).authToken`\n * peek that scattered across the SDK.\n */\n setAuthToken(token: string | undefined): void;\n /**\n * Return the currently configured Bearer auth token, or `undefined`\n * when no token is set.\n */\n getAuthToken(): string | undefined;\n};\n\n/**\n * Configuration for creating an HttpClient instance\n */\nexport type HttpClientConfig = {\n /** Base URL for all requests (e.g. https://validator.example.com/api/v3) */\n baseUrl: string;\n /** Bearer token for Authorization header */\n authToken?: string;\n /** API key for X-API-Key header */\n apiKey?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /**\n * Optional hook invoked when a request returns 401 Unauthorized. Lets the\n * client owner refresh the session (e.g. re-run the web3 challenge-response\n * and call {@link HttpClient.setAuthToken}); the failed request is then\n * retried once with the new token. Calls to `/api/v3/{,baas/}auth/*` are excluded so the\n * refresh flow itself can never recurse, and concurrent 401s share a single\n * in-flight refresh. Without this hook a 401 propagates unchanged.\n */\n onUnauthorized?: () => Promise<void>;\n};\n\n/**\n * SDK-level error class used across all clients\n */\nexport class SdkHttpError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: any\n ) {\n super(message);\n this.name = 'SdkHttpError';\n }\n\n /**\n * True for transient failures worth retrying: a 5xx, a 429 (rate limit), a 408\n * (timeout), or a 0 (network/abort). Deterministic 4xx client errors are not.\n */\n get isRetryable(): boolean {\n return (\n this.statusCode === 0 ||\n this.statusCode === 408 ||\n this.statusCode === 429 ||\n this.statusCode >= 500\n );\n }\n}\n\n/**\n * Create a concrete HttpClient from config.\n * This is the single place where `fetch` is called in the entire SDK.\n */\nexport function createHttpClient(config: HttpClientConfig): HttpClient {\n const timeout = config.timeout ?? 30000;\n\n function getHeaders(contentType?: string, opts?: HttpCallOptions): Record<string, string> {\n const headers: Record<string, string> = {};\n if (contentType) {\n headers['Content-Type'] = contentType;\n }\n if (config.authToken) {\n headers['Authorization'] = `Bearer ${config.authToken}`;\n }\n if (config.apiKey) {\n headers['X-API-Key'] = config.apiKey;\n }\n // Per-call end-user token for app-as-proxy metering. Distinct from the\n // app's own Authorization above — both can ride the same request.\n if (opts?.customerToken) {\n headers['X-Customer-Session-Token'] = opts.customerToken;\n }\n // Owner-acting: forward the end user's Mode-1 JWT as the Authorization\n // bearer (overriding the app token for this request) AND the host's\n // claim-resolution header. Verbatim pass-through — no signing.\n if (opts?.onBehalfOf) {\n headers['Authorization'] = `Bearer ${opts.onBehalfOf}`;\n headers['X-Customer-Session-Claim'] = opts.onBehalfOf;\n }\n if (opts?.headers) {\n Object.assign(headers, opts.headers);\n }\n return headers;\n }\n\n /** Update auth token (e.g. after authentication flow) */\n function setAuthToken(token: string | undefined): void {\n config.authToken = token;\n }\n\n /** Read the current auth token (or undefined when none is set). */\n function getAuthToken(): string | undefined {\n return config.authToken;\n }\n\n async function request<T>(method: string, path: string, body?: unknown, opts?: HttpCallOptions): Promise<T> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const init: RequestInit = {\n method,\n headers: getHeaders('application/json', opts),\n signal: controller.signal,\n };\n\n if (body !== undefined) {\n init.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, init);\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({})) as Record<string, unknown>;\n throw new SdkHttpError(\n (errorData.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n // Handle empty responses (204 No Content)\n const text = await response.text();\n if (!text) return undefined as T;\n return JSON.parse(text) as T;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getText(path: string, opts?: HttpCallOptions): Promise<string> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // The error path still tries JSON — server-side error responses\n // are JSON even when the success path is text/plain (e.g.\n // Prometheus metrics). Fall back to text if that fails.\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n return await response.text();\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getBinary(path: string, opts?: HttpCallOptions): Promise<Uint8Array> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // Error bodies stay JSON even when the success body is binary.\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n // Raw bytes — never JSON.parse / text-decode, which would corrupt a file.\n return new Uint8Array(await response.arrayBuffer());\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function getBinaryWithMeta(\n path: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: getHeaders(undefined, opts),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n throw new SdkHttpError(\n (errBody.message as string) || `API error: ${response.status} ${response.statusText}`,\n response.status,\n errBody,\n );\n }\n\n const bytes = new Uint8Array(await response.arrayBuffer());\n const contentType = response.headers.get('content-type') ?? undefined;\n // Pull `filename` out of content-disposition (filename* RFC 5987 or plain).\n const disposition = response.headers.get('content-disposition') ?? '';\n const match = /filename\\*?=(?:UTF-8'')?\"?([^\"\\n;]+)\"?/i.exec(disposition);\n const filename = match ? decodeURIComponent(match[1].trim()) : undefined;\n return { bytes, contentType, filename };\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Request timeout', 408);\n }\n throw new SdkHttpError(`Network error: ${err.message}`, 0, error);\n }\n }\n\n async function upload<T>(\n path: string,\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n fieldName: string = 'file',\n opts?: HttpCallOptions,\n ): Promise<T> {\n const url = `${config.baseUrl}${path}`;\n const controller = new AbortController();\n // Uploads get 2x timeout\n const timeoutId = setTimeout(() => controller.abort(), timeout * 2);\n\n try {\n const formData = new FormData();\n const blob = file instanceof Blob ? file : new Blob([new Uint8Array(file as Buffer)]);\n formData.append(fieldName, blob, filename);\n\n if (metadata) {\n for (const [key, value] of Object.entries(metadata)) {\n formData.append(key, value);\n }\n }\n\n // Don't set Content-Type — browser/node will set multipart boundary\n const headers: Record<string, string> = {};\n if (config.authToken) {\n headers['Authorization'] = `Bearer ${config.authToken}`;\n }\n if (config.apiKey) {\n headers['X-API-Key'] = config.apiKey;\n }\n if (opts?.customerToken) {\n headers['X-Customer-Session-Token'] = opts.customerToken;\n }\n if (opts?.onBehalfOf) {\n headers['Authorization'] = `Bearer ${opts.onBehalfOf}`;\n headers['X-Customer-Session-Claim'] = opts.onBehalfOf;\n }\n if (opts?.headers) {\n Object.assign(headers, opts.headers);\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: formData,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({})) as Record<string, unknown>;\n throw new SdkHttpError(\n (errorData.message as string) || `Upload error: ${response.status} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n return response.json() as Promise<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof SdkHttpError) throw error;\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new SdkHttpError('Upload timeout', 408);\n }\n throw new SdkHttpError(`Upload error: ${err.message}`, 0, error);\n }\n }\n\n // Transparent session refresh: when a request 401s, invoke `onUnauthorized`\n // (which re-authenticates and updates the token) and retry the request once.\n // Concurrent 401s share a single in-flight refresh; `/api/v3/{,baas/}auth/*` is excluded\n // so the refresh's own challenge/verify can never trigger another refresh.\n let reauthInFlight: Promise<void> | null = null;\n async function withAuthRetry<T>(path: string, op: () => Promise<T>): Promise<T> {\n try {\n return await op();\n } catch (error) {\n const refreshable =\n !!config.onUnauthorized &&\n !path.startsWith('/api/v3/baas/auth/') &&\n !path.startsWith('/api/v3/auth/') &&\n error instanceof SdkHttpError &&\n error.statusCode === 401;\n if (!refreshable) throw error;\n if (!reauthInFlight) {\n reauthInFlight = Promise.resolve(config.onUnauthorized!()).finally(() => {\n reauthInFlight = null;\n });\n }\n try {\n await reauthInFlight;\n } catch {\n throw error; // refresh failed → surface the original 401\n }\n return await op(); // retry once with the refreshed token\n }\n }\n\n const client: HttpClient = {\n post: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('POST', path, body, opts)),\n get: <T>(path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('GET', path, undefined, opts)),\n put: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('PUT', path, body, opts)),\n patch: <T>(path: string, body: unknown, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('PATCH', path, body, opts)),\n delete: <T>(path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => request<T>('DELETE', path, undefined, opts)),\n getText: (path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => getText(path, opts)),\n getBinary: (path: string, opts?: HttpCallOptions) => withAuthRetry(path, () => getBinary(path, opts)),\n getBinaryWithMeta: (path: string, opts?: HttpCallOptions) =>\n withAuthRetry(path, () => getBinaryWithMeta(path, opts)),\n upload: ((path: string, file: Blob | Buffer, filename: string, metadata?: Record<string, string>, fieldName?: string, opts?: HttpCallOptions) =>\n withAuthRetry(path, () => upload(path, file, filename, metadata, fieldName, opts))) as HttpClient['upload'],\n setAuthToken,\n getAuthToken,\n };\n\n return client;\n}\n\n/**\n * Encode a path parameter to prevent injection attacks.\n * Removes path traversal attempts and encodes special characters.\n */\nexport function encodePathParam(param: string): string {\n return encodeURIComponent(param).replace(/%2F/gi, '');\n}\n\n/**\n * Body shape of an HTTP 403 `rule_rejected` envelope raised by the validator's\n * rule-enforcement hooks (e.g. the NFT-transfer hook):\n *\n * ```json\n * { \"error\": \"rule_rejected\", \"reason\": \"<atom-reason>\", \"ruleAtoms\": [\"SoulboundNftAtom\"] }\n * ```\n */\nexport interface RuleRejectedDetails {\n /** Literal discriminator — always 'rule_rejected'. */\n error: 'rule_rejected';\n /** Atom-supplied reason string, e.g. 'soulbound_transfer_rejected'. */\n reason: string;\n /** Names of the rule atoms that fired the rejection. */\n ruleAtoms: string[];\n}\n\n/**\n * Type predicate: narrows an unknown error to a 403 `rule_rejected` envelope.\n *\n * Use in smart-app code to branch on rules-engine rejections without\n * inspecting raw HTTP details:\n *\n * ```typescript\n * try {\n * await sdk.transactions.prepareNftTransfer({ chain: 'hedera', ... });\n * } catch (err) {\n * if (isRuleRejected(err)) {\n * console.log(`Blocked by ${err.details.ruleAtoms.join(', ')}: ${err.details.reason}`);\n * return;\n * }\n * throw err;\n * }\n * ```\n *\n * Status-code AND shape are both checked — non-403 errors and 403s without\n * the rule_rejected envelope (e.g. plain auth failures) return false.\n *\n * @public SDK-SOULBOUND-1\n */\nexport function isRuleRejected(\n err: unknown,\n): err is SdkHttpError & { details: RuleRejectedDetails } {\n if (!(err instanceof SdkHttpError)) return false;\n if (err.statusCode !== 403) return false;\n const d = err.details as unknown;\n if (d === null || typeof d !== 'object') return false;\n const obj = d as Record<string, unknown>;\n if (obj.error !== 'rule_rejected') return false;\n if (typeof obj.reason !== 'string') return false;\n if (!Array.isArray(obj.ruleAtoms)) return false;\n return obj.ruleAtoms.every((a) => typeof a === 'string');\n}\n\n/**\n * Type predicate: narrows an unknown error to the SDK's {@link SdkHttpError}.\n * Lets consumers branch on SDK HTTP failures without importing the class purely\n * for an `instanceof` check.\n */\nexport function isSmartEngineSdkError(err: unknown): err is SdkHttpError {\n return err instanceof SdkHttpError;\n}\n\n/**\n * Normalize any thrown value into an HTTP-shaped record a server (e.g. a NestJS\n * exception filter) can re-emit. An {@link SdkHttpError} maps verbatim; a sub-400\n * status (0 network / unexpected) is clamped to 502 Bad Gateway (a failed\n * upstream call is a gateway error, not a success); a non-SDK error becomes 500.\n * `isRetryable` follows {@link SdkHttpError.isRetryable}.\n */\nexport function toHttpError(err: unknown): {\n statusCode: number;\n code: string;\n message: string;\n isRetryable: boolean;\n details?: unknown;\n} {\n if (isSmartEngineSdkError(err)) {\n return {\n statusCode: err.statusCode >= 400 ? err.statusCode : 502,\n code: 'SDK_HTTP_ERROR',\n message: err.message,\n isRetryable: err.isRetryable,\n details: err.details,\n };\n }\n const message = err instanceof Error ? err.message : 'Unknown error';\n return { statusCode: 500, code: 'INTERNAL_ERROR', message, isRetryable: false };\n}\n","/**\n * Discovery Sub-Client — `client.discovery.*`\n *\n * Thin typed wrapper over the validator's `/api/v3/discovery/*` HTTP\n * surface. Backs the cluster-registry browser endpoints (active set,\n * all-nodes debug view, per-nodeId lookup) **and** the platform-image\n * manifest discovery endpoints (list, per-image versions, single-version\n * fetch, verify gate, signed envelopes).\n *\n * Trust model — discovery endpoints are intentionally `@Public`\n * server-side:\n *\n * - Cluster registry rows are signed cluster-internal data; the\n * advertised `publicKey` is the SDK's verification anchor.\n * - Platform-image manifests are DKG-threshold signed at publish time;\n * pulling them by SHA-256 digest + content-addressed verification\n * keeps the read surface authentication-free.\n *\n * The {@link ClusterDiscoveryClient} in this same module already wraps\n * the active-set endpoint for the bootstrap → random-pick connect flow.\n * This client exists for callers that want the **typed** endpoints\n * directly (operator dashboards, supply-chain auditors, smart-apps\n * inspecting validator membership).\n *\n * Mounted at `client.discovery` over the `/api/v3`-rooted shared\n * `HttpClient` — every method here resolves to `/api/v3/discovery/...`.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\n\n/**\n * Cluster endpoints payload, mirrored from the server-side\n * `ClusterEndpointsPayload` shape.\n *\n * Re-declared here (not imported from `./cluster-discovery`) so this\n * client stays compileable in environments that tree-shake the\n * mirror-node / HCS path out.\n */\nexport type DiscoveryClusterEndpoints = {\n clusterId: string;\n gatewayUrl: string;\n harborUrl?: string;\n natsUrl?: string;\n publicIp?: string;\n region?: string;\n};\n\n/**\n * Active-set cluster row returned by `GET /api/v3/discovery/clusters`.\n *\n * `nodeIds` is the validator-pod identity set whose announcements\n * contributed to this cluster's record — the HCS trust-anchor uses\n * these for cross-checking against the on-chain validator registry.\n */\nexport type DiscoveryClusterRecord = {\n clusterId: string;\n endpoints: DiscoveryClusterEndpoints;\n nodeIds: string[];\n};\n\n/**\n * Per-node registry row returned by `GET /api/v3/discovery/clusters/all`\n * and `GET /api/v3/discovery/clusters/:nodeId`. Carries the publish-time\n * `publicKey` (SDK's verification anchor), the cluster-internal `status`,\n * and the content-addressed envelope CID.\n */\nexport type DiscoveryNodeRecord = {\n nodeId: string;\n publicKey?: string;\n status?: string;\n endpoints: DiscoveryClusterEndpoints;\n endpointsCid: string;\n /** ISO-8601 timestamp of the last cluster-registry event for this node. */\n lastEventTs: string;\n};\n\n/**\n * Platform image manifest — content-addressed kubelet-pull payload.\n * Mirrors `PlatformImageManifest` from `service-registry.events.ts`.\n * Re-declared as an `unknown`-leaning structural type so the SDK does\n * not pull the full server-side schema package into customer bundles.\n */\nexport type DiscoveryPlatformImageManifest = {\n imageName: string;\n version: string;\n sha256digest: string;\n publishedAt: string;\n publisherNodeId?: string;\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Signed platform-image envelope — manifest + DKG-threshold signature +\n * the cluster's aggregated public key. Used by external re-verifiers\n * that want to independently confirm authenticity without trusting\n * the discovery endpoint.\n */\nexport type DiscoveryPlatformImageEnvelope = {\n manifest: DiscoveryPlatformImageManifest;\n signature: string;\n publicKey: string;\n};\n\n/**\n * Result of the `/verify` gate — whether the supplied `sha256digest`\n * matches the on-record manifest for `(imageName, version)`. The\n * server returns a structured `{ verified, reason? }` object even on\n * mismatch so callers don't have to disambiguate HTTP 200 + 404 + 400.\n */\nexport type DiscoveryVerifyResult = {\n verified: boolean;\n reason?: string;\n};\n\n/**\n * Top-level discovery client.\n *\n * Exposes two namespaces via the `client.discovery` surface:\n *\n * - `clusters` (default — flat methods on this instance):\n * `listClusters` / `listAllClusters` / `getClusterByNode`.\n * - `platformImages` (sub-object): manifest browsing, per-version\n * fetch, content-addressed verify, signed envelope retrieval.\n *\n * The two namespaces share the underlying `/api/v3/discovery` URL\n * prefix; splitting them at the SDK boundary mirrors the server-side\n * controller split (`ServiceRegistryController` + `ImageManifestController`)\n * and keeps the API discoverable in IDE autocomplete.\n *\n * @example List active clusters + drill into platform images\n * ```ts\n * const { clusters } = await client.discovery.listClusters();\n * console.log(`${clusters.length} active clusters in this validator's registry view`);\n *\n * const manifests = await client.discovery.platformImages.list();\n * ```\n */\nexport class DiscoveryClient {\n /** Platform-image manifest discovery endpoints. */\n public readonly platformImages: PlatformImagesClient;\n\n constructor(private readonly http: HttpClient) {\n this.platformImages = new PlatformImagesClient(http);\n }\n\n /**\n * `GET /api/v3/discovery/clusters` — active-set cluster registry,\n * grouped by `clusterId`. This is the same data the bootstrap-seed\n * flow consumes for random-pick connect.\n */\n async listClusters(): Promise<{ clusters: DiscoveryClusterRecord[] }> {\n return this.http.get('/discovery/clusters');\n }\n\n /**\n * `GET /api/v3/discovery/clusters/all` — every node-level record\n * (debug / audit view). Includes nodes that the active-set filter\n * dropped (e.g. recently-departed validators still in the registry's\n * eventual-consistency window).\n */\n async listAllClusters(): Promise<{ records: DiscoveryNodeRecord[] }> {\n return this.http.get('/discovery/clusters/all');\n }\n\n /**\n * `GET /api/v3/discovery/clusters/:nodeId` — per-nodeId registry row.\n * Returns `{ record: null }` (not 404) when the nodeId is unknown to\n * this validator's registry view, so callers can branch without\n * try/catch.\n */\n async getClusterByNode(nodeId: string): Promise<{ record: DiscoveryNodeRecord | null }> {\n return this.http.get(`/discovery/clusters/${encodePathParam(nodeId)}`);\n }\n}\n\n/**\n * Platform-image manifest browser. Mounted under\n * `client.discovery.platformImages`.\n *\n * The kubelet pulls platform images by their `sha256digest` (per-image\n * content-addressed pinning at the deploy boundary); this client lets\n * smart-app builders inspect WHICH digests the cluster has DKG-signed\n * as canonical for `(imageName, version)` pairs.\n */\nexport class PlatformImagesClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /api/v3/discovery/platform-images` — every signed manifest the\n * cluster has on record. One row per `(imageName, version)` pair.\n */\n async list(): Promise<{ manifests: DiscoveryPlatformImageManifest[] }> {\n return this.http.get('/discovery/platform-images');\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/envelopes` — full signed\n * envelopes (manifest + signature + publicKey). Heavier payload than\n * {@link list}; for external re-verifiers that want to independently\n * confirm authenticity.\n */\n async listEnvelopes(): Promise<{ envelopes: DiscoveryPlatformImageEnvelope[] }> {\n return this.http.get('/discovery/platform-images/envelopes');\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName` — every version\n * of a single image. Useful for \"which tags has the cluster\n * authorized?\" queries.\n */\n async get(imageName: string): Promise<{\n imageName: string;\n manifests: DiscoveryPlatformImageManifest[];\n }> {\n return this.http.get(`/discovery/platform-images/${encodePathParam(imageName)}`);\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName/:version` —\n * single signed manifest. Returns `{ manifest: null }` when the\n * `(imageName, version)` pair is unknown.\n */\n async getVersion(\n imageName: string,\n version: string,\n ): Promise<{ manifest: DiscoveryPlatformImageManifest | null }> {\n return this.http.get(\n `/discovery/platform-images/${encodePathParam(imageName)}/${encodePathParam(version)}`,\n );\n }\n\n /**\n * `GET /api/v3/discovery/platform-images/:imageName/:version/verify?digest=...`\n * — content-addressed verify gate. Returns `{ verified: true }` only\n * when the supplied SHA-256 digest matches the on-record manifest.\n *\n * Use before pulling an image off a registry to make sure you're\n * about to run cluster-signed bits and not whatever drifted into\n * the registry namespace.\n */\n async verify(\n imageName: string,\n version: string,\n digest: string,\n ): Promise<DiscoveryVerifyResult> {\n return this.http.get(\n `/discovery/platform-images/${encodePathParam(imageName)}/${encodePathParam(\n version,\n )}/verify?digest=${encodeURIComponent(digest)}`,\n );\n }\n}\n","/**\n * Network presets for the Smart Engines SDK.\n *\n * Built so SDK consumers don't have to hand-roll a gateway URL or remember\n * which HCS topic ID is the validator-registry trust anchor. The \"zero-\n * config\" entrypoint flow:\n *\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * network: 'testnet',\n * appId: 'app_abc',\n * });\n * ```\n *\n * ↓ the SDK internally:\n * 1. Resolves `KNOWN_NETWORKS['testnet'].bootstrap` to the canonical\n * `https://gateway.<network>.hsuite.network` entrypoint.\n * 2. Fetches `GET /api/v3/discovery/clusters` from that gateway.\n * 3. Random-picks an active cluster's gatewayUrl.\n * 4. Returns a `BaasClient`/`SmartEngineClient` pointed at that cluster.\n *\n * The on-chain trust-anchor (validator-registry HCS topic) is **per\n * deployment** — the testnet that ships today, a customer-run private\n * testnet, or future mainnet all have different topic IDs. We deliberately\n * do NOT bake a registryTopicId in here; callers who want anchored discovery\n * pass `trustAnchor` explicitly. Callers who don't get the same security\n * guarantees as a plain HTTPS fetch of a public endpoint, which is the same\n * trust model as every other \"talk to gateway.testnet.X\" SDK in the wild.\n */\n\n/** Network identifiers the SDK knows about by name. */\nexport type NetworkName = 'testnet' | 'mainnet';\n\n/** Resolved network preset — what the SDK needs to bootstrap discovery. */\nexport interface NetworkPreset {\n /**\n * Bootstrap seeds for `ClusterDiscoveryClient`. Ordered: first reachable\n * wins. Operators can append fallback URLs locally; the SDK only ships\n * the canonical Cloudflare-fronted gateway here.\n */\n readonly bootstrap: readonly string[];\n}\n\n/**\n * Canonical entrypoints for each supported HSuite network.\n *\n * Update this map (and ship a SDK minor bump) when DNS for a network changes\n * or when a new network goes live. Customers who run their own validators\n * should NOT extend this map — they should pass `bootstrap: [...]` directly.\n */\nexport const KNOWN_NETWORKS: Readonly<Record<NetworkName, NetworkPreset>> = {\n testnet: {\n bootstrap: ['https://gateway.testnet.hsuite.network'],\n },\n mainnet: {\n // Mainnet entrypoint reserved. The SDK still resolves the name so\n // upgrade-by-flipping-NETWORK works; the bootstrap URL is the\n // pre-allocated DNS we own. If mainnet isn't deployed yet, the discovery\n // fetch will fail at runtime with the same \"no seed reachable\" error\n // any unreachable URL produces — the caller learns the network is not\n // live, rather than getting a baffling \"unknown network\" TypeScript\n // error at compile time.\n bootstrap: ['https://gateway.hsuite.network'],\n },\n} as const;\n\n/**\n * Resolve a network name to its preset. Throws on unknown name — this is the\n * one place a stringly-typed call (e.g. from a config file) gets validated.\n *\n * Callers passing a `NetworkName`-typed value compile-time-guarantee this\n * never throws.\n */\nexport function resolveNetwork(name: NetworkName): NetworkPreset {\n const preset = KNOWN_NETWORKS[name];\n if (!preset) {\n // Defensive guard for the runtime string case. NetworkName is a closed\n // union, but JS callers can pass anything.\n throw new Error(\n `Unknown network: \"${name}\". Known networks: ${Object.keys(KNOWN_NETWORKS).join(', ')}`,\n );\n }\n return preset;\n}\n\n/**\n * Type guard for `NetworkName`. Useful when accepting input from configs,\n * env vars, or CLI flags.\n */\nexport function isKnownNetwork(name: string): name is NetworkName {\n return Object.prototype.hasOwnProperty.call(KNOWN_NETWORKS, name);\n}\n","/**\n * Shared bootstrap → cluster resolution helper.\n *\n * `BaasClient.connectToCluster` (and, before SDK 4.0, the now-removed\n * `SmartEngineClient.connectToCluster`) had ~25 lines of identical scaffolding\n * (resolve `bootstrap | network` → `ClusterDiscoveryClient` → `getRandomCluster`\n * → throw if null). This helper collapses that duplication; the factory delegates\n * here and wraps the null-case in its own error class.\n */\n\nimport { ClusterDiscoveryClient, type ClusterInfo } from './cluster-discovery';\nimport { resolveNetwork, type NetworkName } from '../network-presets';\n\n/**\n * Discovery-seed half of every `connectToCluster` config — must supply\n * exactly one of `bootstrap` or `network` (the call-sites encode the\n * exactly-one constraint via a discriminated union; this type intersects\n * with the auth / config half).\n */\nexport type ResolveClusterSeed = {\n /** Bootstrap seeds: URLs that serve `GET /api/v3/discovery/clusters`. */\n bootstrap?: string[];\n /** Named network — resolves the canonical gateway entrypoint. */\n network?: NetworkName;\n};\n\n/**\n * Optional HCS trust-anchor (cross-checks the bootstrap response against\n * the on-chain validator-registry topic so a compromised bootstrap seed\n * can't inject rogue clusters).\n */\nexport type ResolveClusterTrustAnchor = {\n network: 'mainnet' | 'testnet' | 'previewnet';\n registryTopicId: string;\n mirrorNodeUrl?: string;\n};\n\n/**\n * Common config inputs for {@link resolveClusterEndpoint}.\n */\nexport type ResolveClusterConfig = ResolveClusterSeed & {\n allowInsecure?: boolean;\n trustAnchor?: ResolveClusterTrustAnchor;\n};\n\n/**\n * Outcomes from {@link resolveClusterEndpoint}.\n *\n * - `'no-seeds'` — neither a `bootstrap` list nor a known `network` was\n * supplied (caller passed an empty list explicitly, or the network\n * preset has no seeds).\n * - `'no-clusters'` — discovery completed but found no active cluster\n * via any seed (network reachability / bootstrap URLs are likely off).\n */\nexport type ResolveClusterFailure = 'no-seeds' | 'no-clusters';\n\nexport type ResolveClusterResult =\n | { ok: true; cluster: ClusterInfo }\n | { ok: false; reason: ResolveClusterFailure };\n\n/**\n * Resolve a cluster endpoint via bootstrap seeds or a named network.\n *\n * `BaasClient.connectToCluster` calls this. The factory handles wrapping\n * the failure cases in its error class (so callers keep getting `BaasError`\n * rather than a leaked helper-side type).\n */\nexport async function resolveClusterEndpoint(\n config: ResolveClusterConfig,\n): Promise<ResolveClusterResult> {\n const allowInsecure = config.allowInsecure ?? false;\n\n // Resolve the seed half. `bootstrap` wins when both are set under\n // `any`-cast usage; the call-site types prevent that under normal TS.\n const bootstrap: string[] = config.bootstrap\n ? [...config.bootstrap]\n : config.network\n ? [...resolveNetwork(config.network).bootstrap]\n : [];\n\n if (bootstrap.length === 0) {\n return { ok: false, reason: 'no-seeds' };\n }\n\n const discovery = new ClusterDiscoveryClient({\n bootstrap,\n allowInsecure,\n trustAnchor: config.trustAnchor\n ? {\n network: config.trustAnchor.network,\n registryTopicId: config.trustAnchor.registryTopicId,\n mirrorNodeUrl: config.trustAnchor.mirrorNodeUrl,\n allowInsecure,\n }\n : undefined,\n });\n\n const cluster = await discovery.getRandomCluster();\n if (!cluster) {\n return { ok: false, reason: 'no-clusters' };\n }\n\n return { ok: true, cluster };\n}\n","/**\n * Validator Authentication Client\n *\n * Web3-style authentication for connecting to smart-engine validators.\n * Supports challenge-response authentication with Hedera, XRPL, Polkadot,\n * Stellar, or Solana wallets.\n */\n\n/**\n * Supported blockchain types for authentication.\n *\n * All five are verified end-to-end server-side by {@link Web3AuthService}\n * (Hedera ed25519, XRPL secp256k1/ed25519, Polkadot sr25519/ed25519,\n * Stellar ed25519, Solana ed25519). The partial-mode prepare guards\n * enforce `session.chain === request.chain`, so a caller who wants to\n * prepare sovereignty on chain X must authenticate with chain X's wallet.\n */\nexport type AuthChain = 'hedera' | 'xrpl' | 'polkadot' | 'stellar' | 'solana';\n\nconst SUPPORTED_AUTH_CHAINS: readonly AuthChain[] = [\n 'hedera',\n 'xrpl',\n 'polkadot',\n 'stellar',\n 'solana',\n];\n\n/**\n * Security configuration for auth client\n */\nexport interface SecurityConfig {\n /** Allow HTTP (insecure) connections - default false, use only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Structural type of a Hedera-style signer — matches the `PrivateKey`\n * surface in `@hashgraph/sdk` without importing it. Accepts any of the\n * three return shapes the SDK has historically used: a raw `Uint8Array`,\n * a Node `Buffer`, or an object with `toBytes()`.\n *\n * Defined here rather than imported to keep `@hashgraph/sdk` out of the\n * SDK's runtime — it stays a peer/optional dep of the consumer.\n */\nexport type HederaSigner = {\n sign(message: Uint8Array): Uint8Array | Buffer | { toBytes(): Uint8Array };\n};\n\n/**\n * Structural type of an XRPL-style signer — matches the `Wallet.sign`\n * surface in the `xrpl` library without importing it. Returns either a\n * bare hex/base58 string or a `{ signedTransaction }` envelope.\n */\nexport type XrplSigner = {\n sign(message: string): string | { signedTransaction: string };\n};\n\n/**\n * Normalize the three Hedera-signer return shapes into a `Uint8Array`.\n */\nfunction toBytes(value: Uint8Array | Buffer | { toBytes(): Uint8Array }): Uint8Array {\n // Buffer extends Uint8Array, so this branch catches both.\n if (value instanceof Uint8Array) return value;\n return value.toBytes();\n}\n\n/**\n * Validate and sanitize a validator URL\n */\nfunction validateValidatorUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n\n // Only allow http/https protocols\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new ValidatorAuthError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n\n // Enforce HTTPS unless explicitly allowed for development\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new ValidatorAuthError(\n 'HTTPS is required for validator connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n\n // Block private IP ranges in production to prevent SSRF\n const hostname = parsed.hostname.toLowerCase();\n const isLocalhost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';\n\n if (isLocalhost && !allowInsecure) {\n throw new ValidatorAuthError(\n 'Localhost connections blocked in secure mode. Set allowInsecure=true for local development.',\n 400\n );\n }\n\n return parsed.origin;\n } catch (error) {\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n throw new ValidatorAuthError(`Invalid validator URL: ${url}`, 400);\n }\n}\n\n/**\n * Sanitize input to prevent injection attacks\n */\nfunction sanitizeInput(input: string, fieldName: string, maxLength = 256): string {\n if (typeof input !== 'string') {\n throw new ValidatorAuthError(`${fieldName} must be a string`, 400);\n }\n\n if (input.length > maxLength) {\n throw new ValidatorAuthError(`${fieldName} exceeds maximum length of ${maxLength}`, 400);\n }\n\n // Remove any control characters\n return input.replace(/[\\x00-\\x1F\\x7F]/g, '');\n}\n\n/**\n * Challenge response from validator\n */\nexport interface ChallengeResponse {\n /** Whether the request was successful */\n success: boolean;\n /** Challenge string to sign */\n challenge: string;\n /** Informational message */\n message: string;\n /** Challenge expiration time */\n expiresIn: string;\n}\n\n/**\n * Authentication request payload\n */\nexport interface AuthenticateRequest {\n /** Blockchain type */\n chain: AuthChain;\n /** Wallet address (account ID for Hedera, address for XRPL) */\n address: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Signed challenge (hex encoded signature) */\n signature: string;\n /** Original challenge string */\n challenge: string;\n /** Optional metadata */\n metadata?: {\n nodeId?: string;\n endpoint?: string;\n capabilities?: string[];\n appId?: string;\n appName?: string;\n };\n}\n\n/**\n * Authentication response with session token\n */\nexport interface AuthenticateResponse {\n /** JWT session token */\n token: string;\n /** Session ID */\n sessionId: string;\n /** Assigned validator ID */\n validatorId: string;\n /** Token expiration timestamp */\n expiresAt: string;\n /** Informational message */\n message: string;\n}\n\n/**\n * Session information\n */\nexport interface SessionInfo {\n /** Session ID */\n sessionId: string;\n /** Validator ID */\n validatorId: string;\n /** Wallet address */\n address: string;\n /** Blockchain type */\n chain: AuthChain;\n /** Session creation time */\n createdAt: string;\n /** Session expiration time */\n expiresAt: string;\n /** Whether session is valid */\n isValid: boolean;\n}\n\n/**\n * Validator auth configuration\n */\nexport interface ValidatorAuthConfig {\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Security configuration */\n security?: SecurityConfig;\n}\n\n/**\n * Validator Authentication Client\n *\n * Implements Web3-style challenge-response authentication:\n * 1. Request challenge from validator\n * 2. Sign challenge with wallet private key\n * 3. Authenticate with signed challenge to get session token\n *\n * @example\n * ```typescript\n * const auth = new ValidatorAuthClient();\n *\n * // Request challenge\n * const challenge = await auth.requestChallenge(\n * 'https://validator.example.com',\n * 'hedera',\n * '0.0.123456'\n * );\n *\n * // Sign challenge (using @hashgraph/sdk)\n * const signature = auth.signChallengeHedera(challenge.challenge, privateKey);\n *\n * // Authenticate\n * const session = await auth.authenticate('https://validator.example.com', {\n * chain: 'hedera',\n * address: '0.0.123456',\n * publicKey: publicKeyHex,\n * signature,\n * challenge: challenge.challenge,\n * });\n *\n * console.log('Token:', session.token);\n * ```\n */\nexport class ValidatorAuthClient {\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n\n constructor(config?: ValidatorAuthConfig) {\n this.timeout = config?.timeout ?? 30000;\n this.allowInsecure = config?.security?.allowInsecure ?? false;\n }\n\n /**\n * Request authentication challenge from validator\n *\n * @param validatorUrl - Validator API base URL\n * @param chain - Blockchain type\n * @param address - Wallet address\n * @returns Challenge to sign\n */\n async requestChallenge(\n validatorUrl: string,\n chain: AuthChain,\n address: string\n ): Promise<ChallengeResponse> {\n // Validate and sanitize inputs\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n const safeAddress = sanitizeInput(address, 'address', 128);\n\n if (!SUPPORTED_AUTH_CHAINS.includes(chain)) {\n throw new ValidatorAuthError(`Invalid chain type: ${chain}`, 400);\n }\n\n const url = `${safeUrl}/auth/validator/challenge`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ chain, address: safeAddress }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Challenge request failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as ChallengeResponse;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Challenge request timeout', 408);\n }\n throw new ValidatorAuthError(`Challenge request failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Authenticate with signed challenge\n *\n * @param validatorUrl - Validator API base URL\n * @param request - Authentication request with signature\n * @returns Session token and info\n */\n async authenticate(\n validatorUrl: string,\n request: AuthenticateRequest\n ): Promise<AuthenticateResponse> {\n // Validate URL\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n\n // Validate and sanitize request fields\n const sanitizedRequest: AuthenticateRequest = {\n chain: request.chain,\n address: sanitizeInput(request.address, 'address', 128),\n publicKey: sanitizeInput(request.publicKey, 'publicKey', 512),\n signature: sanitizeInput(request.signature, 'signature', 1024),\n challenge: sanitizeInput(request.challenge, 'challenge', 512),\n metadata: request.metadata\n ? {\n nodeId: request.metadata.nodeId\n ? sanitizeInput(request.metadata.nodeId, 'nodeId', 64)\n : undefined,\n endpoint: request.metadata.endpoint\n ? sanitizeInput(request.metadata.endpoint, 'endpoint', 256)\n : undefined,\n capabilities: request.metadata.capabilities,\n appId: request.metadata.appId\n ? sanitizeInput(request.metadata.appId, 'appId', 64)\n : undefined,\n appName: request.metadata.appName\n ? sanitizeInput(request.metadata.appName, 'appName', 128)\n : undefined,\n }\n : undefined,\n };\n\n if (!SUPPORTED_AUTH_CHAINS.includes(sanitizedRequest.chain)) {\n throw new ValidatorAuthError(`Invalid chain type: ${sanitizedRequest.chain}`, 400);\n }\n\n // Validate signature is hex\n if (!/^[0-9a-fA-F]+$/.test(sanitizedRequest.signature.replace(/_.*$/, ''))) {\n throw new ValidatorAuthError('Invalid signature format: must be hex encoded', 400);\n }\n\n const url = `${safeUrl}/auth/validator/authenticate`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(sanitizedRequest),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Authentication failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as AuthenticateResponse;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Authentication request timeout', 408);\n }\n throw new ValidatorAuthError(`Authentication failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Get current session info\n *\n * @param validatorUrl - Validator API base URL\n * @param token - Session token\n * @returns Session information\n */\n async getSession(validatorUrl: string, token: string): Promise<SessionInfo> {\n // Validate URL and token\n const safeUrl = validateValidatorUrl(validatorUrl, this.allowInsecure);\n const safeToken = sanitizeInput(token, 'token', 2048);\n\n const url = `${safeUrl}/auth/validator/session`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${safeToken}`,\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new ValidatorAuthError(\n `Session request failed: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return (await response.json()) as SessionInfo;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof ValidatorAuthError) {\n throw error;\n }\n const err = error as Error;\n if (err.name === 'AbortError') {\n throw new ValidatorAuthError('Session request timeout', 408);\n }\n throw new ValidatorAuthError(`Session request failed: ${err.message}`, 0);\n }\n }\n\n /**\n * Sign challenge with Hedera private key.\n *\n * Structurally typed against the surface of `@hashgraph/sdk`'s\n * `PrivateKey`. We don't `import` the SDK directly — pulling it into\n * the smart-engine SDK's runtime would bloat browser bundles and bring\n * peer-dep churn — but any object with a compatible `sign(...)` method\n * works.\n *\n * @param challenge - Challenge string from validator\n * @param privateKey - Hedera PrivateKey instance (or compatible signer)\n * @returns Hex-encoded signature\n */\n signChallengeHedera(challenge: string, privateKey: HederaSigner): string {\n const messageBytes = new Uint8Array(Buffer.from(challenge, 'utf-8'));\n const signature = privateKey.sign(messageBytes);\n return Buffer.from(toBytes(signature)).toString('hex');\n }\n\n /**\n * Sign challenge with XRPL wallet.\n *\n * Structurally typed against the surface of xrpl's `Wallet` — see the\n * comment on {@link HederaSigner} for the \"no direct import\" rationale.\n * Accepts both the `{ signedTransaction }` envelope and the bare-string\n * return shapes that xrpl signer libraries expose.\n *\n * @param challenge - Challenge string from validator\n * @param wallet - XRPL Wallet instance (or compatible signer)\n * @returns Hex-encoded signature\n */\n signChallengeXRPL(challenge: string, wallet: XrplSigner): string {\n const signature = wallet.sign(challenge);\n // XRPL libs expose two return shapes: a bare hex/base58 string, or a\n // `{ signedTransaction }` envelope. Normalize to hex.\n if (typeof signature === 'string') {\n if (/^[0-9A-Fa-f]+$/.test(signature)) return signature;\n return Buffer.from(signature).toString('hex');\n }\n return signature.signedTransaction;\n }\n\n /**\n * Complete authentication flow in one call\n *\n * @param validatorUrl - Validator API base URL\n * @param chain - Blockchain type\n * @param address - Wallet address\n * @param publicKey - Public key (hex)\n * @param signFn - Function to sign the challenge\n * @param metadata - Optional metadata\n * @returns Session token and info\n */\n async authenticateWithSigner(\n validatorUrl: string,\n chain: AuthChain,\n address: string,\n publicKey: string,\n signFn: (challenge: string) => string | Promise<string>,\n metadata?: AuthenticateRequest['metadata']\n ): Promise<AuthenticateResponse> {\n // Step 1: Request challenge\n const challengeResponse = await this.requestChallenge(validatorUrl, chain, address);\n\n // Step 2: Sign challenge\n const signature = await signFn(challengeResponse.challenge);\n\n // Step 3: Authenticate\n return this.authenticate(validatorUrl, {\n chain,\n address,\n publicKey,\n signature,\n challenge: challengeResponse.challenge,\n metadata,\n });\n }\n}\n\n/**\n * Authentication error\n */\nexport class ValidatorAuthError extends Error {\n constructor(\n message: string,\n public statusCode: number,\n public details?: any\n ) {\n super(message);\n this.name = 'ValidatorAuthError';\n }\n}\n","/**\n * Subscription Sub-Client\n *\n * Manages application subscriptions for using the validator network.\n */\n\n/**\n * Subscription tier names.\n *\n * The ladder is `builder → growth → scale → enterprise`. Every tier is paid;\n * the previous free_testnet/starter/professional names were retired.\n *\n * - builder: Entry-level paid tier\n * - growth: Mid-tier with usage analytics\n * - scale: High-volume tier with advanced features\n * - enterprise: Full-featured enterprise tier (custom / unlimited)\n *\n * BREAKING: this union changed from `free_testnet | starter | professional |\n * enterprise`. Consumers pinning the old names must migrate.\n */\nexport type SubscriptionTierName = 'builder' | 'growth' | 'scale' | 'enterprise';\n\n/**\n * Subscription statuses.\n *\n * NOTE: `'deposit_confirmed'` is the mint-ready status — the validator's\n * `activateSubscription` refuses to mint the subscription NFT unless the\n * subscription is in `deposit_confirmed` (there is no `'pending_mint'` status).\n * After a successful mint the status advances to `'active'`.\n */\nexport type SubscriptionStatus =\n | 'pending_deposit'\n | 'deposit_confirmed'\n | 'active'\n | 'expired'\n | 'cancelled';\n\n/**\n * Deposit wallet statuses\n */\nexport type DepositWalletStatus = 'pending' | 'locked' | 'expired' | 'slashed' | 'released';\n\n/**\n * Subscription tier information for API responses\n */\nexport type SubscriptionTierInfo = {\n /** Tier name identifier */\n name: SubscriptionTierName;\n /** Display name for UI */\n displayName: string;\n /** Tier description */\n description: string;\n /** Monthly price in USD */\n priceUsd: number;\n /** Deposit amount in HSUITE tokens */\n depositAmount: string;\n /** API calls per day limit */\n apiCallsPerDay: number;\n /** Supported networks for this tier */\n supportedNetworks: ('hedera' | 'xrpl')[];\n /** Additional features included in this tier */\n features: string[];\n};\n\n/**\n * Subscription request\n */\nexport type SubscriptionRequest = {\n /** Application ID */\n appId: string;\n /** Application name */\n appName: string;\n /** Developer's account ID on the chosen chain */\n developerAccountId: string;\n /** Chain for deposit */\n chain: 'hedera' | 'xrpl';\n /** Selected subscription tier */\n selectedTier: SubscriptionTierName;\n /** Selected networks to support */\n selectedNetworks: ('hedera' | 'xrpl')[];\n /** App logo URL (optional) */\n logoUrl?: string;\n /** App description (optional) */\n appDescription?: string;\n /** Additional metadata (optional) */\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Subscription response\n */\nexport type SubscriptionResponse = {\n success: boolean;\n subscriptionId?: string;\n status?: SubscriptionStatus;\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n message: string;\n};\n\n/**\n * Subscription status response\n */\nexport type SubscriptionStatusResponse = {\n appId: string;\n hasSubscription: boolean;\n subscriptionId?: string;\n appName?: string;\n status: SubscriptionStatus | 'not_found';\n depositWallet?: {\n walletAddress: string;\n chain: string;\n depositAmount: string;\n actualDepositAmount?: string;\n status: DepositWalletStatus;\n lockedUntil?: string;\n };\n subscriptionNftSerial?: number;\n /**\n * Per-chain minted-NFT coordinates exposed by the validator once the\n * subscription NFT is minted. For XRPL this carries the NFTokenID, the\n * issuing account (the cluster SignerList issuer), and the brokered\n * sell-offer tx id — enough for a client to resolve + accept the sell offer\n * so the NFT lands on the developer wallet (`NFTokenAcceptOffer`).\n */\n chainNfts?: {\n xrpl?: {\n nftId?: string;\n issuerAddress?: string;\n offerTxId?: string;\n };\n } & Record<string, unknown>;\n expiresAt?: string;\n remainingBalance?: string;\n createdAt?: string;\n /** Current subscription tier */\n tier?: SubscriptionTierName;\n /** Networks selected for this subscription */\n selectedNetworks?: string[];\n /** API calls made today */\n apiCallsToday?: number;\n /** Daily API call limit based on tier */\n apiCallsLimit?: number;\n};\n\n/**\n * Mint NFT response\n */\nexport type MintNftResponse = {\n success: boolean;\n subscriptionId?: string;\n appId?: string;\n expiresAt?: string;\n message: string;\n};\n\n/**\n * Subscription renewal request\n */\nexport type SubscriptionRenewalRequest = {\n appId: string;\n additionalDays?: number;\n};\n\n/**\n * Subscription renewal response\n */\nexport type SubscriptionRenewalResponse = {\n success: boolean;\n appId: string;\n status?: string;\n newExpiresAt?: string;\n message: string;\n};\n\n/**\n * Subscription configuration\n */\nexport type SubscriptionConfig = {\n subscriptionDepositAmount: string;\n lockDurationDays: number;\n renewalWindowDays: number;\n hsuiteTokenIds: Record<string, string>;\n /** Available subscription tiers */\n availableTiers: SubscriptionTierInfo[];\n};\n\n/**\n * Subscription list response\n */\nexport type SubscriptionListResponse = {\n count: number;\n subscriptions: Array<{\n subscriptionId: string;\n appId: string;\n appName: string;\n status: SubscriptionStatus;\n expiresAt?: string;\n createdAt: string;\n }>;\n};\n\n/**\n * Pending tier change envelope returned by downgrade/upgrade endpoints.\n * The validator records the change without applying it until the next\n * renewal (downgrade) or until the on-chain top-up is confirmed (upgrade).\n */\nexport type PendingTierChange = {\n fromTier?: SubscriptionTierName;\n toTier?: SubscriptionTierName;\n direction?: 'upgrade' | 'downgrade';\n effectiveAt?: string;\n /** Top-up deposit (upgrade only). */\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n};\n\n/** Response shape for `POST /subscription/downgrade`. */\nexport type DowngradeSubscriptionRequest = {\n appId: string;\n toTier: SubscriptionTierName;\n};\n\nexport type DowngradeSubscriptionResponse = {\n success: boolean;\n appId: string;\n pendingTierChange?: PendingTierChange;\n message: string;\n};\n\n/** Response shape for `POST /subscription/upgrade`. */\nexport type UpgradeSubscriptionRequest = {\n appId: string;\n toTier: SubscriptionTierName;\n};\n\nexport type UpgradeSubscriptionResponse = {\n success: boolean;\n appId: string;\n pendingTierChange?: PendingTierChange;\n /** Top-up deposit instructions; flip activates once on-chain. */\n depositInstructions?: {\n walletAddress: string;\n tokenId: string;\n amount: string;\n chain: string;\n };\n message: string;\n};\n\nexport type CancelTierChangeRequest = {\n appId: string;\n};\n\nexport type CancelTierChangeResponse = {\n success: boolean;\n appId: string;\n message: string;\n};\n\n/**\n * Response shape for `GET /subscription/active-for/:walletAddress`.\n *\n * **Internal-by-design.** Server-side this is allowlisted under\n * `ApiKeyGuard.INTERNAL_SERVICE_MESH_ROUTES` — smart-host pods call it via\n * `X-API-Key`. Smart-app callers SHOULD NOT use this endpoint; it is\n * exposed for completeness and for in-cluster tooling.\n */\nexport type ActiveSubscriptionForWalletResponse = {\n active: boolean;\n};\n\n/**\n * Response shape for `GET /subscription/usage/:appId`. Mirrors the\n * server-side `UsageBreakdown` projection.\n */\nexport type SubscriptionUsageSummaryResponse = {\n appId: string;\n total: number;\n byCategory: {\n database: number;\n functions: number;\n messaging: number;\n storage: number;\n ipfs: number;\n snapshots: number;\n other: number;\n };\n recordCount: number;\n lastUpdated: string;\n};\n\n/** Response shape for `GET /subscription/usage/status/:appId`. */\nexport type SubscriptionUsageStatusResponse = {\n appId: string;\n usagePercent: number;\n currentUsage: number;\n dailyLimit: number;\n overagePercent: number;\n inGracePeriod: boolean;\n graceExpiresAt: string | null;\n blocked: boolean;\n suggestUpgrade: boolean;\n nextTier: {\n tier: SubscriptionTierName;\n name: string;\n apiCallsPerDay: number;\n monthlyPriceHsuite: number;\n } | null;\n projectedDaysUntilLimit: number | null;\n};\n\n/** Response shape for `GET /subscription/billing/:appId`. */\nexport type SubscriptionBillingLedgerEntry = {\n id: string;\n subscriptionId: string;\n operation: string;\n amount: string;\n balanceAfter: string;\n timestamp: string;\n metadata?: Record<string, unknown>;\n};\n\nexport type SubscriptionBillingResponse = {\n appId: string;\n entries: SubscriptionBillingLedgerEntry[];\n total: number;\n hasMore: boolean;\n};\n\nexport type GetBillingOptions = {\n limit?: number;\n offset?: number;\n /** ISO-8601 lower bound. */\n from?: string;\n /** ISO-8601 upper bound. */\n to?: string;\n};\n\n/** Response shape for `POST /subscription/customer/mint`. */\nexport type MintCustomerSubscriptionRequest = {\n appId: string;\n customerAddress: string;\n /** v1 is XRPL-only — Hedera/Solana/Polkadot not supported server-side. */\n customerChain: 'xrpl';\n metadataCid: string;\n};\n\nexport type MintCustomerSubscriptionResponse = {\n success: true;\n nftSerial: number;\n txHash: string;\n};\n\n/**\n * Balance response\n */\nexport type BalanceResponse = {\n appId: string;\n subscriptionId: string;\n status: SubscriptionStatus;\n remainingBalance: string;\n expiresAt?: string;\n};\n\nimport { encodePathParam, type HttpClient } from '../http';\n\n/**\n * Subscription Sub-Client\n *\n * Manages application subscriptions including:\n * - Subscription requests with deposit wallets\n * - Deposit verification and NFT minting\n * - Subscription renewal\n * - Balance checking\n */\nexport class SubscriptionClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Request a new subscription.\n * Creates a deposit wallet and returns deposit instructions.\n */\n async request(request: SubscriptionRequest): Promise<SubscriptionResponse> {\n return this.http.post('/subscription/request', request);\n }\n\n /**\n * Get subscription status by app ID\n */\n async getStatus(appId: string): Promise<SubscriptionStatusResponse> {\n return this.http.get(`/subscription/status/${encodePathParam(appId)}`);\n }\n\n /**\n * Mint subscription NFT after deposit is confirmed\n */\n async mintNft(appId: string): Promise<MintNftResponse> {\n return this.http.post(`/subscription/mint/${encodePathParam(appId)}`, {});\n }\n\n /**\n * Renew subscription by extending period\n */\n async renew(request: SubscriptionRenewalRequest): Promise<SubscriptionRenewalResponse> {\n return this.http.post('/subscription/renew', request);\n }\n\n /**\n * Fetch available subscription tiers from the network.\n *\n * Use this instead of hard-coding tier names -- the validator returns the\n * canonical list of tiers together with pricing, limits, and features.\n *\n * @returns Array of {@link SubscriptionTierInfo} objects.\n *\n * @example\n * ```typescript\n * const tiers = await subscription.getTiers();\n * console.log(tiers.map(t => `${t.name}: $${t.priceUsd}/mo`));\n * ```\n */\n async getTiers(): Promise<SubscriptionTierInfo[]> {\n try {\n return await this.http.get<SubscriptionTierInfo[]>('/subscription/tiers');\n } catch (err) {\n // Backwards compatibility: older validator builds don't have the\n // dedicated /tiers endpoint yet. Fall back to /config, which\n // returns the same tiers under `availableTiers` (though in the\n // raw pricing-core shape rather than SubscriptionTierInfo).\n const isNotFound =\n err != null &&\n typeof err === 'object' &&\n 'statusCode' in err &&\n (err as { statusCode?: number }).statusCode === 404;\n if (!isNotFound) throw err;\n const cfg = await this.http.get<{\n availableTiers: Array<Record<string, unknown>>;\n }>('/subscription/config');\n // Normalize: pricing-core's SubscriptionTierConfig uses\n // { tier, name, monthlyPriceHsuite, allowedNetworks, ... } — map\n // to the SDK contract so callers see a stable shape across\n // server versions.\n return (cfg.availableTiers || []).map((raw) => {\n const tier = (raw.tier ?? raw.name) as SubscriptionTierName;\n const displayName = (raw.name ?? raw.displayName ?? String(tier)) as string;\n const monthlyPriceHsuite = Number(\n raw.monthlyPriceHsuite ?? raw.depositAmount ?? 0\n );\n const apiCallsPerDay = Number(raw.apiCallsPerDay ?? 0);\n const rawNetworks = (raw.allowedNetworks ?? raw.supportedNetworks ?? []) as string[];\n const supportedNetworks: ('hedera' | 'xrpl')[] = rawNetworks.some(\n (n) => n === 'mainnet'\n )\n ? ['hedera', 'xrpl']\n : ['hedera'];\n return {\n name: tier,\n displayName,\n description:\n (raw.description as string | undefined) ??\n `${displayName} tier`,\n priceUsd: Number(raw.priceUsd ?? 0),\n depositAmount: String(monthlyPriceHsuite),\n apiCallsPerDay: Number.isFinite(apiCallsPerDay)\n ? apiCallsPerDay\n : Number.MAX_SAFE_INTEGER,\n supportedNetworks,\n features: (raw.features as string[]) ?? [],\n };\n });\n }\n }\n\n /**\n * Get subscription configuration\n */\n async getConfig(): Promise<SubscriptionConfig> {\n return this.http.get('/subscription/config');\n }\n\n /**\n * List all subscriptions\n */\n async list(): Promise<SubscriptionListResponse> {\n return this.http.get('/subscription/list');\n }\n\n /**\n * List subscriptions by status\n */\n async listByStatus(status: SubscriptionStatus): Promise<SubscriptionListResponse> {\n return this.http.get(`/subscription/list/status/${encodePathParam(status)}`);\n }\n\n /**\n * Get subscription balance\n */\n async getBalance(appId: string): Promise<BalanceResponse> {\n return this.http.get(`/subscription/balance/${encodePathParam(appId)}`);\n }\n\n // ─── Tier-Change Endpoints ────────────────────────────────────────────────\n\n /**\n * Schedule a tier downgrade. The downgrade takes effect at the next\n * renewal — the deposit is NOT partially refunded mid-lock. Excess\n * collateral returns on eventual cancel.\n */\n async downgrade(\n request: DowngradeSubscriptionRequest,\n ): Promise<DowngradeSubscriptionResponse> {\n return this.http.post('/subscription/downgrade', request);\n }\n\n /**\n * Request a tier upgrade. The server records the upgrade and returns\n * top-up deposit instructions for the price delta. The new tier flips\n * only once the on-chain top-up is confirmed by the deposit monitor.\n */\n async upgrade(\n request: UpgradeSubscriptionRequest,\n ): Promise<UpgradeSubscriptionResponse> {\n return this.http.post('/subscription/upgrade', request);\n }\n\n /** Cancel a pending (not-yet-applied) tier change. */\n async cancelTierChange(\n request: CancelTierChangeRequest,\n ): Promise<CancelTierChangeResponse> {\n return this.http.post('/subscription/tier-change/cancel', request);\n }\n\n // ─── Internal / Usage / Billing ───────────────────────────────────────────\n\n /**\n * Check whether a developer wallet has any active subscription. Used by\n * smart-host's deploy gate via the cluster-internal API-key path; smart-app\n * callers should not rely on this endpoint (server-side it requires the\n * `INTERNAL_SERVICE_MESH_ROUTES` allowlist + an `X-API-Key` header).\n */\n async getActiveFor(walletAddress: string): Promise<ActiveSubscriptionForWalletResponse> {\n return this.http.get(\n `/subscription/active-for/${encodePathParam(walletAddress)}`,\n );\n }\n\n /** Today's consumption breakdown by category for an app. Owner-only. */\n async getUsage(appId: string): Promise<SubscriptionUsageSummaryResponse> {\n return this.http.get(`/subscription/usage/${encodePathParam(appId)}`);\n }\n\n /**\n * Current usage with overage info: usage percent, grace status,\n * upgrade suggestion, projected days until limit. Owner-only.\n */\n async getUsageStatus(appId: string): Promise<SubscriptionUsageStatusResponse> {\n return this.http.get(`/subscription/usage/status/${encodePathParam(appId)}`);\n }\n\n /**\n * Subscription balance deduction history. Pagination + ISO-8601 range\n * filtering supported. Owner-only.\n */\n async getBilling(\n appId: string,\n options?: GetBillingOptions,\n ): Promise<SubscriptionBillingResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n if (options?.from) params.append('from', options.from);\n if (options?.to) params.append('to', options.to);\n const qs = params.toString();\n return this.http.get(\n `/subscription/billing/${encodePathParam(appId)}${qs ? `?${qs}` : ''}`,\n );\n }\n\n /**\n * Mint a customer-subscription NFT on behalf of a smart-app.\n *\n * Distinct from `mintNft(appId)`, which mints the smart-app's own\n * developer-level subscription NFT. This endpoint mints a *customer*\n * NFT held by an end-user wallet — used by smart-host's\n * `XrplCustomerNftIssuerAdapter` when an app calls\n * `SubscriptionService.issueCustomerSubscription()` from the sandbox.\n *\n * v1 is XRPL-only (the `customerChain` field is a literal `'xrpl'`).\n * Internal-by-design — server-side gated by `X-API-Key`.\n */\n async mintCustomer(\n request: MintCustomerSubscriptionRequest,\n ): Promise<MintCustomerSubscriptionResponse> {\n return this.http.post('/subscription/customer/mint', request);\n }\n}\n","/**\n * Faucet Sub-Client\n *\n * Public bootstrap surface for dispensing testnet HSUITE (HST) to a recipient\n * address via a challenge/response signature flow.\n */\n\nimport { type HttpClient } from '../http';\n\n/**\n * Challenge envelope returned by `POST /faucet/hsuite/challenge`.\n *\n * The caller signs `message` with the key controlling `recipientAddress` and\n * echoes the `challengeId` back on the dispense call.\n */\nexport type FaucetChallenge = {\n /** Opaque challenge identifier; echo on the dispense call. */\n challengeId: string;\n /** The exact string to sign with the recipient's key. */\n message: string;\n /** Seconds until the challenge expires and must be re-requested. */\n expiresInSeconds: number;\n};\n\n/**\n * Request body for `POST /faucet/hsuite`.\n */\nexport type FaucetDispenseRequest = {\n /** Chain the recipient address lives on (e.g. `'xrpl'`). */\n chain: string;\n /** Address to receive the dispensed HST. */\n recipientAddress: string;\n /** `challengeId` from the prior {@link FaucetChallenge}. */\n challengeId: string;\n /** Signature over the challenge `message`, hex-encoded. */\n signature: string;\n /** Public key (hex) that produced `signature`; optional when derivable. */\n publicKey?: string;\n};\n\n/**\n * Successful dispense — HST was sent on-chain.\n */\nexport type FaucetDispensed = {\n status: 'dispensed';\n /** Amount of HST dispensed. */\n amount: string;\n /** On-chain transaction hash of the dispense. */\n txHash: string;\n /** Remaining HST the recipient may still claim today. */\n remainingDailyAllowance: string;\n};\n\n/**\n * The recipient must establish a trust line for the HST issued-currency\n * before it can receive any. Set the returned trust line, then re-dispense\n * with a fresh challenge.\n */\nexport type FaucetTrustlineRequired = {\n status: 'trustline_required';\n /** Trust line the recipient must set before re-dispensing. */\n trustLine: {\n /** Issued-currency code (e.g. `'HST'`). */\n currency: string;\n /** Issuer address of the currency. */\n issuer: string;\n /** Trust line limit to set. */\n limit: string;\n };\n};\n\n/**\n * The recipient hit the daily rate limit; retry after the given delay.\n */\nexport type FaucetRateLimited = {\n status: 'rate_limited';\n /** Seconds to wait before the next dispense attempt is allowed. */\n retryAfterSeconds: number;\n};\n\n/**\n * Discriminated union over `status` returned by `POST /faucet/hsuite`.\n */\nexport type FaucetDispenseResult =\n | FaucetDispensed\n | FaucetTrustlineRequired\n | FaucetRateLimited;\n\n/**\n * Response shape for `GET /faucet/hsuite/status`.\n */\nexport type FaucetStatusResponse = {\n /** HST already dispensed to the recipient today. */\n dispensedToday: string;\n /** Forward-compatible: server may add allowance/reset fields. */\n [key: string]: unknown;\n};\n\n/**\n * Faucet Sub-Client\n *\n * Dispenses testnet HSUITE (HST) through a Web3-style challenge/response.\n * These are `@Public` bootstrap routes — no bearer token is required (a token\n * on the shared HTTP client is harmless).\n *\n * Lifecycle:\n * 1. {@link FaucetClient.requestChallenge} — get a {@link FaucetChallenge}.\n * 2. Sign `challenge.message` with the key controlling `recipientAddress`.\n * 3. {@link FaucetClient.dispense} — submit `{challengeId, signature, publicKey?}`.\n * 4. If the result is `status: 'trustline_required'`, the signer MUST set the\n * returned `trustLine` on `recipientAddress`, then request a NEW challenge\n * and re-dispense (the consumed challenge can't be reused).\n * 5. If the result is `status: 'rate_limited'`, wait `retryAfterSeconds` and retry.\n * 6. On `status: 'dispensed'`, the HST `txHash` confirms the on-chain transfer.\n *\n * @example\n * ```typescript\n * const challenge = await faucet.requestChallenge('xrpl', wallet.address);\n * const signature = await sign(challenge.message);\n * let result = await faucet.dispense({\n * chain: 'xrpl',\n * recipientAddress: wallet.address,\n * challengeId: challenge.challengeId,\n * signature,\n * publicKey: wallet.publicKey,\n * });\n * if (result.status === 'trustline_required') {\n * await setTrustLine(result.trustLine); // set on recipientAddress, then retry\n * }\n * ```\n */\nexport class FaucetClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Request a signing challenge for a recipient address. The returned\n * `message` must be signed by the key controlling `recipientAddress`.\n */\n async requestChallenge(\n chain: string,\n recipientAddress: string,\n ): Promise<FaucetChallenge> {\n return this.http.post('/faucet/hsuite/challenge', { chain, recipientAddress });\n }\n\n /**\n * Submit a signed challenge to dispense HST. The result is a discriminated\n * union on `status` — branch on `'dispensed' | 'trustline_required' |\n * 'rate_limited'`. On `'trustline_required'`, set the returned trust line on\n * the recipient and re-dispense with a fresh challenge.\n */\n async dispense(req: FaucetDispenseRequest): Promise<FaucetDispenseResult> {\n return this.http.post('/faucet/hsuite', req);\n }\n\n /**\n * Get today's dispense status for a recipient (e.g. amount already\n * dispensed today).\n */\n async getStatus(\n chain: string,\n recipientAddress: string,\n ): Promise<FaucetStatusResponse> {\n const params = new URLSearchParams();\n params.append('chain', chain);\n params.append('recipientAddress', recipientAddress);\n return this.http.get(`/faucet/hsuite/status?${params.toString()}`);\n }\n}\n","/**\n * TSS (Threshold Signature Scheme) Sub-Client\n *\n * Provides access to TSS/MPC operations for multi-sig entity management.\n * All operations are chain-agnostic — pass `chain` as a parameter.\n */\nimport type {\n EntityCreationOptions,\n EntityCreationResponse,\n ReshareRequest,\n ReshareResponse,\n EntityDetails,\n MPCSigningRequest,\n MPCSigningResponse,\n ValidatorListResponse,\n TSSStats,\n EntityListResponse,\n TSSHealthResponse,\n CeremonyListResponse,\n MultiSigStatusResponse,\n TssJobAccepted,\n TssJobResponse,\n SignForAppRequest,\n SignForAppResponse,\n} from './types';\nimport { encodePathParam, type HttpClient } from '../http';\n\nexport * from './types';\n\n/**\n * TSS Sub-Client\n *\n * Manages Threshold Signature Scheme operations including:\n * - Multi-sig entity creation (chain-agnostic)\n * - Key resharing for membership changes\n * - MPC transaction signing for any supported chain\n * - DKG ceremony monitoring\n *\n * @example\n * ```typescript\n * // Sign a transaction on any chain\n * const result = await client.tss.signMPC({\n * chain: 'hedera',\n * entityId: 'entity-123',\n * transactionBytes: '0x...',\n * });\n * ```\n */\nexport class TSSClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a multi-sig entity via a synchronous DKG ceremony.\n *\n * @param options Entity-creation parameters (chain, threshold, participants).\n * @returns The created entity's identity (ids + group public keys).\n */\n async createEntity(options: EntityCreationOptions): Promise<EntityCreationResponse> {\n return this.http.post('/tss/entity/create', options);\n }\n\n /**\n * Reshare keys when cluster membership changes. Redistributes secret shares\n * WITHOUT changing public keys.\n *\n * @param request The new membership / threshold to reshare to.\n * @returns The reshare outcome.\n */\n async reshareCluster(request: ReshareRequest): Promise<ReshareResponse> {\n return this.http.post('/tss/cluster/reshare', request);\n }\n\n /**\n * Get entity details by id.\n *\n * @param entityId The entity id to look up.\n * @returns The entity's details.\n */\n async getEntity(entityId: string): Promise<EntityDetails> {\n return this.http.get(`/tss/entity/${encodePathParam(entityId)}`);\n }\n\n /**\n * Sign a transaction using MPC.\n *\n * Routes to `POST /api/v3/tss/hedera/sign-mpc`. Only `'hedera'` is wired\n * server-side; other chain signing paths run via their own controllers (XRPL\n * multisig, Polkadot MPC) and are not exposed through this sub-client. The\n * `chain` field is carried into the request body so the validator can log +\n * route, but any non-`'hedera'` value will 404.\n *\n * @param request The MPC signing request; `chain` is forced to `'hedera'`.\n * @returns The MPC signing result.\n */\n async signMPC(\n request: MPCSigningRequest & { chain?: 'hedera' },\n ): Promise<MPCSigningResponse> {\n const chain = 'hedera' as const;\n return this.http.post(`/tss/${chain}/sign-mpc`, { ...request, chain });\n }\n\n /**\n * Get known validators and their public keys.\n *\n * @returns The validator list with public keys.\n */\n async getValidators(): Promise<ValidatorListResponse> {\n return this.http.get('/tss/validators');\n }\n\n /**\n * Force announcement of this node's public key.\n *\n * @returns Whether the announcement was accepted, plus a status message.\n */\n async announceKey(): Promise<{ success: boolean; message: string }> {\n return this.http.post('/tss/announce', {});\n }\n\n /**\n * Get TSS statistics.\n *\n * @returns Aggregate TSS statistics.\n */\n async getStats(): Promise<TSSStats> {\n return this.http.get('/tss/stats');\n }\n\n /**\n * List all TSS entities.\n *\n * @returns The full entity list.\n */\n async listEntities(): Promise<EntityListResponse> {\n return this.http.get('/tss/entities');\n }\n\n /**\n * TSS health check.\n *\n * @returns The TSS subsystem health report.\n */\n async getHealth(): Promise<TSSHealthResponse> {\n return this.http.get('/tss/health');\n }\n\n /**\n * List DKG ceremonies and their statistics.\n *\n * @returns The ceremony list.\n */\n async listCeremonies(): Promise<CeremonyListResponse> {\n return this.http.get('/tss/multisig/ceremonies');\n }\n\n /**\n * Get multi-sig transaction status by transaction id.\n *\n * @param txId The multi-sig transaction id.\n * @returns The current status of that transaction.\n */\n async getMultiSigStatus(txId: string): Promise<MultiSigStatusResponse> {\n return this.http.get(`/tss/multisig/transactions/${encodePathParam(txId)}`);\n }\n\n /**\n * Async-job variant of {@link createEntity}.\n *\n * Server returns 202 + `{ jobId, statusUrl, status: 'pending' }` immediately;\n * the DKG ceremony runs in the background. Poll {@link getJob} until the\n * status reaches `'success'` or `'failed'`.\n *\n * @param options Entity-creation parameters.\n * @returns A job descriptor (`jobId`, `statusUrl`, initial status).\n */\n async createEntityAsync(options: EntityCreationOptions): Promise<TssJobAccepted> {\n return this.http.post('/tss/entity/create/async', options);\n }\n\n /**\n * Async-job variant of {@link reshareCluster}. Returns 202 + a polling\n * descriptor; resharing runs in the background.\n *\n * @param request The new membership / threshold to reshare to.\n * @returns A job descriptor to poll via {@link getJob}.\n */\n async reshareClusterAsync(request: ReshareRequest): Promise<TssJobAccepted> {\n return this.http.post('/tss/cluster/reshare/async', request);\n }\n\n /**\n * Poll the status of an async TSS-ceremony job kicked off via\n * {@link createEntityAsync} or {@link reshareClusterAsync}.\n *\n * @param jobId The job id returned by the async kickoff call.\n * @returns The job's current status (and result once terminal).\n */\n async getJob(jobId: string): Promise<TssJobResponse> {\n return this.http.get(`/tss/jobs/${encodePathParam(jobId)}`);\n }\n\n /**\n * Sign a hex payload as smart-app entity `appId` via the cluster's TSS\n * quorum. Used by smart-deployer for per-entity BLS12-381 signatures over\n * deployment-context payloads (trustless APP_TOKEN replacement).\n *\n * Payload constraints (enforced server-side):\n * - even-length lowercase hex\n * - ≥32 bytes, ≤8KB\n *\n * @param appId The smart-app entity id to sign as.\n * @param request The hex payload to sign.\n * @returns The aggregate signature over the payload.\n */\n async signForApp(appId: string, request: SignForAppRequest): Promise<SignForAppResponse> {\n return this.http.post(`/tss/entity/${encodePathParam(appId)}/sign`, request);\n }\n}\n","/**\n * IPFS Sub-Client\n *\n * Provides access to IPFS operations for decentralized file storage.\n *\n * @example\n * ```typescript\n * // Upload a file\n * const result = await client.ipfs.upload(fileBuffer, 'document.pdf');\n *\n * // Pin content\n * await client.ipfs.pin(result.cid);\n *\n * // Get file\n * const file = await client.ipfs.getFile(result.cid);\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n IpfsUploadResult,\n IpfsPinResult,\n IpfsFileMetadata,\n IpfsPinListResponse,\n IpfsStatusResponse,\n IpfsStorageUsageResponse,\n} from './types';\n\nexport * from './types';\n\n/**\n * IPFS Sub-Client\n *\n * Manages IPFS operations including:\n * - File upload and retrieval\n * - Content pinning and unpinning\n * - Metadata queries\n * - Storage usage monitoring\n */\nexport class IPFSClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Upload a file to IPFS\n *\n * @param file - File data as Blob or Buffer\n * @param filename - Name of the file\n * @param metadata - Optional metadata key-value pairs\n * @returns Upload result with CID\n */\n async upload(\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>\n ): Promise<IpfsUploadResult> {\n return this.http.upload('/ipfs/upload', file, filename, metadata);\n }\n\n /**\n * Pin content by CID to ensure it persists\n */\n async pin(cid: string): Promise<IpfsPinResult> {\n return this.http.post(`/ipfs/pin/${encodePathParam(cid)}`, {});\n }\n\n /**\n * Unpin content by CID\n */\n async unpin(cid: string): Promise<IpfsPinResult> {\n return this.http.delete(`/ipfs/unpin/${encodePathParam(cid)}`);\n }\n\n /**\n * Get a file by CID\n */\n async getFile(cid: string): Promise<any> {\n return this.http.get(`/ipfs/file/${encodePathParam(cid)}`);\n }\n\n /**\n * Get raw content by CID\n */\n async getContent(cid: string): Promise<any> {\n return this.http.get(`/ipfs/${encodePathParam(cid)}`);\n }\n\n /**\n * Get file metadata by CID\n */\n async getMetadata(cid: string): Promise<IpfsFileMetadata> {\n return this.http.get(`/ipfs/metadata/${encodePathParam(cid)}`);\n }\n\n /**\n * List all pinned content\n */\n async listPins(): Promise<IpfsPinListResponse> {\n return this.http.get('/ipfs/pins');\n }\n\n /**\n * Get IPFS node status\n */\n async getStatus(): Promise<IpfsStatusResponse> {\n return this.http.get('/ipfs/status');\n }\n\n /**\n * Get storage usage information\n */\n async getStorageUsage(): Promise<IpfsStorageUsageResponse> {\n return this.http.get('/ipfs/storage');\n }\n}\n","/**\n * Hedera TSS Sub-Client\n *\n * Server-side controller: the server\n * (route prefix `/api/v3/hedera/tss`).\n *\n * These endpoints are **TSS-signed immediate-execute** — the cluster signs AND\n * submits in one call, distinct from:\n * - `client.hedera.*` (prepare-only, the caller signs + submits)\n * - `client.tss.signMPC(...)` (signs an externally-built tx, doesn't submit)\n *\n * Mounted on the main client as `client.hedera.tss`.\n *\n * Wire format: every request goes to `/api/v3/hedera/tss/<op>`. The injected\n * `HttpClient` must be rooted at `${baseUrl}/api/v3` (the same one\n * `TSSClient`/`SubscriptionClient`/etc. use).\n */\n\nimport type { HttpClient } from '../http';\n\n/** Sovereignty security mode for TSS-controlled Hedera accounts. */\nexport type HederaTssSecurityMode = 'full' | 'partial';\n\n/** Common validator-binding fields required to anchor an op to on-chain rules. */\ntype ValidatorBoundRequest = {\n /** TSS entity id (already created via `client.tss.createEntity*`). */\n entityId: string;\n /** HCS timestamp of the rules message (`SECONDS.NANOS`). */\n validatorTimestamp: string;\n /** HCS topic that holds the rules message. */\n validatorTopicId: string;\n /** Payer for the on-chain fee. Validator operator pays when omitted. */\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-account` request body. */\nexport type CreateHederaAccountRequest = ValidatorBoundRequest & {\n /** Initial HBAR balance for the new account. */\n initialBalance?: number;\n /** Defaults to `full` server-side. `partial` requires `appOwnerPublicKey`. */\n securityMode?: HederaTssSecurityMode;\n /** Required when `securityMode === 'partial'`. */\n appOwnerPublicKey?: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-account` response body. */\nexport type CreateHederaAccountResponse = {\n success: boolean;\n accountId: string;\n transactionId: string;\n hashscanUrl: string;\n securityMode: HederaTssSecurityMode;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/** POST `/api/v3/hedera/tss/update-memo` request body. */\nexport type UpdateHederaMemoRequest = {\n entityId: string;\n accountId: string;\n newMemo: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/update-memo` response body. */\nexport type UpdateHederaMemoResponse = {\n success: boolean;\n transactionId: string;\n hashscanUrl: string;\n status: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-topic` request body. */\nexport type CreateHederaTopicRequest = ValidatorBoundRequest;\n\n/** POST `/api/v3/hedera/tss/create-topic` response body. */\nexport type CreateHederaTopicResponse = {\n success: boolean;\n topicId: string;\n transactionId: string;\n hashscanUrl: string;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/** POST `/api/v3/hedera/tss/submit-message` request body. */\nexport type SubmitHederaMessageRequest = {\n entityId: string;\n topicId: string;\n message: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/submit-message` response body. */\nexport type SubmitHederaMessageResponse = {\n success: boolean;\n sequenceNumber: string | number;\n transactionId: string;\n hashscanUrl: string;\n};\n\n/** POST `/api/v3/hedera/tss/create-token` request body. */\nexport type CreateHederaTokenRequest = ValidatorBoundRequest & {\n name: string;\n symbol: string;\n decimals: number;\n initialSupply: number;\n maxSupply?: number;\n treasuryAccountId: string;\n enableAdminKey?: boolean;\n enableSupplyKey?: boolean;\n enableFreezeKey?: boolean;\n enablePauseKey?: boolean;\n enableWipeKey?: boolean;\n};\n\n/** POST `/api/v3/hedera/tss/create-token` response body. */\nexport type CreateHederaTokenResponse = {\n success: boolean;\n tokenId: string;\n transactionId: string;\n hashscanUrl: string;\n tokenUrl: string;\n keys: Record<string, string>;\n validatorBinding: {\n timestamp: string;\n topicId: string;\n memo: string;\n rulesUrl: string;\n };\n};\n\n/**\n * POST `/api/v3/hedera/tss/mint-token` request body.\n *\n * `validatorTopicId` is OPTIONAL here (unlike the create-* ops) — when\n * supplied + the validator has TokenValidationService wired, the cluster\n * enforces the rules-message mint policy. When omitted, mint runs unchecked.\n */\nexport type MintHederaTokenRequest = {\n entityId: string;\n tokenId: string;\n amount: number;\n decimals?: number;\n validatorTopicId?: string;\n payerAccountId?: string;\n};\n\n/** POST `/api/v3/hedera/tss/mint-token` response body. */\nexport type MintHederaTokenResponse = {\n success: boolean;\n transactionId: string;\n hashscanUrl: string;\n newTotalSupply: string;\n mintedAmount: string | number;\n tokenId: string;\n decimals: number;\n};\n\n/**\n * Hedera TSS sub-client — immediate-execute paths where the cluster's TSS\n * quorum signs AND submits the transaction in one HTTP call.\n *\n * Distinct from `client.hedera` (prepare-only) and from\n * `client.tss.signMPC(...)` (sign-only, no submission).\n *\n * @example Mint an HTS token created by the TSS cluster\n * ```ts\n * const minted = await client.hedera.tss.mintToken({\n * entityId: 'tss-entity-1',\n * validatorTimestamp: '1700000000.000000001',\n * validatorTopicId: '0.0.98765',\n * tokenId: '0.0.123456',\n * amount: '1000',\n * });\n * console.log(`Minted tx ${minted.transactionId}, new supply ${minted.newTotalSupply}`);\n * ```\n */\nexport class HederaTssClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a Hedera account whose keys are controlled by the TSS cluster. */\n async createAccount(request: CreateHederaAccountRequest): Promise<CreateHederaAccountResponse> {\n return this.http.post('/hedera/tss/create-account', request);\n }\n\n /** Update an existing account's memo via TSS-signed transaction. */\n async updateMemo(request: UpdateHederaMemoRequest): Promise<UpdateHederaMemoResponse> {\n return this.http.post('/hedera/tss/update-memo', request);\n }\n\n /** Create a TSS-controlled HCS topic. */\n async createTopic(request: CreateHederaTopicRequest): Promise<CreateHederaTopicResponse> {\n return this.http.post('/hedera/tss/create-topic', request);\n }\n\n /** Submit a message to an HCS topic via TSS signing. */\n async submitMessage(request: SubmitHederaMessageRequest): Promise<SubmitHederaMessageResponse> {\n return this.http.post('/hedera/tss/submit-message', request);\n }\n\n /** Create an HTS token with TSS-controlled admin/supply/freeze/pause/wipe keys. */\n async createToken(request: CreateHederaTokenRequest): Promise<CreateHederaTokenResponse> {\n return this.http.post('/hedera/tss/create-token', request);\n }\n\n /** Mint tokens via TSS signing — optionally rule-validated via `validatorTopicId`. */\n async mintToken(request: MintHederaTokenRequest): Promise<MintHederaTokenResponse> {\n return this.http.post('/hedera/tss/mint-token', request);\n }\n}\n","/**\n * Hedera-Specific Transaction Preparation Sub-Client\n *\n * Hedera-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.hedera.*`\n *\n * Operations exposed here:\n * - HCS topic create + topic message (Hedera Consensus Service — no analog on\n * other chains. Most app developers will not need these.)\n * - HTS compliance enable/disable (KYC grant/revoke — server hard-dispatches\n * to the Hedera capability; even though the request schema accepts other\n * chains, the handler always treats it as Hedera).\n * - HTS wipe (force-remove tokens from an account — Hedera-only by schema).\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, etc.), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\nimport { HederaTssClient } from '../../hedera-tss';\n\n/** Topic creation preparation request (Hedera HCS only). */\nexport type PrepareTopicCreateRequest = {\n payerAccountId?: string;\n memo?: string;\n adminKeyRequired?: boolean;\n submitKeyRequired?: boolean;\n entityId: string;\n};\n\n/** Topic message preparation request (Hedera HCS only). */\nexport type PrepareTopicMessageRequest = {\n payerAccountId?: string;\n topicId: string;\n message: string | Record<string, unknown>;\n entityId: string;\n};\n\n/** Token compliance-enable (grant KYC) — Hedera-only by handler dispatch. */\nexport type PrepareTokenComplianceEnableRequest = {\n payerAccountId?: string;\n tokenId: string;\n accountId: string;\n entityId: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n memo?: string;\n};\n\n/** Token compliance-disable (revoke KYC) — Hedera-only by handler dispatch. */\nexport type PrepareTokenComplianceDisableRequest = PrepareTokenComplianceEnableRequest;\n\n/** Token wipe — Hedera-only (literal schema). Force-removes tokens from an account. */\nexport type PrepareTokenWipeRequest = {\n payerAccountId?: string;\n tokenId: string;\n accountId: string;\n amount: string;\n entityId: string;\n memo?: string;\n};\n\n/**\n * Hedera-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'hedera'` before\n * POSTing — callers never write the chain literal themselves.\n *\n * Nested sub-client:\n * - `client.hedera.tss` — TSS-signed immediate-execute paths\n * (HCS topic + HTS token, account create + memo update, all submitted by\n * the cluster in one round-trip). Routes under `/api/v3/hedera/tss/*` —\n * distinct base path from the prepare-only routes on this class.\n */\nexport class HederaTransactionsClient {\n /**\n * TSS-signed Hedera operations (`/api/v3/hedera/tss/*`).\n *\n * Distinct from the prepare-only routes on this class:\n * - `client.hedera.prepareTopicCreate(...)` returns bytes for local sign+submit.\n * - `client.hedera.tss.createTopic(...)` makes the cluster sign+submit in one call.\n *\n * `tssHttp` is the validator's `/api/v3`-rooted HTTP client (different from\n * the `/api/v3/transactions` one this class uses for prepare paths). Both\n * clients are required — the previous single-arg fallback to `http` was\n * unreachable through `SmartEngineClient` (the only call site always\n * passes both).\n */\n public readonly tss: HederaTssClient;\n\n constructor(private readonly http: HttpClient, tssHttp: HttpClient) {\n this.tss = new HederaTssClient(tssHttp);\n }\n\n /** Prepare an HCS topic creation transaction. */\n async prepareTopicCreate(request: PrepareTopicCreateRequest): Promise<PreparedTransaction> {\n return this.http.post('/topic/create/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare an HCS topic message submission. */\n async prepareTopicMessage(request: PrepareTopicMessageRequest): Promise<PreparedTransaction> {\n return this.http.post('/topic/message/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token compliance-enable (KYC grant) transaction. */\n async prepareTokenComplianceEnable(\n request: PrepareTokenComplianceEnableRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/compliance/enable/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token compliance-disable (KYC revoke) transaction. */\n async prepareTokenComplianceDisable(\n request: PrepareTokenComplianceDisableRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/compliance/disable/prepare', { ...request, chain: 'hedera' });\n }\n\n /** Prepare a token wipe transaction (force-remove tokens from an account). */\n async prepareTokenWipe(request: PrepareTokenWipeRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/wipe/prepare', { ...request, chain: 'hedera' });\n }\n}\n","/**\n * XRPL-Specific Transaction Preparation Sub-Client\n *\n * XRPL-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.xrpl.*`\n *\n * Operations exposed here:\n * - Trust line setup (XRPL TrustSet — XRPL's account-to-issuer authorization\n * for an issued currency. The chain-agnostic analog `associateToken` does\n * not yet exist on the validator; once added, callers should prefer that.)\n *\n * For multi-chain operations (transfer, mint, burn, NFT ops), use the\n * chain-agnostic top-level `client.transactions.*` or top-level `client.*`\n * methods with `chain: 'xrpl'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Trust line preparation request (XRPL TrustSet). */\nexport type PrepareTrustLineRequest = {\n /**\n * XRPL account authorising the trust line. Falls back to `payerAccountId`\n * and ultimately the authenticated session wallet.\n */\n accountAddress?: string;\n payerAccountId?: string;\n /** ISO-4217-like currency code (e.g. \"USD\") or 40-char hex. */\n currency: string;\n /** Classic-address of the issuer. */\n issuerAddress: string;\n /** Decimal-string trust-line limit. Defaults to validator policy when omitted. */\n limit?: string;\n entityId: string;\n};\n\n/**\n * XRPL account-setup preparation request (SignerList + DisableMaster).\n *\n * Builds the ordered transaction set required to flip an XRPL account into\n * sovereignty mode: install the validator-derived SignerList, then disable\n * the master key. Two-step response — caller signs + submits in order.\n *\n * Server schema (the server):\n * - `accountAddress` 25–34 chars (XRPL classic address).\n * - `validatorTimestamp` + `validatorTopicId` required for rule anchoring.\n * - `securityMode='partial'` requires `appOwnerPublicKey` + `entityId`.\n */\nexport type PrepareXrplAccountSetupRequest = {\n payerAccountId?: string;\n /** XRPL classic address whose authorization we're configuring. */\n accountAddress: string;\n validatorTimestamp: string;\n validatorTopicId: string;\n /** Sovereignty mode — `partial` requires `appOwnerPublicKey`. */\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n /** Required in `partial`/`full` modes to identify the TSS entity. */\n entityId?: string;\n};\n\n/**\n * Sovereignty descriptor attached to a prepared XRPL account-setup response.\n * Field shape mirrors the server's `PreparedTransactionSovereignty`.\n */\nexport type PreparedTransactionSovereignty = {\n mode: SecurityMode | 'none';\n appOwnerPublicKey?: string;\n signerListEntries?: Array<{ account: string; weight: number }>;\n signerQuorum?: number;\n};\n\n/**\n * Two-step response from `POST /xrpl/account-setup/prepare`. The caller must\n * sign + submit each step in order — step 0 installs the SignerList, step 1\n * disables the master key.\n */\nexport type XrplAccountSetupSteps = {\n steps: Array<{\n step: number;\n description?: string;\n transactionBytes: string;\n transactionId?: string;\n [k: string]: unknown;\n }>;\n sovereignty: PreparedTransactionSovereignty;\n};\n\n/**\n * XRPL-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'xrpl'` before\n * POSTing — callers never write the chain literal themselves.\n */\nexport class XrplTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare an XRPL TrustSet (trust line) transaction. */\n async prepareTrustLine(request: PrepareTrustLineRequest): Promise<PreparedTransaction> {\n return this.http.post('/trustline/prepare', { ...request, chain: 'xrpl' });\n }\n\n /**\n * Prepare the ordered XRPL account-setup transaction set\n * (SignerListSet + AccountSet DisableMaster) for sovereignty mode.\n *\n * Returns `{ steps, sovereignty }`. Caller signs + submits each step in\n * order; the master key remains usable until the final AccountSet lands.\n */\n async prepareAccountSetup(\n request: PrepareXrplAccountSetupRequest,\n ): Promise<XrplAccountSetupSteps> {\n return this.http.post('/xrpl/account-setup/prepare', { ...request, chain: 'xrpl' });\n }\n}\n","/**\n * Solana-Specific Transaction Preparation Sub-Client\n *\n * Solana-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.solana.*`\n *\n * Operations exposed here:\n * - Token close-account (SPL Token CloseAccount — closes an empty ATA and\n * recovers the SOL rent. No analog on Hedera/XRPL/Polkadot/Cardano.)\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, NFT ops), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods with `chain: 'solana'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Token close-account preparation request (Solana SPL Token). */\nexport type PrepareTokenCloseAccountRequest = {\n payerAccountId?: string;\n /** ATA address to close. Must have zero token balance. */\n account: string;\n /** Recipient of recovered SOL rent lamports. */\n destination: string;\n /** ATA owner — required when not using TSS multisig; vault PDA used for partial/full. */\n owner?: string;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n memo?: string;\n};\n\n/**\n * Solana-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'solana'` before\n * POSTing — callers never write the chain literal themselves.\n */\nexport class SolanaTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare an SPL Token close-account transaction. */\n async prepareTokenCloseAccount(\n request: PrepareTokenCloseAccountRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/close-account/prepare', { ...request, chain: 'solana' });\n }\n}\n","/**\n * Polkadot-Specific Transaction Preparation Sub-Client\n *\n * Polkadot Asset Hub-only escape hatches that have no multi-chain analog.\n *\n * Available via: `client.polkadot.*`\n *\n * Operations exposed here:\n * - assets.setTeam — transfer issuer/admin/freezer roles of a pallet-assets\n * asset to new SS58 addresses. No analog on Hedera/XRPL.\n * - assets.setMetadata — update on-chain name/symbol/decimals of a pallet-\n * assets asset post-creation.\n *\n * For multi-chain operations (createToken, transfer, mint, burn, pause,\n * restrict, NFT ops), use the chain-agnostic top-level `client.transactions.*`\n * or top-level `client.*` methods with `chain: 'polkadot'`.\n */\n\nimport type { HttpClient } from '../../http';\nimport type { PreparedTransaction, SecurityMode } from '../types';\n\n/** Asset setTeam preparation request (Polkadot Asset Hub). */\nexport type PrepareAssetSetTeamRequest = {\n payerAccountId?: string;\n /** pallet-assets asset id (u32). */\n assetId: number;\n /** SS58 address — new issuer. */\n issuer: string;\n /** SS58 address — new admin. */\n admin: string;\n /** SS58 address — new freezer. */\n freezer: string;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n ss58Format?: number;\n};\n\n/** Asset setMetadata preparation request (Polkadot Asset Hub). */\nexport type PrepareAssetSetMetadataRequest = {\n payerAccountId?: string;\n /** pallet-assets asset id (u32). */\n assetId: number;\n /** Human-readable asset name (max 64 chars). */\n name: string;\n /** Asset symbol (max 16 chars). */\n symbol: string;\n /** Decimal precision (0..18). */\n decimals: number;\n entityId?: string;\n securityMode?: SecurityMode;\n appOwnerPublicKey?: string;\n ss58Format?: number;\n};\n\n/**\n * Polkadot-specific transaction preparation sub-client.\n *\n * Wire format: every request body is augmented with `chain: 'polkadot'`\n * before POSTing — callers never write the chain literal themselves.\n */\nexport class PolkadotTransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Prepare a pallet-assets.setTeam transaction. */\n async prepareAssetSetTeam(request: PrepareAssetSetTeamRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/set-team/prepare', { ...request, chain: 'polkadot' });\n }\n\n /** Prepare a pallet-assets.setMetadata transaction. */\n async prepareAssetSetMetadata(\n request: PrepareAssetSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/set-metadata/prepare', { ...request, chain: 'polkadot' });\n }\n}\n","/**\n * Transactions Sub-Client — Chain-Agnostic\n *\n * Provides transaction preparation for the sovereignty model:\n * transactions are prepared on the validator but signed locally by the user.\n *\n * **Every method here accepts the `ChainType` union — never a chain literal.**\n * Chain-specific escape hatches (Hedera HCS topics, XRPL trust lines, Solana\n * close-account, Polkadot setTeam/setMetadata) are exposed via namespaced\n * sub-clients on the main client: `client.hedera`, `client.xrpl`,\n * `client.solana`, `client.polkadot`.\n *\n * @example\n * ```typescript\n * // Multi-chain transfer\n * const prepared = await client.transactions.prepareTransfer({\n * chain: 'xrpl',\n * from: 'rXXX',\n * to: 'rYYY',\n * amount: '100',\n * });\n *\n * // Multi-chain token mint\n * const prepared = await client.transactions.prepareTokenMint({\n * chain: 'solana',\n * tokenId: '<mint-pubkey>',\n * amount: '1000',\n * });\n * ```\n */\n\nimport type { HttpClient } from '../http';\nimport type {\n PreparedTransaction,\n PrepareTransferRequest,\n PrepareNftMintRequest,\n PrepareNftBurnRequest,\n PrepareNftTransferRequest,\n PrepareNftCollectionCreateRequest,\n PrepareNftSetMetadataRequest,\n PrepareNftCollectionSetMetadataRequest,\n PrepareNftCollectionLockRequest,\n PrepareTokenCreateRequest,\n PrepareTokenMintRequest,\n PrepareTokenBurnRequest,\n PrepareTokenAssociateRequest,\n PrepareTokenPauseRequest,\n PrepareTokenUnpauseRequest,\n PrepareTokenRestrictRequest,\n PrepareTokenUnrestrictRequest,\n TransactionInfoResponse,\n} from './types';\n\nexport * from './types';\nexport * from './chains';\n\n/**\n * Chain-agnostic transactions sub-client.\n *\n * NOTE: This client targets `/api/v3/transactions`.\n * The injected `HttpClient` must be configured with that base URL.\n */\nexport class TransactionsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Get transaction preparation service info. */\n async getInfo(): Promise<TransactionInfoResponse> {\n return this.http.get('/info');\n }\n\n /** Prepare a transfer transaction (any supported chain). */\n async prepareTransfer(request: PrepareTransferRequest): Promise<PreparedTransaction> {\n return this.http.post('/transfer/prepare', request);\n }\n\n /** Prepare an NFT mint transaction (any supported chain). */\n async prepareNftMint(request: PrepareNftMintRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/mint/prepare', request);\n }\n\n /** Prepare an NFT burn transaction (any supported chain). */\n async prepareNftBurn(request: PrepareNftBurnRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/burn/prepare', request);\n }\n\n /** Prepare an NFT transfer transaction (any supported chain). */\n async prepareNftTransfer(request: PrepareNftTransferRequest): Promise<PreparedTransaction> {\n return this.http.post('/nft/transfer/prepare', request);\n }\n\n /**\n * Prepare an NFT collection-create transaction (Polkadot pallet-nfts /\n * Solana Metaplex master-edition).\n */\n async prepareNftCollectionCreate(\n request: PrepareNftCollectionCreateRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/create/prepare', request);\n }\n\n /** Prepare an NFT item set-metadata transaction (Polkadot pallet-nfts/uniques). */\n async prepareNftSetMetadata(\n request: PrepareNftSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/set-metadata/prepare', request);\n }\n\n /** Prepare an NFT collection set-metadata transaction (Polkadot pallet-nfts/uniques). */\n async prepareNftCollectionSetMetadata(\n request: PrepareNftCollectionSetMetadataRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/set-metadata/prepare', request);\n }\n\n /**\n * Prepare an NFT collection-lock transaction (Polkadot pallet-nfts only).\n * Asset Hub runtimes on pallet-uniques fallback will reject with a 4xx.\n */\n async prepareNftCollectionLock(\n request: PrepareNftCollectionLockRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/nft/collection/lock/prepare', request);\n }\n\n /** Prepare a token creation transaction (Hedera, Solana, Polkadot, Cardano). */\n async prepareTokenCreate(request: PrepareTokenCreateRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/create/prepare', request);\n }\n\n /** Prepare a token mint transaction (any supported chain). */\n async prepareTokenMint(request: PrepareTokenMintRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/mint/prepare', request);\n }\n\n /**\n * Prepare a fungible token burn transaction (Hedera, Solana, Polkadot,\n * Cardano). For NFT burn use `prepareNftBurn` with a `serialNumber`.\n */\n async prepareTokenBurn(request: PrepareTokenBurnRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/burn/prepare', request);\n }\n\n /**\n * Prepare a token association transaction (Hedera HTS associate / Solana\n * ATA create). On chains that don't need explicit association (XRPL uses\n * trustlines — see `client.xrpl.prepareTrustLine`), the server returns 400.\n */\n async prepareTokenAssociate(\n request: PrepareTokenAssociateRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/associate/prepare', request);\n }\n\n /** Prepare a token pause transaction (Hedera, Polkadot, Solana). */\n async prepareTokenPause(request: PrepareTokenPauseRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/pause/prepare', request);\n }\n\n /** Prepare a token unpause transaction (Hedera, Polkadot, Solana). */\n async prepareTokenUnpause(request: PrepareTokenUnpauseRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/unpause/prepare', request);\n }\n\n /**\n * Prepare a token restrict (freeze account) transaction (Hedera, Polkadot,\n * Solana). Freezes `accountId`/`who`/`account` from transacting the token.\n */\n async prepareTokenRestrict(request: PrepareTokenRestrictRequest): Promise<PreparedTransaction> {\n return this.http.post('/token/restrict/prepare', request);\n }\n\n /** Prepare a token unrestrict (unfreeze account) transaction. */\n async prepareTokenUnrestrict(\n request: PrepareTokenUnrestrictRequest,\n ): Promise<PreparedTransaction> {\n return this.http.post('/token/unrestrict/prepare', request);\n }\n}\n","/**\n * Snapshots Sub-Client\n *\n * Provides token holder snapshot generation and retrieval.\n *\n * @example\n * ```typescript\n * // Generate a snapshot\n * const { snapshotId } = await client.snapshots.generate('0.0.12345');\n *\n * // Check status\n * const info = await client.snapshots.get(snapshotId);\n *\n * // Download when ready\n * const data = await client.snapshots.download(snapshotId, 'csv');\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n SnapshotInfo,\n SnapshotGenerateOptions,\n SnapshotGenerateResponse,\n SnapshotListResponse,\n SnapshotFormat,\n PaginationOptions,\n} from './types';\n\nexport * from './types';\n\n/**\n * Snapshots Sub-Client\n *\n * Manages token holder snapshots:\n * - Generate point-in-time snapshots of token holders\n * - Query snapshot status and metadata\n * - Download snapshot data in JSON or CSV\n */\nexport class SnapshotsClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate a new snapshot for a token\n *\n * @param tokenId - Token identifier\n * @param options - Generation options (format, filters)\n */\n async generate(\n tokenId: string,\n options?: SnapshotGenerateOptions\n ): Promise<SnapshotGenerateResponse> {\n return this.http.post(\n `/snapshots/generate/${encodePathParam(tokenId)}`,\n options || {}\n );\n }\n\n /**\n * Get snapshot details by ID\n */\n async get(snapshotId: string): Promise<SnapshotInfo> {\n return this.http.get(`/snapshots/${encodePathParam(snapshotId)}`);\n }\n\n /**\n * List snapshots for a token\n */\n async listByToken(\n tokenId: string,\n pagination?: PaginationOptions\n ): Promise<SnapshotListResponse> {\n const params = new URLSearchParams();\n if (pagination?.page !== undefined) params.set('page', String(pagination.page));\n if (pagination?.limit !== undefined) params.set('limit', String(pagination.limit));\n const qs = params.toString();\n return this.http.get(\n `/snapshots/token/${encodePathParam(tokenId)}${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Download snapshot data\n *\n * @param snapshotId - Snapshot ID\n * @param format - Output format (json or csv)\n */\n async download(snapshotId: string, format?: SnapshotFormat): Promise<any> {\n const params = format ? `?format=${encodeURIComponent(format)}` : '';\n return this.http.get(\n `/snapshots/${encodePathParam(snapshotId)}/download${params}`\n );\n }\n}\n","/**\n * HistoricalBalanceClient — thin HTTP wrapper around\n * `POST /api/v3/historical-balance/query`.\n *\n * Two construction modes:\n * 1. **Standalone (CLI):** `new HistoricalBalanceClient({ baseUrl, ... })`.\n * The client builds its own `fetch` URL + headers + timeout.\n * 2. **As a sub-client of `SmartEngineClient`:** the parent passes its\n * shared `HttpClient` via the static `HistoricalBalanceClient.fromHttp`\n * factory so that auth, timeouts, and base-URL resolution stay in one\n * place. See `client.ts`.\n *\n * Zero internal `@hsuite/*` imports — wire types are locally declared in\n * `./historical-balance-types` so the published SDK has no workspace\n * dependency.\n */\n\nimport type { HttpClient } from '../http';\nimport type {\n HistoricalBalanceClientConfig,\n HistoricalBalanceQueryParams,\n HistoricalBalanceResult,\n} from './historical-balance-types';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst ENDPOINT_PATH = '/api/v3/historical-balance/query';\n\n/**\n * Error thrown by `HistoricalBalanceClient` on non-2xx responses or transport\n * failures. Surfaces `statusCode` so callers can map specific codes (400 →\n * input error / unsupported chain, 502 → upstream archive issue) without\n * string-matching messages.\n */\nexport class HistoricalBalanceClientError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: unknown\n ) {\n super(message);\n this.name = 'HistoricalBalanceClientError';\n }\n}\n\nexport class HistoricalBalanceClient {\n // Standalone-mode fields (set when the client builds its own fetch).\n private readonly baseUrl?: string;\n private readonly authToken?: string;\n private readonly apiKey?: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl?: typeof fetch;\n\n // Sub-client-mode field (set when wired via SmartEngineClient).\n private readonly http?: HttpClient;\n\n constructor(config: HistoricalBalanceClientConfig | { http: HttpClient }) {\n if ('http' in config) {\n this.http = config.http;\n this.timeoutMs = DEFAULT_TIMEOUT_MS;\n return;\n }\n if (!config.baseUrl) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient: baseUrl is required for standalone construction',\n 400\n );\n }\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.authToken = config.authToken;\n this.apiKey = config.apiKey;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.fetchImpl = config.fetchImpl;\n }\n\n /**\n * Factory used by `SmartEngineClient` to wire this sub-client onto the\n * parent's shared `HttpClient` (which already carries auth + baseUrl + a\n * `/api/v3` prefix). Routes through `/historical-balance/query` since the\n * parent's HttpClient is rooted at `/api/v3`.\n */\n static fromHttp(http: HttpClient): HistoricalBalanceClient {\n return new HistoricalBalanceClient({ http });\n }\n\n /**\n * Query a point-in-time balance.\n *\n * The validator returns the on-chain bigint as a base-10 decimal string.\n * Callers needing arithmetic precision should wrap the result:\n *\n * ```ts\n * const { balance } = await client.historicalBalance.getBalance({ ... });\n * const value = BigInt(balance);\n * ```\n */\n async getBalance(params: HistoricalBalanceQueryParams): Promise<HistoricalBalanceResult> {\n this.validateParams(params);\n\n if (this.http) {\n // Sub-client mode: delegate to the shared HttpClient. The path is\n // relative because the parent client roots at `/api/v3`.\n return this.http.post<HistoricalBalanceResult>('/historical-balance/query', params);\n }\n return this.standaloneFetch(params);\n }\n\n private validateParams(params: HistoricalBalanceQueryParams): void {\n if (!params || typeof params !== 'object') {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: params object is required',\n 400\n );\n }\n const { chain, entityId, account, atTimestamp } = params;\n if (chain !== 'hedera' && chain !== 'xrpl' && chain !== 'polkadot') {\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient.getBalance: unsupported chain \"${String(chain)}\" (expected hedera | xrpl | polkadot)`,\n 400\n );\n }\n if (typeof entityId !== 'string' || entityId.length === 0) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: entityId must be a non-empty string',\n 400\n );\n }\n if (typeof account !== 'string' || account.length === 0) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: account must be a non-empty string',\n 400\n );\n }\n if (\n typeof atTimestamp !== 'number' ||\n !Number.isInteger(atTimestamp) ||\n atTimestamp <= 0\n ) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient.getBalance: atTimestamp must be a positive integer (unix seconds)',\n 400\n );\n }\n }\n\n private async standaloneFetch(\n params: HistoricalBalanceQueryParams\n ): Promise<HistoricalBalanceResult> {\n const url = `${this.baseUrl}${ENDPOINT_PATH}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n if (this.authToken) headers.Authorization = `Bearer ${this.authToken}`;\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n const fetchFn = this.fetchImpl ?? (typeof fetch !== 'undefined' ? fetch : undefined);\n if (!fetchFn) {\n throw new HistoricalBalanceClientError(\n 'HistoricalBalanceClient: no fetch implementation available (provide fetchImpl)',\n 500\n );\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetchFn(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(params),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const message = err instanceof Error ? err.message : String(err);\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: transport error: ${message}`,\n 0,\n err\n );\n }\n clearTimeout(timer);\n\n let body: unknown;\n const text = await response.text();\n if (text.length > 0) {\n try {\n body = JSON.parse(text);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: non-JSON response (status=${response.status}): ${message}`,\n response.status,\n { raw: text }\n );\n }\n }\n\n if (!response.ok) {\n const detail =\n body && typeof body === 'object' && 'message' in (body as any)\n ? String((body as any).message)\n : `HTTP ${response.status}`;\n throw new HistoricalBalanceClientError(\n `HistoricalBalanceClient: ${detail}`,\n response.status,\n body\n );\n }\n\n return body as HistoricalBalanceResult;\n }\n}\n","/**\n * Settlement Sub-Client\n *\n * Manages cross-chain settlement operations including initiation,\n * status tracking, XRP landing confirmation, and history retrieval.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\n\nexport type {\n SettlementPurpose,\n SettlementAsset,\n SettlementInitiateRequest,\n SettlementStatusResponse,\n SettlementHistoryEntry,\n} from './types';\n\nimport type {\n SettlementInitiateRequest,\n SettlementStatusResponse,\n SettlementHistoryEntry,\n} from './types';\n\nexport class SettlementClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a new settlement operation.\n * Submits source-chain payment details and begins the conversion pipeline.\n */\n async initiate(request: SettlementInitiateRequest): Promise<SettlementStatusResponse> {\n return this.http.post('/settlement/initiate', request);\n }\n\n /**\n * Get the current status of a settlement by ID.\n */\n async getStatus(settlementId: string): Promise<SettlementStatusResponse> {\n return this.http.get(`/settlement/${encodePathParam(settlementId)}/status`);\n }\n\n /**\n * Confirm that XRP has landed on the destination address.\n * Advances the settlement to the next processing step.\n */\n async confirmXrpLanded(settlementId: string): Promise<SettlementStatusResponse> {\n return this.http.post(`/settlement/${encodePathParam(settlementId)}/confirm-xrp`, {});\n }\n\n /**\n * Get settlement history for a given entity.\n */\n async getHistory(entityId: string): Promise<SettlementHistoryEntry[]> {\n return this.http.get(`/settlement/history/${encodePathParam(entityId)}`);\n }\n}\n","/**\n * Governance Sub-Client.\n *\n * Thin HTTP wrapper around `POST /api/v3/governance/simulate`. Lets\n * smart-app authors dry-run governance-rule validation against fixture data\n * without depending on the rules-engine package.\n *\n * Zero internal-lib coupling: types are declared locally in\n * `./governance-types`; the only runtime dependency is the SDK's own\n * `HttpClient` abstraction.\n */\nimport type { HttpClient } from '../http';\nimport type {\n GovernanceSimulateRequest,\n GovernanceValidationResult,\n} from './governance-types';\n\n/**\n * Governance Sub-Client.\n *\n * Exposed as `client.governance` on `SmartEngineClient`.\n *\n * @example\n * ```typescript\n * const result = await client.governance.simulate({\n * config: { governanceTokenId: '0.0.123', proposalThreshold: '100', votingPeriodMs: 604800000 },\n * context: { callerAccountId: '0.0.111', action: 'create_proposal', tokenBalance: '500' },\n * });\n * if (!result.isValid) {\n * console.error('proposal rejected:', result.reason);\n * }\n * ```\n */\nexport class GovernanceClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Dry-run a governance proposal/vote/etc. against `GovernanceMolecule.validate(...)`.\n *\n * Returns whatever `ValidationResult` the molecule produced. A `false`\n * `isValid` is **not** an error — it is a successful \"this proposal is\n * invalid\" outcome and is surfaced via the normal return value.\n *\n * HTTP errors (400 malformed body, 500 unexpected) bubble up as\n * `SdkHttpError` via the shared `HttpClient` layer.\n */\n async simulate(params: GovernanceSimulateRequest): Promise<GovernanceValidationResult> {\n return this.http.post<GovernanceValidationResult>('/governance/simulate', params);\n }\n}\n","/**\n * DAO Dashboard Sub-Client.\n *\n * Read-only rollups indexed by user wallet address — backs the smart-app\n * \"your governance\" home screen. Maps 1:1 to `dao.controller.ts`'s\n * `dashboard/*` route group.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n DaoActiveProposalForUser,\n DaoActivityEntry,\n DaoDashboardStats,\n DaoGovernanceImpact,\n DaoPendingAction,\n DaoVote,\n DashboardActivityOptions,\n DashboardListOptions,\n} from './types';\n\nfunction buildQuery(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, String(value));\n }\n const qs = search.toString();\n return qs ? `?${qs}` : '';\n}\n\nexport class DaoDashboardClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Aggregated dashboard counters for a user's governance home screen. */\n async getStats(userAddress: string): Promise<DaoDashboardStats> {\n return this.http.get(\n `/dao/dashboard/stats/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Active proposals across every DAO the user belongs to, with vote state. */\n async getActiveProposals(\n userAddress: string,\n ): Promise<DaoActiveProposalForUser[]> {\n return this.http.get(\n `/dao/dashboard/active-proposals/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Paginated vote history across DAOs. */\n async getVoteHistory(\n userAddress: string,\n opts: DashboardListOptions = {},\n ): Promise<{ count: number; votes: DaoVote[] }> {\n const qs = buildQuery({ limit: opts.limit, offset: opts.offset });\n return this.http.get(\n `/dao/dashboard/vote-history/${encodePathParam(userAddress)}${qs}`,\n );\n }\n\n /** Activity feed (proposal-created/vote-cast/etc.) across user's DAOs. */\n async getActivity(\n userAddress: string,\n opts: DashboardActivityOptions = {},\n ): Promise<DaoActivityEntry[]> {\n const qs = buildQuery({ limit: opts.limit, daoId: opts.daoId });\n return this.http.get(\n `/dao/dashboard/activity/${encodePathParam(userAddress)}${qs}`,\n );\n }\n\n /** Items the user must act on (sign prepared messages, claim NFTs, …). */\n async getPendingActions(userAddress: string): Promise<DaoPendingAction[]> {\n return this.http.get(\n `/dao/dashboard/pending-actions/${encodePathParam(userAddress)}`,\n );\n }\n\n /** Governance impact metrics — weight delivered, success rate, streak. */\n async getImpact(userAddress: string): Promise<DaoGovernanceImpact> {\n return this.http.get(\n `/dao/dashboard/impact/${encodePathParam(userAddress)}`,\n );\n }\n}\n","/**\n * DAO Sub-Client.\n *\n * Wraps every public DAO endpoint (mounted under `/api/v3/dao`).\n *\n * Why a dedicated sub-client:\n * - The controller exposes ~30 endpoints across 5 surfaces (DAOs,\n * proposals, votes, treasury, members) plus a dashboard rollup. Before\n * this client there was no SDK entrypoint at all — smart-apps were\n * hand-rolling fetch calls.\n * - Types mirror `multi-chain-core`'s `dao.types.ts` over the wire (see\n * `./types`) so smart-app bundles don't drag NestJS / Mongoose.\n */\n\nimport { encodePathParam, type HttpClient } from '../http';\nimport { DaoDashboardClient } from './dashboard-client';\nimport type {\n AddDaoMemberRequest,\n AddMemberResponse,\n CastVoteRequest,\n CastVoteResponse,\n ClaimDaoMemberNftRequest,\n ClaimNftResponse,\n CreateDaoProposalRequest,\n CreateDaoRequest,\n CreateDaoResponse,\n CreateProposalResponse,\n DaoConfig,\n DaoProposalConfig,\n DaoVote,\n DaoWithProposalsResponse,\n ExecuteProposalResponse,\n ListDaosOptions,\n ListDaosResponse,\n ListMembersOptions,\n ListMembersResponse,\n ListProposalsOptions,\n ListProposalsResponse,\n MemberNftResponse,\n PrepareDaoProposalRequest,\n PrepareProposalResponse,\n PrepareVoteRequest,\n PrepareVoteResponse,\n ProposalResultsResponse,\n RemoveMemberResponse,\n SubmitSignedProposalRequest,\n SubmitSignedProposalResponse,\n SubmitSignedVoteRequest,\n TreasuryBalancesResponse,\n TreasuryHistoryOptions,\n TreasuryHistoryResponse,\n VoteListOptions,\n VotesListResponse,\n} from './types';\n\nfunction buildQuery(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, String(value));\n }\n const qs = search.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction encodeDaoId(daoId: string): string {\n return encodePathParam(daoId);\n}\n\nfunction encodeProposalId(proposalId: string): string {\n return encodePathParam(proposalId);\n}\n\nfunction encodeAddress(address: string): string {\n return encodePathParam(address);\n}\n\n/**\n * DAO Sub-Client — exposed as `client.dao` on `SmartEngineClient`.\n *\n * @example Create a DAO and submit a proposal\n * ```typescript\n * const { dao } = await client.dao.create({\n * name: 'Foo DAO',\n * description: '...',\n * membershipModel: 'token-only',\n * governanceToken: { symbol: 'FOO', chains: [{ chain: 'xrpl', tokenId: 'FOO.rISSUER', decimals: 8 }] },\n * votingRules: { ... },\n * treasuryChains: ['xrpl'],\n * createdBy: 'rUserAddress',\n * });\n * const { proposal } = await client.dao.createProposal(dao.daoId, {\n * type: 'dao_treasury_transfer',\n * title: 'Pay grant',\n * description: '...',\n * proposer: 'rUserAddress',\n * actions: [...],\n * });\n * ```\n */\nexport class DaoClient {\n /** Per-user rollups for the smart-app's governance home screen. */\n public readonly dashboard: DaoDashboardClient;\n\n constructor(private readonly http: HttpClient) {\n this.dashboard = new DaoDashboardClient(http);\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n /** Create a new DAO. */\n async create(request: CreateDaoRequest): Promise<CreateDaoResponse> {\n return this.http.post('/dao/create', request);\n }\n\n /** List DAOs with optional status / creator filters. */\n async list(opts: ListDaosOptions = {}): Promise<ListDaosResponse> {\n const qs = buildQuery({ status: opts.status, createdBy: opts.createdBy });\n return this.http.get(`/dao/list${qs}`);\n }\n\n /** Fetch a single DAO by ID. */\n async get(daoId: string): Promise<DaoConfig> {\n return this.http.get(`/dao/${encodeDaoId(daoId)}`);\n }\n\n /** Fetch a DAO together with its proposals (single round-trip). */\n async getWithProposals(daoId: string): Promise<DaoWithProposalsResponse> {\n return this.http.get(`/dao/${encodeDaoId(daoId)}/with-proposals`);\n }\n\n // ─── Proposals ────────────────────────────────────────────────────────────\n\n /** List proposals for a DAO, optionally filtered by status / proposer. */\n async listProposals(\n daoId: string,\n opts: ListProposalsOptions = {},\n ): Promise<ListProposalsResponse> {\n const qs = buildQuery({ status: opts.status, proposer: opts.proposer });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/proposals${qs}`);\n }\n\n /** Create a proposal (server activates the proposal immediately). */\n async createProposal(\n daoId: string,\n request: CreateDaoProposalRequest,\n ): Promise<CreateProposalResponse> {\n return this.http.post(`/dao/${encodeDaoId(daoId)}/proposals`, request);\n }\n\n /**\n * Prepare a proposal for off-chain signing (returns the message to sign).\n * Use {@link signProposal} to submit the signature once captured.\n */\n async prepareProposal(\n daoId: string,\n request: PrepareDaoProposalRequest,\n ): Promise<PrepareProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/prepare`,\n request,\n );\n }\n\n /** Submit the signed prepared-proposal payload. */\n async signProposal(\n daoId: string,\n proposalId: string,\n request: SubmitSignedProposalRequest,\n ): Promise<SubmitSignedProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/sign`,\n request,\n );\n }\n\n /** Prepare a vote message for off-chain signing. */\n async prepareVote(\n daoId: string,\n proposalId: string,\n request: PrepareVoteRequest,\n ): Promise<PrepareVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/prepare-vote`,\n request,\n );\n }\n\n /** Submit the signed prepared-vote payload. */\n async submitVote(\n daoId: string,\n proposalId: string,\n request: SubmitSignedVoteRequest,\n ): Promise<CastVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/submit-vote`,\n request,\n );\n }\n\n /**\n * Cast a vote directly (no separate prepare/sign hop — server records the\n * vote on the caller's behalf). Use {@link prepareVote} + {@link submitVote}\n * when the smart-app's signing model requires client-side signing.\n */\n async vote(\n daoId: string,\n proposalId: string,\n request: CastVoteRequest,\n ): Promise<CastVoteResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/vote`,\n request,\n );\n }\n\n /**\n * Manually execute a passed proposal via TSS. Proposals auto-execute after\n * the execution delay; this endpoint is for the governance-admin override\n * path.\n */\n async execute(\n daoId: string,\n proposalId: string,\n ): Promise<ExecuteProposalResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/execute`,\n {},\n );\n }\n\n /** Paginated vote list for a proposal. */\n async getVotes(\n daoId: string,\n proposalId: string,\n opts: VoteListOptions = {},\n ): Promise<VotesListResponse> {\n const qs = buildQuery({ limit: opts.limit, offset: opts.offset });\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/votes${qs}`,\n );\n }\n\n /** Resolved tally / quorum / pass-fail for a proposal. */\n async getResults(\n daoId: string,\n proposalId: string,\n ): Promise<ProposalResultsResponse> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/results`,\n );\n }\n\n /** Raw vote counts by option ID (no quorum / pass logic). */\n async getVoteCounts(\n daoId: string,\n proposalId: string,\n ): Promise<Record<string, number>> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/vote-counts`,\n );\n }\n\n /** Fetch a single voter's vote on a proposal. */\n async getVoterRecord(\n daoId: string,\n proposalId: string,\n voterAddress: string,\n ): Promise<DaoVote> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}/voter/${encodeAddress(voterAddress)}`,\n );\n }\n\n /** Fetch a single proposal by ID. */\n async getProposal(\n daoId: string,\n proposalId: string,\n ): Promise<DaoProposalConfig> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/proposals/${encodeProposalId(proposalId)}`,\n );\n }\n\n // ─── Treasury ─────────────────────────────────────────────────────────────\n\n /** Per-chain treasury balances for a DAO. */\n async getTreasury(\n daoId: string,\n chain?: string,\n ): Promise<TreasuryBalancesResponse> {\n const qs = buildQuery({ chain });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/treasury${qs}`);\n }\n\n /** Paginated treasury transaction history (in/out/swap). */\n async getTreasuryHistory(\n daoId: string,\n opts: TreasuryHistoryOptions = {},\n ): Promise<TreasuryHistoryResponse> {\n const qs = buildQuery({\n chain: opts.chain,\n limit: opts.limit,\n offset: opts.offset,\n });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/treasury/history${qs}`);\n }\n\n // ─── Members ──────────────────────────────────────────────────────────────\n\n /** List a DAO's members, optionally filtered by status. */\n async listMembers(\n daoId: string,\n opts: ListMembersOptions = {},\n ): Promise<ListMembersResponse> {\n const qs = buildQuery({ status: opts.status });\n return this.http.get(`/dao/${encodeDaoId(daoId)}/members${qs}`);\n }\n\n /** Add a member to a DAO. */\n async addMember(\n daoId: string,\n request: AddDaoMemberRequest,\n ): Promise<AddMemberResponse> {\n return this.http.post(`/dao/${encodeDaoId(daoId)}/members`, request);\n }\n\n /** Remove a member from a DAO. */\n async removeMember(\n daoId: string,\n address: string,\n ): Promise<RemoveMemberResponse> {\n return this.http.delete(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}`,\n );\n }\n\n /** Bind a held membership NFT serial to a member record. */\n async claimMemberNft(\n daoId: string,\n address: string,\n request: ClaimDaoMemberNftRequest,\n ): Promise<ClaimNftResponse> {\n return this.http.post(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}/claim-nft`,\n request,\n );\n }\n\n /** Fetch the NFT serials + status for a member. */\n async getMemberNft(\n daoId: string,\n address: string,\n ): Promise<MemberNftResponse> {\n return this.http.get(\n `/dao/${encodeDaoId(daoId)}/members/${encodeAddress(address)}/nft`,\n );\n }\n}\n","/**\n * Personhood Sub-Client\n *\n * Thin HTTP wrapper around `POST /api/v3/personhood/verify`. Pure HTTP —\n * never imports a server-side personhood module or the baas-core types.\n * The locally-declared types in `./personhood-types` mirror the server's\n * wire shape; see that file for the source-of-truth annotation.\n *\n * @example\n * ```typescript\n * const cert = await client.personhood.verify({\n * candidate: '0.0.12345',\n * proof: {\n * attestationMethod: 'web-of-trust',\n * payload: { vouchers: ['0.0.111', '0.0.222'] },\n * },\n * });\n * if (!cert) {\n * console.log('verification rejected');\n * return;\n * }\n * console.log('cert expires at', cert.expiresAt);\n * ```\n */\nimport type { HttpClient } from '../http';\nimport { SdkHttpError } from '../http';\nimport type {\n PersonhoodCert,\n PersonhoodVerifyParams,\n} from './personhood-types';\n\n/**\n * Error envelope emitted by the validator when the hub has no\n * `IPersonhoodVerifier` wired. Exposed as a constant so callers can\n * branch on the `error` discriminator without re-typing the string.\n */\nexport const PERSONHOOD_VERIFIER_NOT_CONFIGURED = 'personhood_verifier_not_configured' as const;\n\n/**\n * Thin HTTP client for the personhood endpoint.\n *\n * Method outcomes:\n * - HTTP 200 with a cert object → resolves to `PersonhoodCert`.\n * - HTTP 200 with `null` body → resolves to `null` (clean rejection).\n * - HTTP 400 → throws `SdkHttpError(400)`.\n * - HTTP 503 → throws `SdkHttpError(503)` whose\n * `.details.error === 'personhood_verifier_not_configured'`.\n * - HTTP 5xx → throws `SdkHttpError` with the upstream status.\n * - Network / timeout → throws `SdkHttpError(0|408)`.\n */\nexport class PersonhoodClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Verify a personhood proof for `candidate`.\n *\n * Returns the issued cert on accept, `null` on clean rejection. All\n * other failure modes (validation, transport, 5xx) propagate as\n * `SdkHttpError`.\n */\n async verify(params: PersonhoodVerifyParams): Promise<PersonhoodCert | null> {\n const result = await this.http.post<PersonhoodCert | null>(\n '/personhood/verify',\n {\n candidate: params.candidate,\n proof: params.proof,\n },\n );\n // The validator returns `null` literally on clean rejection, and the\n // HTTP layer surfaces empty `204 No Content` bodies as `undefined`.\n // Treat both as the same \"no cert\" outcome so callers only branch on\n // `=== null`.\n if (result === undefined) return null;\n return result;\n }\n}\n\nexport type { PersonhoodCert, PersonhoodVerifyParams } from './personhood-types';\n\n/**\n * Predicate: narrows an unknown error to a 503\n * `personhood_verifier_not_configured` envelope. Use in smart-app code to\n * treat unconfigured hubs as a graceful downgrade.\n */\nexport function isPersonhoodVerifierNotConfigured(\n err: unknown,\n): err is SdkHttpError & { details: { error: typeof PERSONHOOD_VERIFIER_NOT_CONFIGURED } } {\n if (!(err instanceof SdkHttpError)) return false;\n if (err.statusCode !== 503) return false;\n const d = err.details as unknown;\n if (d === null || typeof d !== 'object') return false;\n return (d as Record<string, unknown>).error === PERSONHOOD_VERIFIER_NOT_CONFIGURED;\n}\n","/**\n * Agents Sub-Client\n *\n * Manages autonomous smart agents on the host platform.\n *\n * @example\n * ```typescript\n * // Register an agent\n * const agent = await baas.agents.register({\n * name: 'Trading Bot',\n * capabilities: ['trade', 'withdraw'],\n * rules: { maxTradeAmount: '1000', allowedPairs: ['HBAR/USDC'] },\n * });\n *\n * // Fund and trade\n * await baas.agents.fund(agent.agentId, { chain: 'hedera', amount: '500' });\n * await baas.agents.trade(agent.agentId, { chain: 'hedera', pair: 'HBAR/USDC', side: 'buy', amount: '100' });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type { PreparedTransactionResponse } from '../../_vendor';\nimport type {\n AgentRegisterRequest,\n AgentInfo,\n AgentCertification,\n AgentRules,\n AgentEvent,\n AgentBalance,\n AgentFundRequest,\n AgentTradeRequest,\n AgentWithdrawRequest,\n AgentExecuteRequest,\n AgentExecuteResponse,\n} from './types';\n\nexport * from './types';\nexport { validateAgentRules } from './types';\nexport type { PreparedTransactionResponse } from '../../_vendor';\n\n/**\n * Envelope returned by `fund` / `trade` / `withdraw` on the host. The\n * server wraps the underlying `PreparedTransactionResponse` with a\n * `success: true` flag so the caller can distinguish the\n * lifecycle-success path from a 400/404 error response.\n */\nexport type AgentPreparedTransactionResponse = PreparedTransactionResponse & {\n success: true;\n};\n\n/**\n * Envelope returned by `fund` when the requested amount trips an\n * approval-required rule: instead of prepared transaction bytes the host\n * records a pending operation and returns its id for later approve/reject.\n * Discriminate from {@link AgentPreparedTransactionResponse} with\n * {@link isAgentFundPending}.\n */\nexport type AgentPendingApprovalResponse = {\n success: true;\n pendingOpId: string;\n agentId: string;\n action: string;\n status: 'awaiting_approval';\n description: string;\n};\n\n/**\n * Type guard distinguishing the pending-approval envelope from the\n * prepared-transaction envelope returned by {@link AgentsClient.fund}.\n */\nexport function isAgentFundPending(\n r: AgentPreparedTransactionResponse | AgentPendingApprovalResponse,\n): r is AgentPendingApprovalResponse {\n return 'pendingOpId' in r;\n}\n\nexport class AgentsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Register a new agent */\n async register(request: AgentRegisterRequest, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.post('/api/v3/baas/agents/register', request, opts);\n }\n\n /** Get agent details */\n async get(agentId: string, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}`, opts);\n }\n\n /** List all agents */\n async list(opts?: HttpCallOptions): Promise<{ agents: AgentInfo[]; total: number }> {\n return this.http.get('/api/v3/baas/agents', opts);\n }\n\n /**\n * Fund agent treasury (owner-only). Normally returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope —\n * the caller is expected to sign and submit the prepared bytes. When the\n * amount trips an approval-required rule the host instead returns an\n * {@link AgentPendingApprovalResponse}; discriminate with\n * {@link isAgentFundPending}.\n */\n async fund(\n agentId: string,\n request: AgentFundRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse | AgentPendingApprovalResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/fund`, request, opts);\n }\n\n /**\n * Execute a trade (agent-wallet OR owner). Returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope.\n */\n async trade(\n agentId: string,\n request: AgentTradeRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/trade`, request, opts);\n }\n\n /**\n * Withdraw from agent treasury (owner-only). Returns a\n * `PreparedTransactionResponse` wrapped in a `success: true` envelope.\n */\n async withdraw(\n agentId: string,\n request: AgentWithdrawRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentPreparedTransactionResponse> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/withdraw`, request, opts);\n }\n\n /**\n * Execute a generic, declared capability (agent-wallet OR owner). The\n * chain-agnostic general form of an agent action: the capability may settle\n * on-chain, act off-chain, or both. Returns the ordered step results.\n */\n async execute(\n agentId: string,\n request: AgentExecuteRequest,\n opts?: HttpCallOptions,\n ): Promise<AgentExecuteResponse & { success: true }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/execute`, request, opts);\n }\n\n /** Pause an agent */\n async pause(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/pause`, {}, opts);\n }\n\n /** Resume a paused agent */\n async resume(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/resume`, {}, opts);\n }\n\n /** Revoke an agent (permanent) */\n async revoke(agentId: string, opts?: HttpCallOptions): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/revoke`, {}, opts);\n }\n\n /**\n * Get an agent's certification snapshot (identity, rule refs, BLS group key,\n * and recent on-chain activity). A 404 throws `SdkHttpError` via `http.get`\n * — parity with {@link get}.\n */\n async certification(agentId: string, opts?: HttpCallOptions): Promise<AgentCertification> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/certification`, opts);\n }\n\n /**\n * Update agent rules.\n *\n * Server route is PATCH `/api/v3/baas/agents/:agentId/rules`\n * (`agents.controller.ts:375`). The previous PUT variant 404'd because\n * Nest matched the dynamic `:agentId` GET/POST handlers and rejected\n * the verb mismatch.\n */\n async updateRules(agentId: string, rules: Partial<AgentRules>, opts?: HttpCallOptions): Promise<AgentInfo> {\n return this.http.patch(`/api/v3/baas/agents/${encodePathParam(agentId)}/rules`, rules, opts);\n }\n\n /** Get agent events */\n async getEvents(agentId: string, opts?: HttpCallOptions): Promise<{ events: AgentEvent[]; total: number }> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/events`, opts);\n }\n\n /** Get agent balances across chains */\n async getBalances(agentId: string, opts?: HttpCallOptions): Promise<{ balances: AgentBalance[] }> {\n return this.http.get(`/api/v3/baas/agents/${encodePathParam(agentId)}/balances`, opts);\n }\n\n /** Approve a pending agent operation */\n async approve(agentId: string, operationId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/approve/${encodePathParam(operationId)}`, {}, opts);\n }\n\n /** Reject a pending agent operation */\n async reject(agentId: string, operationId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n return this.http.post(`/api/v3/baas/agents/${encodePathParam(agentId)}/reject/${encodePathParam(operationId)}`, {}, opts);\n }\n}\n","/**\n * Deployment Sub-Client — runtime orchestration.\n *\n * The four-step deploy flow:\n *\n * 1. `init` — server allocates appId + per-app Harbor project + ephemeral push robot creds.\n * 2. (out-of-band) — customer `docker login <registry.server>` then `docker push <registry.server>/<registry.repository>:<tag>`.\n * 3. `uploadFrontend` — (optional) tarball with the SPA bundle.\n * 4. `deploy` — server reconciles to k8s.\n *\n * @example\n * ```typescript\n * const init = await baas.deployment.init({ name: 'my-app', port: 3200, services: ['database'] });\n *\n * // Use the credentials returned in init.registry to push the backend image.\n * // init.registry.server → e.g. 'harbor.testnet.hsuite.network' (public round-robin)\n * // init.registry.repository → e.g. 'hsuite-customers-<appId>'\n * // init.registry.username → per-project robot account\n * // init.registry.password → per-app push secret (re-derivable, not persisted as plaintext)\n * //\n * // docker login <init.registry.server> -u <init.registry.username> -p <init.registry.password>\n * // docker push <init.registry.server>/<init.registry.repository>:v1\n *\n * await baas.deployment.deploy(init.appId, { tag: 'v1', replicas: 2 });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n BaasInitRequest,\n BaasInitResponse,\n BaasReissuePushCredentialsResponse,\n BaasDeployRequest,\n BaasDeployResponse,\n BaasUploadFrontendResponse,\n BaasRollbackRequest,\n BaasRuntimeStatus,\n BaasAppListResponse,\n BaasSetWebhookResponse,\n BaasRotateKekResponse,\n BaasRevokeKekResponse,\n DeployedAppInfo,\n} from '../types';\n\nexport class DeploymentClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Step 1 — allocate appId + receive ephemeral push credentials for\n * the cluster's per-tenant Harbor project.\n *\n * Each app gets its own Harbor project (`hsuite-customers-<appId>`)\n * isolated by Harbor's RBAC. The push robot returned in\n * `registry.{username, password}` is scoped to that project only —\n * it cannot read or write any other tenant's images.\n *\n * **Single-use secret discipline:** `registry.password` is returned\n * exactly once and is NOT persisted server-side. Store it locally\n * for the `docker push` and discard. To rotate, call `init` again\n * (issues a new robot under the same project).\n *\n * Use the credentials to `docker login` + `docker push`, then call\n * {@link deploy} with the pushed image tag.\n */\n async init(request: BaasInitRequest): Promise<BaasInitResponse> {\n return this.http.post('/api/v3/baas/deployment/apps/init', request);\n }\n\n /**\n * Issue ephemeral Harbor push credentials for a smart-app that ALREADY\n * EXISTS — the MINT-FIRST / DEPLOY-LAST credentials-push call.\n *\n * Unlike {@link init} (which historically allocated a fresh entity), this\n * takes the developer's pre-existing `appId` — the `SUBSCRIPTION_APP_ID`\n * minted by `hsuite subscribe` (`appId == DKG entityId`) — and ONLY\n * (re)provisions the per-app Harbor project + push robot. The server creates\n * no DKG entity and no subscription; it asserts the caller owns the app and\n * that its subscription is ACTIVE (402 otherwise) first.\n *\n * Returns the same `{ appId, registry }` shape as {@link init}. Single-use\n * secret discipline applies to `registry.password` exactly as in `init`.\n *\n * This is the credentials path the mint-first `hsuite deploy` uses to obtain\n * push creds for the developer's already-minted subscription app\n * (`POST /apps/:appId/credentials/push`). The `hsuite redeploy` re-push path\n * uses {@link reissuePushCredentials} instead, which targets a dedicated\n * `credentials/reissue` route with stricter SUSPENDED-app + Harbor-failure\n * handling.\n */\n async pushCredentials(appId: string): Promise<BaasInitResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/push`,\n {},\n );\n }\n\n /**\n * Reissue ephemeral Harbor push credentials for an EXISTING app, WITHOUT\n * allocating a new appId / entity. Unlike {@link init} — which historically\n * forked a fresh smart-app entity (and a fresh paid subscription) on every\n * call — this re-binds to an app the developer already owns: the `appId` is\n * echoed back unchanged and only a new single-use `registry.password` push\n * robot is minted. Same `{ appId, registry }` response shape as `init`.\n *\n * Owner-only + active-subscription gated server-side. This is the credential\n * path `hsuite redeploy` uses so a re-push does not cost a new entity +\n * subscription each run. Targets the dedicated\n * `POST /apps/:appId/credentials/reissue` route (distinct from\n * {@link pushCredentials}'s first-deploy `credentials/push`): the reissue\n * route additionally refuses SUSPENDED apps and surfaces Harbor failures\n * loudly rather than returning placeholder creds.\n */\n async reissuePushCredentials(\n appId: string,\n ): Promise<BaasReissuePushCredentialsResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/reissue`,\n {},\n );\n }\n\n /**\n * Step 3 (optional) — upload the SPA tarball.\n *\n * The tarball is content-addressed (SHA-256) and mounted read-only\n * into the customer's pod alongside the backend container. Returns\n * the hash + size so the caller can verify the upload.\n */\n async uploadFrontend(\n appId: string,\n bundle: Blob | Buffer,\n filename = 'bundle.tar.gz'\n ): Promise<BaasUploadFrontendResponse> {\n // The smart-host upload handler uses `FileInterceptor('bundle', ...)` —\n // the multipart field name MUST be `bundle`, not the SDK's default\n // `'file'`. Override explicitly.\n return this.http.upload(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/frontend`,\n bundle,\n filename,\n undefined,\n 'bundle',\n );\n }\n\n /**\n * Step 4 — reconcile the runtime to k8s.\n *\n * Returns immediately with `status: 'deploying'`. Poll {@link status}\n * until `runtime.runtimeState === 'RUNNING'` for the URL to be live.\n */\n async deploy(appId: string, request: BaasDeployRequest): Promise<BaasDeployResponse> {\n return this.http.post(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/deploy`, request);\n }\n\n /**\n * Roll back to a previously-deployed image tag (must exist in\n * `runtime.deploymentHistory[]`).\n */\n async rollback(appId: string, request: BaasRollbackRequest): Promise<BaasDeployResponse> {\n return this.http.post(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/rollback`, request);\n }\n\n /**\n * Live combined lifecycle + runtime status of an app.\n */\n async status(appId: string): Promise<BaasRuntimeStatus> {\n return this.http.get(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/status`);\n }\n\n /**\n * List all deployed apps for the authenticated developer.\n */\n async list(): Promise<BaasAppListResponse> {\n return this.http.get('/api/v3/smart-apps');\n }\n\n /**\n * Get app details.\n */\n async get(appId: string): Promise<DeployedAppInfo> {\n return this.http.get(`/api/v3/smart-apps/${encodePathParam(appId)}`);\n }\n\n /**\n * Update app configuration.\n *\n * @param appId - The app to update.\n * @param updates - Partial deploy-request fields to apply.\n * @returns The updated app info.\n */\n async update(appId: string, updates: Partial<BaasDeployRequest>): Promise<DeployedAppInfo> {\n return this.http.put(`/api/v3/smart-apps/${encodePathParam(appId)}`, updates);\n }\n\n /**\n * Delete an app (runtime effect: namespace teardown).\n */\n async delete(appId: string): Promise<{ success: boolean }> {\n return this.http.delete(`/api/v3/smart-apps/${encodePathParam(appId)}`);\n }\n\n /**\n * Suspend an app (runtime effect: scale to zero).\n */\n async suspend(appId: string): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/smart-apps/${encodePathParam(appId)}/suspend`, {});\n }\n\n /**\n * Resume a suspended app (runtime effect: scale back up).\n */\n async resume(appId: string): Promise<{ success: boolean; status: string }> {\n return this.http.post(`/api/v3/smart-apps/${encodePathParam(appId)}/resume`, {});\n }\n\n /**\n * Get deployment statistics.\n */\n async getStats(): Promise<{\n totalApps: number;\n activeApps: number;\n totalOwners: number;\n }> {\n return this.http.get('/api/v3/smart-apps/stats');\n }\n\n /**\n * Register or update the developer-facing webhook URL for runtime\n * lifecycle events (`runtime.deploying` / `running` / `failed` /\n * `suspended` / `resumed` / `retired`).\n *\n * The host's `DeployWebhookDispatcher` POSTs to this URL whenever the\n * smart-deployer reconciler emits a `runtime.*` NATS event, signed with\n * the returned `webhookSecret`:\n *\n * `X-HSuite-Signature: sha256=<hmac-sha256(secret, raw-body)>`\n *\n * Store `webhookSecret` server-side and re-compute the signature over\n * the raw delivery body to verify authenticity. The secret is surfaced\n * only on PUT — re-call this method to rotate.\n *\n * Server validates: HTTPS only, no loopback / RFC1918 / link-local /\n * CGNAT / cloud metadata destinations (SSRF guard).\n */\n async setWebhook(appId: string, webhookUrl: string): Promise<BaasSetWebhookResponse> {\n return this.http.put(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/webhook`, {\n webhookUrl,\n });\n }\n\n /**\n * Per-app Prometheus metrics in the standard exposition format\n * (text/plain; version=0.0.4). The server filters smart-deployer's\n * `/metrics` to lines that mention this app's `appId` label, while\n * preserving HELP / TYPE comment lines and cluster-wide metrics.\n *\n * Returned as a raw string so callers can pipe directly into a\n * Prometheus parser (`prom-client`, `parse-prometheus-text-format`,\n * etc.) without an intermediate JSON decode that would corrupt the\n * exposition format.\n */\n async getMetrics(appId: string): Promise<string> {\n return this.http.getText(`/api/v3/baas/deployment/apps/${encodePathParam(appId)}/metrics`);\n }\n\n /**\n * Rotate the smart-app's tenant-secret KEK.\n *\n * Re-encrypts every `runtime.env` envelope at the new KEK version\n * transparently. Previous versions remain valid until explicitly\n * revoked via {@link revokeKek}. Owner-only.\n */\n async rotateKek(appId: string): Promise<BaasRotateKekResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/rotate-kek`,\n {},\n );\n }\n\n /**\n * Revoke a tenant-secret KEK version (emergency burn).\n *\n * Envelopes at the revoked version become operationally dead —\n * decryption inside the smart-app pod fails. Owner-only and\n * **irreversible**. Returns the cumulative list of revoked versions\n * for this app.\n */\n async revokeKek(appId: string, version: number): Promise<BaasRevokeKekResponse> {\n return this.http.post(\n `/api/v3/baas/deployment/apps/${encodePathParam(appId)}/credentials/revoke-kek`,\n { version },\n );\n }\n}\n","/**\n * Bridge Sub-Client.\n *\n * Mounted on `client.bridge`. Endpoints map 1:1 to the validator bridge routes:\n *\n * - POST `/bridge/create` → `create`\n * - GET `/bridge/list` → `list` (Public)\n * - GET `/bridge/:bridgeId` → `get` (Public)\n * - POST `/bridge/:bridgeId/port` → `port`\n * - POST `/bridge/:bridgeId/return` → `return`\n * - GET `/bridge/:bridgeId/status/:claimId` → `getStatus` (Public)\n * - GET `/bridge/:bridgeId/supply` → `getSupply` (Public)\n * - GET `/bridge/:bridgeId/claims` → `listClaims` (Public)\n *\n * Operator-only routes (PATCH `/rules`, POST `/pause`, POST `/close`) are\n * intentionally not surfaced — those flip the cross-cluster state of a\n * live bridge and belong in governance tooling, not SDK callers.\n *\n * @example List bridges then port tokens through one\n * ```ts\n * const { bridges } = await client.bridge.list();\n * const port = await client.bridge.port(bridges[0].bridgeId, {\n * fromChain: 'hedera',\n * toChain: 'xrpl',\n * amount: '100',\n * recipient: 'rRecipient...',\n * });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n CreateBridgeRequest,\n CreateBridgeResponse,\n BridgeConfig,\n ListBridgesOptions,\n ListBridgesResponse,\n PortRequest,\n ReturnRequest,\n PortResult,\n BridgeClaimRecord,\n BridgeSupply,\n ListClaimsOptions,\n ListClaimsResponse,\n} from './bridge-types';\n\nexport class BridgeClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new bridge instance — triggers DKG + TSS entity creation server-side. */\n async create(request: CreateBridgeRequest): Promise<CreateBridgeResponse> {\n return this.http.post('/bridge/create', request);\n }\n\n /** List bridges. Both filters are optional. */\n async list(options?: ListBridgesOptions): Promise<ListBridgesResponse> {\n const params = new URLSearchParams();\n if (options?.status) params.append('status', options.status);\n if (options?.sourceChain) params.append('sourceChain', options.sourceChain);\n const qs = params.toString();\n return this.http.get(`/bridge/list${qs ? `?${qs}` : ''}`);\n }\n\n /** Get bridge configuration. */\n async get(bridgeId: string): Promise<BridgeConfig> {\n return this.http.get(`/bridge/${encodePathParam(bridgeId)}`);\n }\n\n /** Port tokens from source → destination. */\n async port(bridgeId: string, request: PortRequest): Promise<PortResult> {\n return this.http.post(`/bridge/${encodePathParam(bridgeId)}/port`, request);\n }\n\n /**\n * Return tokens from destination → source. Only meaningful on two-way\n * bridges; the validator rejects the call on one-way bridges with a 400.\n *\n * Method name is `return_` to avoid colliding with the reserved JS\n * keyword in some downstream codegen. Prefer `client.bridge.return(...)`\n * via the named alias below.\n */\n async return(bridgeId: string, request: ReturnRequest): Promise<PortResult> {\n return this.http.post(`/bridge/${encodePathParam(bridgeId)}/return`, request);\n }\n\n /** Get claim status by claim ID under a given bridge. */\n async getStatus(bridgeId: string, claimId: string): Promise<BridgeClaimRecord> {\n return this.http.get(\n `/bridge/${encodePathParam(bridgeId)}/status/${encodePathParam(claimId)}`,\n );\n }\n\n /** Get aggregate supply view for a bridge. */\n async getSupply(bridgeId: string): Promise<BridgeSupply> {\n return this.http.get(`/bridge/${encodePathParam(bridgeId)}/supply`);\n }\n\n /** List bridge claims with optional pagination. */\n async listClaims(\n bridgeId: string,\n options?: ListClaimsOptions,\n ): Promise<ListClaimsResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n const qs = params.toString();\n return this.http.get(\n `/bridge/${encodePathParam(bridgeId)}/claims${qs ? `?${qs}` : ''}`,\n );\n }\n}\n","/**\n * Resources Sub-Client.\n *\n * Mounted on `client.resources`. Wraps the validator resources routes:\n *\n * - GET `/resources/summary` → `getSummary`\n * - GET `/resources/consumption/:appId` → `getConsumption`\n * - GET `/resources/consumption/:appId/history` → `getHistory`\n * - GET `/resources/consumption/:appId/ledger` → `getLedger`\n * - GET `/resources/consumption/:appId/status` → `getStatus`\n * - GET `/resources/consumption/:appId/breakdown` → `getBreakdown`\n * - GET `/resources/nodes` → `listNodes`\n * - GET `/resources/nodes/:nodeId` → `getNode`\n *\n * The two resource controllers (`ResourcesController` here +\n * `ResourceController` in `monitoring/`) are kept separate because they\n * serve different audiences; this wrapper exposes the smart-app facing\n * surface only.\n *\n * @example Inspect today's consumption for a smart-app\n * ```ts\n * const summary = await client.resources.getConsumption('app_abc');\n * console.log(`${summary.requests} requests, ${summary.storageMb} MB storage today`);\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n ResourceSummaryResponse,\n ResourceConsumptionResponse,\n ResourceHistoryResponse,\n ResourceLedgerResponse,\n ResourceStatusResponse,\n ResourceBreakdownResponse,\n ResourceNodesResponse,\n ResourceNodeResponse,\n ResourceLedgerOptions,\n ResourceBreakdownOptions,\n} from './resources-types';\n\nexport class ResourcesClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Network-wide consumption summary across all nodes. */\n async getSummary(): Promise<ResourceSummaryResponse> {\n return this.http.get('/resources/summary');\n }\n\n /** Current-day consumption breakdown for an app. */\n async getConsumption(appId: string): Promise<ResourceConsumptionResponse> {\n return this.http.get(`/resources/consumption/${encodePathParam(appId)}`);\n }\n\n /** Daily usage history from the persistent store. `days` defaults to 30 server-side. */\n async getHistory(appId: string, days?: number): Promise<ResourceHistoryResponse> {\n const qs = days !== undefined ? `?days=${days}` : '';\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/history${qs}`,\n );\n }\n\n /** Paginated billing ledger. All filters optional. */\n async getLedger(\n appId: string,\n options?: ResourceLedgerOptions,\n ): Promise<ResourceLedgerResponse> {\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.append('limit', String(options.limit));\n if (options?.offset !== undefined) params.append('offset', String(options.offset));\n if (options?.since) params.append('since', options.since);\n if (options?.until) params.append('until', options.until);\n if (options?.category) params.append('category', options.category);\n const qs = params.toString();\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/ledger${qs ? `?${qs}` : ''}`,\n );\n }\n\n /**\n * Current consumption status with threshold warnings and upgrade hints.\n * `dailyLimit` overrides the per-app tier default and is rare —\n * smart-app callers should leave it unset.\n */\n async getStatus(appId: string, dailyLimit?: number): Promise<ResourceStatusResponse> {\n const qs = dailyLimit !== undefined ? `?dailyLimit=${dailyLimit}` : '';\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/status${qs}`,\n );\n }\n\n /** Consumption aggregated by category over the supplied window. */\n async getBreakdown(\n appId: string,\n options?: ResourceBreakdownOptions,\n ): Promise<ResourceBreakdownResponse> {\n const params = new URLSearchParams();\n if (options?.since) params.append('since', options.since);\n if (options?.until) params.append('until', options.until);\n const qs = params.toString();\n return this.http.get(\n `/resources/consumption/${encodePathParam(appId)}/breakdown${qs ? `?${qs}` : ''}`,\n );\n }\n\n /** Per-node consumption reports. */\n async listNodes(): Promise<ResourceNodesResponse> {\n return this.http.get('/resources/nodes');\n }\n\n /** Single node's report. */\n async getNode(nodeId: string): Promise<ResourceNodeResponse> {\n return this.http.get(`/resources/nodes/${encodePathParam(nodeId)}`);\n }\n}\n","/**\n * Envelope Sub-Client.\n *\n * Mounted on `client.envelope`. Wraps the validator envelope routes:\n *\n * - POST `/envelope/encrypt` → `encrypt`\n * - POST `/envelope/decrypt` → `decrypt`\n *\n * The cluster master KEK and the derived per-app KEK NEVER cross the HTTP\n * boundary. Only the envelope (ciphertext + nonce + tag + metadata) is\n * persisted client-side; the validator handles all key material.\n *\n * @example Seal a tenant secret + recover it later\n * ```ts\n * const sealed = await client.envelope.encrypt({\n * appId: 'app_abc',\n * plaintext: 'super-secret-api-key',\n * });\n *\n * const opened = await client.envelope.decrypt({\n * appId: 'app_abc',\n * envelope: sealed.envelope,\n * });\n * ```\n */\nimport type { HttpClient } from '../http';\nimport type {\n EncryptRequest,\n EncryptResponse,\n DecryptRequest,\n DecryptResponse,\n} from './envelope-types';\n\nexport class EnvelopeClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Seal `plaintext` under the per-app KEK for `appId` at `kekVersion`.\n * Returns the canonical envelope shape suitable for persistence in\n * Mongo / NATS / on the EventBus.\n */\n async encrypt(request: EncryptRequest): Promise<EncryptResponse> {\n return this.http.post('/envelope/encrypt', request);\n }\n\n /**\n * Open `envelope` for `appId`. The plaintext is returned in the response\n * body — callers MUST treat it as ephemeral (no logs, no Mongo, no\n * NATS broadcast). The validator never persists or replays it.\n */\n async decrypt(request: DecryptRequest): Promise<DecryptResponse> {\n return this.http.post('/envelope/decrypt', request);\n }\n}\n","/**\n * Tokens (Migration) Sub-Client.\n *\n * Mounted on `client.tokens`. Wraps the validator's token-migration routes:\n *\n * - POST `/tokens/migrate` → `migrate`\n * - GET `/tokens/migrations` → `listMigrations`\n * - GET `/tokens/migrations/:id` → `getMigration`\n * - GET `/tokens/:tokenId/migrations` → `getMigrationsForToken`\n *\n * For per-token details, use `client.getTokenInfo(chain, tokenId)`.\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n TokenMigrationRequest,\n TokenMigrationResponse,\n TokenMigrationStatus,\n ListMigrationsResponse,\n TokenMigrationsForTokenResponse,\n} from './tokens-types';\n\nexport class TokensClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Initiate a token migration to TSS-controlled keys. */\n async migrate(request: TokenMigrationRequest): Promise<TokenMigrationResponse> {\n return this.http.post('/tokens/migrate', request);\n }\n\n /** List all known migrations on this validator. */\n async listMigrations(): Promise<ListMigrationsResponse> {\n return this.http.get('/tokens/migrations');\n }\n\n /**\n * Get one migration's status by id. The server returns\n * `{ error: string }` (NOT a 404) when the migration is unknown, so the\n * union type makes the failure mode explicit.\n */\n async getMigration(\n migrationId: string,\n ): Promise<TokenMigrationStatus | { error: string }> {\n return this.http.get(`/tokens/migrations/${encodePathParam(migrationId)}`);\n }\n\n /** All migrations recorded against a specific token id. */\n async getMigrationsForToken(\n tokenId: string,\n ): Promise<TokenMigrationsForTokenResponse> {\n return this.http.get(`/tokens/${encodePathParam(tokenId)}/migrations`);\n }\n}\n","/**\n * Operator Funding Sub-Client.\n *\n * Mounted on `client.operator`. Wraps the validator operator-funding routes:\n *\n * - GET `/operator/balance/:chain/:accountId` → `getBalance`\n * - GET `/operator/topup/:chain/:accountId` → `getTopup`\n *\n * Both endpoints are `@Public()` server-side — no auth required.\n *\n * @example Check operator funding before submitting a chain op\n * ```ts\n * const balance = await client.operator.getBalance('hedera', '0.0.12345');\n * const topup = await client.operator.getTopup('hedera', '0.0.12345');\n * if (topup.status !== 'healthy') {\n * console.warn(`Operator needs top-up: recommended=${topup.recommendedBalance}`);\n * }\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../http';\nimport type {\n OperatorChain,\n OperatorBalanceResponse,\n OperatorTopUpResponse,\n} from './operator-types';\n\nexport class OperatorClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Get the on-chain HBAR + token balance of an operator account. */\n async getBalance(\n chain: OperatorChain,\n accountId: string,\n ): Promise<OperatorBalanceResponse> {\n return this.http.get(\n `/operator/balance/${encodePathParam(chain)}/${encodePathParam(accountId)}`,\n );\n }\n\n /** Get top-up guidance for an operator account (recommended balance + status). */\n async getTopup(\n chain: OperatorChain,\n accountId: string,\n ): Promise<OperatorTopUpResponse> {\n return this.http.get(\n `/operator/topup/${encodePathParam(chain)}/${encodePathParam(accountId)}`,\n );\n }\n}\n","import {\n CreateAccountRequestSchema,\n ValidatorCreateAccountRequest,\n CreateAccountResponse,\n TransferRequestSchema,\n TransferRequest,\n TransferResponse,\n CreateTokenRequestSchema,\n ValidatorCreateTokenRequest,\n CreateTokenResponse,\n MintTokenRequestSchema,\n MintTokenRequest,\n BurnTokenRequestSchema,\n BurnTokenRequest,\n TokenActionRequestSchema,\n TokenActionRequest,\n ActionResult,\n AccountBalance,\n AccountInfo,\n Transaction,\n TokenInfo,\n ChainType,\n} from './_vendor';\nimport { type CircuitBreakerSnapshot } from './_vendor';\nimport {\n ValidatorDiscoveryClient,\n ValidatorInfo,\n DiscoveryClient,\n} from './discovery';\nimport { ValidatorAuthClient, AuthChain, AuthenticateResponse } from './auth';\nimport { createHttpClient, encodePathParam, type HttpClient } from './http';\n\n// Sub-client imports — public API only (for third-party smart-app developers)\nimport { SubscriptionClient } from './subscription';\nimport { FaucetClient } from './faucet';\nimport { TSSClient } from './tss';\nimport { IPFSClient } from './ipfs';\nimport {\n TransactionsClient,\n HederaTransactionsClient,\n XrplTransactionsClient,\n SolanaTransactionsClient,\n PolkadotTransactionsClient,\n} from './transactions';\nimport { SnapshotsClient } from './snapshots';\nimport { HistoricalBalanceClient } from './historical-balance';\nimport { SettlementClient } from './settlement';\nimport { GovernanceClient } from './governance';\nimport { DaoClient } from './dao';\nimport { PersonhoodClient } from './personhood';\nimport { AgentsClient } from './baas/agents';\nimport { DeploymentClient } from './baas/deployment';\nimport { BridgeClient } from './bridge';\nimport { ResourcesClient } from './resources';\nimport { EnvelopeClient } from './envelope';\nimport { TokensClient } from './tokens';\nimport { OperatorClient } from './operator';\n\n/**\n * Smart Engine Client Configuration.\n *\n * TYPE-FENCE (SDK 4.0): `SmartEngineClient` is the IN-CLUSTER / VALIDATOR-DIRECT\n * profile. It targets the validator's RAW tier (`/api/v3/{transactions,tss,\n * faucet,tokens,...}`), which is un-ingressed at the public gateway — calling it\n * with a gateway origin 404s. To make that footgun structurally impossible the\n * config requires an EXPLICIT `validatorBaseUrl` (not a generic `baseUrl`): the\n * caller must consciously hand over a validator origin, never a gateway URL that\n * happened to flow out of cluster discovery. App-as-proxy / external consumers\n * must use {@link BaasClient} instead (host BaaS tier).\n */\nexport interface SmartEngineClientConfig {\n /**\n * VALIDATOR API base URL (the in-cluster validator origin — NOT a gateway).\n * The raw `/api/v3/*` tier is reachable only here; a gateway URL will 404.\n */\n validatorBaseUrl: string;\n /** API key for authenticated requests */\n apiKey?: string;\n /** Session token from validator auth */\n authToken?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Network connection configuration for auto-discovery\n */\nexport interface NetworkConnectionConfig {\n /** Hedera network (mainnet, testnet, previewnet) */\n network: 'mainnet' | 'testnet' | 'previewnet';\n /** HCS topic ID for validator registry */\n registryTopicId: string;\n /** Blockchain type for authentication */\n chain: AuthChain;\n /** Wallet address for authentication */\n address: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Function to sign the challenge */\n signFn: (challenge: string) => string | Promise<string>;\n /** Optional metadata for authentication */\n metadata?: {\n appId?: string;\n appName?: string;\n };\n /** Custom mirror node URL */\n mirrorNodeUrl?: string;\n /** Allow HTTP (insecure) connections - only for local development */\n allowInsecure?: boolean;\n}\n\n/**\n * Connection result from connectToNetwork\n */\nexport interface NetworkConnectionResult {\n /** Configured client ready to use */\n client: SmartEngineClient;\n /** Validator that was connected to */\n validator: ValidatorInfo;\n /** Authentication session */\n session: AuthenticateResponse;\n}\n\n/**\n * Smart Engine Client — IN-CLUSTER / VALIDATOR-DIRECT profile.\n *\n * Unified, type-safe client for interacting with Smart Engines validators over\n * the RAW tier (`/api/v3/{transactions,tss,faucet,tokens,...}`).\n *\n * **TYPE-FENCE (SDK 4.0):** this client is constructible ONLY with an explicit\n * validator origin ({@link SmartEngineClientConfig.validatorBaseUrl}). The raw\n * `/api/v3/*` tier is un-ingressed at the public gateway, so pointing this\n * client at a gateway URL 404s — that footgun is removed by requiring a\n * conscious validator origin and by NOT shipping a gateway-discovery factory on\n * this client. External / app-as-proxy consumers must use `BaasClient` (the\n * host BaaS tier at `{gateway}/host/api/v3/baas/*`) instead. The only\n * auto-discovery path here ({@link connectToNetwork}) resolves a real validator\n * `apiEndpoint` from the HCS registry, never a gateway URL.\n *\n * Supports direct connection or HCS-registry auto-discovery.\n *\n * Sub-clients for third-party app developers:\n * - `client.subscription` — Application subscription management\n * - `client.tss` — Threshold Signature Scheme (chain-agnostic MPC)\n * - `client.ipfs` — Decentralized file storage\n * - `client.transactions` — Transaction sovereignty (prepare-sign-submit) — **chain-agnostic**\n *\n * Chain-namespaced advanced sub-clients (escape hatches with no multi-chain analog):\n * - `client.hedera` — HCS topics, KYC compliance, HTS wipe\n * - `client.xrpl` — Trust lines\n * - `client.solana` — Token close-account\n * - `client.polkadot` — Asset setTeam/setMetadata\n *\n * @example Direct connection (explicit validator origin)\n * ```typescript\n * const client = new SmartEngineClient({\n * validatorBaseUrl: 'https://validator.example.com', // a VALIDATOR origin, never a gateway\n * apiKey: 'your-api-key',\n * });\n * ```\n *\n * @example Auto-discovery with authentication\n * ```typescript\n * const { client, validator, session } = await SmartEngineClient.connectToNetwork({\n * network: 'testnet',\n * registryTopicId: '0.0.123456',\n * chain: 'hedera',\n * address: '0.0.789',\n * publicKey: 'your-public-key-hex',\n * signFn: (challenge) => privateKey.sign(Buffer.from(challenge)).toString('hex'),\n * });\n *\n * // Use sub-clients\n * const result = await client.tss.signMPC({\n * chain: 'hedera',\n * entityId: 'entity-123',\n * transactionBytes: '0x...',\n * });\n * ```\n */\nexport class SmartEngineClient {\n private baseUrl: string;\n private allowInsecure: boolean;\n private readonly http: HttpClient;\n /** Separate HTTP client for /api/v3/transactions */\n private readonly txHttp: HttpClient;\n /** Last HTTP error (for getHttpHealth) */\n private lastHttpError?: Error;\n\n // ========== Sub-Clients ==========\n\n /** Application subscription management */\n public readonly subscription: SubscriptionClient;\n /** Testnet HST faucet (challenge -> sign -> dispense) */\n public readonly faucet: FaucetClient;\n /** Threshold Signature Scheme — chain-agnostic MPC operations */\n public readonly tss: TSSClient;\n /** IPFS decentralized file storage */\n public readonly ipfs: IPFSClient;\n /** Transaction preparation for local signing (sovereignty model) — chain-agnostic */\n public readonly transactions: TransactionsClient;\n /** Hedera-specific transaction preparation (HCS topics, KYC, wipe) */\n public readonly hedera: HederaTransactionsClient;\n /** XRPL-specific transaction preparation (trust lines) */\n public readonly xrpl: XrplTransactionsClient;\n /** Solana-specific transaction preparation (close-account) */\n public readonly solana: SolanaTransactionsClient;\n /** Polkadot-specific transaction preparation (asset setTeam/setMetadata) */\n public readonly polkadot: PolkadotTransactionsClient;\n /** Token holder snapshot generation and retrieval */\n public readonly snapshots: SnapshotsClient;\n /** Historical balance archive reads (chain-native bigint, returned as decimal string) */\n public readonly historicalBalance: HistoricalBalanceClient;\n /** Cross-chain settlement operations */\n public readonly settlement: SettlementClient;\n /** Governance proposal dry-run (simulate-only) */\n public readonly governance: GovernanceClient;\n /** DAO governance — DAOs, proposals, votes, treasury, members, dashboard */\n public readonly dao: DaoClient;\n /** Personhood verification (HPP one-human-one-member) */\n public readonly personhood: PersonhoodClient;\n /** BaaS smart-agent lifecycle (register/fund/trade/withdraw/pause/resume/revoke/...) */\n public readonly agents: AgentsClient;\n /** BaaS smart-app deployment lifecycle (init/uploadFrontend/deploy/rollback/status/...) */\n public readonly deployments: DeploymentClient;\n /** Universal Token Bridge — port/return/claim across chains */\n public readonly bridge: BridgeClient;\n /** Network + per-app resource consumption (summary, history, ledger, nodes) */\n public readonly resources: ResourcesClient;\n /** AES-256-GCM envelope encrypt/decrypt under the TSS-backed master KEK */\n public readonly envelope: EnvelopeClient;\n /** Token migration — move existing tokens to TSS-controlled keys */\n public readonly tokens: TokensClient;\n /** Operator account funding helpers (balance + top-up guidance) */\n public readonly operator: OperatorClient;\n /** Discovery endpoints — cluster registry + platform-image manifests */\n public readonly discovery: DiscoveryClient;\n\n constructor(config: SmartEngineClientConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n this.baseUrl = validateClientUrl(config.validatorBaseUrl, this.allowInsecure);\n\n // Create shared HTTP client for /api/v3 endpoints\n this.http = createHttpClient({\n baseUrl: `${this.baseUrl}/api/v3`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n // Create separate HTTP client for /api/v3/transactions\n this.txHttp = createHttpClient({\n baseUrl: `${this.baseUrl}/api/v3/transactions`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n // Initialize sub-clients\n this.subscription = new SubscriptionClient(this.http);\n this.faucet = new FaucetClient(this.http);\n this.tss = new TSSClient(this.http);\n this.ipfs = new IPFSClient(this.http);\n this.transactions = new TransactionsClient(this.txHttp);\n // Pass `this.http` (rooted at `/api/v3`) as the second arg so\n // `client.hedera.tss.*` reaches `/api/v3/hedera/tss/*` — the prepare paths\n // continue to use `this.txHttp` (rooted at `/api/v3/transactions`).\n this.hedera = new HederaTransactionsClient(this.txHttp, this.http);\n this.xrpl = new XrplTransactionsClient(this.txHttp);\n this.solana = new SolanaTransactionsClient(this.txHttp);\n this.polkadot = new PolkadotTransactionsClient(this.txHttp);\n this.snapshots = new SnapshotsClient(this.http);\n this.historicalBalance = HistoricalBalanceClient.fromHttp(this.http);\n this.settlement = new SettlementClient(this.http);\n this.governance = new GovernanceClient(this.http);\n this.dao = new DaoClient(this.http);\n this.personhood = new PersonhoodClient(this.http);\n // BaaS sub-clients — they call fully-qualified `/api/v3/baas/<x>` (host) and\n // `/api/v3/smart-apps/<x>` (validator) paths directly, so they need an HTTP\n // client rooted at the bare `baseUrl` (NO `/api/v3` suffix — the suffix is\n // already baked into each method's path). Reuse of `txHttp` is wrong because\n // its base is `${baseUrl}/api/v3/transactions`. Build a fresh, root-scoped\n // client just for these.\n const rootHttp = createHttpClient({\n baseUrl: this.baseUrl,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n this.agents = new AgentsClient(rootHttp);\n this.deployments = new DeploymentClient(rootHttp);\n this.bridge = new BridgeClient(this.http);\n this.resources = new ResourcesClient(this.http);\n this.envelope = new EnvelopeClient(this.http);\n this.tokens = new TokensClient(this.http);\n this.operator = new OperatorClient(this.http);\n this.discovery = new DiscoveryClient(this.http);\n }\n\n /**\n * Build a `SmartEngineClient` from a plain env object. Reads:\n * - `VALIDATOR_URL` (required) — gateway/validator base URL\n * - `VALIDATOR_API_KEY` (optional) — API key for authenticated calls\n * - `APP_TOKEN` (optional) — session JWT from prior auth\n * - `ALLOW_INSECURE` (optional, `'true'`) — only for local dev\n * - `REQUEST_TIMEOUT` (optional, ms)\n *\n * Throws if `VALIDATOR_URL` is missing or invalid. Designed for BaaS\n * scheduled functions: `const client = SmartEngineClient.fromEnv(ctx.env)`.\n */\n static fromEnv(env: Record<string, string | undefined>): SmartEngineClient {\n const baseUrl = env['VALIDATOR_URL'];\n if (!baseUrl) {\n throw new SmartEngineError('VALIDATOR_URL is required to build a SmartEngineClient', 500);\n }\n const timeoutRaw = env['REQUEST_TIMEOUT'];\n const timeout = timeoutRaw ? Number.parseInt(timeoutRaw, 10) : undefined;\n return new SmartEngineClient({\n validatorBaseUrl: baseUrl,\n apiKey: env['VALIDATOR_API_KEY'],\n authToken: env['APP_TOKEN'],\n allowInsecure: env['ALLOW_INSECURE'] === 'true',\n timeout: Number.isFinite(timeout) ? timeout : undefined,\n });\n }\n\n /**\n * Connect to the smart-engines network with auto-discovery and authentication.\n *\n * Steps:\n * 1. Discovers validators via the HCS registry topic.\n * 2. Selects a random validator with an API endpoint.\n * 3. Authenticates with Web3-style challenge-response.\n * 4. Returns a configured client ready to use.\n *\n * @param config - Network, registry topic, and auth signer config.\n * @returns The configured client, the chosen validator, and the auth session.\n * @throws SmartEngineError 503 if no validator with an API endpoint is found.\n */\n static async connectToNetwork(config: NetworkConnectionConfig): Promise<NetworkConnectionResult> {\n const allowInsecure = config.allowInsecure ?? false;\n\n // Step 1: Discover validators\n const discovery = new ValidatorDiscoveryClient({\n network: config.network,\n registryTopicId: config.registryTopicId,\n mirrorNodeUrl: config.mirrorNodeUrl,\n });\n\n const validator = await discovery.getRandomValidator();\n\n if (!validator || !validator.networkEndpoints?.apiEndpoint) {\n throw new SmartEngineError(\n 'No validators available. Check registry topic and network configuration.',\n 503\n );\n }\n\n const validatorUrl = validator.networkEndpoints.apiEndpoint;\n validateClientUrl(validatorUrl, allowInsecure);\n\n // Step 2: Authenticate\n const auth = new ValidatorAuthClient({\n security: { allowInsecure },\n });\n const session = await auth.authenticateWithSigner(\n validatorUrl,\n config.chain,\n config.address,\n config.publicKey,\n config.signFn,\n config.metadata\n );\n\n // Step 3: Create client with auth token. `validatorUrl` is the validator's\n // own `apiEndpoint` resolved from the HCS registry — a validator origin, NOT\n // a gateway URL — so it satisfies the validator-origin type-fence.\n const client = new SmartEngineClient({\n validatorBaseUrl: validatorUrl,\n authToken: session.token,\n allowInsecure,\n });\n\n return { client, validator, session };\n }\n\n // NOTE (SDK 4.0 type-fence): the former `SmartEngineClient.connectToCluster`\n // was REMOVED. It resolved a cluster's `gatewayUrl` and fed it into\n // `new SmartEngineClient({ baseUrl: gatewayUrl })` — a gateway-pointed\n // validator-direct client whose raw `/api/v3/*` calls 404 (the raw tier is\n // un-ingressed at the gateway). That was the footgun. To reach web3 through a\n // cluster use `BaasClient.connectToCluster({ network })` (the host BaaS tier);\n // for an explicit in-cluster validator origin use `new SmartEngineClient({\n // validatorBaseUrl })` or `connectToNetwork` (which resolves a real validator\n // `apiEndpoint` from the HCS registry, never a gateway URL).\n\n /** Get the current validator URL */\n getBaseUrl(): string {\n return this.baseUrl;\n }\n\n /** Check if client has an auth token */\n isAuthenticated(): boolean {\n return this.http.getAuthToken() !== undefined;\n }\n\n /**\n * Get HTTP resilience health information\n * @returns Object with circuit breaker state and last error (if any)\n */\n getHttpHealth(): { breaker: CircuitBreakerSnapshot | null; lastError?: Error } {\n // Note: In a real implementation, we would get the circuit breaker state\n // from the resilient HTTP layer. For now, return null since the base\n // HTTP client doesn't expose it yet.\n return {\n breaker: null,\n lastError: this.lastHttpError,\n };\n }\n\n // ========== Health & Info ==========\n\n /** Get health status of the validator */\n async getHealth(): Promise<{ status: string; timestamp: string; chains: any[] }> {\n return this.http.get('/health');\n }\n\n /** Get list of supported chains */\n async getSupportedChains(): Promise<{ chains: string[] }> {\n return this.http.get('/chains');\n }\n\n // ========== Account Operations ==========\n\n /** Create a new account on the specified chain */\n async createAccount(request: ValidatorCreateAccountRequest): Promise<CreateAccountResponse> {\n const validated = CreateAccountRequestSchema.parse(request);\n return this.http.post('/accounts', validated);\n }\n\n /** Get account information */\n async getAccountInfo(chain: string, accountId: string): Promise<AccountInfo> {\n return this.http.get(`/accounts/${encodePathParam(chain)}/${encodePathParam(accountId)}`);\n }\n\n /** Get account balance */\n async getBalance(chain: string, accountId: string): Promise<AccountBalance> {\n return this.http.get(`/accounts/${encodePathParam(chain)}/${encodePathParam(accountId)}/balance`);\n }\n\n // ========== Transaction Operations ==========\n\n /** Execute a transfer transaction */\n async transfer(request: TransferRequest): Promise<TransferResponse> {\n const validated = TransferRequestSchema.parse(request);\n return this.http.post('/transfer', validated);\n }\n\n /** Get transaction details */\n async getTransaction(chain: string, txId: string): Promise<Transaction> {\n return this.http.get(`/transactions/${encodePathParam(chain)}/${encodePathParam(txId)}`);\n }\n\n /** Get transaction receipt */\n async getTransactionReceipt(chain: string, txId: string): Promise<any> {\n return this.http.get(`/transactions/${encodePathParam(chain)}/${encodePathParam(txId)}/receipt`);\n }\n\n // ========== Token Operations ==========\n\n /** Create a new token */\n async createToken(request: ValidatorCreateTokenRequest): Promise<CreateTokenResponse> {\n const validated = CreateTokenRequestSchema.parse(request);\n return this.http.post('/tokens', validated);\n }\n\n /** Mint tokens */\n async mintToken(request: MintTokenRequest): Promise<any> {\n const validated = MintTokenRequestSchema.parse(request);\n return this.http.post('/tokens/mint', validated);\n }\n\n /**\n * Get token information for a token on the given chain.\n *\n * @param chain - Chain identifier (e.g. `'hedera'`, `'xrpl'`).\n * @param tokenId - Chain-native token identifier.\n * @returns Token metadata and supply information.\n */\n async getTokenInfo(chain: string, tokenId: string): Promise<TokenInfo> {\n return this.http.get(`/tokens/${encodePathParam(chain)}/${encodePathParam(tokenId)}`);\n }\n\n /** Burn tokens to reduce supply */\n async burnToken(request: BurnTokenRequest): Promise<ActionResult> {\n const validated = BurnTokenRequestSchema.parse(request);\n return this.http.post('/tokens/burn', validated);\n }\n\n /** Pause all token operations globally */\n async pauseToken(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n return this.http.post('/tokens/pause', validated);\n }\n\n /** Unpause token operations */\n async unpauseToken(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n return this.http.post('/tokens/unpause', validated);\n }\n\n /** Freeze/restrict an account from transacting the token */\n async restrictAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for restrictAccount', 400);\n }\n return this.http.post('/tokens/restrict', validated);\n }\n\n /** Unfreeze an account */\n async unrestrictAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for unrestrictAccount', 400);\n }\n return this.http.post('/tokens/unrestrict', validated);\n }\n\n /** Grant KYC/compliance approval to an account */\n async enableCompliance(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for enableCompliance', 400);\n }\n return this.http.post('/tokens/compliance/enable', validated);\n }\n\n /** Revoke KYC/compliance approval from an account */\n async disableCompliance(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for disableCompliance', 400);\n }\n return this.http.post('/tokens/compliance/disable', validated);\n }\n\n /** Force remove tokens from an account (compliance action) */\n async wipeFromAccount(request: TokenActionRequest): Promise<ActionResult> {\n const validated = TokenActionRequestSchema.parse(request);\n if (!validated.accountId) {\n throw new SmartEngineError('accountId is required for wipeFromAccount', 400);\n }\n if (!validated.amount) {\n throw new SmartEngineError('amount is required for wipeFromAccount', 400);\n }\n return this.http.post('/tokens/wipe', validated);\n }\n\n // ========== Capabilities Discovery ==========\n\n /** Get capability support matrix for all chains */\n async getAllCapabilities(): Promise<any> {\n return this.http.get('/capabilities');\n }\n\n /** Get capability support for a specific chain */\n async getChainCapabilities(chain: ChainType): Promise<any> {\n return this.http.get(`/capabilities/${encodePathParam(chain)}`);\n }\n\n /** Get comprehensive system status */\n async getSystemStatus(): Promise<any> {\n return this.http.get('/status');\n }\n\n // ========== Messaging Operations ==========\n\n /**\n * Submit a message to consensus.\n *\n * @deprecated Operator-funded message submission is RETIRED on the validator\n * under transaction sovereignty — `POST /api/v3/messages/:chain/:topicId`\n * now returns `403 Forbidden` (the operator must never front the chain fee\n * for a customer-supplied message). Use the payer-funded prepare path\n * instead: prepare a topic-message transaction via\n * `POST /api/transactions/topic/message/prepare`, then have the payer sign\n * and submit the returned bytes.\n */\n async submitMessage(chain: string, topicId: string, message: string): Promise<any> {\n if (message.length > 1024 * 1024) {\n throw new SmartEngineError('Message too large (max 1MB)', 400);\n }\n return this.http.post(`/messages/${encodePathParam(chain)}/${encodePathParam(topicId)}`, {\n message,\n });\n }\n\n // ========== Cluster Operations ==========\n\n /** Get cluster health status */\n async getClusterHealth(): Promise<{\n status: string;\n nodes: number;\n healthy: number;\n unhealthy: number;\n }> {\n return this.http.get('/cluster/health');\n }\n\n /** Get cluster status including node details */\n async getClusterStatus(): Promise<{\n status: string;\n nodeId: string;\n nodes: Array<{\n nodeId: string;\n endpoint: string;\n status: string;\n lastSeen?: string;\n }>;\n quorum: {\n required: number;\n current: number;\n reached: boolean;\n };\n }> {\n return this.http.get('/cluster/status');\n }\n\n // ========== Metrics & Monitoring ==========\n\n /** Get Prometheus-format metrics */\n async getMetrics(): Promise<string> {\n return this.http.get('/metrics');\n }\n\n /** Get queue statistics for monitoring */\n async getQueueStats(): Promise<{\n queues: Record<\n string,\n { pending: number; processing: number; completed: number; failed: number }\n >;\n timestamp: string;\n }> {\n return this.http.get('/monitoring/queue');\n }\n\n /** Get circuit breaker status for all services */\n async getCircuitBreakerStatus(): Promise<{\n breakers: Record<\n string,\n {\n state: 'closed' | 'open' | 'half-open';\n failures: number;\n successes: number;\n lastFailure?: string;\n nextRetry?: string;\n }\n >;\n timestamp: string;\n }> {\n return this.http.get('/monitoring/circuit-breakers');\n }\n\n // ========== Signature Verification ==========\n\n /** Verify an arbitrary signature */\n async verifySignature(request: {\n chain: ChainType;\n message: string;\n signature: string;\n publicKey: string;\n }): Promise<{ valid: boolean; chain: ChainType }> {\n return this.http.post('/auth/verify-signature', request);\n }\n}\n\n/**\n * Custom error class for Smart Engine client\n */\nexport class SmartEngineError extends Error {\n constructor(\n message: string,\n public statusCode: number,\n public details?: any\n ) {\n super(message);\n this.name = 'SmartEngineError';\n }\n}\n\n/**\n * Validate URL and enforce security requirements\n */\nfunction validateClientUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new SmartEngineError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new SmartEngineError(\n 'HTTPS is required for secure connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n return parsed.origin;\n } catch (error) {\n if (error instanceof SmartEngineError) throw error;\n throw new SmartEngineError(`Invalid URL: ${url}`, 400);\n }\n}\n","/**\n * Routing Sub-Client\n *\n * Manages host registration, routing configuration, and request proxying.\n * Wire shapes mirror the server.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n RegisterHostRequest,\n RegisterHostResponse,\n HostInfo,\n HostListResponse,\n RoutingConfig,\n ProxyRequest,\n ProxyResponse,\n RoutingStatsResponse,\n MapDomainToAppResponse,\n} from '../types';\n\n/**\n * Routing Sub-Client\n *\n * @example\n * ```typescript\n * await gateway.routing.registerHost({\n * appId: 'my-app',\n * address: '10.0.0.5',\n * port: 3000,\n * });\n *\n * const stats = await gateway.routing.getStats();\n * ```\n */\nexport class RoutingClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Register a new host. The server validates the payload via Zod (appId\n * pattern, IP/hostname format, port range) and kicks off async\n * verification. Response includes the registered host plus a status\n * message about verification.\n */\n async registerHost(request: RegisterHostRequest): Promise<RegisterHostResponse> {\n return this.http.post('/routing/hosts', request);\n }\n\n /** Unregister a host. */\n async unregisterHost(hostId: string): Promise<{ success: boolean; message: string }> {\n return this.http.delete(`/routing/hosts/${encodePathParam(hostId)}`);\n }\n\n /** Get all registered hosts. */\n async getAllHosts(): Promise<HostListResponse> {\n return this.http.get('/routing/hosts');\n }\n\n /** Get only verified hosts. */\n async getVerifiedHosts(): Promise<HostListResponse> {\n return this.http.get('/routing/hosts/verified');\n }\n\n /** Get a specific host by ID. */\n async getHost(hostId: string): Promise<HostInfo> {\n return this.http.get(`/routing/hosts/${encodePathParam(hostId)}`);\n }\n\n /** Trigger host re-verification. */\n async verifyHost(\n hostId: string,\n ): Promise<{\n success: boolean;\n hostId: string;\n verified: boolean;\n attestationScore?: number;\n message: string;\n }> {\n return this.http.post(`/routing/hosts/${encodePathParam(hostId)}/verify`, {});\n }\n\n /** Set routing configuration for an app. */\n async setRoutingConfig(\n appId: string,\n config: RoutingConfig,\n ): Promise<{ success: boolean; appId: string; message: string }> {\n return this.http.put(`/routing/config/${encodePathParam(appId)}`, config);\n }\n\n /** Get routing configuration for an app. */\n async getRoutingConfig(appId: string): Promise<RoutingConfig> {\n return this.http.get(`/routing/config/${encodePathParam(appId)}`);\n }\n\n /** Proxy a request through the gateway. */\n async proxyRequest(request: ProxyRequest): Promise<ProxyResponse> {\n return this.http.post('/routing/proxy', request);\n }\n\n /** Get routing statistics. */\n async getStats(): Promise<RoutingStatsResponse> {\n return this.http.get('/routing/stats');\n }\n\n /**\n * Map a domain/subdomain to an application for hostname-based routing.\n * The server returns `{ domain, appId, message }` — there is no `success`\n * field; treat `appId` as the success signal.\n */\n async mapDomainToApp(domain: string, appId: string): Promise<MapDomainToAppResponse> {\n return this.http.post(`/routing/domains/${encodePathParam(domain)}/map`, { appId });\n }\n}\n","/**\n * Domains Sub-Client\n *\n * Manages domain registration, verification, DNS configuration, and transfers.\n * Wire shapes mirror the server.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n DomainRegistrationRequest,\n DomainInfo,\n DomainListResponse,\n DomainAvailabilityResponse,\n VerificationMethod,\n VerificationTokenResponse,\n VerificationResult,\n DnsRecord,\n DomainTransferRequest,\n} from '../types';\n\n/**\n * Domains Sub-Client\n *\n * @example\n * ```typescript\n * const domain = await gateway.domains.register({ domain: 'myapp.example.com', owner: '0.0.123' });\n *\n * const token = await gateway.domains.generateVerificationToken('myapp.example.com', 'dns-txt');\n * const result = await gateway.domains.verifyOwnership('myapp.example.com', token.token);\n * ```\n */\nexport class DomainsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Register a new domain */\n async register(request: DomainRegistrationRequest): Promise<DomainInfo> {\n return this.http.post('/domains', request);\n }\n\n /** Check domain availability */\n async checkAvailability(domain: string): Promise<DomainAvailabilityResponse> {\n return this.http.get(`/domains/check/${encodePathParam(domain)}`);\n }\n\n /** Get domain information */\n async getInfo(domain: string): Promise<DomainInfo> {\n return this.http.get(`/domains/${encodePathParam(domain)}`);\n }\n\n /** List domains, optionally filtered by owner */\n async list(owner?: string): Promise<DomainListResponse> {\n const params = owner ? `?owner=${encodeURIComponent(owner)}` : '';\n return this.http.get(`/domains${params}`);\n }\n\n /**\n * Generate a verification token. Server accepts one of `dns-txt`,\n * `dns-cname`, `http-file`, `email`.\n */\n async generateVerificationToken(\n domain: string,\n method: VerificationMethod,\n ): Promise<VerificationTokenResponse> {\n return this.http.post(`/domains/${encodePathParam(domain)}/verification`, { method });\n }\n\n /** Verify domain ownership */\n async verifyOwnership(domain: string, token: string): Promise<VerificationResult> {\n return this.http.post(`/domains/${encodePathParam(domain)}/verify`, { token });\n }\n\n /** Configure DNS records for a domain */\n async configureDns(\n domain: string,\n records: DnsRecord[],\n ): Promise<{ success: boolean; records: DnsRecord[] }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dns`, { records });\n }\n\n /** Enable DNSSEC for a domain */\n async enableDnssec(domain: string): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dnssec/enable`, {});\n }\n\n /** Disable DNSSEC for a domain */\n async disableDnssec(domain: string): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/dnssec/disable`, {});\n }\n\n /** Renew a domain */\n async renew(domain: string, years?: number): Promise<DomainInfo> {\n return this.http.post(`/domains/${encodePathParam(domain)}/renew`, { years: years ?? 1 });\n }\n\n /** Initiate a domain transfer */\n async transfer(\n domain: string,\n request: DomainTransferRequest,\n ): Promise<{ success: boolean; message: string }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer`, request);\n }\n\n /** Approve a pending domain transfer */\n async approveTransfer(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer/approve`, {});\n }\n\n /** Reject a pending domain transfer */\n async rejectTransfer(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/transfer/reject`, {});\n }\n\n /** Suspend a domain */\n async suspend(domain: string, reason: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/suspend`, { reason });\n }\n\n /** Unsuspend a domain */\n async unsuspend(domain: string): Promise<{ success: boolean }> {\n return this.http.post(`/domains/${encodePathParam(domain)}/unsuspend`, {});\n }\n}\n","/**\n * DNS Sub-Client\n *\n * Manages DNS resolution, zone management, and DNSSEC.\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n DnsResolveResponse,\n DnsBatchQuery,\n DnsBatchResolveResponse,\n DnsZone,\n DnsZoneListResponse,\n DnsRecord,\n DnsRecordInfo,\n DnssecKey,\n DnssecDsRecord,\n} from '../types';\n\n/**\n * DNS Sub-Client\n *\n * @example\n * ```typescript\n * // Resolve a name\n * const result = await gateway.dns.resolve('myapp.example.com', 'A');\n *\n * // Manage zones\n * const zones = await gateway.dns.listZones();\n * ```\n */\nexport class DnsClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Resolve a DNS name */\n async resolve(name: string, type?: string, dnssec?: boolean): Promise<DnsResolveResponse> {\n const params = new URLSearchParams({ name });\n if (type) params.set('type', type);\n if (dnssec !== undefined) params.set('dnssec', String(dnssec));\n return this.http.get(`/dns/resolve?${params.toString()}`);\n }\n\n /** Batch resolve multiple DNS queries */\n async resolveBatch(queries: DnsBatchQuery[]): Promise<DnsBatchResolveResponse> {\n return this.http.post('/dns/resolve/batch', { queries });\n }\n\n /** List all DNS zones */\n async listZones(): Promise<DnsZoneListResponse> {\n return this.http.get('/dns/zones');\n }\n\n /** Get a specific zone */\n async getZone(zoneName: string): Promise<DnsZone & { records: DnsRecordInfo[] }> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}`);\n }\n\n /** Create a new DNS zone */\n async createZone(request: { zoneName: string; description?: string }): Promise<DnsZone> {\n return this.http.post('/dns/zones', request);\n }\n\n /** Delete a DNS zone */\n async deleteZone(zoneName: string): Promise<{ success: boolean }> {\n return this.http.delete(`/dns/zones/${encodePathParam(zoneName)}`);\n }\n\n /** Add a record to a zone */\n async addRecord(zoneName: string, record: DnsRecord): Promise<DnsRecordInfo> {\n return this.http.post(`/dns/zones/${encodePathParam(zoneName)}/records`, record);\n }\n\n /** Update a record in a zone */\n async updateRecord(\n zoneName: string,\n recordId: string,\n updates: Partial<DnsRecord>\n ): Promise<DnsRecordInfo> {\n return this.http.put(\n `/dns/zones/${encodePathParam(zoneName)}/records/${encodePathParam(recordId)}`,\n updates\n );\n }\n\n /** Delete a record from a zone */\n async deleteRecord(zoneName: string, recordId: string): Promise<{ success: boolean }> {\n return this.http.delete(\n `/dns/zones/${encodePathParam(zoneName)}/records/${encodePathParam(recordId)}`\n );\n }\n\n /** Generate DNSSEC keys for a zone */\n async generateDnssecKeys(\n zoneName: string,\n algorithm?: string\n ): Promise<{ keys: DnssecKey[] }> {\n return this.http.post(`/dns/zones/${encodePathParam(zoneName)}/dnssec/keys`, {\n algorithm,\n });\n }\n\n /** Get DNSSEC keys for a zone */\n async getDnssecKeys(zoneName: string): Promise<{ keys: DnssecKey[] }> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}/dnssec/keys`);\n }\n\n /** Get DS record for a zone (for registrar configuration) */\n async getDsRecord(zoneName: string): Promise<DnssecDsRecord> {\n return this.http.get(`/dns/zones/${encodePathParam(zoneName)}/dnssec/ds`);\n }\n\n /** Clear DNS cache */\n async clearCache(): Promise<{ success: boolean; entriesCleared: number }> {\n return this.http.post('/dns/cache/clear', {});\n }\n}\n","/**\n * Health Sub-Client\n *\n * Wraps the gateway's health endpoints, including the per-cluster\n * `GET /cluster/health` aggregate that merges local validator + host +\n * genesis state (used by the cross-cluster metrics aggregator and any SDK\n * caller probing a single cluster). All endpoints are `@Public()` on the\n * server — no auth required.\n */\nimport type { HttpClient } from '../../http';\nimport type { ClusterHealthAggregate } from '../types';\n\nexport class HealthClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Per-cluster aggregate health probe. Wraps `GET /api/v3/cluster/health`.\n * Returns local validator + host + genesis state in a single payload.\n */\n async getCluster(): Promise<ClusterHealthAggregate> {\n return this.http.get('/cluster/health');\n }\n}\n","/**\n * Smart Gateway Client\n *\n * Top-level client for interacting with Smart Engines Gateway.\n * Manages host routing, domain registration, and DNS resolution.\n *\n * @example\n * ```typescript\n * import { SmartGatewayClient } from '@hsuite/smart-engines-sdk';\n *\n * const gateway = new SmartGatewayClient({\n * baseUrl: 'https://gateway.smartengines.io',\n * apiKey: 'your-api-key',\n * });\n *\n * // Routing\n * const hosts = await gateway.routing.getAllHosts();\n *\n * // Domains\n * const available = await gateway.domains.checkAvailability('myapp.example.com');\n *\n * // DNS\n * const resolved = await gateway.dns.resolve('myapp.example.com', 'A');\n *\n * // Health\n * const health = await gateway.getHealth();\n * const cluster = await gateway.health.getCluster();\n * ```\n */\nimport { createHttpClient, SdkHttpError, type HttpClient } from '../http';\nimport { RoutingClient } from './routing';\nimport { DomainsClient } from './domains';\nimport { DnsClient } from './dns';\nimport { HealthClient } from './health';\nimport type {\n GatewayHealthResponse,\n GatewayStatusResponse,\n GatewayReadinessResponse,\n GatewayLivenessResponse,\n GatewayMetricsResponse,\n GatewayMetricsSummaryResponse,\n} from './types';\n\n/**\n * Configuration for SmartGatewayClient\n */\nexport type SmartGatewayClientConfig = {\n /** Gateway API base URL */\n baseUrl: string;\n /** API key for authenticated requests */\n apiKey?: string;\n /** Bearer token from authentication */\n authToken?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Allow HTTP connections (only for local development) */\n allowInsecure?: boolean;\n};\n\n/**\n * Smart Gateway Client\n *\n * Primary client for gateway operations: routing, domains, DNS, and\n * cluster-aggregate health.\n */\nexport class SmartGatewayClient {\n private readonly http: HttpClient;\n\n /** Host routing and proxy management */\n public readonly routing: RoutingClient;\n /** Domain registration and management */\n public readonly domains: DomainsClient;\n /** DNS resolution and zone management */\n public readonly dns: DnsClient;\n /** Per-cluster aggregate health probe (validator + host + genesis state) */\n public readonly health: HealthClient;\n\n constructor(config: SmartGatewayClientConfig) {\n const baseUrl = config.baseUrl.replace(/\\/+$/, '');\n\n this.http = createHttpClient({\n baseUrl: `${baseUrl}/api/v3`,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n });\n\n this.routing = new RoutingClient(this.http);\n this.domains = new DomainsClient(this.http);\n this.dns = new DnsClient(this.http);\n this.health = new HealthClient(this.http);\n }\n\n // ========== Health & Metrics ==========\n\n /** Get gateway-only health status (binary `status: 'ok'` snapshot). */\n async getHealth(): Promise<GatewayHealthResponse> {\n return this.http.get('/health');\n }\n\n /**\n * Get detailed gateway status — `subsystems` tree (dns/routing/verification)\n * plus the operating `mode` snapshot. Aggregated counts live on `getMetrics()`.\n */\n async getStatus(): Promise<GatewayStatusResponse> {\n return this.http.get('/status');\n }\n\n /**\n * Check gateway readiness. Resolves to either `{ status: 'ready', ... }`\n * with a verified host count or `{ status: 'not_ready', reason, ... }`.\n *\n * NOTE: `/api/v3/ready` returns **HTTP 503** when not ready (so load\n * balancers / k8s probes drain the origin). This method unwraps that 503's\n * body and still RESOLVES to a `GatewayReadinessResponse` — it does not\n * throw for a not-ready gateway. Genuine errors (non-readiness 503s, 5xx,\n * network) still throw.\n */\n async getReadiness(): Promise<GatewayReadinessResponse> {\n try {\n return await this.http.get<GatewayReadinessResponse>('/ready');\n } catch (err) {\n // The not-ready 503 carries the `{status:'not_ready', ...}` body. The\n // gateway's global exception filter wraps it as\n // {statusCode,error,message,context:{...}} — payload under `context` —\n // while a non-filtered server would return it top-level. Accept either\n // and surface the inner body instead of throwing.\n if (err instanceof SdkHttpError && err.statusCode === 503) {\n const d = err.details as\n | { status?: string; context?: GatewayReadinessResponse }\n | undefined;\n const body = (d?.context ?? d) as\n | (GatewayReadinessResponse & { status?: string })\n | undefined;\n if (body?.status === 'not_ready') {\n return body as GatewayReadinessResponse;\n }\n }\n throw err;\n }\n }\n\n /** Check gateway liveness. */\n async getLiveness(): Promise<GatewayLivenessResponse> {\n return this.http.get('/live');\n }\n\n /**\n * Get aggregated network metrics across all clusters — per-cluster health,\n * chain connectivity, gateway counts, and genesis state. Server caches the\n * payload (default 30s); pass `refresh=true` to force a fresh fetch.\n */\n async getMetrics(refresh?: boolean): Promise<GatewayMetricsResponse> {\n const params = refresh ? '?refresh=true' : '';\n return this.http.get(`/metrics${params}`);\n }\n\n /** Get lightweight network summary (status-badge-friendly). */\n async getMetricsSummary(): Promise<GatewayMetricsSummaryResponse> {\n return this.http.get('/metrics/summary');\n }\n}\n","/**\n * Database Sub-Client\n *\n * Trustless database with state proofs and Merkle verification.\n *\n * @example\n * ```typescript\n * // CRUD operations\n * const result = await baas.db.insert('users', { name: 'Alice' });\n * const users = await baas.db.find('users', { name: 'Alice' });\n *\n * // State proofs\n * const root = await baas.db.getStateRoot();\n * const proof = await baas.db.getDocumentProof('doc-123');\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type {\n BaasInsertResult,\n BaasUpdateResult,\n BaasDeleteResult,\n BaasFindResult,\n BaasQueryOptions,\n BaasMerkleProof,\n BaasStateTransition,\n} from '../types';\n\n/** State root response */\nexport type StateRootResponse = {\n appId: string;\n stateRoot: string;\n blockHeight: number;\n timestamp: string;\n};\n\n/** Document proof response */\nexport type DocumentProofResponse = {\n documentId: string;\n exists: boolean;\n proof: BaasMerkleProof;\n stateRoot: string;\n};\n\n/** State transitions response */\nexport type StateTransitionsResponse = {\n transitions: BaasStateTransition[];\n total: number;\n fromBlock: number;\n toBlock: number;\n};\n\n/** Database stats response */\nexport type DatabaseStatsResponse = {\n collections: number;\n documents: number;\n storageSize: number;\n stateRoot: string;\n blockHeight: number;\n};\n\nexport class DatabaseClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Insert a document into a collection\n */\n async insert(collection: string, document: Record<string, unknown>): Promise<BaasInsertResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}`,\n document\n );\n }\n\n /**\n * Find documents in a collection\n */\n async find(\n collection: string,\n query?: Record<string, unknown>,\n options?: BaasQueryOptions\n ): Promise<BaasFindResult> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (query && Object.keys(query).length > 0) {\n params.set('query', JSON.stringify(query));\n }\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.skip !== undefined) params.set('skip', String(options.skip));\n if (options?.sort) params.set('sort', options.sort);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Update a document in a collection\n */\n async update(\n collection: string,\n documentId: string,\n updates: Record<string, unknown>\n ): Promise<BaasUpdateResult> {\n const appId = this.getAppId();\n return this.http.put(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}/${encodePathParam(documentId)}`,\n updates\n );\n }\n\n /**\n * Delete a document from a collection\n */\n async delete(collection: string, documentId: string): Promise<BaasDeleteResult> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(collection)}/${encodePathParam(documentId)}`\n );\n }\n\n /**\n * List collections for the app.\n *\n * Server route is `/api/v3/baas/db/:appId/collections`\n * (`database.controller.ts:106`). The previous bare-`:appId` GET 404'd\n * — Nest reserves that pattern for the document-find router below.\n */\n async listCollections(): Promise<{ collections: string[] }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/collections`);\n }\n\n /**\n * Create a new collection in the database.\n *\n * Server returns `{ success: true; collection: string }`\n * (`database.controller.ts:96`).\n */\n async createCollection(name: string): Promise<{ success: boolean; collection: string }> {\n const appId = this.getAppId();\n return this.http.post(`/api/v3/baas/db/${encodePathParam(appId)}/collections`, { name });\n }\n\n /**\n * Drop a collection and all its documents.\n *\n * Server returns `{ success: true }`\n * (`database.controller.ts:133`).\n */\n async dropCollection(name: string): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/db/${encodePathParam(appId)}/collections/${encodePathParam(name)}`\n );\n }\n\n // ========== State Proofs ==========\n\n /**\n * Get the current state root for the app\n */\n async getStateRoot(): Promise<StateRootResponse> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/state/root`);\n }\n\n /**\n * Get a Merkle proof for a specific document\n */\n async getDocumentProof(documentId: string): Promise<DocumentProofResponse> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/${encodePathParam(documentId)}/proof`\n );\n }\n\n /**\n * Get state transitions (audit log)\n */\n async getStateTransitions(options?: {\n fromBlock?: number;\n toBlock?: number;\n limit?: number;\n }): Promise<StateTransitionsResponse> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.fromBlock !== undefined) params.set('fromBlock', String(options.fromBlock));\n if (options?.toBlock !== undefined) params.set('toBlock', String(options.toBlock));\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/db/${encodePathParam(appId)}/state/transitions${qs ? `?${qs}` : ''}`\n );\n }\n\n /**\n * Get database statistics\n */\n async getDbStats(): Promise<DatabaseStatsResponse> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/db/${encodePathParam(appId)}/stats`);\n }\n}\n","/**\n * Storage Sub-Client\n *\n * Manages decentralized file storage on the host.\n *\n * @example\n * ```typescript\n * const result = await baas.storage.upload(fileBuffer, 'report.pdf');\n * const exists = await baas.storage.exists(result.cid);\n * const file = await baas.storage.download(result.cid);\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasUploadResult,\n BaasFileInfo,\n BaasFileMetadata,\n BaasStorageUsage,\n} from '../types';\n\nexport class StorageClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Upload a file to storage\n */\n async upload(\n file: Blob | Buffer,\n filename: string,\n metadata?: Record<string, string>,\n opts?: HttpCallOptions\n ): Promise<BaasUploadResult> {\n const appId = this.getAppId();\n return this.http.upload(`/api/v3/baas/storage/${encodePathParam(appId)}/upload`, file, filename, metadata, undefined, opts);\n }\n\n /**\n * Download a file by CID. Returns the raw file bytes as a `Uint8Array`\n * (binary-safe — never JSON-parsed or text-decoded).\n */\n async download(cid: string, opts?: HttpCallOptions): Promise<Uint8Array> {\n const appId = this.getAppId();\n return this.http.getBinary(`/api/v3/baas/storage/${encodePathParam(appId)}/download/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * Download a file by CID WITH its response metadata — the raw bytes plus the\n * host-supplied `contentType` (derived from the stored file's metadata) and,\n * when present, the `filename`. Use this instead of {@link download} when the\n * caller must echo the content-type back to its own client; a bytes-only\n * download cannot recover it.\n */\n async downloadWithMeta(\n cid: string,\n opts?: HttpCallOptions,\n ): Promise<{ bytes: Uint8Array; contentType?: string; filename?: string }> {\n const appId = this.getAppId();\n return this.http.getBinaryWithMeta(\n `/api/v3/baas/storage/${encodePathParam(appId)}/download/${encodePathParam(cid)}`,\n opts,\n );\n }\n\n /**\n * Get file metadata\n */\n async getMetadata(cid: string, opts?: HttpCallOptions): Promise<BaasFileMetadata> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/metadata/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * Delete a file\n */\n async delete(cid: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(`/api/v3/baas/storage/${encodePathParam(appId)}/${encodePathParam(cid)}`, opts);\n }\n\n /**\n * List all files for the app.\n *\n * @param pagination - Optional `limit` and `offset` (the server reads\n * `offset` for pagination).\n * @returns The file list and total count.\n */\n async listFiles(pagination?: { limit?: number; offset?: number }, opts?: HttpCallOptions): Promise<{ files: BaasFileInfo[]; total: number }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (pagination?.limit !== undefined) params.set('limit', String(pagination.limit));\n if (pagination?.offset !== undefined) params.set('offset', String(pagination.offset));\n const qs = params.toString();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/files${qs ? `?${qs}` : ''}`, opts);\n }\n\n /**\n * Get storage usage for the current app\n */\n async getUsage(opts?: HttpCallOptions): Promise<BaasStorageUsage> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/usage`, opts);\n }\n\n /**\n * Check if a file exists\n */\n async exists(cid: string, opts?: HttpCallOptions): Promise<{ exists: boolean; cid: string }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/storage/${encodePathParam(appId)}/exists/${encodePathParam(cid)}`, opts);\n }\n}\n","/**\n * Functions Sub-Client\n *\n * Manages serverless function deployment, invocation, and monitoring.\n *\n * @example\n * ```typescript\n * // Deploy a function\n * const fn = await baas.functions.deploy({\n * name: 'process-order',\n * runtime: 'nodejs18',\n * handler: 'index.handler',\n * code: functionCode,\n * });\n *\n * // Invoke it\n * const result = await baas.functions.invoke(fn.functionId, { orderId: '123' });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasFunctionDeployRequest,\n BaasFunctionEvalRequest,\n BaasFunctionDeployResult,\n BaasFunctionResult,\n BaasFunctionInfo,\n BaasFunctionCode,\n BaasFunctionLog,\n BaasFunctionLogOptions,\n BaasSignedCode,\n} from '../types';\n\nexport class FunctionsClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Build the Ed25519 signed-code envelope the host mandates for every deploy\n * and eval. A fresh ephemeral keypair is generated per call, so no long-lived\n * signing key is held anywhere — each artifact carries its own signature.\n *\n * Scheme (must match the host verifier): `hash = sha256(code)` (hex),\n * `message = \"<hash>:<timestamp>\"`, signed Ed25519; `publicKey` is SPKI-DER\n * (base64). `crypto` is imported lazily so this never pulls Node built-ins\n * into a browser bundle that doesn't sign code.\n */\n async signCode(code: string): Promise<BaasSignedCode> {\n const { generateKeyPairSync, createHash, sign } = await import('crypto');\n const { publicKey, privateKey } = generateKeyPairSync('ed25519');\n const hash = createHash('sha256').update(code, 'utf8').digest('hex');\n const timestamp = new Date().toISOString();\n const signature = sign(null, Buffer.from(`${hash}:${timestamp}`, 'utf8'), privateKey).toString('base64');\n const publicKeyDer = publicKey.export({ format: 'der', type: 'spki' }).toString('base64');\n return { code, hash, timestamp, signature, publicKey: publicKeyDer };\n }\n\n /**\n * Deploy a new function. If `signedCode` is omitted it is auto-built from\n * `request.code` via {@link signCode} — the host requires it, so the default\n * is to sign rather than 400. Pass your own envelope to override.\n */\n async deploy(request: BaasFunctionDeployRequest, opts?: HttpCallOptions): Promise<BaasFunctionDeployResult> {\n const appId = this.getAppId();\n const signedCode = request.signedCode ?? (await this.signCode(request.code));\n return this.http.post(`/api/v3/baas/functions/${encodePathParam(appId)}`, { ...request, signedCode }, opts);\n }\n\n /**\n * Invoke a function\n */\n async invoke(functionId: string, payload?: unknown, opts?: HttpCallOptions): Promise<BaasFunctionResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/invoke`,\n payload ?? {},\n opts\n );\n }\n\n /**\n * Evaluate signed code once (ephemeral) — no persistent deploy.\n *\n * For throwaway / AI-generated snippets. The host runs it in the same hardened\n * isolate and discards it; metered + quota'd like a normal invocation. As with\n * {@link deploy}, `signedCode` is auto-built from `request.code` when omitted.\n */\n async eval(request: BaasFunctionEvalRequest, opts?: HttpCallOptions): Promise<BaasFunctionResult> {\n const appId = this.getAppId();\n const signedCode = request.signedCode ?? (await this.signCode(request.code));\n return this.http.post(`/api/v3/baas/functions/${encodePathParam(appId)}/eval`, { ...request, signedCode }, opts);\n }\n\n /**\n * List all functions for the current app\n */\n async list(opts?: HttpCallOptions): Promise<{ functions: BaasFunctionInfo[]; total: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/functions/${encodePathParam(appId)}`, opts);\n }\n\n /**\n * Get function details\n */\n async get(functionId: string, opts?: HttpCallOptions): Promise<BaasFunctionInfo> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n opts\n );\n }\n\n /**\n * Get a function's source code\n */\n async getCode(functionId: string, opts?: HttpCallOptions): Promise<BaasFunctionCode> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/code`,\n opts\n );\n }\n\n /**\n * Update a function\n */\n async update(functionId: string, updates: Partial<BaasFunctionDeployRequest>, opts?: HttpCallOptions): Promise<BaasFunctionInfo> {\n const appId = this.getAppId();\n return this.http.put(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n updates,\n opts\n );\n }\n\n /**\n * Delete a function\n */\n async delete(functionId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}`,\n opts\n );\n }\n\n /**\n * Get function execution logs\n */\n async getLogs(functionId: string, options?: BaasFunctionLogOptions, opts?: HttpCallOptions): Promise<{ logs: BaasFunctionLog[]; total: number }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.startTime) params.set('startTime', options.startTime);\n if (options?.level) params.set('level', options.level);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/functions/${encodePathParam(appId)}/${encodePathParam(functionId)}/logs${qs ? `?${qs}` : ''}`,\n opts\n );\n }\n\n /**\n * Get function statistics for an app\n */\n async getStats(opts?: HttpCallOptions): Promise<any> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/functions/${encodePathParam(appId)}/stats`, opts);\n }\n}\n","/**\n * Messaging Sub-Client\n *\n * Full pub/sub messaging with channels, history, and presence.\n *\n * @example\n * ```typescript\n * // Create a channel\n * await baas.messaging.createChannel({ name: 'events', persistent: true });\n *\n * // Publish a message\n * await baas.messaging.publish('events', { type: 'order.created', orderId: '123' });\n *\n * // Get history\n * const history = await baas.messaging.getHistory('events', { limit: 50 });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type {\n BaasChannelConfig,\n BaasPublishResult,\n BaasPresenceMember,\n BaasPresenceInfo,\n BaasHistoryOptions,\n BaasMessage,\n} from '../types';\n\nexport class MessagingClient {\n constructor(\n private readonly http: HttpClient,\n private readonly getAppId: () => string\n ) {}\n\n /**\n * Create a new channel\n */\n async createChannel(config: BaasChannelConfig, opts?: HttpCallOptions): Promise<BaasChannelConfig & { channelId: string }> {\n const appId = this.getAppId();\n return this.http.post(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels`, config, opts);\n }\n\n /**\n * Delete a channel\n */\n async deleteChannel(channelId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channelId)}`, opts);\n }\n\n /**\n * Get a channel by ID\n */\n async getChannel(channelId: string, opts?: HttpCallOptions): Promise<BaasChannelConfig & { channelId: string; messageCount: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channelId)}`, opts);\n }\n\n /**\n * List all channels for the app\n */\n async listChannels(opts?: HttpCallOptions): Promise<{ channels: Array<BaasChannelConfig & { channelId: string }>; total: number }> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/channels`, opts);\n }\n\n /**\n * Publish a message to a channel\n */\n async publish(\n channel: string,\n message: Record<string, unknown>,\n metadata?: Record<string, unknown>,\n opts?: HttpCallOptions\n ): Promise<BaasPublishResult> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/publish`,\n { data: message, metadata },\n opts\n );\n }\n\n /**\n * Get message history for a channel\n */\n async getHistory(\n channel: string,\n options?: BaasHistoryOptions,\n opts?: HttpCallOptions\n ): Promise<{ messages: BaasMessage[]; total: number; hasMore: boolean }> {\n const appId = this.getAppId();\n const params = new URLSearchParams();\n if (options?.limit !== undefined) params.set('limit', String(options.limit));\n if (options?.before) params.set('before', options.before);\n if (options?.after) params.set('after', options.after);\n const qs = params.toString();\n return this.http.get(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/history${qs ? `?${qs}` : ''}`,\n opts\n );\n }\n\n /**\n * Set presence for a member in a channel.\n *\n * BREAKING CHANGE (SDK 3.3.0): presence is channel-scoped on the server\n * (`messaging.controller.ts:312`). Previous signature\n * `setPresence(member)` hit a non-existent appId-scoped route and 404'd\n * in production. The channel is now the first argument.\n */\n async setPresence(channel: string, member: BaasPresenceMember, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.post(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence`,\n member,\n opts\n );\n }\n\n /**\n * Remove a member's presence from a channel.\n *\n * BREAKING CHANGE (SDK 3.3.0): server route is\n * `/api/v3/baas/messaging/:appId/channels/:channel/presence/:clientId`\n * (`messaging.controller.ts:352`). `channel` is now the first arg and\n * `clientId` (not `memberId`) the second — they're the same identifier\n * but renamed to match the server param.\n */\n async removePresence(channel: string, clientId: string, opts?: HttpCallOptions): Promise<{ success: boolean }> {\n const appId = this.getAppId();\n return this.http.delete(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence/${encodePathParam(clientId)}`,\n opts\n );\n }\n\n /**\n * Get presence info for a channel\n */\n async getPresence(channel: string, opts?: HttpCallOptions): Promise<BaasPresenceInfo> {\n const appId = this.getAppId();\n return this.http.get(\n `/api/v3/baas/messaging/${encodePathParam(appId)}/channels/${encodePathParam(channel)}/presence`,\n opts\n );\n }\n\n /**\n * Get messaging statistics\n */\n async getStats(opts?: HttpCallOptions): Promise<any> {\n const appId = this.getAppId();\n return this.http.get(`/api/v3/baas/messaging/${encodePathParam(appId)}/stats`, opts);\n }\n}\n","/**\n * Customer-Session Sub-Client (TokenGate Face B).\n *\n * Wraps the smart-host's customer→smart-app session bridge:\n * POST /api/v3/baas/customer-session/challenge (public)\n * POST /api/v3/baas/customer-session/verify (public)\n * GET /api/v3/baas/customer-session/validate (Bearer)\n * POST /api/v3/baas/customer-session/end (Bearer)\n *\n * Used by smart-apps to authenticate their customers without API keys: the\n * customer signs a chain-X challenge with their wallet, the host verifies the\n * signature against the chosen chain (and optionally a TokenGate NFT for\n * paid tiers), and returns a short-lived JWT (≤15 min by default).\n *\n * Free_testnet smart-apps gracefully skip the NFT step — customers only need\n * to prove wallet ownership via signature.\n */\n\nexport type CustomerSessionChallenge = {\n challenge: string;\n};\n\nexport type CustomerSessionVerifyRequest = {\n appId: string;\n chain: string;\n address: string;\n /** Public key (chain-dependent, e.g. ED25519 for Hedera, secp256k1 for XRPL). */\n publicKey?: string;\n signature: string;\n challenge: string;\n};\n\nexport type CustomerSessionToken = {\n /** Short-lived JWT to attach as `Authorization: Bearer ...` on subsequent calls. */\n token: string;\n sessionId: string;\n validatorId: string;\n expiresAt: string;\n sessionSecret: string;\n};\n\nexport type CustomerSessionInfo = {\n sessionId: string;\n appId: string;\n customerChain: string;\n customerAddress: string;\n /** Optional — present only when the customer holds a TokenGate-recognised NFT. */\n subscriptionContext?: {\n nftSerial: number;\n // Subscription tier ladder: builder | growth | scale | enterprise.\n tier: 'builder' | 'growth' | 'scale' | 'enterprise';\n expiresAt: string;\n allowedAutomations?: string[];\n };\n createdAt: string;\n expiresAt: string;\n lastActivityAt: string;\n};\n\nexport class CustomerSessionClient {\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number = 30_000,\n ) {}\n\n /**\n * Step 1: ask the host to issue a fresh challenge for the customer to sign.\n */\n async challenge(input: { chain: string; address: string }): Promise<CustomerSessionChallenge> {\n return this.fetch<CustomerSessionChallenge>('POST', '/api/v3/baas/customer-session/challenge', input);\n }\n\n /**\n * Step 2: submit the customer's signed challenge. On success returns a\n * short-lived bearer JWT scoped to {appId, chain, address}.\n */\n async verify(req: CustomerSessionVerifyRequest): Promise<CustomerSessionToken> {\n return this.fetch<CustomerSessionToken>('POST', '/api/v3/baas/customer-session/verify', req);\n }\n\n /**\n * Validate a customer bearer + return the decoded session info. Used by\n * smart-app backends to authorise incoming customer requests.\n */\n async validate(bearer: string): Promise<CustomerSessionInfo> {\n return this.fetch<CustomerSessionInfo>('GET', '/api/v3/baas/customer-session/validate', undefined, bearer);\n }\n\n /**\n * Revoke a customer session. Idempotent.\n */\n async end(bearer: string): Promise<{ revoked: boolean; sessionId: string }> {\n return this.fetch<{ revoked: boolean; sessionId: string }>(\n 'POST',\n '/api/v3/baas/customer-session/end',\n undefined,\n bearer,\n );\n }\n\n private async fetch<T>(\n method: 'GET' | 'POST',\n path: string,\n body?: unknown,\n bearer?: string,\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (bearer) headers['Authorization'] = `Bearer ${bearer}`;\n const init: RequestInit = { method, headers, signal: controller.signal };\n if (body !== undefined) init.body = JSON.stringify(body);\n const response = await fetch(url, init);\n clearTimeout(timeoutId);\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as { message?: string };\n const err = new Error(\n errBody.message ?? `customer-session ${path} failed: ${response.status} ${response.statusText}`,\n ) as Error & { status: number };\n err.status = response.status;\n throw err;\n }\n const text = await response.text();\n if (!text) return undefined as T;\n return JSON.parse(text) as T;\n } catch (error) {\n clearTimeout(timeoutId);\n const e = error as Error;\n if (e.name === 'AbortError') {\n throw new Error(`customer-session ${path} timeout`);\n }\n throw error;\n }\n }\n}\n","/**\n * Rules Sub-Client\n *\n * Smart-app authoring surface for canonical validator rules: publish a\n * `ValidatorRules` document to HCS, fetch a published rule by consensus\n * timestamp, list rules owned by the authenticated entity, simulate\n * cluster-side evaluation, and walk version history.\n *\n * @example\n * ```typescript\n * import { Rules } from '@hsuite/smart-engines-sdk';\n *\n * const rule = Rules.forToken()\n * .withSecurity('full')\n * .withOperations({ mint: { enabled: true, limits: { dailyLimit: '1000000' } } })\n * .build();\n *\n * const { ruleRef } = await baas.rules.publish(rule);\n * const sim = await baas.rules.simulate({ ruleRef, action: 'mint', context: { amount: '500' } });\n * ```\n */\nimport { encodePathParam, type HttpClient } from '../../http';\nimport type { PublishedRule, RuleRef, ValidatorRules } from '../../rules';\nimport type {\n DeprecateRuleResponse,\n ListRulesFilter,\n ListRulesResponse,\n PublishRuleResponse,\n SimulateRuleRequest,\n ValidationResult,\n VersionHistoryResponse,\n} from './types';\n\n/** Public surface of {@link RulesClient}. */\nexport interface IRulesClient {\n publish(rule: ValidatorRules): Promise<PublishRuleResponse>;\n get(consensusTimestamp: string): Promise<PublishedRule>;\n listByOwner(filter?: ListRulesFilter): Promise<ListRulesResponse>;\n simulate(params: SimulateRuleRequest): Promise<ValidationResult>;\n getVersionHistory(consensusTimestamp: string): Promise<VersionHistoryResponse>;\n deprecate(consensusTimestamp: string): Promise<DeprecateRuleResponse>;\n}\n\nexport class RulesClient implements IRulesClient {\n constructor(private readonly http: HttpClient) {}\n\n /** Publish a canonical ValidatorRules document to HCS. */\n async publish(rule: ValidatorRules): Promise<PublishRuleResponse> {\n return this.http.post('/api/v3/baas/rules/publish', rule);\n }\n\n /** Fetch a published rule by its HCS consensus timestamp. */\n async get(consensusTimestamp: string): Promise<PublishedRule> {\n return this.http.get(`/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}`);\n }\n\n /** List rules owned by the authenticated entity, optionally filtered by type. */\n async listByOwner(filter?: ListRulesFilter): Promise<ListRulesResponse> {\n const path = filter?.type\n ? `/api/v3/baas/rules?type=${encodeURIComponent(filter.type)}`\n : '/api/v3/baas/rules';\n return this.http.get(path);\n }\n\n /**\n * Simulate cluster-side evaluation of an action against a rule. Either\n * `ruleRef` (published) or `rule` (inline) must be supplied by the caller.\n */\n async simulate(params: SimulateRuleRequest): Promise<ValidationResult> {\n return this.http.post('/api/v3/baas/rules/simulate', params);\n }\n\n /** Walk the version history of a published rule. */\n async getVersionHistory(consensusTimestamp: string): Promise<VersionHistoryResponse> {\n return this.http.get(\n `/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}/versions`,\n );\n }\n\n /** Deprecate a published rule (owner-only). */\n async deprecate(consensusTimestamp: string): Promise<DeprecateRuleResponse> {\n return this.http.post(\n `/api/v3/baas/rules/${encodePathParam(consensusTimestamp)}/deprecate`,\n {},\n );\n }\n}\n\nexport type { RuleRef };\n","/**\n * Entities Sub-Client\n *\n * Smart-app authoring surface for canonical chain-bound entities. Each entity\n * arm (token / account / topic / agent) has a per-arm typed creator that\n * requires a published `ruleRef` — the cluster resolves the rule and stamps\n * it on the entity binding. A `launchpad(...)` mega-helper publishes a token\n * rule with an attached launchpad ModuleEntry and creates the token in one\n * call.\n *\n * @example\n * ```typescript\n * import { Rules } from '@hsuite/smart-engines-sdk';\n *\n * const rule = Rules.forToken().withSecurity('full').build();\n * const { ruleRef } = await baas.rules.publish(rule);\n *\n * const token = await baas.entities.createToken({\n * chain: 'hedera',\n * name: 'My Token',\n * symbol: 'MYT',\n * decimals: 6,\n * ruleRef,\n * });\n * ```\n */\nimport { encodePathParam, type HttpClient, type HttpCallOptions } from '../../http';\nimport type { ChainType, RuleRef } from '../..';\nimport type {\n BurnEntityRequest,\n ComplianceEntityRequest,\n CreateAccountRequest,\n CreateAgentRequest,\n CreateTokenRequest,\n CreateTopicRequest,\n EntityCreationResult,\n EntityInfo,\n EntitySecurityMode,\n EntityType,\n LaunchpadEntityRequest,\n LaunchpadEntityResult,\n ListEntitiesFilter,\n ListEntitiesResponse,\n MintEntityRequest,\n PreparedEntityCreation,\n PreparedEntityTransactionResult,\n TransferEntityRequest,\n TrustlineEntityRequest,\n WithdrawEntityRequest,\n} from './types';\n\n/**\n * Normalize a raw `EntityInfo` response from the cluster into the stable\n * SDK shape. The cluster historically returns `entityType`/`ownerWallet` and\n * sometimes omits `chain`; this helper adds `type`, `owner`, `chain`, and a\n * stable `agentId` so consumers don't need their own mapping logic.\n */\nfunction normalizeEntityInfo(raw: unknown): EntityInfo {\n const r = raw as Record<string, unknown>;\n const entityId = String(r.entityId ?? '');\n const entityType = (r.entityType as EntityType) ?? 'account';\n const ownerWallet = String(r.ownerWallet ?? '');\n const ruleRef = (r.ruleRef ?? {}) as RuleRef;\n const chainAccounts = (r.chainAccounts ?? {}) as Record<string, string>;\n const createdAt = String(r.createdAt ?? '');\n\n let chain: ChainType = (r.chain as ChainType) ?? ruleRef.chain;\n if (!chain) {\n const firstChain = Object.keys(chainAccounts)[0];\n chain = (firstChain as ChainType) ?? 'hedera';\n }\n\n const rawAgentId = r.agentId as string | undefined;\n const agentId = rawAgentId ?? entityId;\n\n return {\n entityId,\n type: entityType,\n entityType,\n owner: ownerWallet,\n ownerWallet,\n chain,\n ruleRef,\n chainAccounts,\n createdAt,\n agentId,\n };\n}\n\n/**\n * Guarantee a non-null `agentId` on every entity creation result by backfilling\n * `entityId` when the host omits it.\n */\nfunction normalizeEntityCreationResult(\n raw: unknown,\n): EntityCreationResult {\n const r = raw as EntityCreationResult;\n return {\n ...r,\n agentId: r.agentId ?? r.entityId,\n };\n}\n\n/** Public surface of {@link EntitiesClient}. */\nexport interface IEntitiesClient {\n prepareCreateToken(req: Omit<CreateTokenRequest, 'fundWith'>): Promise<PreparedEntityCreation>;\n executeCreateToken(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n createTxId?: string;\n signedFundingBlob?: string;\n }): Promise<EntityCreationResult>;\n createToken(req: CreateTokenRequest): Promise<EntityCreationResult>;\n prepareCreateAccount(req: Omit<CreateAccountRequest, 'fundWith'>): Promise<PreparedEntityCreation>;\n executeCreateAccount(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n createTxId?: string;\n }): Promise<EntityCreationResult>;\n createAccount(req: CreateAccountRequest): Promise<EntityCreationResult>;\n prepareCreateTopic(req: Omit<CreateTopicRequest, 'fundWith'>): Promise<PreparedEntityCreation>;\n executeCreateTopic(req: {\n entityId: string;\n chain: ChainType;\n createTxId: string;\n securityMode?: EntitySecurityMode;\n }): Promise<EntityCreationResult>;\n createTopic(req: CreateTopicRequest): Promise<EntityCreationResult>;\n createAgent(req: CreateAgentRequest): Promise<EntityCreationResult>;\n prepareCreateAgent(req: Omit<CreateAgentRequest, 'fundWith'>): Promise<PreparedEntityCreation>;\n executeCreateAgent(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n createTxId?: string;\n }): Promise<EntityCreationResult>;\n launchpad(req: LaunchpadEntityRequest): Promise<LaunchpadEntityResult>;\n get(entityId: string): Promise<EntityInfo>;\n listByOwner(filter?: ListEntitiesFilter): Promise<ListEntitiesResponse>;\n transfer(\n entityId: string,\n body: TransferEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n withdraw(\n entityId: string,\n body: WithdrawEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n mint(\n entityId: string,\n body: MintEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n burn(\n entityId: string,\n body: BurnEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n compliance(\n entityId: string,\n body: ComplianceEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n trustline(\n entityId: string,\n body: TrustlineEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult>;\n}\n\nexport class EntitiesClient implements IEntitiesClient {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Chains whose token-create routes through the payer-funded 3-step (prepare →\n * fund → execute), mirroring `createAccount`. Hedera = real HTS TokenCreate\n * (admin/supply = the per-entity DKG slot-pubkey KeyList; treasury = the\n * entity's own account; `0.0.X` token id is network-assigned, resolved from the\n * receipt via the threaded `createTxId`). Cardano/Solana/Polkadot = the\n * AUTHORITY entity (the entity IS the policy/mint/Assets-admin multisig — same\n * address as an account; the asset MINT itself is a later operate-tab payer\n * call). XRPL/Stellar token = an ISSUER ACCOUNT (reuses the account preparer) +\n * issuer flags set at finalize: XRPL relays the funding Payment then finalizes\n * (issuer-flag AccountSets + SignerListSet + disable-master); Stellar relays the\n * CreateAccount then finalizes (SetOptions install incl. issuer setFlags +\n * master lock). Every OTHER chain (EVM) stays on the legacy synchronous path.\n */\n private static readonly PAYER_FUNDED_TOKEN_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>([\n 'hedera',\n 'cardano',\n 'solana',\n 'polkadot',\n 'xrpl',\n 'stellar',\n ]);\n\n /**\n * PREPARE half of the payer-funded token-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'token'`. The cluster\n * runs the per-entity DKG, builds the payer-funded create (Hedera: TokenCreate\n * keyed by the slot-pubkey KeyList with the entity account as treasury;\n * Cardano/Solana/Polkadot: funds/provisions the authority multisig), and returns\n * the prepared blob. The prepared `transactionId` is the `createTxId` for\n * execute (Hedera).\n */\n async prepareCreateToken(\n req: Omit<CreateTokenRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'token',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded token-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'token'`. For Hedera,\n * pass `createTxId` (the prepared create's `transactionId`) so the validator\n * resolves the network-assigned `0.0.X` token id from the receipt and stamps\n * `chainAccounts.hedera`. For the authority-entity chains (cardano/solana/\n * polkadot) execute just verifies the binding and echoes the stamped authority\n * address (no `createTxId` needed).\n */\n async executeCreateToken(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n /** Hedera only: the prepared create's TransactionId (resolves the token id from the receipt). */\n createTxId?: string;\n /**\n * XRPL/Stellar issuer-account only: the payer's signed funding blob for the\n * validator to submit before finalizing the issuer-flag install. Omitted for\n * the other chains (their execute-create rejects a non-undefined blob).\n */\n signedFundingBlob?: string;\n }): Promise<EntityCreationResult> {\n const { createTxId, signedFundingBlob, ...rest } = req;\n const result = await this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n ...(signedFundingBlob !== undefined ? { signedFundingBlob } : {}),\n entityType: 'token',\n });\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * Create a canonical token entity bound to a published rule.\n *\n * Dispatches by `chain` (mirrors `createAccount`):\n * - **Hedera / Cardano / Solana / Polkadot** = payer-funded 3-step (prepare →\n * caller funds via `fundWith` → execute). Hedera resolves the network-assigned\n * `0.0.X` token id from the receipt (threads `createTxId`); the authority-\n * entity chains verify/echo the stamped authority address. `fundWith` is\n * REQUIRED; to drive the steps manually call `prepareCreateToken` /\n * `executeCreateToken` directly.\n * - **XRPL / Stellar** = payer-funded too (account-model issuer): `fundWith`\n * REQUIRED; the caller's signed funding blob is RELAYED to the validator,\n * which submits it then finalizes the issuer multisig (master-locked). NO\n * issuer flags are set at create — issuer auth flags / DefaultRipple / clawback\n * are an operate-tab, rules-validated concern.\n * - **EVM / other** = legacy synchronous `POST /api/v3/baas/entities/createToken`\n * (payer-funded-only fields ignored) until it migrates.\n */\n async createToken(req: CreateTokenRequest): Promise<EntityCreationResult> {\n if (EntitiesClient.PAYER_FUNDED_TOKEN_CHAINS.has(req.chain)) {\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateToken(prepReq);\n if (!fundWith) {\n throw new Error(\n `createToken(${req.chain}): pass fundWith (sign+submit the prepared create tx), or call prepareCreateToken/executeCreateToken directly`,\n );\n }\n // The caller signs the fee + submits the create tx with their OWN wallet.\n // XRPL/Stellar issuer accounts return a signed funding blob for the validator\n // to RELAY (then finalize on-chain); the other chains submit directly.\n const funded = await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n // Hedera threads the prepared create's TransactionId (network-assigned token\n // id is resolved from the receipt at execute); the authority-entity chains\n // need no createTxId (their address is deterministic / already stamped).\n // XRPL/Stellar (account-model issuer) RELAY the signed funding blob so the\n // validator submits it before finalizing the issuer-flag install.\n return this.executeCreateToken({\n entityId: prep.entityId,\n chain: req.chain,\n securityMode: req.securityMode,\n signedFundingBlob: EntitiesClient.FUNDING_BLOB_RELAY_CHAINS.has(req.chain)\n ? funded?.signedFundingBlob\n : undefined,\n createTxId:\n req.chain === 'hedera' ? prep.prepared?.[0]?.transactionId : undefined,\n });\n }\n // legacy synchronous create (unchanged) — only EVM remains on this path until\n // it migrates to the payer-funded flow.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n const result = await this.http.post('/api/v3/baas/entities/createToken', legacyReq);\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * PREPARE half of the payer-funded account-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create`. The cluster runs the per-entity DKG\n * (persists the binding, submits nothing on-chain) and returns the unsigned\n * payer-funding `Payment`(s) the caller signs + submits with their own wallet.\n */\n async prepareCreateAccount(\n req: Omit<CreateAccountRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'account',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded account-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create`. The entity already exists (its DKG\n * ran during prepare); pass `signedFundingBlob` for the validator to submit\n * the payer's signed funding `Payment` (XRPL only), or omit it when the caller\n * already submitted the funding tx themselves (then execute just finalizes /\n * verifies).\n *\n * `createTxId` is the HEDERA thread: a Hedera AccountCreate gets its\n * network-assigned `0.0.X` id only from the on-chain receipt after the payer\n * submits. The caller threads the prepared create's `transactionId` (from\n * `prepared[0].transactionId`) back here so the validator resolves the id from\n * the receipt server-side. Ignored for non-Hedera chains.\n */\n async executeCreateAccount(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n /** Hedera only: the prepared create's TransactionId (resolves the id from the receipt). */\n createTxId?: string;\n }): Promise<EntityCreationResult> {\n // Build a clean body: `createTxId` is the Hedera-only receipt thread, so it\n // is included ONLY when actually defined — non-Hedera bodies stay\n // `{ entityId, chain, securityMode?, signedFundingBlob? }` with no spurious\n // `createTxId: undefined`. `entityType` is omitted for accounts: the\n // execute-create DTO defaults a missing `entityType` to `account`, so the\n // receipt resolver reads `accountId` without the field being relayed.\n const { createTxId, ...rest } = req;\n const result = await this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n });\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * Chains whose account-create routes through the payer-funded 3-step\n * (prepare → fund → execute). All are ledgers where the validators never pay:\n * XRPL funds a reserve; Bitcoin funds a P2WSH UTXO; Cardano funds a\n * native-script enterprise address above min-UTXO; Polkadot funds a\n * pallet_multisig SS58 above the existential deposit; Solana funds a Squads\n * multisig PDA (deterministic from the createKey) via a payer-paid\n * `multisigCreateV2` — the payer's submission IS the create (no separate\n * finalizer). Hedera is create-WITH-KEY: the payer submits an AccountCreate\n * whose controlling key is the per-entity DKG slot-pubkey KeyList, so the\n * payer's submit IS the create; its `0.0.X` id is network-assigned (resolved\n * from the receipt at execute-create via the threaded `createTxId`). Stellar is\n * account-MODEL (like XRPL): the payer funds the entity's slot-0 `G...` master\n * via a CreateAccount, the validator RELAYS the signed funding blob, then\n * execute-create finalizes on-chain (threshold-signs a SetOptions installing\n * the validator chain-key multisig + locking the master). EVM stays on the\n * legacy synchronous create until it migrates.\n */\n private static readonly PAYER_FUNDED_CREATE_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>([\n 'xrpl',\n 'bitcoin',\n 'cardano',\n 'polkadot',\n 'solana',\n 'hedera',\n 'stellar',\n ]);\n\n /**\n * Chains whose execute-create RELAYS the payer's signed funding blob for the\n * validator to submit (then finalizes on-chain). Both are account-model ledgers\n * with a validator-side finalize step: XRPL (SignerListSet + disable-master),\n * Stellar (SetOptions install + master lock). Every OTHER payer-funded chain\n * has the PAYER submit the funding tx directly with their own wallet — their\n * execute-create REJECTS a non-undefined `signedFundingBlob` (400), so the blob\n * is omitted for them.\n */\n private static readonly FUNDING_BLOB_RELAY_CHAINS: ReadonlySet<ChainType> =\n new Set<ChainType>(['xrpl', 'stellar']);\n\n /**\n * Create a canonical account entity bound to a published rule.\n *\n * Dispatches by `chain`:\n * - **XRPL / Stellar / Bitcoin / Cardano / Polkadot / Solana / Hedera** =\n * payer-funded 3-step (prepare → fund → execute). The cluster runs the\n * per-entity DKG and returns the unsigned payer-funding tx(s); the\n * caller-supplied `fundWith` callback signs + submits (or just signs) the\n * funding tx with their OWN wallet — the SDK never holds the customer's chain\n * key nor opens a network connection — then `executeCreateAccount` finalizes\n * (XRPL + Stellar finalize on-chain after relaying the funding blob; the\n * deterministic ledgers + Solana verify/stamp the binding; Hedera resolves\n * the network-assigned id from the receipt). `fundWith` is REQUIRED on these\n * chains; to drive the steps manually call `prepareCreateAccount` /\n * `executeCreateAccount` directly.\n * - **other chains** (EVM) = legacy synchronous create — a single\n * `POST /api/v3/baas/entities/createAccount`, unchanged from pre-3.9.0. These chains\n * migrate to the payer-funded flow in a later phase; until then the\n * payer-funded-only fields (`fundWith` / `payerAccountId` / `securityMode`)\n * are ignored.\n */\n async createAccount(req: CreateAccountRequest): Promise<EntityCreationResult> {\n if (EntitiesClient.PAYER_FUNDED_CREATE_CHAINS.has(req.chain)) {\n // payer-funded 3-step (the 3.9.0 logic, now multi-chain) — requires fundWith\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateAccount(prepReq);\n if (!fundWith) {\n throw new Error(\n `createAccount(${req.chain}): pass fundWith (sign+submit the prepared funding tx), or call prepareCreateAccount/executeCreateAccount directly`,\n );\n }\n const funded = await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n // Only the account-model finalize chains (XRPL, Stellar) relay the payer's\n // signed blob for the validator to submit (their execute-create finalizes\n // on-chain after the funding lands). The deterministic ledgers\n // (bitcoin/cardano/polkadot), Solana AND Hedera have the PAYER submit the tx\n // directly with their own wallet; their execute-create REJECTS a\n // non-undefined `signedFundingBlob` with a 400 (the payer is the submitter,\n // not the validator). So omit the blob for every non-relay chain.\n //\n // Hedera additionally threads `createTxId`: its create-with-key id is\n // network-assigned, so execute-create needs the prepared create's\n // TransactionId (on prepared[0].transactionId, the same tx the payer just\n // submitted via fundWith) to resolve the 0.0.X id from the receipt.\n return this.executeCreateAccount({\n entityId: prep.entityId,\n chain: req.chain,\n securityMode: req.securityMode,\n signedFundingBlob: EntitiesClient.FUNDING_BLOB_RELAY_CHAINS.has(req.chain)\n ? funded?.signedFundingBlob\n : undefined,\n createTxId:\n req.chain === 'hedera' ? prep.prepared?.[0]?.transactionId : undefined,\n });\n }\n // legacy synchronous create (unchanged from pre-3.9.0) — only EVM remains on\n // this path; it migrates to payer-funded in a later phase.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n const result = await this.http.post('/api/v3/baas/entities/createAccount', legacyReq);\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * PREPARE half of the payer-funded topic-create flow (Hedera).\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'topic'`. The cluster\n * runs the per-entity DKG (persists the binding), builds the payer-funded\n * TopicCreate keyed by the slot-pubkey KeyList, attaches the validator admin\n * threshold sig, and returns the prepared blob for the caller to add the fee\n * sig + submit. The prepared `transactionId` is the `createTxId` for execute.\n */\n async prepareCreateTopic(\n req: Omit<CreateTopicRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'topic',\n ...req,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded topic-create flow (Hedera).\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'topic'`. The topic\n * already exists once the payer submitted the create tx; pass `createTxId` (the\n * prepared create's `transactionId`) so the validator resolves the network-\n * assigned `0.0.X` topic id from the receipt and stamps `chainAccounts.hedera`.\n */\n async executeCreateTopic(req: {\n entityId: string;\n chain: ChainType;\n createTxId: string;\n securityMode?: EntitySecurityMode;\n }): Promise<EntityCreationResult> {\n const result = await this.http.post('/api/v3/baas/entities/execute-create', {\n ...req,\n entityType: 'topic',\n });\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * Create a canonical topic entity bound to a published rule.\n *\n * Dispatches by `chain`:\n * - **Hedera** = payer-funded 3-step (prepare → caller submits the TopicCreate\n * via `fundWith` → execute resolves the `0.0.X` topic id from the receipt).\n * `fundWith` is REQUIRED; to drive the steps manually call\n * `prepareCreateTopic` / `executeCreateTopic` directly.\n * - **other chains** = legacy synchronous `POST /api/v3/baas/entities/createTopic`\n * (topics are a Hedera primitive; the legacy path is unchanged).\n */\n async createTopic(req: CreateTopicRequest): Promise<EntityCreationResult> {\n if (req.chain === 'hedera') {\n const { fundWith, ...prepReq } = req;\n const prep = await this.prepareCreateTopic(prepReq);\n if (!fundWith) {\n throw new Error(\n 'createTopic(hedera): pass fundWith (sign+submit the prepared TopicCreate), or call prepareCreateTopic/executeCreateTopic directly',\n );\n }\n // The caller signs the fee + submits the create tx with their OWN wallet.\n // Hedera topics have no reserve/address at prepare (the id is receipt-only).\n await fundWith(prep.prepared, {\n address: prep.address,\n reserveRequirement: prep.reserveRequirement,\n });\n const createTxId = prep.prepared?.[0]?.transactionId;\n if (!createTxId) {\n throw new Error(\n 'createTopic(hedera): prepared TopicCreate carries no transactionId — cannot resolve the topic id from the receipt',\n );\n }\n return this.executeCreateTopic({\n entityId: prep.entityId,\n chain: req.chain,\n createTxId,\n securityMode: req.securityMode,\n });\n }\n // legacy synchronous create (unchanged) — topics are a Hedera primitive.\n const {\n fundWith: _ignoredFundWith,\n payerAccountId: _ignoredPayer,\n securityMode: _ignoredSecurityMode,\n ...legacyReq\n } = req;\n const result = await this.http.post('/api/v3/baas/entities/createTopic', legacyReq);\n return normalizeEntityCreationResult(result);\n }\n\n /** Create a canonical agent entity bound to a published rule. */\n async createAgent(req: CreateAgentRequest): Promise<EntityCreationResult> {\n const result = await this.http.post('/api/v3/baas/entities/createAgent', req);\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * PREPARE half of the payer-funded agent-create flow.\n *\n * POSTs `/api/v3/baas/entities/prepare-create` with `entityType: 'agent'`. The cluster\n * runs the per-entity DKG (persists the binding, submits nothing on-chain) and\n * returns the unsigned payer-funding `Payment`(s) the caller signs + submits with\n * their own wallet — mirroring `prepareCreateAccount`. The agent's primary chain\n * is relayed as `chain` (the generic prepare/execute DTO key) so the host's\n * chain-bound preparer runs; `name` / `agentType` / `ruleRef` ride along.\n */\n async prepareCreateAgent(\n req: Omit<CreateAgentRequest, 'fundWith'>,\n ): Promise<PreparedEntityCreation> {\n const { primaryChain, ...rest } = req;\n return this.http.post('/api/v3/baas/entities/prepare-create', {\n entityType: 'agent',\n chain: primaryChain,\n ...rest,\n });\n }\n\n /**\n * EXECUTE half of the payer-funded agent-create flow.\n *\n * POSTs `/api/v3/baas/entities/execute-create` with `entityType: 'agent'`. The entity\n * already exists (its DKG ran during prepare); pass `signedFundingBlob` for the\n * validator to submit the payer's signed funding tx (XRPL/Stellar account-model\n * relay), or omit it when the caller already submitted the funding tx themselves.\n * `createTxId` is the Hedera receipt thread (the prepared create's\n * `transactionId`); ignored for non-Hedera chains. Mirrors\n * `executeCreateAccount` but tags `entityType: 'agent'`.\n */\n async executeCreateAgent(req: {\n entityId: string;\n chain: ChainType;\n securityMode?: EntitySecurityMode;\n signedFundingBlob?: string;\n /** Hedera only: the prepared create's TransactionId (resolves the id from the receipt). */\n createTxId?: string;\n }): Promise<EntityCreationResult> {\n // Build a clean body: `createTxId` / `signedFundingBlob` are included ONLY when\n // actually defined (mirrors executeCreateAccount), so non-relay / non-Hedera\n // bodies stay `{ entityId, chain, securityMode?, entityType: 'agent' }`.\n const { createTxId, signedFundingBlob, ...rest } = req;\n const result = await this.http.post('/api/v3/baas/entities/execute-create', {\n ...rest,\n ...(createTxId !== undefined ? { createTxId } : {}),\n ...(signedFundingBlob !== undefined ? { signedFundingBlob } : {}),\n entityType: 'agent',\n });\n return normalizeEntityCreationResult(result);\n }\n\n /**\n * Mega-helper: build a token rule with a launchpad ModuleEntry attached,\n * publish it, create the token, and return the combined result in one HTTP\n * round-trip.\n */\n async launchpad(req: LaunchpadEntityRequest): Promise<LaunchpadEntityResult> {\n return this.http.post('/api/v3/baas/entities/launchpad', req);\n }\n\n /** Fetch an entity by its canonical `entityId`. */\n async get(entityId: string): Promise<EntityInfo> {\n const raw = await this.http.get(`/api/v3/baas/entities/${encodePathParam(entityId)}`);\n return normalizeEntityInfo(raw);\n }\n\n /** List entities owned by the authenticated wallet, optionally filtered by type. */\n async listByOwner(filter?: ListEntitiesFilter): Promise<ListEntitiesResponse> {\n const path = filter?.type\n ? `/api/v3/baas/entities?type=${encodeURIComponent(filter.type)}`\n : '/api/v3/baas/entities';\n const raw = await this.http.get(path);\n const response = raw as ListEntitiesResponse;\n return {\n ...response,\n entities: response.entities?.map(normalizeEntityInfo) ?? [],\n };\n }\n\n // ─── Value-movement (prepare-bytes only) ──────────────────────────────────\n //\n // Each method POSTs the host's entity-scoped value-movement route. The entity\n // is the source / treasury / authority + fee-payer (resolved server-side from\n // the entity record — never the body), so a caller can never name a foreign\n // payer or drain another account. The host authorises the call (session\n // caller identity + `loadOwnedEntity` ownership), delegates to the validator\n // preparer, and returns prepared bytes for the caller to sign + submit; the\n // host never submits and never pays. A rule-deny surfaces as an HTTP 403\n // `rule_rejected` (use `isRuleRejected`), never as signed bytes.\n //\n // `opts` threads {@link HttpCallOptions} (`onBehalfOf` / `customerToken` /\n // `headers`) so an app-as-proxy can act on behalf of an owner — the owner's\n // Mode-1 customer-session JWT rides as both `Authorization: Bearer` and\n // `X-Customer-Session-Claim`, exactly as `agents.execute` does.\n\n /**\n * Prepare a native or token transfer FROM an account entity.\n *\n * `POST /api/v3/baas/entities/:entityId/transfer`.\n */\n async transfer(\n entityId: string,\n body: TransferEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/transfer`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a withdrawal FROM an account entity to a destination.\n *\n * `POST /api/v3/baas/entities/:entityId/withdraw`.\n */\n async withdraw(\n entityId: string,\n body: WithdrawEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/withdraw`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a token/NFT mint whose supply authority is the account entity.\n *\n * `POST /api/v3/baas/entities/:entityId/mint`.\n */\n async mint(\n entityId: string,\n body: MintEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/mint`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a token/NFT burn from the account entity's treasury.\n *\n * `POST /api/v3/baas/entities/:entityId/burn`.\n */\n async burn(\n entityId: string,\n body: BurnEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/burn`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare a compliance action (pause / restrict / wipe) on a token whose\n * compliance authority is the account entity. The body `account` is the\n * per-account subject for restrict/wipe — never the payer.\n *\n * `POST /api/v3/baas/entities/:entityId/compliance`.\n */\n async compliance(\n entityId: string,\n body: ComplianceEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/compliance`,\n body,\n opts,\n );\n }\n\n /**\n * Prepare an XRPL TrustSet authorising the account entity to hold a currency\n * from an issuer.\n *\n * `POST /api/v3/baas/entities/:entityId/trustline`.\n */\n async trustline(\n entityId: string,\n body: TrustlineEntityRequest,\n opts?: HttpCallOptions,\n ): Promise<PreparedEntityTransactionResult> {\n return this.http.post(\n `/api/v3/baas/entities/${encodePathParam(entityId)}/trustline`,\n body,\n opts,\n );\n }\n}\n","/**\n * BaaS Client\n *\n * SDK client for interacting with Smart Engines Backend-as-a-Service.\n *\n * Provides:\n * - Wallet-based authentication (challenge-response)\n * - App registration and management\n * - Trustless database operations with state transitions and Merkle proofs\n * - Decentralized file storage\n * - Serverless function deployment and invocation\n * - Real-time pub/sub messaging with channels, history, and presence\n * - App deployment lifecycle management\n * - Autonomous smart agent management\n *\n * @example\n * ```typescript\n * import { BaasClient } from '@hsuite/smart-engines-sdk';\n *\n * const baas = new BaasClient({\n * hostUrl: 'https://host.smartengines.io',\n * appId: 'my-app',\n * });\n *\n * await baas.authenticate({\n * chain: 'hedera',\n * walletAddress: '0.0.12345',\n * publicKey: 'your-public-key',\n * signFn: async (message) => wallet.sign(message),\n * });\n *\n * // Database with state proofs\n * const result = await baas.db.insert('users', { name: 'Alice' });\n * const proof = await baas.db.getDocumentProof(result.document._id);\n *\n * // File storage\n * const upload = await baas.storage.upload(fileBuffer, 'document.pdf');\n *\n * // Messaging\n * await baas.messaging.publish('events', { type: 'user.created' });\n *\n * // Functions\n * const fn = await baas.functions.deploy({ name: 'handler', runtime: 'nodejs20', code: '...', codeType: 'inline' });\n *\n * // Agents\n * const agent = await baas.agents.register({ name: 'Bot', capabilities: ['trade'], rules: {} });\n * ```\n */\n\nimport type {\n BaasClientConfig,\n BaasSupportedChain,\n BaasChallengeResponse,\n BaasAuthResult,\n BaasSessionInfo,\n BaasErrorDetails,\n} from './types';\nimport { type CircuitBreakerSnapshot } from '../_vendor';\nimport { createHttpClient, SdkHttpError, type HttpClient } from '../http';\nimport { resolveClusterEndpoint } from '../discovery';\nimport { type NetworkName } from '../network-presets';\nimport { DatabaseClient } from './database';\nimport { StorageClient } from './storage';\nimport { FunctionsClient } from './functions';\nimport { MessagingClient } from './messaging';\nimport { DeploymentClient } from './deployment';\nimport { AgentsClient } from './agents';\nimport { CustomerSessionClient } from './customer-session';\nimport { RulesClient } from './rules';\nimport { EntitiesClient } from './entities';\n\n/**\n * Authentication options for wallet-based auth\n */\nexport type AuthenticateOptions = {\n /** Blockchain chain */\n chain: BaasSupportedChain;\n /** Wallet address on the chain */\n walletAddress: string;\n /** Public key (hex encoded) */\n publicKey: string;\n /** Function to sign the challenge message */\n signFn: (message: string) => string | Promise<string>;\n};\n\n/**\n * Fields shared across both arms of {@link BaasConnectToClusterConfig}.\n * Pulled out so the discriminated-union arms below stay focused on the\n * \"where to discover from\" decision.\n */\ninterface BaasConnectToClusterShared {\n /** Application ID (for existing apps) */\n appId?: string;\n /** Application name (for registration) */\n appName?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Allow HTTP connections (for local development only) */\n allowInsecure?: boolean;\n /**\n * Path prefix prepended to every request to the chosen host. Defaults to\n * `/host` because cluster discovery returns the gateway URL, and the\n * gateway routes BaaS traffic at `/host/*`. Override to `''` if you are\n * pointing the SDK directly at a host that doesn't sit behind the\n * gateway path rewrite.\n */\n pathPrefix?: string;\n /**\n * Optional HCS trust anchor — cross-checks the bootstrap response\n * against the on-chain validator-registry topic so a compromised\n * bootstrap seed can't inject rogue clusters. Per deployment.\n */\n trustAnchor?: {\n network: 'mainnet' | 'testnet' | 'previewnet';\n registryTopicId: string;\n mirrorNodeUrl?: string;\n };\n}\n\n/**\n * Config for {@link BaasClient.connectToCluster}. Exactly ONE of\n * `network` or `bootstrap` must be supplied — encoded as a discriminated\n * union so passing both is a compile-time error.\n *\n * `network` is the recommended default for smart-app callers; the SDK\n * resolves the canonical gateway entrypoint from {@link KNOWN_NETWORKS}.\n * `bootstrap` is the manual escape hatch for private deployments.\n */\nexport type BaasConnectToClusterConfig =\n | ({\n /** Named network — SDK resolves the canonical gateway entrypoint. */\n network: NetworkName;\n bootstrap?: never;\n } & BaasConnectToClusterShared)\n | ({\n /** Bootstrap seeds: URLs that serve `GET /api/v3/discovery/clusters`. */\n bootstrap: string[];\n network?: never;\n } & BaasConnectToClusterShared);\n\n/** Public instance surface of {@link BaasClient}. */\nexport interface IBaasClient {\n readonly db: DatabaseClient;\n readonly storage: StorageClient;\n readonly functions: FunctionsClient;\n readonly messaging: MessagingClient;\n readonly deployment: DeploymentClient;\n readonly agents: AgentsClient;\n readonly customerSession: CustomerSessionClient;\n readonly rules: RulesClient;\n readonly entities: EntitiesClient;\n authenticate(options: AuthenticateOptions): Promise<BaasAuthResult>;\n validateSession(): Promise<BaasSessionInfo>;\n logout(): Promise<void>;\n isAuthenticated(): boolean;\n getAppId(): string | undefined;\n setAppId(appId: string): void;\n getHostUrl(): string;\n getHttpHealth(): { breaker: CircuitBreakerSnapshot | null; lastError?: Error };\n}\n\nexport class BaasClient implements IBaasClient {\n private readonly hostUrl: string;\n private readonly pathPrefix: string;\n private appId: string | undefined;\n private readonly timeout: number;\n private readonly allowInsecure: boolean;\n private readonly http: HttpClient;\n /** Last HTTP error (for getHttpHealth) */\n private lastHttpError?: Error;\n /**\n * Auth options from the last {@link authenticate} call, retained so the\n * client can transparently re-authenticate when the session token expires\n * (the http client invokes {@link reauthenticate} on a 401). Undefined until\n * the first successful authenticate.\n */\n private authContext?: AuthenticateOptions;\n\n // ========== Sub-Clients ==========\n\n /** Trustless database with state proofs and Merkle verification */\n public readonly db: DatabaseClient;\n /** Decentralized file storage */\n public readonly storage: StorageClient;\n /** Serverless function deployment and invocation */\n public readonly functions: FunctionsClient;\n /** Real-time pub/sub messaging with channels, history, and presence */\n public readonly messaging: MessagingClient;\n /** App deployment lifecycle management */\n public readonly deployment: DeploymentClient;\n /** Autonomous smart agent management */\n public readonly agents: AgentsClient;\n /** Customer→smart-app session bridge (TokenGate Face B). */\n public readonly customerSession: CustomerSessionClient;\n /** Canonical validator-rules authoring surface (publish/get/list/simulate). */\n public readonly rules: RulesClient;\n /** Canonical entity authoring surface (token/account/topic/agent + launchpad). */\n public readonly entities: EntitiesClient;\n\n constructor(config: BaasClientConfig) {\n this.allowInsecure = config.allowInsecure ?? false;\n this.hostUrl = validateUrl(config.hostUrl, this.allowInsecure);\n this.appId = config.appId;\n this.timeout = config.timeout ?? 30000;\n\n // Strip trailing slash from pathPrefix and ensure leading slash; empty if none.\n const prefix = (config.pathPrefix ?? '').replace(/\\/$/, '');\n this.pathPrefix = prefix ? (prefix.startsWith('/') ? prefix : `/${prefix}`) : '';\n const baseUrlWithPrefix = this.pathPrefix\n ? this.hostUrl.replace(/\\/$/, '') + this.pathPrefix\n : this.hostUrl;\n\n // Create shared HTTP client. baseUrl includes optional pathPrefix so all\n // /api/v3/baas/* paths get routed to the host even when consumed via a gateway.\n this.http = createHttpClient({\n baseUrl: baseUrlWithPrefix,\n timeout: this.timeout,\n // Transparent session refresh: on a 401, re-run the challenge-response\n // with the retained signer and retry once. No-op until authenticate() has\n // been called (authContext set). Excludes /api/v3/{,baas/}auth/* (see http client).\n onUnauthorized: () => this.reauthenticate(),\n });\n\n // Helper to get appId with validation\n const getAppId = () => this.requireAppId();\n\n // Initialize sub-clients\n this.db = new DatabaseClient(this.http, getAppId);\n this.storage = new StorageClient(this.http, getAppId);\n this.functions = new FunctionsClient(this.http, getAppId);\n this.messaging = new MessagingClient(this.http, getAppId);\n this.deployment = new DeploymentClient(this.http);\n this.agents = new AgentsClient(this.http);\n this.customerSession = new CustomerSessionClient(baseUrlWithPrefix, this.timeout);\n this.rules = new RulesClient(this.http);\n this.entities = new EntitiesClient(this.http);\n }\n\n /**\n * Connect to the Smart Engines BaaS via cluster auto-discovery.\n *\n * Zero-config entrypoint flow:\n *\n * 1. Resolves the bootstrap seed list:\n * - `network: 'testnet' | 'mainnet'` → canonical Cloudflare-fronted\n * gateway via {@link KNOWN_NETWORKS}.\n * - `bootstrap: string[]` → explicit seed list (private deployments).\n * 2. Fetches `GET /api/v3/discovery/clusters` from the first reachable\n * seed; the response carries every active cluster's gateway URL.\n * 3. Random-picks one active cluster.\n * 4. Returns a `BaasClient` pointed at that cluster's gatewayUrl, with\n * `pathPrefix: '/host'` so all BaaS sub-clients (db / storage /\n * functions / messaging / agents / rules / entities) route through\n * the gateway's `/host/*` rewrite.\n *\n * @example Zero-config (recommended)\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * network: 'testnet',\n * appId: 'app_abc',\n * });\n *\n * await baas.db.insert('users', { name: 'Alice' });\n * ```\n *\n * @example Custom seeds (private deployments)\n * ```ts\n * const baas = await BaasClient.connectToCluster({\n * bootstrap: ['https://gateway.my-private-net.example'],\n * appId: 'app_abc',\n * });\n * ```\n *\n * @throws {BaasError} `503` when no cluster is reachable via any seed.\n * @throws {BaasError} `400` when bootstrap resolution yields an empty list\n * (only possible when the caller passes an empty array explicitly).\n */\n static async connectToCluster(config: BaasConnectToClusterConfig): Promise<BaasClient> {\n const allowInsecure = config.allowInsecure ?? false;\n\n const resolved = await resolveClusterEndpoint({\n bootstrap: config.bootstrap,\n network: config.network,\n allowInsecure,\n trustAnchor: config.trustAnchor,\n });\n\n if (!resolved.ok) {\n if (resolved.reason === 'no-seeds') {\n throw new BaasError(\n 'connectToCluster requires either a non-empty `bootstrap` list or a known `network` name.',\n 400,\n );\n }\n throw new BaasError(\n 'No active clusters available via bootstrap seeds. Check network reachability or bootstrap URLs.',\n 503,\n );\n }\n\n const cluster = resolved.cluster;\n return new BaasClient({\n hostUrl: cluster.endpoints.gatewayUrl,\n appId: config.appId,\n appName: config.appName,\n timeout: config.timeout,\n allowInsecure,\n // BaaS traffic is gateway-routed at `/host/*` by default. Callers\n // pointing at a bare host can override with `pathPrefix: ''`.\n pathPrefix: config.pathPrefix ?? '/host',\n });\n }\n\n /** Set the app ID (for newly registered apps) */\n setAppId(appId: string): void {\n this.appId = appId;\n }\n\n /** Check if the client is authenticated */\n isAuthenticated(): boolean {\n return this.http.getAuthToken() !== undefined;\n }\n\n /** Get the current app ID */\n getAppId(): string | undefined {\n return this.appId;\n }\n\n /**\n * Get the configured host URL. After\n * {@link BaasClient.connectToCluster} this is the gateway URL of the\n * cluster the SDK landed on after random-pick — useful for logging,\n * \"behind the curtain\" UIs, or debugging which cluster is serving a\n * given request.\n */\n getHostUrl(): string {\n return this.hostUrl;\n }\n\n /**\n * Get HTTP resilience health information\n * @returns Object with circuit breaker state and last error (if any)\n */\n getHttpHealth(): { breaker: CircuitBreakerSnapshot | null; lastError?: Error } {\n // Note: In a real implementation, we would get the circuit breaker state\n // from the resilient HTTP layer. For now, return null since the base\n // HTTP client doesn't expose it yet.\n return {\n breaker: null,\n lastError: this.lastHttpError,\n };\n }\n\n private requireAppId(): string {\n if (!this.appId) {\n throw new BaasError(\n 'App ID required. Provide appId in config (e.g. from a prior deployment.init() call).',\n 400\n );\n }\n return this.appId;\n }\n\n // ========== Authentication ==========\n\n /**\n * Authenticate with the BaaS host using wallet challenge-response\n *\n * 1. Requests a challenge message from the host\n * 2. Signs the challenge with the provided signing function\n * 3. Submits the signature for verification\n * 4. Stores the JWT token for subsequent requests\n */\n async authenticate(options: AuthenticateOptions): Promise<BaasAuthResult> {\n const { chain, walletAddress, publicKey, signFn } = options;\n // Retain for transparent re-authentication when the token later expires.\n this.authContext = options;\n\n // Step 1: Request challenge — `this.http` already includes the\n // pathPrefix in its baseUrl, so we use the same /api/v3/baas/* path the\n // server route exposes.\n let challenge: BaasChallengeResponse;\n try {\n challenge = await this.http.post<BaasChallengeResponse>('/api/v3/baas/auth/challenge', {\n chain,\n walletAddress,\n appId: this.appId,\n });\n } catch (err) {\n throw asBaasError(err);\n }\n\n // Step 2: Sign the challenge\n const signature = await signFn(challenge.message);\n\n // Step 3: Verify and get token\n let result: BaasAuthResult;\n try {\n result = await this.http.post<BaasAuthResult>('/api/v3/baas/auth/verify', {\n challengeId: challenge.challengeId,\n signature,\n publicKey,\n });\n } catch (err) {\n throw asBaasError(err);\n }\n\n // Persist the token on the shared HTTP client so every subsequent\n // sub-client request automatically carries Authorization: Bearer ...\n this.http.setAuthToken(result.token);\n\n return result;\n }\n\n /**\n * Re-run the challenge-response with the retained signer to mint a fresh\n * session token. Invoked by the http client's `onUnauthorized` hook when a\n * request 401s because the token expired — so long-lived clients keep working\n * without the caller re-implementing refresh. No-op if {@link authenticate}\n * was never called. The `/api/v3/baas/auth/*` calls below are excluded from the http\n * client's 401-retry path, so this can never recurse.\n */\n private async reauthenticate(): Promise<void> {\n const ctx = this.authContext;\n if (!ctx) return; // never authenticated — nothing to refresh\n const challenge = await this.http.post<BaasChallengeResponse>('/api/v3/baas/auth/challenge', {\n chain: ctx.chain,\n walletAddress: ctx.walletAddress,\n appId: this.appId,\n });\n const signature = await ctx.signFn(challenge.message);\n const result = await this.http.post<BaasAuthResult>('/api/v3/baas/auth/verify', {\n challengeId: challenge.challengeId,\n signature,\n publicKey: ctx.publicKey,\n });\n this.http.setAuthToken(result.token);\n }\n\n /** Validate the current session */\n async validateSession(): Promise<BaasSessionInfo> {\n this.requireAuth();\n try {\n return await this.http.get<BaasSessionInfo>('/api/v3/baas/auth/session');\n } catch (err) {\n throw asBaasError(err);\n }\n }\n\n /** Destroy the current session on server and clear local token */\n async logout(): Promise<void> {\n if (this.http.getAuthToken()) {\n try {\n await this.http.post('/api/v3/baas/auth/logout', {});\n } catch {\n // Best effort — clear locally even if server request fails\n }\n }\n this.http.setAuthToken(undefined);\n }\n\n // ========== HTTP Helpers ==========\n\n private requireAuth(): void {\n if (!this.http.getAuthToken()) {\n throw new BaasError('Authentication required. Call authenticate() first.', 401);\n }\n }\n}\n\n/**\n * BaaS Error\n */\nexport class BaasError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly details?: BaasErrorDetails\n ) {\n super(message);\n this.name = 'BaasError';\n }\n}\n\n/**\n * Convert a thrown `SdkHttpError` (raised by the shared HTTP client) into\n * a `BaasError` so BaaS callers continue to see the historically expected\n * error type, with a uniform `statusCode` field and the raw server-side\n * `details` payload preserved.\n */\nfunction asBaasError(err: unknown): BaasError {\n if (err instanceof BaasError) return err;\n if (err instanceof SdkHttpError) {\n const details = (err.details ?? undefined) as BaasErrorDetails | undefined;\n return new BaasError(err.message, err.statusCode, details);\n }\n const e = err as Error;\n return new BaasError(`Network error: ${e?.message ?? String(err)}`, 0, {\n originalError: e?.message ?? String(err),\n });\n}\n\nfunction validateUrl(url: string, allowInsecure = false): string {\n try {\n const parsed = new URL(url);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new BaasError(`Invalid protocol: ${parsed.protocol}`, 400);\n }\n if (!allowInsecure && parsed.protocol !== 'https:') {\n throw new BaasError(\n 'HTTPS is required for secure connections. Set allowInsecure=true for local development.',\n 400\n );\n }\n return parsed.origin;\n } catch (error) {\n if (error instanceof BaasError) throw error;\n throw new BaasError(`Invalid URL: ${url}`, 400);\n }\n}\n","import {\n Injectable,\n Logger,\n OnModuleInit,\n OnModuleDestroy,\n Inject,\n Optional,\n} from '@nestjs/common';\nimport { SmartEngineClient, SmartEngineClientConfig, SmartEngineError } from '../client';\nimport { SmartGatewayClient } from '../gateway';\nimport { BaasClient as SdkBaasClient } from '../baas';\n\n/**\n * Configuration for SmartEngineService\n */\nexport interface SmartEngineServiceConfig extends SmartEngineClientConfig {\n /** Enable automatic connection test on module init */\n testConnection?: boolean;\n /** Enable auto-reconnect on connection failure */\n autoReconnect?: boolean;\n /** Reconnection interval in milliseconds */\n reconnectInterval?: number;\n /** Maximum reconnection attempts (0 = infinite) */\n maxReconnectAttempts?: number;\n}\n\n/**\n * Configuration token for dependency injection\n */\nexport const SMART_ENGINE_CONFIG = 'SMART_ENGINE_CONFIG';\n\n/**\n * Injection token for the full SDK `BaasClient` (with `.rules`, `.entities`,\n * `.db`, `.storage`, etc. as sub-clients). Use this when a consumer wants the\n * parent BaaS surface.\n */\nexport const SDK_BAAS_CLIENT = 'SDK_BAAS_CLIENT';\n\n/**\n * Injection token for the BaaS `RulesClient` sub-client (publish/get/list/\n * simulate/deprecate canonical validator rules).\n */\nexport const RULES_CLIENT = 'RULES_CLIENT';\n\n/**\n * Injection token for the BaaS `EntitiesClient` sub-client (create\n * token/account/topic/agent + launchpad).\n */\nexport const ENTITIES_CLIENT = 'ENTITIES_CLIENT';\n\n/**\n * BaaS (Blockchain-as-a-Service) client interface\n *\n * Provides simplified access to blockchain operations for BaaS scenarios\n * where applications need managed blockchain infrastructure without\n * direct validator management.\n */\nexport interface BaasClient {\n /** The underlying SmartEngineClient */\n readonly client: SmartEngineClient;\n /** Check if the client is connected and healthy */\n isHealthy(): Promise<boolean>;\n /** Get the validator base URL */\n getBaseUrl(): string;\n}\n\n/**\n * SmartEngineService - NestJS injectable service for Smart Engines SDK\n *\n * Provides lifecycle-managed access to SmartEngineClient with:\n * - Automatic connection testing on module init\n * - Graceful shutdown on module destroy\n * - BaaS client wrapper for simplified access\n * - Optional auto-reconnect functionality\n *\n * @example Module configuration with forRoot\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRoot({\n * validatorBaseUrl: 'https://validator.example.com',\n * apiKey: process.env.SMART_ENGINE_API_KEY,\n * testConnection: true,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Direct service injection\n * ```typescript\n * import { Injectable } from '@nestjs/common';\n * import { SmartEngineService } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Injectable()\n * export class MyService {\n * constructor(private readonly smartEngine: SmartEngineService) {}\n *\n * async doSomething() {\n * const client = this.smartEngine.getClient();\n * const health = await client.getHealth();\n * }\n * }\n * ```\n */\n@Injectable()\nexport class SmartEngineService implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(SmartEngineService.name);\n private client: SmartEngineClient | null = null;\n private baasClient: BaasClient | null = null;\n private connected = false;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private reconnectAttempts = 0;\n\n constructor(\n @Optional()\n @Inject(SMART_ENGINE_CONFIG)\n private readonly config?: SmartEngineServiceConfig\n ) {}\n\n /**\n * Initialize the service when the module starts\n */\n async onModuleInit(): Promise<void> {\n if (!this.config) {\n this.logger.warn(\n 'SmartEngineService initialized without configuration. Call configure() before using.'\n );\n return;\n }\n\n await this.initialize(this.config);\n }\n\n /**\n * Clean up resources when the module is destroyed\n */\n async onModuleDestroy(): Promise<void> {\n await this.shutdown();\n }\n\n /**\n * Initialize the service with configuration\n *\n * Can be called manually if not using DI configuration\n */\n async initialize(config: SmartEngineServiceConfig): Promise<void> {\n this.logger.log(`Initializing SmartEngineService for ${config.validatorBaseUrl}`);\n\n try {\n this.client = new SmartEngineClient({\n // SDK 4.0 validator-origin type-fence: the service config extends\n // SmartEngineClientConfig, so it carries `validatorBaseUrl` directly.\n validatorBaseUrl: config.validatorBaseUrl,\n apiKey: config.apiKey,\n authToken: config.authToken,\n timeout: config.timeout,\n allowInsecure: config.allowInsecure,\n });\n\n // Create BaaS client wrapper\n this.baasClient = this.createBaasClient(this.client);\n\n // Test connection if enabled\n if (config.testConnection !== false) {\n await this.testConnection();\n }\n\n this.connected = true;\n this.reconnectAttempts = 0;\n this.logger.log('SmartEngineService initialized successfully');\n } catch (error) {\n const err = error as Error;\n this.logger.error(`Failed to initialize SmartEngineService: ${err.message}`);\n\n if (config.autoReconnect) {\n this.scheduleReconnect(config);\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Gracefully shutdown the service\n */\n async shutdown(): Promise<void> {\n this.logger.log('Shutting down SmartEngineService');\n\n // Clear reconnect timer\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Clear client references\n this.client = null;\n this.baasClient = null;\n this.connected = false;\n\n this.logger.log('SmartEngineService shutdown complete');\n }\n\n /**\n * Get the SmartEngineClient instance\n *\n * @throws SmartEngineError if client is not initialized\n */\n getClient(): SmartEngineClient {\n if (!this.client) {\n throw new SmartEngineError(\n 'SmartEngineClient not initialized. Ensure SmartEngineService is configured properly.',\n 500\n );\n }\n return this.client;\n }\n\n /**\n * Get the BaaS client for simplified blockchain access\n *\n * The BaaS client provides a simplified interface for applications\n * that need managed blockchain infrastructure access.\n *\n * @throws SmartEngineError if client is not initialized\n */\n getBaasClient(): BaasClient {\n if (!this.baasClient) {\n throw new SmartEngineError(\n 'BaasClient not initialized. Ensure SmartEngineService is configured properly.',\n 500\n );\n }\n return this.baasClient;\n }\n\n /**\n * Check if the service is connected and healthy\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Test the connection to the validator\n */\n async testConnection(): Promise<boolean> {\n if (!this.client) {\n return false;\n }\n\n try {\n const health = await this.client.getHealth();\n this.connected = health.status === 'healthy' || health.status === 'ok';\n return this.connected;\n } catch (error) {\n const err = error as Error;\n this.logger.warn(`Connection test failed: ${err.message}`);\n this.connected = false;\n return false;\n }\n }\n\n /**\n * Get the current connection status\n */\n getStatus(): {\n connected: boolean;\n baseUrl: string | null;\n authenticated: boolean;\n reconnectAttempts: number;\n } {\n return {\n connected: this.connected,\n baseUrl: this.client?.getBaseUrl() ?? null,\n authenticated: this.client?.isAuthenticated() ?? false,\n reconnectAttempts: this.reconnectAttempts,\n };\n }\n\n /**\n * Create a SmartGatewayClient for gateway operations\n */\n createGatewayClient(config: {\n baseUrl: string;\n apiKey?: string;\n authToken?: string;\n timeout?: number;\n allowInsecure?: boolean;\n }): SmartGatewayClient {\n return new SmartGatewayClient(config);\n }\n\n /**\n * Create a BaaS client for host operations\n */\n createHostClient(config: {\n hostUrl: string;\n appId?: string;\n timeout?: number;\n allowInsecure?: boolean;\n }): SdkBaasClient {\n return new SdkBaasClient(config);\n }\n\n /**\n * Create a BaaS client wrapper around the SmartEngineClient\n */\n private createBaasClient(client: SmartEngineClient): BaasClient {\n return {\n client,\n isHealthy: async () => {\n try {\n const health = await client.getHealth();\n return health.status === 'healthy' || health.status === 'ok';\n } catch {\n return false;\n }\n },\n getBaseUrl: () => client.getBaseUrl(),\n };\n }\n\n /**\n * Schedule a reconnection attempt\n */\n private scheduleReconnect(config: SmartEngineServiceConfig): void {\n const maxAttempts = config.maxReconnectAttempts ?? 0;\n const interval = config.reconnectInterval ?? 5000;\n\n if (maxAttempts > 0 && this.reconnectAttempts >= maxAttempts) {\n this.logger.error(`Max reconnection attempts (${maxAttempts}) reached. Giving up.`);\n return;\n }\n\n this.reconnectAttempts++;\n this.logger.log(`Scheduling reconnection attempt ${this.reconnectAttempts} in ${interval}ms`);\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.initialize(config);\n } catch {\n // Error already logged in initialize\n }\n }, interval);\n }\n}\n","import { DynamicModule, Module, Provider, Type } from '@nestjs/common';\nimport {\n SmartEngineService,\n SmartEngineServiceConfig,\n SMART_ENGINE_CONFIG,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n} from './smart-engine.service';\nimport { BaasClient as SdkBaasClient } from '../baas';\n\n/**\n * Options for async module configuration\n */\nexport interface SmartEngineModuleAsyncOptions {\n /** Imports required for the factory */\n imports?: any[];\n /** Factory function to create configuration */\n useFactory?: (...args: any[]) => Promise<SmartEngineServiceConfig> | SmartEngineServiceConfig;\n /** Dependencies to inject into the factory */\n inject?: any[];\n /** Class to use for configuration */\n useClass?: Type<SmartEngineOptionsFactory>;\n /** Existing provider to use for configuration */\n useExisting?: Type<SmartEngineOptionsFactory>;\n /** Make the module global */\n isGlobal?: boolean;\n}\n\n/**\n * Factory interface for creating SmartEngine configuration\n */\nexport interface SmartEngineOptionsFactory {\n createSmartEngineOptions(): Promise<SmartEngineServiceConfig> | SmartEngineServiceConfig;\n}\n\n/**\n * SmartEngineModule - NestJS module for Smart Engines SDK integration\n *\n * Provides dependency injection for SmartEngineService with support for\n * both synchronous and asynchronous configuration.\n *\n * @example Synchronous configuration with forRoot\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRoot({\n * validatorBaseUrl: 'https://validator.example.com',\n * apiKey: 'your-api-key',\n * testConnection: true,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Async configuration with forRootAsync\n * ```typescript\n * import { Module } from '@nestjs/common';\n * import { ConfigService, ConfigModule } from '@nestjs/config';\n * import { SmartEngineModule } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRootAsync({\n * imports: [ConfigModule],\n * useFactory: (configService: ConfigService) => ({\n * validatorBaseUrl: configService.get('SMART_ENGINE_URL'),\n * apiKey: configService.get('SMART_ENGINE_API_KEY'),\n * testConnection: true,\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Using a configuration class\n * ```typescript\n * import { Injectable } from '@nestjs/common';\n * import { SmartEngineModule, SmartEngineOptionsFactory } from '@hsuite/smart-engines-sdk/nestjs';\n *\n * @Injectable()\n * class SmartEngineConfigService implements SmartEngineOptionsFactory {\n * createSmartEngineOptions() {\n * return {\n * validatorBaseUrl: process.env.SMART_ENGINE_URL,\n * apiKey: process.env.SMART_ENGINE_API_KEY,\n * };\n * }\n * }\n *\n * @Module({\n * imports: [\n * SmartEngineModule.forRootAsync({\n * useClass: SmartEngineConfigService,\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@Module({})\nexport class SmartEngineModule {\n /**\n * Configure the module with static configuration.\n *\n * @param config - SmartEngine service configuration.\n * @param isGlobal - Whether to make the module global. @defaultValue true\n * @returns A `DynamicModule` exporting {@link SmartEngineService} plus the\n * BaaS / rules / entities clients.\n */\n static forRoot(config: SmartEngineServiceConfig, isGlobal = true): DynamicModule {\n return {\n module: SmartEngineModule,\n global: isGlobal,\n providers: [\n {\n provide: SMART_ENGINE_CONFIG,\n useValue: config,\n },\n SmartEngineService,\n ...this.createBaasProviders(),\n ],\n exports: [\n SmartEngineService,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n ],\n };\n }\n\n /**\n * Configure the module with async configuration.\n *\n * Supports factory functions, configuration classes, and existing providers.\n *\n * @param options - Async configuration options.\n * @returns A `DynamicModule` exporting {@link SmartEngineService} plus the\n * BaaS / rules / entities clients.\n * @throws Error if `options` provides none of `useFactory`, `useClass`, or\n * `useExisting`.\n */\n static forRootAsync(options: SmartEngineModuleAsyncOptions): DynamicModule {\n const asyncProviders = this.createAsyncProviders(options);\n\n return {\n module: SmartEngineModule,\n global: options.isGlobal ?? true,\n imports: options.imports || [],\n providers: [\n ...asyncProviders,\n SmartEngineService,\n ...this.createBaasProviders(),\n ],\n exports: [\n SmartEngineService,\n SDK_BAAS_CLIENT,\n RULES_CLIENT,\n ENTITIES_CLIENT,\n ],\n };\n }\n\n /**\n * Build the BaaS SDK providers — the full `BaasClient` and its `rules` /\n * `entities` sub-clients — all bound to dedicated injection tokens. Wired\n * into both `forRoot` and `forRootAsync` so consumers can\n * `@Inject(RULES_CLIENT) rules: RulesClient` directly.\n */\n private static createBaasProviders(): Provider[] {\n return [\n {\n provide: SDK_BAAS_CLIENT,\n useFactory: (config: SmartEngineServiceConfig) =>\n new SdkBaasClient({\n // SDK 4.0: the service config carries a single origin field\n // (`validatorBaseUrl`); the BaaS client uses it as its `hostUrl`,\n // preserving the prior single-URL wiring.\n hostUrl: config.validatorBaseUrl,\n timeout: config.timeout,\n allowInsecure: config.allowInsecure,\n }),\n inject: [SMART_ENGINE_CONFIG],\n },\n {\n provide: RULES_CLIENT,\n useFactory: (baas: SdkBaasClient) => baas.rules,\n inject: [SDK_BAAS_CLIENT],\n },\n {\n provide: ENTITIES_CLIENT,\n useFactory: (baas: SdkBaasClient) => baas.entities,\n inject: [SDK_BAAS_CLIENT],\n },\n ];\n }\n\n /**\n * Create async providers based on configuration options\n */\n private static createAsyncProviders(options: SmartEngineModuleAsyncOptions): Provider[] {\n if (options.useFactory) {\n return [\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: options.useFactory,\n inject: options.inject || [],\n },\n ];\n }\n\n if (options.useClass) {\n return [\n {\n provide: options.useClass,\n useClass: options.useClass,\n },\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: async (optionsFactory: SmartEngineOptionsFactory) =>\n optionsFactory.createSmartEngineOptions(),\n inject: [options.useClass],\n },\n ];\n }\n\n if (options.useExisting) {\n return [\n {\n provide: SMART_ENGINE_CONFIG,\n useFactory: async (optionsFactory: SmartEngineOptionsFactory) =>\n optionsFactory.createSmartEngineOptions(),\n inject: [options.useExisting],\n },\n ];\n }\n\n throw new Error(\n 'Invalid SmartEngineModuleAsyncOptions: must provide useFactory, useClass, or useExisting'\n );\n }\n}\n"]}
|