@ottochain/sdk 1.0.3 → 1.1.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.
Files changed (153) hide show
  1. package/dist/cjs/generated/index.js +11 -1
  2. package/dist/cjs/metakit/drop-nulls.js +50 -0
  3. package/dist/cjs/metakit/normalize.js +147 -0
  4. package/dist/cjs/ottochain/metagraph-client.js +147 -0
  5. package/dist/cjs/validation.js +1 -1
  6. package/dist/esm/generated/index.js +11 -1
  7. package/dist/esm/metakit/drop-nulls.js +46 -0
  8. package/dist/esm/metakit/normalize.js +140 -0
  9. package/dist/esm/ottochain/metagraph-client.js +147 -0
  10. package/dist/esm/validation.js +1 -1
  11. package/dist/types/generated/index.d.ts +11 -1
  12. package/dist/types/metakit/drop-nulls.d.ts +29 -0
  13. package/dist/types/metakit/normalize.d.ts +67 -0
  14. package/dist/types/ottochain/index.d.ts +1 -1
  15. package/dist/types/ottochain/metagraph-client.d.ts +90 -0
  16. package/package.json +12 -12
  17. package/dist/apps/contracts/index.d.ts +0 -21
  18. package/dist/apps/contracts/index.js +0 -39
  19. package/dist/apps/contracts/types.d.ts +0 -24
  20. package/dist/apps/contracts/types.js +0 -48
  21. package/dist/apps/identity/index.d.ts +0 -22
  22. package/dist/apps/identity/index.js +0 -40
  23. package/dist/apps/identity/types.d.ts +0 -30
  24. package/dist/apps/identity/types.js +0 -53
  25. package/dist/apps/index.d.ts +0 -29
  26. package/dist/apps/index.js +0 -60
  27. package/dist/apps/markets/index.d.ts +0 -26
  28. package/dist/apps/markets/index.js +0 -46
  29. package/dist/apps/markets/types.d.ts +0 -185
  30. package/dist/apps/markets/types.js +0 -252
  31. package/dist/apps/oracles/index.d.ts +0 -26
  32. package/dist/apps/oracles/index.js +0 -46
  33. package/dist/apps/oracles/types.d.ts +0 -211
  34. package/dist/apps/oracles/types.js +0 -306
  35. package/dist/cjs/apps/contracts/types.js +0 -48
  36. package/dist/cjs/apps/corporate/types.js +0 -44
  37. package/dist/cjs/apps/governance/types.js +0 -42
  38. package/dist/cjs/apps/identity/types.js +0 -53
  39. package/dist/cjs/apps/markets/types.js +0 -219
  40. package/dist/cjs/apps/oracles/types.js +0 -282
  41. package/dist/cjs/generated/ottochain/apps/contracts/v1/contract_pb.js +0 -100
  42. package/dist/cjs/generated/ottochain/apps/corporate/v1/corporate_pb.js +0 -392
  43. package/dist/cjs/generated/ottochain/apps/governance/v1/governance_pb.js +0 -235
  44. package/dist/cjs/generated/ottochain/apps/identity/v1/agent_pb.js +0 -116
  45. package/dist/cjs/generated/ottochain/apps/identity/v1/attestation_pb.js +0 -79
  46. package/dist/cjs/generated/ottochain/apps/markets/v1/market_pb.js +0 -151
  47. package/dist/cjs/generated/ottochain/apps/oracles/v1/oracle_pb.js +0 -109
  48. package/dist/cjs/generated/ottochain/v1/common_pb.js +0 -37
  49. package/dist/cjs/generated/ottochain/v1/fiber_pb.js +0 -86
  50. package/dist/cjs/generated/ottochain/v1/messages_pb.js +0 -44
  51. package/dist/cjs/generated/ottochain/v1/records_pb.js +0 -44
  52. package/dist/errors.d.ts +0 -221
  53. package/dist/errors.js +0 -293
  54. package/dist/esm/apps/contracts/types.js +0 -44
  55. package/dist/esm/apps/corporate/types.js +0 -38
  56. package/dist/esm/apps/governance/types.js +0 -35
  57. package/dist/esm/apps/identity/types.js +0 -50
  58. package/dist/esm/apps/markets/types.js +0 -206
  59. package/dist/esm/apps/oracles/types.js +0 -267
  60. package/dist/esm/generated/ottochain/apps/contracts/v1/contract_pb.js +0 -97
  61. package/dist/esm/generated/ottochain/apps/corporate/v1/corporate_pb.js +0 -389
  62. package/dist/esm/generated/ottochain/apps/governance/v1/governance_pb.js +0 -232
  63. package/dist/esm/generated/ottochain/apps/identity/v1/agent_pb.js +0 -113
  64. package/dist/esm/generated/ottochain/apps/identity/v1/attestation_pb.js +0 -76
  65. package/dist/esm/generated/ottochain/apps/markets/v1/market_pb.js +0 -148
  66. package/dist/esm/generated/ottochain/apps/oracles/v1/oracle_pb.js +0 -106
  67. package/dist/esm/generated/ottochain/v1/common_pb.js +0 -34
  68. package/dist/esm/generated/ottochain/v1/fiber_pb.js +0 -83
  69. package/dist/esm/generated/ottochain/v1/messages_pb.js +0 -41
  70. package/dist/esm/generated/ottochain/v1/records_pb.js +0 -41
  71. package/dist/generated/index.d.ts +0 -15
  72. package/dist/generated/index.js +0 -34
  73. package/dist/generated/ottochain/apps/contracts/v1/contract_pb.d.ts +0 -274
  74. package/dist/generated/ottochain/apps/contracts/v1/contract_pb.js +0 -100
  75. package/dist/generated/ottochain/apps/identity/v1/agent_pb.d.ts +0 -211
  76. package/dist/generated/ottochain/apps/identity/v1/agent_pb.js +0 -116
  77. package/dist/generated/ottochain/apps/identity/v1/attestation_pb.d.ts +0 -238
  78. package/dist/generated/ottochain/apps/identity/v1/attestation_pb.js +0 -79
  79. package/dist/generated/ottochain/apps/markets/v1/market_pb.d.ts +0 -436
  80. package/dist/generated/ottochain/apps/markets/v1/market_pb.js +0 -151
  81. package/dist/generated/ottochain/apps/oracles/v1/oracle_pb.d.ts +0 -393
  82. package/dist/generated/ottochain/apps/oracles/v1/oracle_pb.js +0 -109
  83. package/dist/generated/ottochain/v1/common_pb.d.ts +0 -86
  84. package/dist/generated/ottochain/v1/common_pb.js +0 -37
  85. package/dist/generated/ottochain/v1/fiber_pb.d.ts +0 -292
  86. package/dist/generated/ottochain/v1/fiber_pb.js +0 -86
  87. package/dist/generated/ottochain/v1/messages_pb.d.ts +0 -190
  88. package/dist/generated/ottochain/v1/messages_pb.js +0 -44
  89. package/dist/generated/ottochain/v1/records_pb.d.ts +0 -221
  90. package/dist/generated/ottochain/v1/records_pb.js +0 -44
  91. package/dist/index.d.ts +0 -21
  92. package/dist/index.js +0 -77
  93. package/dist/metakit/binary.d.ts +0 -38
  94. package/dist/metakit/binary.js +0 -58
  95. package/dist/metakit/canonicalize.d.ts +0 -26
  96. package/dist/metakit/canonicalize.js +0 -40
  97. package/dist/metakit/codec.d.ts +0 -16
  98. package/dist/metakit/codec.js +0 -45
  99. package/dist/metakit/currency-transaction.d.ts +0 -157
  100. package/dist/metakit/currency-transaction.js +0 -319
  101. package/dist/metakit/currency-types.d.ts +0 -55
  102. package/dist/metakit/currency-types.js +0 -13
  103. package/dist/metakit/hash.d.ts +0 -50
  104. package/dist/metakit/hash.js +0 -84
  105. package/dist/metakit/index.d.ts +0 -23
  106. package/dist/metakit/index.js +0 -74
  107. package/dist/metakit/network/client.d.ts +0 -23
  108. package/dist/metakit/network/client.js +0 -78
  109. package/dist/metakit/network/currency-l1-client.d.ts +0 -71
  110. package/dist/metakit/network/currency-l1-client.js +0 -101
  111. package/dist/metakit/network/data-l1-client.d.ts +0 -57
  112. package/dist/metakit/network/data-l1-client.js +0 -76
  113. package/dist/metakit/network/index.d.ts +0 -10
  114. package/dist/metakit/network/index.js +0 -16
  115. package/dist/metakit/network/types.d.ts +0 -74
  116. package/dist/metakit/network/types.js +0 -20
  117. package/dist/metakit/sign.d.ts +0 -65
  118. package/dist/metakit/sign.js +0 -120
  119. package/dist/metakit/signed-object.d.ts +0 -66
  120. package/dist/metakit/signed-object.js +0 -100
  121. package/dist/metakit/types.d.ts +0 -67
  122. package/dist/metakit/types.js +0 -14
  123. package/dist/metakit/verify.d.ts +0 -55
  124. package/dist/metakit/verify.js +0 -217
  125. package/dist/metakit/wallet.d.ts +0 -70
  126. package/dist/metakit/wallet.js +0 -127
  127. package/dist/ottochain/index.d.ts +0 -13
  128. package/dist/ottochain/index.js +0 -45
  129. package/dist/ottochain/metagraph-client.d.ts +0 -111
  130. package/dist/ottochain/metagraph-client.js +0 -157
  131. package/dist/ottochain/snapshot.d.ts +0 -86
  132. package/dist/ottochain/snapshot.js +0 -110
  133. package/dist/ottochain/types.d.ts +0 -278
  134. package/dist/ottochain/types.js +0 -11
  135. package/dist/types/apps/contracts/types.d.ts +0 -24
  136. package/dist/types/apps/corporate/types.d.ts +0 -9861
  137. package/dist/types/apps/governance/types.d.ts +0 -344
  138. package/dist/types/apps/identity/types.d.ts +0 -30
  139. package/dist/types/apps/markets/types.d.ts +0 -155
  140. package/dist/types/apps/oracles/types.d.ts +0 -193
  141. package/dist/types/generated/ottochain/apps/contracts/v1/contract_pb.d.ts +0 -274
  142. package/dist/types/generated/ottochain/apps/corporate/v1/corporate_pb.d.ts +0 -1172
  143. package/dist/types/generated/ottochain/apps/governance/v1/governance_pb.d.ts +0 -772
  144. package/dist/types/generated/ottochain/apps/identity/v1/agent_pb.d.ts +0 -211
  145. package/dist/types/generated/ottochain/apps/identity/v1/attestation_pb.d.ts +0 -238
  146. package/dist/types/generated/ottochain/apps/markets/v1/market_pb.d.ts +0 -436
  147. package/dist/types/generated/ottochain/apps/oracles/v1/oracle_pb.d.ts +0 -393
  148. package/dist/types/generated/ottochain/v1/common_pb.d.ts +0 -86
  149. package/dist/types/generated/ottochain/v1/fiber_pb.d.ts +0 -292
  150. package/dist/types/generated/ottochain/v1/messages_pb.d.ts +0 -190
  151. package/dist/types/generated/ottochain/v1/records_pb.d.ts +0 -221
  152. package/dist/validation.d.ts +0 -449
  153. package/dist/validation.js +0 -312
