@hsuite/smart-engines-sdk 3.2.1 → 3.4.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 CHANGED
@@ -1,5 +1,196 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.4.0 — 2026-05-31
4
+
5
+ **Production-readiness arc.** Closes the audit gap identified after 3.3.0 shipped: ~55 of ~110 third-party-facing server endpoints were wrapped; this release brings coverage to ~95/110 (the remaining ~15 are intentionally internal — operator / DKG ceremony / harbor admin). SDK test suite grew from 477 → 637 (+160 tests).
6
+
7
+ Shipped as 7 stacked PRs (#995, #997, #998, #999, #1000, #1002, #1003).
8
+
9
+ ### Breaking changes
10
+
11
+ - **`baas.messaging.setPresence` / `getPresence` / `removePresence`** — signatures now take `channel` as the first argument. The previous appId-scoped paths returned 404 server-side, so behaviourally the breakage is `404 → works`.
12
+ - **`baas.storage.listFiles`** — pagination option renamed `skip` → `offset` to match the server query-string. The previous `skip` value was silently dropped.
13
+ - **`baas.storage.getFile`** — `@deprecated`, now forwards to `download`. The previous endpoint never resolved server-side.
14
+ - **Gateway response types realigned** — `HealthResponse`, `GatewayStatusResponse`, `GatewayReadinessResponse`, `GatewayMetricsResponse`, `HostInfo`, `RegisterHostRequest`, `VerificationMethod`, `DnsRecordType` all rewritten to match what `apps/smart-gateway` actually returns. Compile-time errors surface latent caller bugs; previous types were fabricated.
15
+ - **`baas.agents.fund` / `trade` / `withdraw`** — return type changed from `{ success; txId? }` to `PreparedTransactionResponse` envelope (sovereignty flow). Callers can now reach the prepared transaction bytes; previously unreachable through the declared type.
16
+ - **`tss.signMPC`** — `chain` parameter restricted to literal `'hedera'`. Other chains were never wired server-side and silently 404'd.
17
+ - **`Rules.module.agent`** — removed. Server retired `AgentOrganism` in Arc 6 Phase 6.5; SDK module factory was silently no-op'ing on the cluster.
18
+
19
+ ### Fixed — BaaS endpoint paths that 404'd in production (PR #995)
20
+
21
+ `apps/smart-host` requires `:appId` in every BaaS path; the SDK omitted it on 9 methods plus used the wrong verb on one:
22
+
23
+ - `storage.download` / `getMetadata` / `exists` / `getUsage` — all now correctly prefixed with `:appId`.
24
+ - `functions.invoke` / `get` / `update` / `delete` / `getLogs` / `list` — same fix.
25
+ - `messaging.setPresence` / `getPresence` / `removePresence` — channel-scoped per server.
26
+ - `agents.updateRules` — verb corrected `PUT` → `PATCH`.
27
+ - `db.listCollections` — path corrected to `/collections`.
28
+ - `db.createCollection` / `dropCollection` — new wrappers for endpoints that lacked SDK methods.
29
+
30
+ Regression spec `libs/smartengine-sdk/src/baas/endpoint-paths.spec.ts` pins every fixed URL + verb.
31
+
32
+ Plumbing: `HttpClient` gained a `patch` method (previously missing) to unblock all PATCH-based endpoints across the SDK.
33
+
34
+ ### Added — `client.dao` (PR #998)
35
+
36
+ Full typed wrapper over the ~30 endpoints registered by `apps/smart-validator/src/dao/dao.controller.ts`. The largest single missing surface from the audit.
37
+
38
+ - **Lifecycle** — `create`, `list`, `get`, `getWithProposals`.
39
+ - **Proposals** — `listProposals`, `createProposal`, `prepareProposal`, `signProposal`, `prepareVote`, `submitVote`, `vote`, `execute`, plus `getVotes` / `getResults` / `getVoteCounts` / `getVoterRecord`.
40
+ - **Treasury** — `getTreasury`, `getTreasuryHistory`.
41
+ - **Members** — `listMembers`, `addMember`, `removeMember`, `claimMemberNft`, `getMemberNft`.
42
+ - **`client.dao.dashboard`** — per-user rollups (`getStats`, `getActiveProposals`, `getVoteHistory`, `getActivity`, `getPendingActions`, `getImpact`).
43
+
44
+ ### Added — Hedera TSS + Async TSS + NFT prepare paths (PR #999)
45
+
46
+ - **`client.hedera.tss`** — six TSS-signed immediate-execute endpoints (cluster signs + submits in one round-trip): `createAccount`, `updateMemo`, `createTopic`, `submitMessage`, `createToken`, `mintToken`.
47
+ - **`client.tss`** — async workflow: `createEntityAsync`, `reshareClusterAsync`, `getJob(jobId)`, `signForApp(appId, ...)`.
48
+ - **`client.transactions`** — four NFT prepare paths for Polkadot pallet-nfts + Solana Metaplex: `prepareNftCollectionCreate`, `prepareNftSetMetadata`, `prepareNftCollectionSetMetadata`, `prepareNftCollectionLock`.
49
+ - **`client.xrpl`** — `prepareAccountSetup` (two-step `SignerListSet` + `DisableMaster` for XRPL sovereignty).
50
+
51
+ ### Added — Six new sub-clients (PR #1000)
52
+
53
+ - **`client.bridge`** — 8 cross-chain bridge endpoints (`create`, `list`, `get`, `port`, `return`, `getStatus`, `getSupply`, `listClaims`).
54
+ - **`client.resources`** — quota / consumption / nodes: 8 endpoints (`getSummary`, `getConsumption`, `getHistory`, `getLedger`, `getStatus`, `getBreakdown`, `listNodes`, `getNode`).
55
+ - **`client.envelope`** — `encrypt` / `decrypt` (third-party crypto utility).
56
+ - **`client.tokens`** — token-migration: `migrate`, `listMigrations`, `getMigration`, `getMigrationsForToken`, `getDetails`. The last collides with `client.getTokenInfo` at Nest route registration; documented as a known limitation.
57
+ - **`client.operator`** — read-only operator-funding: `getBalance`, `getTopup`.
58
+ - **`client.subscription`** — extended with `downgrade`, `upgrade`, `cancelTierChange`, `getActiveFor`, `getUsage`, `getUsageStatus`, `getBilling`, `mintCustomer`.
59
+
60
+ ### Added — Rules-engine parity (PR #1002)
61
+
62
+ - **8 canonical server-mirror templates** field-for-field with `libs/validator-rules-builder/src/templates`: `Rules.template.utilityToken`, `daoGovernedToken`, `soulboundNft`, `subscriptionNft`, `membershipNft`, `managedAccount`, `systemTopic`, `appTopic`. Sits alongside the existing higher-altitude composers (`fairLaunch`, `tradingAgent`, etc.) so devs pick altitude.
63
+ - **12 fluent builder methods** on `BaseRuleBuilder`: `withLimits`, `withRateLimiter`, `withSnapshot`, `withCooldown`, `withApprovalThreshold` (canonical atoms now first-class on token/account/topic); molecule shortcuts `withSwap`, `withAirdrop`, `withVesting`, `withStreaming`, `withGovernanceModule`; plus Phase-6.6 AI atoms `withMaxTradesPerWindow` and `withRequireStructuredOutput` on `AgentRulesBuilder`.
64
+ - **`baas.rules.simulate(req)`** confirmed present and tested against `POST /api/rules/simulate`.
65
+
66
+ **Server-side follow-up required**: the 12 new molecule module types (`swap`, `airdrop`, `vesting`, `streaming`, `governance`, `max-trades-per-window`, `require-structured-output`, etc.) will **fail-closed** at the cluster until `libs/rules-engine/src/modules/builtin-modules.ts` registers them. Today only `launchpad / dex / dao / staking-pool` are registered.
67
+
68
+ ### Added — Discovery extras + Deployment KEK / webhook / metrics (PR #1003)
69
+
70
+ - **`client.discovery`** — `listAllClusters` (full set, not just active), `getClusterByNode(nodeId)`, plus `client.discovery.platformImages` sub-namespace: `list`, `listEnvelopes`, `get`, `getVersion`, `verify`.
71
+ - **`baas.deployment`** — `setWebhook(appId, url)` (returns per-tenant HMAC secret), `getMetrics(appId)` (Prometheus text/plain — `HttpClient.getText` plumbing added to bypass JSON.parse), `rotateKek(appId)`, `revokeKek(appId, version)` (ADR-011 Phase 6 KEK rotation surface).
72
+
73
+ ### Verified
74
+
75
+ - `yarn jest`: 637 passing + 1 skipped = 638 total (was 477 in 3.3.0).
76
+ - `yarn build:tsc`: clean (`tsc --skipLibCheck --declaration`).
77
+
78
+ ## 3.3.0 — 2026-05-29
79
+
80
+ **Smart-App Rules SDK arc.** Adds a complete canonical-rule authoring surface
81
+ so smart-app devs can compose, locally validate, publish, and reference
82
+ canonical `ValidatorRules` from a single SDK — the prerequisite for entity
83
+ creation since the cluster requires a `ruleRef` on every binding.
84
+
85
+ No breaking changes. Bundle grows ~260 KB (vendored Zod schemas mirroring
86
+ `libs/shared/src/dto/validator.dto.ts` + builder/composer/template factories).
87
+ `sideEffects: false` added — tree-shaking excludes any sub-namespace a
88
+ consumer doesn't import.
89
+
90
+ ### Added — `Rules` namespace (`import { Rules } from '@hsuite/smart-engines-sdk'`)
91
+
92
+ - **Fluent builders** — `Rules.forToken()` / `.forAccount()` / `.forTopic()` /
93
+ `.forAgent()` with shared `withSecurity` / `withController` / `withOperations` /
94
+ `withTokenGates` / `withGovernance` / `withInvariants` / `withMetadata` /
95
+ `addModule` / `build()` flow. Throws `RuleBuildError` with dot-path messages
96
+ on schema failure.
97
+ - **Composer factories** — 100% coverage of `libs/rules-engine`:
98
+ - `Rules.atom.*` — 17 atoms (timeRange, limits, permissionList, rateLimiter,
99
+ cooldown, approvalThreshold, approvedPairs, tradeLimit, snapshot,
100
+ cronSchedule, countApproval, externalEvidence, fieldValues,
101
+ registryReference, schemaValidation, stopLoss, workflowState)
102
+ - `Rules.molecule.*` — 6 molecules (tokenGate, swap, airdrop, vesting,
103
+ streaming, governance)
104
+ - `Rules.module.*` — 5 organism wrappers as canonical `ModuleEntry`
105
+ (launchpad, stakingPool, dao, dex, agent)
106
+ - **Templates** — 8 one-call factories producing schema-conformant rules:
107
+ `Rules.template.fairLaunch`, `tieredIDO`, `simpleStaking`, `tokenDAO`,
108
+ `multisigDAO`, `simpleAMM`, `vestingSchedule`, `tradingAgent`.
109
+ - **Preflight** — `Rules.validate(rule)` routes by `type` discriminator for
110
+ path-rich error messages (`operations.mint.enabled: Expected boolean`).
111
+ - **Vendored Zod schemas** — `ValidatorRulesSchema`, `TokenValidatorRulesSchema`,
112
+ `AccountValidatorRulesSchema`, `TopicValidatorRulesSchema`,
113
+ `AgentValidatorRulesSchema`, plus every sub-schema (governance, invariants,
114
+ modules, payloadSchema, soulbound, etc.). Mirrors `libs/shared` verbatim;
115
+ re-vendor on schema upgrades.
116
+
117
+ ### Added — `BaasClient` sub-clients
118
+
119
+ - **`baas.rules: RulesClient`** — publish a canonical rule and get back a
120
+ cluster-stamped `ruleRef`:
121
+ - `publish(rule)` → `{ ruleRef: { chain, topicId, consensusTimestamp } }`
122
+ - `get(consensusTimestamp)` → `PublishedRule`
123
+ - `listByOwner({ type? })` → `{ rules, count }`
124
+ - `simulate({ ruleRef? | rule?, action, context })` → `ValidationResult`
125
+ - `getVersionHistory(consensusTimestamp)` → `{ versions }`
126
+ - `deprecate(consensusTimestamp)` → `{ deprecated: true, consensusTimestamp }`
127
+ - **`baas.entities: EntitiesClient`** — ruleRef-gated entity creation. The
128
+ cluster's mandatory creation gate enforces that every entity references a
129
+ published rule:
130
+ - `createToken({ chain, name, symbol, decimals?, initialSupply?, ruleRef, memo? })`
131
+ - `createAccount({ chain, ruleRef, initialBalance?, publicKey? })`
132
+ - `createTopic({ chain, ruleRef, memo? })`
133
+ - `createAgent({ primaryChain, ruleRef, name, agentType? })`
134
+ - `launchpad({ chain, name, symbol, launchpad })` — mega-helper: publishes
135
+ a token rule with a `launchpad` ModuleEntry attached + creates the token
136
+ entity referencing the new ruleRef. Single round-trip.
137
+ - `get(entityId)` → `EntityInfo`
138
+ - `listByOwner({ type? })` → `{ entities, count }`
139
+
140
+ ### Added — NestJS providers (subpath: `@hsuite/smart-engines-sdk/nestjs`)
141
+
142
+ `SmartEngineModule.forRoot` / `.forRootAsync` now expose three injection
143
+ tokens consumers can `@Inject(...)`:
144
+
145
+ - `SDK_BAAS_CLIENT` — shared `BaasClient` instance
146
+ - `RULES_CLIENT` — `RulesClient` (alias for `baasClient.rules`)
147
+ - `ENTITIES_CLIENT` — `EntitiesClient` (alias for `baasClient.entities`)
148
+
149
+ ```ts
150
+ class MyService {
151
+ constructor(
152
+ @Inject(RULES_CLIENT) private readonly rules: RulesClient,
153
+ @Inject(ENTITIES_CLIENT) private readonly entities: EntitiesClient,
154
+ ) {}
155
+ }
156
+ ```
157
+
158
+ `SmartEngineService` provider unchanged.
159
+
160
+ ### Documentation
161
+
162
+ - Package README extended with a `## Rules — author + publish canonical
163
+ ValidatorRules` section, two new rows in the "Available clients" table,
164
+ and a pointer to the full developer guide.
165
+ - Complete developer guide added at
166
+ `docs/developers/libs/rules-engine.md#smart-app-sdk-guide` — covers
167
+ authoring paths, composer reference tables, publish + entity-create
168
+ end-to-end flow, `baas.rules.*` + `baas.entities.*` reference, and 7
169
+ common pitfalls.
170
+
171
+ ### Cluster-side (FYI for SDK consumers — not in this package)
172
+
173
+ This SDK release lights up server-side endpoints already shipped on the
174
+ `smart-engines-multichain` cluster:
175
+
176
+ - Smart-host: `POST /api/rules/publish`, `GET /api/rules/:ts`,
177
+ `GET /api/rules` (listByOwner), `POST /api/rules/simulate`,
178
+ `GET /api/rules/:ts/versions`, `POST /api/rules/:ts/deprecate`,
179
+ `POST /api/entities/{createToken|createAccount|createTopic|createAgent|launchpad}`,
180
+ `GET /api/entities/:id`, `GET /api/entities` (PRs #949, #950).
181
+ - Smart-validator: `POST /api/v3/entities/create` wrapping
182
+ `EntityCreationOrchestrator.createMultisigEntity` for cluster-internal
183
+ service-mesh calls from smart-host (PR #956).
184
+
185
+ ### Build
186
+
187
+ - tsup CJS bundle: `dist/index.js` 396 KB, `dist/nestjs/index.js` 326 KB,
188
+ `dist/pqc-verify/index.js` 8 KB.
189
+ - `dts-bundle-generator` outputs preserved for all three subpaths.
190
+ - `sideEffects: false` declared so consumers can tree-shake unused
191
+ sub-namespaces (`baas.rules` excludable if you don't use canonical rules,
192
+ etc.).
193
+
3
194
  ## 3.2.1 — 2026-05-16
4
195
 
5
196
  **Documentation-only fix.** No runtime behavior change.
package/README.md CHANGED
@@ -88,6 +88,8 @@ from the dev wallet used to authenticate.
88
88
  | Client | Purpose |
89
89
  |---|---|
90
90
  | `BaasClient` | Authentication + database + storage + functions + messaging + deployment + agents |
91
+ | `baas.rules.*` | Publish / get / list / simulate / deprecate canonical `ValidatorRules` documents on HCS |
92
+ | `baas.entities.*` | Create canonical token / account / topic / agent entities (plus launchpad mega-helper), each bound to a published `ruleRef` |
91
93
  | `SmartEngineClient` | Chain operations: account create, token create / mint / burn / freeze / wipe, transfers, HCS topics, TSS, IPFS |
92
94
  | `SmartGatewayClient` | Gateway operations: routing, domains, DNS |
93
95
  | `ValidatorAuthClient` | Standalone Web3 challenge-response auth (lower-level than `BaasClient.authenticate`) |
@@ -100,6 +102,55 @@ the cluster gateway. Set `pathPrefix: ''` for direct host access.
100
102
 
101
103
  ---
102
104
 
105
+ ## Rules — author + publish canonical ValidatorRules
106
+
107
+ `ValidatorRules` are the canonical, HCS-pinned policy documents the cluster
108
+ quorum evaluates before signing any entity action (mint, burn, transfer,
109
+ trade, …). Smart-apps author rules locally (via templates or a fluent
110
+ builder), publish them to HCS via `baas.rules.publish`, and bind the
111
+ returned `ruleRef` into the entity at creation time via `baas.entities.*`.
112
+ Every action against the entity is then rules-checked + TSS-signed.
113
+
114
+ ```ts
115
+ import { BaasClient, Rules } from '@hsuite/smart-engines-sdk';
116
+
117
+ // Template — opinionated fair-launch token with all knobs pre-set.
118
+ const rule = Rules.template.fairLaunch({
119
+ maxSupply: '1000000000',
120
+ mintWindow: { startsAt: '2026-06-01T00:00:00Z', endsAt: '2026-06-08T00:00:00Z' },
121
+ });
122
+
123
+ const { ruleRef } = await baas.rules.publish(rule);
124
+
125
+ const token = await baas.entities.createToken({
126
+ chain: 'hedera',
127
+ name: 'Fair Launch Token',
128
+ symbol: 'FAIR',
129
+ decimals: 6,
130
+ ruleRef,
131
+ });
132
+ ```
133
+
134
+ ```ts
135
+ // Fluent builder — when you want to compose the rule yourself.
136
+ const rule = Rules.forToken()
137
+ .withSecurity('full') // 'none' | 'partial' | 'full'
138
+ .withOperations({
139
+ mint: { enabled: true, limits: { dailyLimit: '1000000' } },
140
+ burn: { enabled: true },
141
+ })
142
+ .withInvariants({ maxSupply: '1000000000' })
143
+ .build();
144
+
145
+ const { ruleRef } = await baas.rules.publish(rule);
146
+ const sim = await baas.rules.simulate({ ruleRef, action: 'mint', context: { amount: '500' } });
147
+ // sim.isValid === true | false (+ reason)
148
+ ```
149
+
150
+ Full reference: [Smart-App SDK Guide](../../docs/developers/libs/rules-engine.md#smart-app-sdk-guide)
151
+
152
+ ---
153
+
103
154
  ## BaaS sub-clients
104
155
 
105
156
  Once authenticated, every BaaS sub-client is reachable from a single