@ocap/types 1.28.9 → 1.29.1

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.
@@ -0,0 +1,525 @@
1
+ // core/types/interfaces/pipeline.ts
2
+ //
3
+ // Transaction Pipeline Context Type System
4
+ // ========================================
5
+ //
6
+ // This module defines a 5-phase context type hierarchy for transaction processing:
7
+ //
8
+ // Phase 1: IBaseContext -> Initial input (txBase64, statedb, config, indexdb)
9
+ // Phase 2: IDecodedContext -> After DecodeTx + DecodeItx (tx, itx, txType, txHash)
10
+ // Phase 3: IGasContext -> After ExtractState + EnsureTxGas + EnsureTxCost
11
+ // Phase 4: IReadyContext -> After TakeStateSnapshot, ready for business logic
12
+ // Phase 5: IExecutedContext -> After business logic execution complete
13
+ //
14
+ // Protocol-specific states are provided as Mixin interfaces (IWithSender, IWithAsset, etc.)
15
+ // that can be combined with phase types to create protocol-specific context types.
16
+ //
17
+ // Example:
18
+ // type DelegateContext = IReadyContext<TDelegateTx> & IWithSender & IWithReceiver & IWithDelegation;
19
+ //
20
+
21
+ import type { TTokenInput, TTransactionReceipt } from '../lib/type_pb';
22
+ import type { BN } from './base';
23
+ import type { IAny } from './base';
24
+ import type { IChainConfig } from './config';
25
+ import type { IIndexDB } from './indexdb';
26
+ import type {
27
+ IAccountState,
28
+ IAssetFactoryState,
29
+ IAssetState,
30
+ IDelegateState,
31
+ IEvidenceState,
32
+ IRollupBlock,
33
+ IRollupState,
34
+ IStakeState,
35
+ ITokenFactoryState,
36
+ ITokenState,
37
+ TokenBalanceMap,
38
+ } from './state';
39
+ import type { IStateDB } from './statedb';
40
+
41
+ // =============================================================================
42
+ // Common Interfaces
43
+ // =============================================================================
44
+
45
+ /** Logger interface for pipeline operations */
46
+ export interface IPipelineLogger {
47
+ /** Logger methods accept any arguments for flexible logging */
48
+ debug: (message: string, ...args: unknown[]) => void;
49
+ info: (message: string, ...args: unknown[]) => void;
50
+ warn: (message: string, ...args: unknown[]) => void;
51
+ error: (message: string, ...args: unknown[]) => void;
52
+ }
53
+
54
+ /** Decoded transaction structure from protobuf */
55
+ export interface IDecodedTransaction {
56
+ from: string;
57
+ delegator?: string;
58
+ chainId: string;
59
+ nonce: number;
60
+ serviceFee?: string;
61
+ pk: Uint8Array;
62
+ signature?: Uint8Array | string;
63
+ signatures?: IMultiSigData[];
64
+ /** Used during signature verification to hold processed signatures */
65
+ signaturesList?: Array<Omit<IMultiSigData, 'signature'>>;
66
+ itx: IAny;
67
+ /** Index signature for dynamic field access during verification */
68
+ [key: string]: unknown;
69
+ }
70
+
71
+ /** Multi-signature data structure for pipeline (decoded format, not proto) */
72
+ export interface IMultiSigData {
73
+ signer: string;
74
+ delegator?: string;
75
+ pk: Uint8Array;
76
+ signature: Uint8Array;
77
+ data?: IAny;
78
+ }
79
+
80
+ /** Account update record */
81
+ export interface IAccountUpdate {
82
+ address: string;
83
+ delta?: string;
84
+ token?: string;
85
+ action?: string;
86
+ }
87
+
88
+ /** Locked state for stake verification */
89
+ export interface ILockedState {
90
+ address: string;
91
+ tokens: TokenBalanceMap;
92
+ assets: string[];
93
+ }
94
+
95
+ /** Input change tracking for token factory operations */
96
+ export interface IInputChange {
97
+ address: string;
98
+ token?: string;
99
+ delta: string;
100
+ }
101
+
102
+ /** Validated inner transaction for delegation */
103
+ export interface IValidatedItx {
104
+ opsList?: Array<{
105
+ typeUrl?: string;
106
+ limit?: {
107
+ tokensList?: Array<{
108
+ address?: string;
109
+ txCount?: number;
110
+ txAllowance?: string;
111
+ totalAllowance?: string;
112
+ validUntil?: number;
113
+ rate?: { interval?: number; anchor?: number } | null;
114
+ }>;
115
+ assetsList?: Array<{
116
+ address?: string[];
117
+ txCount?: number;
118
+ validUntil?: number;
119
+ rate?: { interval?: number; anchor?: number } | null;
120
+ }>;
121
+ };
122
+ }>;
123
+ }
124
+
125
+ /** Gas stake configuration */
126
+ export interface IGasStake {
127
+ owner?: string;
128
+ stakeId?: string;
129
+ state?: IStakeState | null;
130
+ valid?: boolean;
131
+ }
132
+
133
+ /** Token condition for balance verification */
134
+ export interface ITokenCondition {
135
+ owner: string;
136
+ tokens: Array<{ address: string; value: BN }>;
137
+ }
138
+
139
+ /** Output structure for transaction results */
140
+ export interface IOutput {
141
+ owner: string;
142
+ tokens?: TTokenInput[];
143
+ assets?: string[];
144
+ }
145
+
146
+ /** Input structure for transaction */
147
+ export interface IInput {
148
+ owner: string;
149
+ tokensList?: TTokenInput[];
150
+ assetsList?: string[];
151
+ }
152
+
153
+ // =============================================================================
154
+ // Phase 1: Base Context
155
+ // =============================================================================
156
+
157
+ /**
158
+ * Phase 1: Initial input context
159
+ *
160
+ * This is the starting point of the pipeline. Contains only the required
161
+ * inputs provided by the caller before any processing begins.
162
+ *
163
+ * @template TItx - Inner transaction type (default: unknown)
164
+ */
165
+ export interface IBaseContext<TItx = unknown> {
166
+ /** Base64 encoded transaction */
167
+ txBase64: string;
168
+ /** State database instance */
169
+ statedb: IStateDB;
170
+ /** Chain configuration */
171
+ config: IChainConfig;
172
+ /** Index database instance */
173
+ indexdb: IIndexDB;
174
+ /** Optional logger for pipeline operations */
175
+ logger?: IPipelineLogger;
176
+ /** Extra context data */
177
+ extra?: {
178
+ /** Gas stake headers from HTTP request */
179
+ gasStakeHeaders?: { token?: string; pk?: string };
180
+ /** HTTP request object - format varies by server framework */
181
+ request?: unknown;
182
+ /** Extension point for protocol-specific data */
183
+ [key: string]: unknown;
184
+ };
185
+
186
+ // Internal fields that may be set at any phase
187
+ /** Database transaction handle - type depends on StateDB implementation */
188
+ txn?: unknown;
189
+ /** State helper functions - set by execute.ts */
190
+ states?: unknown;
191
+ /** Event queue for indexdb updates */
192
+ events?: Array<{ table: string; name: string; data: unknown; ctx: Record<string, unknown> }>;
193
+
194
+ // Type hint for TItx (not used at runtime)
195
+ /** @internal Type parameter placeholder */
196
+ readonly __itxType?: TItx;
197
+
198
+ /** Index signature for IOperationContext compatibility and dynamic property access */
199
+ [key: string]: unknown;
200
+ }
201
+
202
+ // =============================================================================
203
+ // Phase 1.5: Tx Only Context (intermediate state)
204
+ // =============================================================================
205
+
206
+ /**
207
+ * Intermediate context after DecodeTx but before DecodeItx
208
+ *
209
+ * At this phase, the outer transaction has been decoded but the inner
210
+ * transaction (itx) has not been extracted yet. Used by DecodeItx pipe.
211
+ *
212
+ * Added by: DecodeTx pipe
213
+ */
214
+ export interface ITxOnlyContext extends IBaseContext {
215
+ /** Decoded transaction object (itx is still encoded as Any) */
216
+ tx: IDecodedTransaction;
217
+ /** Transaction hash (DID format) */
218
+ txHash: string;
219
+ /** Transaction timestamp (ISO 8601) */
220
+ txTime: string;
221
+ /** Transaction size in bytes */
222
+ txSize: number;
223
+ /** Whether to charge base gas */
224
+ txBaseGas: boolean;
225
+ }
226
+
227
+ // =============================================================================
228
+ // Phase 2: Decoded Context
229
+ // =============================================================================
230
+
231
+ /**
232
+ * Phase 2: Context after DecodeTx + DecodeItx
233
+ *
234
+ * At this phase, the transaction has been decoded from base64 and the inner
235
+ * transaction (itx) has been extracted. The transaction can now be routed
236
+ * to the appropriate protocol handler.
237
+ *
238
+ * Added by: DecodeTx, DecodeItx pipes
239
+ *
240
+ * @template TItx - Inner transaction type
241
+ */
242
+ export interface IDecodedContext<TItx = unknown> extends ITxOnlyContext {
243
+ /** Decoded inner transaction */
244
+ itx: TItx;
245
+ /** Transaction type URL (e.g., 'fg:t:transfer') */
246
+ txType: string;
247
+ }
248
+
249
+ // =============================================================================
250
+ // Phase 3: Gas Context
251
+ // =============================================================================
252
+
253
+ /**
254
+ * Phase 3: Context after Gas calculation
255
+ *
256
+ * At this phase, states have been extracted (ExtractState) and gas/cost
257
+ * calculations are complete (EnsureTxGas, EnsureTxCost). The transaction
258
+ * fees have been calculated and sender updates prepared.
259
+ *
260
+ * Added by: ExtractState, EnsureTxGas, EnsureTxCost pipes
261
+ *
262
+ * @template TItx - Inner transaction type
263
+ */
264
+ export interface IGasContext<TItx = unknown> extends IDecodedContext<TItx> {
265
+ /** Total gas consumed (set by EnsureGas pipe) */
266
+ totalGas?: BN;
267
+ /** Gas estimate breakdown (set by EnsureGas pipe) */
268
+ gasEstimate?: { create: number; update: number; payment?: number };
269
+ /** Receipts for balance changes */
270
+ receipts?: TTransactionReceipt[];
271
+
272
+ // Fee calculation results
273
+ /** Pending updates to apply to sender account */
274
+ senderUpdates?: Record<string, string>;
275
+ /** Function to update vault balances */
276
+ updateVaults?: () => Promise<void> | void;
277
+ /** Sender balance change record */
278
+ senderChange?: { address: string; token: string; delta: string } | null;
279
+
280
+ // Vault configuration (optional - depends on chain config)
281
+ /** Gas vault address */
282
+ gasVault?: string;
283
+ /** Fee vault address */
284
+ feeVault?: string;
285
+ /** Gas stake configuration */
286
+ gasStake?: IGasStake;
287
+ /** Fee vault change record */
288
+ feeVaultChange?: { address: string; value: string };
289
+ /** Gas vault change record */
290
+ gasVaultChange?: { address: string; value: string };
291
+
292
+ // Flags
293
+ /** Whether gas has been paid */
294
+ gasPaid?: boolean;
295
+ /** Whether using gas stake */
296
+ isGasStake?: boolean;
297
+
298
+ // Account updates (populated by updateVaults callback)
299
+ /** List of account updates applied */
300
+ updatedAccounts?: IAccountUpdate[];
301
+ }
302
+
303
+ // =============================================================================
304
+ // Phase 4: Ready Context
305
+ // =============================================================================
306
+
307
+ /**
308
+ * Phase 4: Context ready for business logic execution
309
+ *
310
+ * At this phase, all preparation is complete:
311
+ * - Transaction decoded
312
+ * - States extracted
313
+ * - Gas calculated
314
+ * - State snapshot taken
315
+ *
316
+ * This is the input type for protocol-specific business logic pipes.
317
+ * Combine with Mixin interfaces to create protocol-specific context types.
318
+ *
319
+ * Added by: TakeStateSnapshot pipe
320
+ *
321
+ * @template TItx - Inner transaction type
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * // Define protocol-specific context
326
+ * type DelegateContext = IReadyContext<TDelegateTx>
327
+ * & IWithSender
328
+ * & IWithReceiver
329
+ * & Partial<IWithDelegation>;
330
+ *
331
+ * // Use in business logic pipe
332
+ * runner.use(async (context: DelegateContext, next) => {
333
+ * const { senderState, receiverState, delegationState } = context;
334
+ * // ... business logic
335
+ * });
336
+ * ```
337
+ */
338
+ export interface IReadyContext<TItx = unknown> extends IGasContext<TItx> {
339
+ // Vault states (extracted by TakeStateSnapshot if configured)
340
+ /** Fee vault account state */
341
+ feeVaultState?: IAccountState;
342
+ /** Gas vault account state */
343
+ gasVaultState?: IAccountState;
344
+ }
345
+
346
+ // =============================================================================
347
+ // Phase 5: Executed Context
348
+ // =============================================================================
349
+
350
+ /**
351
+ * Phase 5: Context after business logic execution
352
+ *
353
+ * At this phase, the business logic has completed and all state
354
+ * modifications have been applied. Ready for final verification
355
+ * (VerifyStateDiff) and transaction persistence.
356
+ *
357
+ * @template TItx - Inner transaction type
358
+ */
359
+ export interface IExecutedContext<TItx = unknown> extends IReadyContext<TItx> {
360
+ /** List of account updates applied - required at this phase */
361
+ updatedAccounts: IAccountUpdate[];
362
+ }
363
+
364
+ // =============================================================================
365
+ // Mixin Interfaces: Account States
366
+ // =============================================================================
367
+
368
+ /** Mixin: Sender account state is required */
369
+ export interface IWithSender {
370
+ senderState: IAccountState;
371
+ }
372
+
373
+ /** Mixin: Receiver account state is required */
374
+ export interface IWithReceiver {
375
+ receiverState: IAccountState;
376
+ }
377
+
378
+ /** Mixin: Delegator account state is required */
379
+ export interface IWithDelegator {
380
+ delegatorState: IAccountState;
381
+ }
382
+
383
+ /** Mixin: Multiple delegator account states are required */
384
+ export interface IWithDelegators {
385
+ delegatorStates: IAccountState[];
386
+ }
387
+
388
+ /** Mixin: Owner account state is required */
389
+ export interface IWithOwner {
390
+ ownerState: IAccountState;
391
+ ownerAddress: string;
392
+ }
393
+
394
+ /** Mixin: Issuer account state is required */
395
+ export interface IWithIssuer {
396
+ issuerState: IAccountState;
397
+ }
398
+
399
+ /** Mixin: Multiple issuer account states are required */
400
+ export interface IWithIssuers {
401
+ issuerStates: IAccountState[];
402
+ }
403
+
404
+ /** Mixin: Locker account state is required */
405
+ export interface IWithLocker {
406
+ lockerState: IAccountState;
407
+ lockerAddress: string;
408
+ }
409
+
410
+ /** Mixin: Multiple signer states are required */
411
+ export interface IWithSigners {
412
+ signerStates: IAccountState[];
413
+ signers: string[];
414
+ }
415
+
416
+ /** Mixin: Multiple receiver states are required */
417
+ export interface IWithReceivers {
418
+ receiverStates: IAccountState[];
419
+ receivers: string[];
420
+ }
421
+
422
+ /** Mixin: Multiple sender states are required */
423
+ export interface IWithSenders {
424
+ senderStates: IAccountState[];
425
+ senders: string[];
426
+ }
427
+
428
+ // =============================================================================
429
+ // Mixin Interfaces: Protocol States
430
+ // =============================================================================
431
+
432
+ /** Mixin: Asset state is required */
433
+ export interface IWithAsset {
434
+ assetState: IAssetState;
435
+ }
436
+
437
+ /** Mixin: Multiple asset states are required */
438
+ export interface IWithAssets {
439
+ assetStates: IAssetState[];
440
+ }
441
+
442
+ /** Mixin: Token state is required */
443
+ export interface IWithToken {
444
+ tokenState: ITokenState;
445
+ tokenAddress: string;
446
+ }
447
+
448
+ /** Mixin: Multiple token states are required */
449
+ export interface IWithTokens {
450
+ tokenStates: ITokenState[];
451
+ }
452
+
453
+ /** Mixin: Asset factory state is required */
454
+ export interface IWithFactory {
455
+ factoryState: IAssetFactoryState;
456
+ }
457
+
458
+ /** Mixin: Token factory state is required */
459
+ export interface IWithTokenFactory {
460
+ tokenFactoryState: ITokenFactoryState;
461
+ }
462
+
463
+ /** Mixin: Stake state is required */
464
+ export interface IWithStake {
465
+ stakeState: IStakeState;
466
+ stakeAddress: string;
467
+ }
468
+
469
+ /** Mixin: Multiple stake states are required */
470
+ export interface IWithStakes {
471
+ stakeStates: IStakeState[];
472
+ }
473
+
474
+ /** Mixin: Delegation state is required */
475
+ export interface IWithDelegation {
476
+ delegationState: IDelegateState;
477
+ }
478
+
479
+ /** Mixin: Rollup state is required */
480
+ export interface IWithRollup {
481
+ rollupState: IRollupState;
482
+ }
483
+
484
+ /** Mixin: Rollup block state is required */
485
+ export interface IWithRollupBlock {
486
+ rollupBlockState: IRollupState;
487
+ blockState: IRollupBlock;
488
+ }
489
+
490
+ /** Mixin: Evidence state is required */
491
+ export interface IWithEvidence {
492
+ evidenceState: IEvidenceState;
493
+ }
494
+
495
+ /** Mixin: Locked state is required (for stake operations) */
496
+ export interface IWithLocked {
497
+ lockedState: ILockedState;
498
+ }
499
+
500
+ /** FinalizedContext uses unknown for TItx as it represents any possible inner transaction type */
501
+ export type FinalizedContext = IExecutedContext<unknown> &
502
+ IWithSender &
503
+ IWithSenders &
504
+ IWithSigners &
505
+ IWithReceiver &
506
+ IWithReceivers &
507
+ IWithDelegator &
508
+ IWithDelegators &
509
+ IWithOwner &
510
+ IWithIssuer &
511
+ IWithIssuers &
512
+ IWithLocker &
513
+ IWithDelegation &
514
+ IWithAsset &
515
+ IWithAssets &
516
+ IWithToken &
517
+ IWithTokens &
518
+ IWithFactory &
519
+ IWithTokenFactory &
520
+ IWithStake &
521
+ IWithStakes &
522
+ IWithRollup &
523
+ IWithRollupBlock &
524
+ IWithEvidence &
525
+ IWithLocked;