@@ -135,6 +135,153 @@ export class MetagraphClient {
135
135
  return snapshot.value.ordinal;
136
136
  }
137
137
  // -------------------------------------------------------------------------
138
+ // Fiber state subscription
139
+ // -------------------------------------------------------------------------
140
+ /**
141
+ * Subscribe to state changes for a state machine fiber.
142
+ *
143
+ * Polls ML0 at the configured interval and compares `sequenceNumber` to
144
+ * detect changes. Fires the callback with `(current, previous)` on the
145
+ * first poll (if `fireImmediately` is true — the default) and on every
146
+ * subsequent change.
147
+ *
148
+ * ML0 consistency: state is read from snapshot-level `CalculatedState`
149
+ * (via `checkpointService.get`), so a poll never returns a mid-transition
150
+ * value — every observation is a fully committed state.
151
+ *
152
+ * Uses `setTimeout` recursion to prevent overlapping polls when a request
153
+ * takes longer than `pollIntervalMs`.
154
+ *
155
+ * @param fiberId - UUID of the state machine fiber to watch
156
+ * @param callback - Called on first observation and on every state change
157
+ * @param options - Polling interval, error handler, fireImmediately flag
158
+ * @returns Unsubscribe function — call to stop polling immediately
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * const unsub = client.subscribeFiberState(fiberId, (current, prev) => {
163
+ * if (current?.currentState === 'Completed') {
164
+ * unsub();
165
+ * }
166
+ * });
167
+ * // Later:
168
+ * unsub();
169
+ * ```
170
+ */
171
+ subscribeFiberState(fiberId, callback, options) {
172
+ const intervalMs = options?.pollIntervalMs ?? 2000;
173
+ const onError = options?.onError ?? ((e) => console.warn('[subscribeFiberState]', e));
174
+ const fireImmediately = options?.fireImmediately ?? true;
175
+ let previous = null;
176
+ let lastSeqNum = null;
177
+ let firstPoll = true; // Track first poll separately — handles null seqNum on missing fiber
178
+ let active = true;
179
+ const invokeCallback = (current, prev) => {
180
+ try {
181
+ callback(current, prev);
182
+ }
183
+ catch (cbErr) {
184
+ try {
185
+ onError(cbErr instanceof Error ? cbErr : new Error(String(cbErr)));
186
+ }
187
+ catch { /* ignore */ }
188
+ }
189
+ };
190
+ const poll = async () => {
191
+ if (!active)
192
+ return;
193
+ let current;
194
+ try {
195
+ current = await this.getStateMachine(fiberId);
196
+ }
197
+ catch (err) {
198
+ // Network / timeout error — notify and reschedule
199
+ if (!active)
200
+ return;
201
+ try {
202
+ onError(err instanceof Error ? err : new Error(String(err)));
203
+ }
204
+ catch { /* ignore */ }
205
+ if (active)
206
+ setTimeout(poll, intervalMs);
207
+ return;
208
+ }
209
+ // Guard: unsubscribe may have been called while awaiting
210
+ if (!active)
211
+ return;
212
+ const currentSeq = current?.sequenceNumber ?? null;
213
+ if (firstPoll) {
214
+ firstPoll = false;
215
+ lastSeqNum = currentSeq;
216
+ previous = current;
217
+ if (fireImmediately) {
218
+ invokeCallback(current, null);
219
+ }
220
+ }
221
+ else if (currentSeq !== lastSeqNum) {
222
+ // State changed — sequenceNumber differs (handles null → value and value → null)
223
+ const prev = previous;
224
+ previous = current;
225
+ lastSeqNum = currentSeq;
226
+ invokeCallback(current, prev);
227
+ }
228
+ // No change → no callback
229
+ // Schedule next poll (setTimeout recursion prevents overlapping polls)
230
+ if (active)
231
+ setTimeout(poll, intervalMs);
232
+ };
233
+ // Start first poll via setTimeout(0) so Jest fake-timer control works correctly:
234
+ // callers can unsubscribe before the first poll runs, and each
235
+ // jest.runOnlyPendingTimersAsync() advances exactly one poll cycle.
236
+ setTimeout(poll, 0);
237
+ return () => { active = false; };
238
+ }
239
+ /**
240
+ * Wait for a fiber to reach a specific state, with an optional timeout.
241
+ *
242
+ * Builds on `subscribeFiberState` — resolves with the fiber record once
243
+ * `currentState === targetState`, or resolves with `null` after `timeoutMs`.
244
+ * Always calls unsubscribe on resolution or timeout (no memory leaks).
245
+ *
246
+ * @param fiberId - UUID of the state machine fiber
247
+ * @param targetState - State name to wait for (e.g. `'Completed'`)
248
+ * @param timeoutMs - Maximum wait in milliseconds (default: 30 000)
249
+ * @returns Fiber record when target state reached, or `null` on timeout
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const result = await client.waitForState(fiberId, 'Completed', 15_000);
254
+ * if (result === null) console.warn('Timed out waiting for Completed');
255
+ * ```
256
+ */
257
+ waitForState(fiberId, targetState, timeoutMs = 30000, options) {
258
+ return new Promise((resolve) => {
259
+ let resolved = false;
260
+ let timer = null;
261
+ // unsub starts as a no-op so it's safe to call even if subscribeFiberState
262
+ // invokes the callback synchronously (before returning the real unsubscribe).
263
+ let unsub = () => { };
264
+ const done = (result) => {
265
+ if (resolved)
266
+ return;
267
+ resolved = true;
268
+ if (timer !== null)
269
+ clearTimeout(timer);
270
+ unsub(); // safe: either the real unsub or the initial no-op
271
+ resolve(result);
272
+ };
273
+ unsub = this.subscribeFiberState(fiberId, (current) => {
274
+ if (current?.currentState === targetState) {
275
+ done(current);
276
+ }
277
+ }, { fireImmediately: true, ...options });
278
+ // Only arm the timeout if the callback hasn't already resolved (synchronous case)
279
+ if (!resolved) {
280
+ timer = setTimeout(() => done(null), timeoutMs);
281
+ }
282
+ });
283
+ }
284
+ // -------------------------------------------------------------------------
138
285
  // DL1 data submission (framework POST /data)
139
286
  // -------------------------------------------------------------------------
140
287
  /**
@@ -131,7 +131,7 @@ export const PlatformLinkSchema = z.object({
131
131
  /**
132
132
  * Schema for contract terms (flexible structure)
133
133
  */
134
- export const ContractTermsSchema = z.record(z.unknown());
134
+ export const ContractTermsSchema = z.record(z.string(), z.unknown());
135
135
  /**
136
136
  * Schema for ProposeContractRequest
137
137
  */
@@ -2,9 +2,19 @@
2
2
  * Generated Protobuf Types
3
3
  *
4
4
  * Auto-generated from proto/ definitions using ts-proto.
5
- * DO NOT EDIT - regenerate with `pnpm run generate`
5
+ * DO NOT EDIT - regenerate with `npm run generate`
6
6
  *
7
7
  * @packageDocumentation
8
+ *
9
+ * NOTE — Dual-type architecture:
10
+ * These generated types use proto conventions (FIBER_STATUS_ACTIVE, StateId { value } wrappers).
11
+ * The wire-format REST API types in src/ottochain/types.ts use plain strings ('Active').
12
+ * Both coexist intentionally until PR #89 (Migrate fiber-engine to generated Scala types) merges.
13
+ *
14
+ * TODO PR #89 migration: after PR #89 merges and cluster confirms new format,
15
+ * migrate all state-machine JSON files in src/apps/ from Circe-format
16
+ * ({ value: '...' } wrapped initialState) to plain string format.
17
+ * See docs/type-architecture.md for full migration plan.
8
18
  */
9
19
  export { FiberStatus, AccessControlPolicy, PublicAccess, WhitelistAccess, FiberOwnedAccess, StateMachineDefinition, EmittedEvent, EventReceipt, ScriptInvocation, FiberLogEntry, } from './ottochain/v1/fiber.js';
10
20
  export { CreateStateMachine, TransitionStateMachine, ArchiveStateMachine, CreateScript, InvokeScript, OttochainMessage, } from './ottochain/v1/messages.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Drop Null Values from JSON Objects
3
+ *
4
+ * Recursively removes null-valued keys from objects to match
5
+ * the Scala-side `JsonBinaryCodec.dropNulls` behavior in metakit.
6
+ *
7
+ * This ensures that the canonical JSON used for signing on the
8
+ * TypeScript side matches what the Scala metagraph produces when
9
+ * verifying signatures.
10
+ *
11
+ * Note: null values inside arrays are preserved (to maintain index
12
+ * positions). Only object field values that are null are removed.
13
+ */
14
+ /**
15
+ * Recursively remove null values from objects
16
+ *
17
+ * @param value - Any JSON-serializable value
18
+ * @returns A deep copy with null object fields removed
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * dropNulls({ a: 1, b: null, c: { d: null, e: 2 } })
23
+ * // => { a: 1, c: { e: 2 } }
24
+ *
25
+ * dropNulls([1, null, 3])
26
+ * // => [1, null, 3] (array nulls preserved)
27
+ * ```
28
+ */
29
+ export declare function dropNulls<T>(value: T): T;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Normalize OttoChain Messages for Signing
3
+ *
4
+ * Converts OttoChain message objects to the wire format expected by the
5
+ * Scala metagraph. Specifically, ensures all `Option[A]=None` fields are
6
+ * present as explicit `null` values, matching what circe's magnolia encoder
7
+ * produces on the Scala side.
8
+ *
9
+ * This is necessary because metakit's `JsonBinaryCodec.deriveDataUpdate`
10
+ * (rc.8) canonicalizes the circe-encoded JSON **including null fields**.
11
+ * If the TypeScript client omits optional fields (undefined), the canonical
12
+ * JSON won't match and signature verification will fail.
13
+ *
14
+ * Schema mapping (Scala → TypeScript):
15
+ * - `Option[A] = None` → `null` (must be explicit, not undefined/absent)
16
+ * - `Option[A] = Some(v)` → `v`
17
+ * - `List.empty` → `[]`
18
+ * - `Map.empty` → `{}`
19
+ */
20
+ /**
21
+ * Normalize a CreateStateMachine message for wire format
22
+ *
23
+ * Ensures all Option fields are explicit null:
24
+ * - definition.metadata
25
+ * - definition.states[*].metadata
26
+ * - definition.transitions[*].guard
27
+ * - definition.transitions[*].actions
28
+ * - definition.transitions[*].metadata
29
+ * - parentFiberId
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const message = normalizeCreateStateMachine({
34
+ * fiberId: '...',
35
+ * definition: { states: { INIT: { id: { value: 'INIT' }, isFinal: false } }, ... },
36
+ * initialData: {}
37
+ * });
38
+ * // message now has parentFiberId: null, definition.metadata: null, etc.
39
+ * ```
40
+ */
41
+ export declare function normalizeCreateStateMachine(msg: Record<string, unknown>): Record<string, unknown>;
42
+ /**
43
+ * Normalize a TransitionStateMachine message for wire format
44
+ */
45
+ export declare function normalizeTransitionStateMachine(msg: Record<string, unknown>): Record<string, unknown>;
46
+ /**
47
+ * Normalize an ArchiveStateMachine message for wire format
48
+ */
49
+ export declare function normalizeArchiveStateMachine(msg: Record<string, unknown>): Record<string, unknown>;
50
+ /**
51
+ * Normalize any OttochainMessage wrapper for wire format.
52
+ *
53
+ * Detects the message type from the wrapper key and applies the
54
+ * appropriate normalization.
55
+ *
56
+ * @param message - OttochainMessage in wrapper format: `{ CreateStateMachine: {...} }`
57
+ * @returns Normalized message with all Option fields as explicit null
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const normalized = normalizeMessage({
62
+ * CreateStateMachine: { fiberId: '...', definition: {...}, initialData: {} }
63
+ * });
64
+ * const signed = await signDataUpdate(normalized, privateKey);
65
+ * ```
66
+ */
67
+ export declare function normalizeMessage(message: Record<string, unknown>): Record<string, unknown>;
@@ -9,5 +9,5 @@ export * as proto from '../generated/index.js';
9
9
  export type { Address, FiberId, StateId, HashValue, FiberOrdinal, SnapshotOrdinal, JsonLogicValue, JsonLogicExpression, FiberStatus, AccessControlPolicy, StateMachineDefinition, EmittedEvent, EventReceipt, OracleInvocation, FiberLogEntry, StateMachineFiberRecord, ScriptFiberRecord, FiberRecord, FiberCommit, OnChain, CalculatedState, CreateStateMachine, TransitionStateMachine, ArchiveStateMachine, CreateScript, InvokeScript, OttochainMessage, } from './types.js';
10
10
  export type { CurrencySnapshotResponse } from './snapshot.js';
11
11
  export { decodeOnChainState, getSnapshotOnChainState, getLatestOnChainState, getLogsForFiber, getEventReceipts, getScriptInvocations, extractOnChainState, } from './snapshot.js';
12
- export type { Checkpoint, MetagraphClientConfig } from './metagraph-client.js';
12
+ export type { Checkpoint, MetagraphClientConfig, SubscribeOptions, FiberStateCallback, Unsubscribe, } from './metagraph-client.js';
13
13
  export { MetagraphClient } from './metagraph-client.js';
@@ -16,6 +16,45 @@ export interface Checkpoint {
16
16
  ordinal: number;
17
17
  state: CalculatedState;
18
18
  }
19
+ /**
20
+ * Options for subscribeFiberState polling behaviour.
21
+ */
22
+ export interface SubscribeOptions {
23
+ /**
24
+ * Polling interval in milliseconds.
25
+ * @default 2000
26
+ */
27
+ pollIntervalMs?: number;
28
+ /**
29
+ * Called when a poll fails (network error, timeout, etc.) or when the
30
+ * user-supplied callback throws. The subscription continues after an error.
31
+ * @default (e) => console.warn('[subscribeFiberState]', e)
32
+ */
33
+ onError?: (error: Error) => void;
34
+ /**
35
+ * If true, fire the callback immediately after the very first poll even
36
+ * when no previous state exists (current vs. null).
37
+ * Set false to suppress the initial callback and only fire on changes.
38
+ *
39
+ * **Edge case:** When `fireImmediately` is false and the fiber never exists
40
+ * (getStateMachine always returns null), the callback will never fire because
41
+ * the sequence number stays null between polls (no change detected).
42
+ * @default true
43
+ */
44
+ fireImmediately?: boolean;
45
+ }
46
+ /**
47
+ * Callback invoked when fiber state is first observed or changes.
48
+ *
49
+ * @param current - Current fiber state, or null if fiber not found
50
+ * @param previous - Previous fiber state, or null on first callback
51
+ */
52
+ export type FiberStateCallback = (current: StateMachineFiberRecord | null, previous: StateMachineFiberRecord | null) => void;
53
+ /**
54
+ * Unsubscribe function returned by subscribeFiberState.
55
+ * Stops polling immediately and prevents any further callbacks. Idempotent.
56
+ */
57
+ export type Unsubscribe = () => void;
19
58
  /**
20
59
  * Configuration for the MetagraphClient.
21
60
  */
@@ -98,6 +137,57 @@ export declare class MetagraphClient {
98
137
  * Get the latest snapshot ordinal.
99
138
  */
100
139
  getLatestOrdinal(): Promise<number>;
140
+ /**
141
+ * Subscribe to state changes for a state machine fiber.
142
+ *
143
+ * Polls ML0 at the configured interval and compares `sequenceNumber` to
144
+ * detect changes. Fires the callback with `(current, previous)` on the
145
+ * first poll (if `fireImmediately` is true — the default) and on every
146
+ * subsequent change.
147
+ *
148
+ * ML0 consistency: state is read from snapshot-level `CalculatedState`
149
+ * (via `checkpointService.get`), so a poll never returns a mid-transition
150
+ * value — every observation is a fully committed state.
151
+ *
152
+ * Uses `setTimeout` recursion to prevent overlapping polls when a request
153
+ * takes longer than `pollIntervalMs`.
154
+ *
155
+ * @param fiberId - UUID of the state machine fiber to watch
156
+ * @param callback - Called on first observation and on every state change
157
+ * @param options - Polling interval, error handler, fireImmediately flag
158
+ * @returns Unsubscribe function — call to stop polling immediately
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * const unsub = client.subscribeFiberState(fiberId, (current, prev) => {
163
+ * if (current?.currentState === 'Completed') {
164
+ * unsub();
165
+ * }
166
+ * });
167
+ * // Later:
168
+ * unsub();
169
+ * ```
170
+ */
171
+ subscribeFiberState(fiberId: string, callback: FiberStateCallback, options?: SubscribeOptions): Unsubscribe;
172
+ /**
173
+ * Wait for a fiber to reach a specific state, with an optional timeout.
174
+ *
175
+ * Builds on `subscribeFiberState` — resolves with the fiber record once
176
+ * `currentState === targetState`, or resolves with `null` after `timeoutMs`.
177
+ * Always calls unsubscribe on resolution or timeout (no memory leaks).
178
+ *
179
+ * @param fiberId - UUID of the state machine fiber
180
+ * @param targetState - State name to wait for (e.g. `'Completed'`)
181
+ * @param timeoutMs - Maximum wait in milliseconds (default: 30 000)
182
+ * @returns Fiber record when target state reached, or `null` on timeout
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * const result = await client.waitForState(fiberId, 'Completed', 15_000);
187
+ * if (result === null) console.warn('Timed out waiting for Completed');
188
+ * ```
189
+ */
190
+ waitForState(fiberId: string, targetState: string, timeoutMs?: number, options?: Pick<SubscribeOptions, 'pollIntervalMs' | 'onError'>): Promise<StateMachineFiberRecord | null>;
101
191
  /**
102
192
  * Submit a signed data update to the DL1 node.
103
193
  * The POST /data endpoint is framework-provided (no /v1 prefix).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ottochain/sdk",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "TypeScript SDK for ottochain metagraph operations - signing, encoding, and network interactions",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -55,6 +55,11 @@
55
55
  "import": "./dist/esm/apps/index.js",
56
56
  "require": "./dist/cjs/apps/index.js",
57
57
  "types": "./dist/types/apps/index.d.ts"
58
+ },
59
+ "./generated": {
60
+ "import": "./dist/esm/generated/index.js",
61
+ "require": "./dist/cjs/generated/index.js",
62
+ "types": "./dist/types/generated/index.d.ts"
58
63
  }
59
64
  },
60
65
  "files": [
@@ -107,21 +112,16 @@
107
112
  "zod": "^3.22.0"
108
113
  },
109
114
  "devDependencies": {
110
- "@bufbuild/buf": "^1.65.0",
111
- "@bufbuild/protoc-gen-es": "^2.11.0",
112
- "@protobuf-ts/plugin": "^2.11.1",
113
- "@protobuf-ts/runtime": "^2.11.1",
114
- "@types/jest": "^29.5.0",
115
+ "@types/jest": "^30.0.0",
115
116
  "@types/node": "^20.0.0",
116
- "@typescript-eslint/eslint-plugin": "^7.0.0",
117
- "@typescript-eslint/parser": "^7.0.0",
118
- "eslint": "^8.0.0",
119
- "grpc-tools": "^1.13.1",
120
- "jest": "^29.0.0",
117
+ "@typescript-eslint/eslint-plugin": "^8.56.1",
118
+ "@typescript-eslint/parser": "^8.56.1",
119
+ "eslint": "^9.39.3",
120
+ "jest": "^30.2.0",
121
121
  "prettier": "^3.0.0",
122
122
  "ts-jest": "^29.0.0",
123
123
  "ts-proto": "^2.11.2",
124
- "typedoc": "^0.25.0",
124
+ "typedoc": "^0.28.17",
125
125
  "typescript": "^5.0.0"
126
126
  },
127
127
  "peerDependencies": {
@@ -1,21 +0,0 @@
1
- /**
2
- * Contracts Application
3
- *
4
- * Types and utilities for the Contract system on OttoChain.
5
- *
6
- * @example
7
- * ```typescript
8
- * import { ContractState, ContractSchema } from '@ottochain/sdk/apps/contracts';
9
- * import { create } from '@bufbuild/protobuf';
10
- *
11
- * const contract = create(ContractSchema, {
12
- * id: 'fiber-123',
13
- * contractId: 'contract-001',
14
- * state: ContractState.PROPOSED,
15
- * });
16
- * ```
17
- *
18
- * @packageDocumentation
19
- */
20
- export * from '../../generated/ottochain/apps/contracts/v1/contract_pb.js';
21
- export * from './types.js';
@@ -1,39 +0,0 @@
1
- "use strict";
2
- /**
3
- * Contracts Application
4
- *
5
- * Types and utilities for the Contract system on OttoChain.
6
- *
7
- * @example
8
- * ```typescript
9
- * import { ContractState, ContractSchema } from '@ottochain/sdk/apps/contracts';
10
- * import { create } from '@bufbuild/protobuf';
11
- *
12
- * const contract = create(ContractSchema, {
13
- * id: 'fiber-123',
14
- * contractId: 'contract-001',
15
- * state: ContractState.PROPOSED,
16
- * });
17
- * ```
18
- *
19
- * @packageDocumentation
20
- */
21
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
22
- if (k2 === undefined) k2 = k;
23
- var desc = Object.getOwnPropertyDescriptor(m, k);
24
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
25
- desc = { enumerable: true, get: function() { return m[k]; } };
26
- }
27
- Object.defineProperty(o, k2, desc);
28
- }) : (function(o, m, k, k2) {
29
- if (k2 === undefined) k2 = k;
30
- o[k2] = m[k];
31
- }));
32
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
33
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
34
- };
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- // Re-export generated protobuf types
37
- __exportStar(require("../../generated/ottochain/apps/contracts/v1/contract_pb.js"), exports);
38
- // Re-export convenience types and constants
39
- __exportStar(require("./types.js"), exports);
@@ -1,24 +0,0 @@
1
- /**
2
- * Contract Utilities
3
- *
4
- * Constants and utilities for the Contract application.
5
- * Core types are generated from protobuf - see the generated exports.
6
- *
7
- * @packageDocumentation
8
- */
9
- import { ContractState } from '../../generated/ottochain/apps/contracts/v1/contract_pb.js';
10
- /**
11
- * Default contract configuration
12
- */
13
- export declare const DEFAULT_CONTRACT_CONFIG: {
14
- readonly requireBothSignatures: false;
15
- readonly disputeWindowEpochs: 10;
16
- };
17
- /**
18
- * Valid transitions for each contract state
19
- */
20
- export declare const CONTRACT_TRANSITIONS: Record<ContractState, readonly string[]>;
21
- /**
22
- * Check if a contract state is terminal (no further transitions allowed)
23
- */
24
- export declare function isTerminalState(state: ContractState): boolean;
@@ -1,48 +0,0 @@
1
- "use strict";
2
- /**
3
- * Contract Utilities
4
- *
5
- * Constants and utilities for the Contract application.
6
- * Core types are generated from protobuf - see the generated exports.
7
- *
8
- * @packageDocumentation
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.isTerminalState = exports.CONTRACT_TRANSITIONS = exports.DEFAULT_CONTRACT_CONFIG = void 0;
12
- const contract_pb_js_1 = require("../../generated/ottochain/apps/contracts/v1/contract_pb.js");
13
- // ---------------------------------------------------------------------------
14
- // Configuration Defaults
15
- // ---------------------------------------------------------------------------
16
- /**
17
- * Default contract configuration
18
- */
19
- exports.DEFAULT_CONTRACT_CONFIG = {
20
- requireBothSignatures: false,
21
- disputeWindowEpochs: 10,
22
- };
23
- // ---------------------------------------------------------------------------
24
- // State Machine Transitions
25
- // ---------------------------------------------------------------------------
26
- /**
27
- * Valid transitions for each contract state
28
- */
29
- exports.CONTRACT_TRANSITIONS = {
30
- [contract_pb_js_1.ContractState.UNSPECIFIED]: [],
31
- [contract_pb_js_1.ContractState.PROPOSED]: ['accept', 'reject', 'cancel'],
32
- [contract_pb_js_1.ContractState.ACTIVE]: ['complete', 'dispute'],
33
- [contract_pb_js_1.ContractState.DISPUTED]: ['resolve_for_completer', 'resolve_for_disputant'],
34
- [contract_pb_js_1.ContractState.COMPLETED]: [], // Terminal state
35
- [contract_pb_js_1.ContractState.REJECTED]: [], // Terminal state
36
- [contract_pb_js_1.ContractState.CANCELLED]: [], // Terminal state
37
- };
38
- /**
39
- * Check if a contract state is terminal (no further transitions allowed)
40
- */
41
- function isTerminalState(state) {
42
- return [
43
- contract_pb_js_1.ContractState.COMPLETED,
44
- contract_pb_js_1.ContractState.REJECTED,
45
- contract_pb_js_1.ContractState.CANCELLED,
46
- ].includes(state);
47
- }
48
- exports.isTerminalState = isTerminalState;
@@ -1,22 +0,0 @@
1
- /**
2
- * Agent Identity Application
3
- *
4
- * Types and utilities for the Agent Identity system on OttoChain.
5
- *
6
- * @example
7
- * ```typescript
8
- * import { AgentState, AttestationType, AgentIdentitySchema } from '@ottochain/sdk/apps/identity';
9
- * import { create } from '@bufbuild/protobuf';
10
- *
11
- * const agent = create(AgentIdentitySchema, {
12
- * publicKey: '...',
13
- * reputation: 10,
14
- * state: AgentState.REGISTERED,
15
- * });
16
- * ```
17
- *
18
- * @packageDocumentation
19
- */
20
- export * from '../../generated/ottochain/apps/identity/v1/agent_pb.js';
21
- export * from '../../generated/ottochain/apps/identity/v1/attestation_pb.js';
22
- export * from './types.js';
@@ -1,40 +0,0 @@
1
- "use strict";
2
- /**
3
- * Agent Identity Application
4
- *
5
- * Types and utilities for the Agent Identity system on OttoChain.
6
- *
7
- * @example
8
- * ```typescript
9
- * import { AgentState, AttestationType, AgentIdentitySchema } from '@ottochain/sdk/apps/identity';
10
- * import { create } from '@bufbuild/protobuf';
11
- *
12
- * const agent = create(AgentIdentitySchema, {
13
- * publicKey: '...',
14
- * reputation: 10,
15
- * state: AgentState.REGISTERED,
16
- * });
17
- * ```
18
- *
19
- * @packageDocumentation
20
- */
21
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
22
- if (k2 === undefined) k2 = k;
23
- var desc = Object.getOwnPropertyDescriptor(m, k);
24
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
25
- desc = { enumerable: true, get: function() { return m[k]; } };
26
- }
27
- Object.defineProperty(o, k2, desc);
28
- }) : (function(o, m, k, k2) {
29
- if (k2 === undefined) k2 = k;
30
- o[k2] = m[k];
31
- }));
32
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
33
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
34
- };
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- // Re-export generated protobuf types
37
- __exportStar(require("../../generated/ottochain/apps/identity/v1/agent_pb.js"), exports);
38
- __exportStar(require("../../generated/ottochain/apps/identity/v1/attestation_pb.js"), exports);
39
- // Re-export convenience types and constants
40
- __exportStar(require("./types.js"), exports);
@@ -1,30 +0,0 @@
1
- /**
2
- * Agent Identity Utilities
3
- *
4
- * Constants and utilities for the Agent Identity application.
5
- * Core types are generated from protobuf - see the generated exports.
6
- *
7
- * @packageDocumentation
8
- */
9
- import { AgentState } from '../../generated/ottochain/apps/identity/v1/agent_pb.js';
10
- import { AttestationType } from '../../generated/ottochain/apps/identity/v1/attestation_pb.js';
11
- /**
12
- * Default reputation configuration for agent identity
13
- */
14
- export declare const DEFAULT_REPUTATION_CONFIG: {
15
- readonly baseReputation: 10;
16
- readonly completionDelta: 5;
17
- readonly vouchDelta: 2;
18
- readonly violationDelta: -10;
19
- readonly behavioralDelta: 3;
20
- readonly minReputation: 0;
21
- readonly challengeThreshold: 5;
22
- };
23
- /**
24
- * Valid transitions for each agent state
25
- */
26
- export declare const AGENT_TRANSITIONS: Record<AgentState, readonly string[]>;
27
- /**
28
- * Reputation delta by attestation type
29
- */
30
- export declare const ATTESTATION_DELTAS: Record<AttestationType, number>;