@midnightntwrk/wallet-sdk-capabilities 4.0.0-rc.1 → 4.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.
Files changed (62) hide show
  1. package/README.md +10 -3
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/liveness/livenessReads.js +11 -10
  5. package/dist/liveness/livenessService.js +4 -5
  6. package/dist/proving/index.d.ts +1 -0
  7. package/dist/proving/index.js +1 -0
  8. package/dist/proving/provingService.d.ts +16 -49
  9. package/dist/proving/provingService.js +1 -89
  10. package/dist/proving/v8ProvingService.d.ts +34 -7
  11. package/dist/proving/v8ProvingService.js +36 -6
  12. package/dist/proving/v9ProvingService.d.ts +108 -0
  13. package/dist/proving/v9ProvingService.js +146 -0
  14. package/dist/proving/versionedProving.d.ts +22 -4
  15. package/dist/proving/versionedProving.js +28 -2
  16. package/dist/signatures/v8Signatures.d.ts +1 -1
  17. package/dist/simulation/index.d.ts +4 -6
  18. package/dist/simulation/index.js +4 -7
  19. package/dist/simulation/v8/Simulator.d.ts +1 -3
  20. package/dist/simulation/v8/Simulator.js +1 -3
  21. package/dist/simulation/v8/SimulatorState.d.ts +1 -10
  22. package/dist/simulation/v8/SimulatorState.js +1 -9
  23. package/dist/simulation/v8/index.d.ts +1 -1
  24. package/dist/simulation/v8/index.js +1 -1
  25. package/dist/simulation/v9/Simulator.d.ts +0 -2
  26. package/dist/simulation/v9/Simulator.js +0 -2
  27. package/dist/simulation/v9/SimulatorState.d.ts +0 -9
  28. package/dist/simulation/v9/SimulatorState.js +0 -8
  29. package/dist/simulation/v9/index.d.ts +1 -1
  30. package/dist/simulation/v9/index.js +1 -1
  31. package/dist/submission/submissionService.d.ts +57 -9
  32. package/dist/submission/submissionService.js +61 -15
  33. package/dist/transactionLifecycle/SnapshotFormat.d.ts +51 -0
  34. package/dist/transactionLifecycle/SnapshotFormat.js +120 -0
  35. package/dist/transactionLifecycle/index.d.ts +4 -0
  36. package/dist/{pendingTransactions → transactionLifecycle}/index.js +4 -2
  37. package/dist/transactionLifecycle/lifecycle.d.ts +402 -0
  38. package/dist/transactionLifecycle/lifecycle.js +407 -0
  39. package/dist/transactionLifecycle/lifecycleService.d.ts +448 -0
  40. package/dist/transactionLifecycle/lifecycleService.js +350 -0
  41. package/dist/transactionLifecycle/transactionTraits.d.ts +106 -0
  42. package/dist/transactionLifecycle/transactionTraits.js +53 -0
  43. package/dist/validation/blockData.d.ts +23 -4
  44. package/dist/validation/blockData.js +34 -10
  45. package/dist/validation/index.d.ts +1 -0
  46. package/dist/validation/index.js +1 -0
  47. package/dist/validation/promiseBoundary.d.ts +10 -0
  48. package/dist/validation/promiseBoundary.js +30 -0
  49. package/dist/validation/v8ValidationService.d.ts +6 -5
  50. package/dist/validation/v8ValidationService.js +11 -4
  51. package/dist/validation/v9ValidationService.d.ts +30 -0
  52. package/dist/validation/v9ValidationService.js +61 -0
  53. package/dist/validation/validationService.d.ts +54 -32
  54. package/dist/validation/validationService.js +29 -49
  55. package/dist/validation/versionedValidation.d.ts +5 -3
  56. package/dist/validation/versionedValidation.js +5 -3
  57. package/package.json +12 -12
  58. package/dist/pendingTransactions/index.d.ts +0 -2
  59. package/dist/pendingTransactions/pendingTransactions.d.ts +0 -266
  60. package/dist/pendingTransactions/pendingTransactions.js +0 -302
  61. package/dist/pendingTransactions/pendingTransactionsService.d.ts +0 -108
  62. package/dist/pendingTransactions/pendingTransactionsService.js +0 -186
@@ -0,0 +1,407 @@
1
+ /*
2
+ * This file is part of MIDNIGHT-WALLET-SDK.
3
+ * Copyright (C) Midnight Foundation
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * You may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+ /**
16
+ * One record per transaction, from the moment it is balanced to the moment nothing can change its outcome.
17
+ *
18
+ * @remarks
19
+ * The states, what moves a record between them and what each stores are decided in ADR 0011. Every transition here is
20
+ * total: an event that does not apply to a record leaves it as it was, so a final state never moves, save that a
21
+ * reported inclusion overrules an end the wallet only inferred. No transition frees a coin; each wallet's own sweep
22
+ * does.
23
+ */
24
+ import { ProtocolVersion, SnapshotFormat } from '@midnightntwrk/wallet-sdk-abstractions';
25
+ import { Buffer } from 'buffer';
26
+ import { Array as Arr, Data, DateTime, Either, Match, Option, ParseResult, pipe, Schema } from 'effect';
27
+ import { checkV1Store, SNAPSHOT_FORMAT_VERSION, upgradeSnapshotV1ToV2 } from './SnapshotFormat.js';
28
+ import { traitForVersion, } from './transactionTraits.js';
29
+ export const LifecycleState = Data.taggedEnum();
30
+ /** No transaction recorded. */
31
+ export const empty = () => ({ records: [] });
32
+ /** The states a record can still leave. Every other state is final. */
33
+ const LIVE = ['Balanced', 'Finalized', 'Submitted'];
34
+ /** The final states in which the transaction's coins were never spent on chain, so the spend can begin again. */
35
+ const ENDED_UNSPENT = ['Rejected', 'Orphaned', 'Expired', 'Reverted'];
36
+ /**
37
+ * Whether a record can still leave its state: balanced, finalized or submitted.
38
+ *
39
+ * @example
40
+ * const open = state.records.filter(isLive);
41
+ *
42
+ * @param record The record.
43
+ * @returns `true` while some event can still move it.
44
+ */
45
+ export const isLive = (record) => LIVE.includes(record.state._tag);
46
+ /** Moves every record `applies` picks that is in one of the `from` states, leaving every other record as it was. */
47
+ const settle = (state, applies, from, to) => ({
48
+ ...state,
49
+ records: state.records.map((record) => applies(record) && from.includes(record.state._tag) ? { ...record, state: to(record) } : record),
50
+ });
51
+ /** A record stands for the same spend as a transaction when they share any identifier. */
52
+ const isCoveredBy = (identifiers) => (record) => record.identifiers.some((id) => identifiers.includes(id));
53
+ const earliest = (times) => Arr.match(times, { onEmpty: () => Option.none(), onNonEmpty: (all) => Option.some(Arr.min(all, DateTime.Order)) });
54
+ /**
55
+ * Replaces the records `facts` covers with one record in `target`, which the facts describe.
56
+ *
57
+ * When any covered record is in a state the move cannot start from, nothing changes, so a final state is left alone
58
+ * unless the move names it. When none is covered, the record begins here. No move starts from `Submitted`, so the
59
+ * submission time is the one `target` brings, never one a covered record held.
60
+ */
61
+ const moveTo = (state, facts, from, target, createdAt, submittedAt, ttl = () => facts.ttl) => {
62
+ const [rest, covered] = Arr.partition(state.records, isCoveredBy(facts.identifiers));
63
+ return covered.every((record) => from.includes(record.state._tag))
64
+ ? {
65
+ ...state,
66
+ records: Arr.append(rest, {
67
+ identifiers: facts.identifiers,
68
+ intentHashes: facts.intentHashes,
69
+ inputs: facts.inputs,
70
+ ttl: ttl(covered),
71
+ protocolVersion: Option.some(facts.protocolVersion),
72
+ tx: Option.some(facts.tx),
73
+ createdAt: createdAt(covered),
74
+ submittedAt,
75
+ state: target,
76
+ }),
77
+ }
78
+ : state;
79
+ };
80
+ /**
81
+ * A record keeps the earliest TTL known for its spend through every move. The facts read a TTL against the instant of
82
+ * the move, so where it is the Dust grace period after the record began, a later move reads a later one than the
83
+ * transaction has.
84
+ */
85
+ const keptTtl = (facts) => (folded) => new Date(Math.min(facts.ttl.getTime(), ...folded.map((record) => record.ttl.getTime())));
86
+ /** A record keeps the time it began through every move, and folding several keeps the earliest. */
87
+ const keptFrom = (now) => (folded) => pipe(earliest(folded.map((record) => record.createdAt)), Option.getOrElse(() => now));
88
+ /**
89
+ * Records a transaction as balanced, replacing a balanced record of the same spend: balancing it again begins it anew.
90
+ * So does balancing a spend whose record ended without its coins being spent on chain; a confirmed spend stays as it
91
+ * is, and so does one already finalized or submitted.
92
+ *
93
+ * @example
94
+ * const held = balanced(state, { tx: erased, identifiers, intentHashes, inputs, ttl, protocolVersion }, now);
95
+ *
96
+ * @param state The records.
97
+ * @param facts The balanced transaction, with its proofs erased.
98
+ * @param now When it was balanced.
99
+ * @returns The records with the transaction balanced, or unchanged when the spend has already moved past balancing.
100
+ */
101
+ export const balanced = (state, facts, now) => moveTo(state, facts, ['Balanced', ...ENDED_UNSPENT], LifecycleState.Balanced(), () => now, Option.none());
102
+ /**
103
+ * Records a transaction as finalized, from balanced or from nothing. Every record the finalized transaction covers is
104
+ * folded into one, because merging the parts of a recipe makes one transaction.
105
+ *
106
+ * @example
107
+ * const proven = finalized(
108
+ * state,
109
+ * { tx: finalizedTx, identifiers, intentHashes, inputs, ttl, protocolVersion },
110
+ * now,
111
+ * );
112
+ *
113
+ * @param state The records.
114
+ * @param facts The finalized transaction.
115
+ * @param now When it was finalized.
116
+ * @returns The records with the transaction finalized, or unchanged when the spend has already been submitted.
117
+ */
118
+ export const finalized = (state, facts, now) => moveTo(state, facts, ['Balanced', 'Finalized'], LifecycleState.Finalized(), keptFrom(now), Option.none(), keptTtl(facts));
119
+ /**
120
+ * Records a transaction as submitted, from balanced, finalized, reverted or nothing: a transaction proven outside the
121
+ * facade arrives still balanced, and an adopted one arrives unrecorded. A reverted one is sent again after a submission
122
+ * that threw: once it is sent it is in flight, whatever the wallet concluded before.
123
+ *
124
+ * @example
125
+ * const sent = submitted(state, { tx: finalizedTx, identifiers, intentHashes, inputs, ttl, protocolVersion }, now);
126
+ *
127
+ * @param state The records.
128
+ * @param facts The submitted transaction.
129
+ * @param now When it was submitted.
130
+ * @returns The records with the transaction submitted, or unchanged when it already was.
131
+ */
132
+ export const submitted = (state, facts, now) => moveTo(state, facts, ['Balanced', 'Finalized', 'Reverted'], LifecycleState.Submitted(), keptFrom(now), Option.some(now), keptTtl(facts));
133
+ /** Whether the chain itself refused the transaction, rather than the wallet concluding it from the TTL. */
134
+ const isRejectedByChain = (state) => state._tag === 'Rejected' && state.verdict.status !== 'TTL_PASSED';
135
+ /**
136
+ * Records that a transaction was included, whichever live state its record is in: inclusion is a fact, and nothing
137
+ * overrules it afterwards.
138
+ *
139
+ * It also overrules an end the wallet only inferred (expired, rejected at its TTL, orphaned, reverted): a block's time
140
+ * is within the transaction's TTL, so an inclusion reported after such an end happened before it.
141
+ *
142
+ * @example
143
+ * const included = confirmed(state, [...tx.identifiers()]);
144
+ *
145
+ * @param state The records.
146
+ * @param identifiers The included transaction's identifiers.
147
+ * @returns The records with the transaction confirmed; a record whose end the chain reported is left as it was.
148
+ */
149
+ export const confirmed = (state, identifiers) => settle(state, (record) => isCoveredBy(identifiers)(record) && !isRejectedByChain(record.state), [...LIVE, ...ENDED_UNSPENT], () => LifecycleState.Confirmed());
150
+ /**
151
+ * Records that the chain refused a finalized or submitted transaction. A finalized one counts too, because another
152
+ * party may have submitted it, as in a swap, and the chain's answer about it is a fact. A balanced one is left as it
153
+ * was: it is not yet proven, so no chain can have been asked to include it.
154
+ *
155
+ * @example
156
+ * const refused = rejected(state, [...tx.identifiers()], { status: 'FAILURE', segments });
157
+ *
158
+ * @param state The records.
159
+ * @param identifiers The refused transaction's identifiers.
160
+ * @param verdict What the chain reported.
161
+ * @returns The records with the transaction rejected.
162
+ */
163
+ export const rejected = (state, identifiers, verdict) => settle(state, isCoveredBy(identifiers), ['Finalized', 'Submitted'], () => LifecycleState.Rejected({ verdict }));
164
+ /** Whether the epoch `authoredFor` belongs to has ended by `chainNow`. A version no epoch serves has not. */
165
+ const hasEpochEnded = (epochs, authoredFor, chainNow) => pipe(ProtocolVersion.selectEntry(epochs, authoredFor), Option.exists((entry) => chainNow >= entry.range[1]));
166
+ /**
167
+ * Gives up on every live transaction built for an epoch the chain has left. A record whose version was never known is
168
+ * left as it was: that is no evidence it was left behind.
169
+ *
170
+ * @example
171
+ * const stranded = orphanBeyond(state, traits, chainNow);
172
+ *
173
+ * @param state The records.
174
+ * @param epochs The protocol version epochs, as the registry of traits keys them.
175
+ * @param chainNow The version the chain has reached.
176
+ * @returns The records with every stranded transaction orphaned.
177
+ */
178
+ export const orphanBeyond = (state, epochs, chainNow) => ({
179
+ ...state,
180
+ records: state.records.map((record) => pipe(record.protocolVersion, Option.filter((authoredFor) => isLive(record) && hasEpochEnded(epochs, authoredFor, chainNow)), Option.match({
181
+ onNone: () => record,
182
+ onSome: (authoredFor) => ({ ...record, state: LifecycleState.Orphaned({ authoredFor, chainNow }) }),
183
+ }))),
184
+ });
185
+ /**
186
+ * Records that a transaction was reverted, so no chain will be asked to include it.
187
+ *
188
+ * @example
189
+ * const abandoned = reverted(state, [...tx.identifiers()]);
190
+ *
191
+ * @param state The records.
192
+ * @param identifiers The reverted transaction's identifiers.
193
+ * @returns The records with the transaction reverted; a final record is left as it was.
194
+ */
195
+ export const reverted = (state, identifiers) => settle(state, isCoveredBy(identifiers), LIVE, () => LifecycleState.Reverted());
196
+ /**
197
+ * Passed, not reached: the ledger accepts an intent while its TTL is at or after the block's timestamp, so a
198
+ * transaction is still valid at the instant its TTL names.
199
+ */
200
+ const hasTtlPassed = (record, now) => record.ttl.getTime() < DateTime.toEpochMillis(now);
201
+ /**
202
+ * Ends every live record whose TTL `now` has passed: one never submitted expires, and a submitted one is rejected.
203
+ *
204
+ * @param state The records.
205
+ * @param now The instant to expire against.
206
+ * @returns The records with every passed TTL acted on, or the same state when none has passed.
207
+ */
208
+ export const expire = (state, now) => {
209
+ const isDue = (record) => isLive(record) && hasTtlPassed(record, now);
210
+ return Arr.some(state.records, isDue)
211
+ ? {
212
+ ...state,
213
+ records: state.records.map((record) => isDue(record)
214
+ ? {
215
+ ...record,
216
+ state: record.state._tag === 'Submitted'
217
+ ? LifecycleState.Rejected({ verdict: { status: 'TTL_PASSED' } })
218
+ : LifecycleState.Expired(),
219
+ }
220
+ : record),
221
+ }
222
+ : state;
223
+ };
224
+ /**
225
+ * Drops every final record whose TTL `now` has passed.
226
+ *
227
+ * @param state The records.
228
+ * @param now The instant to drop against.
229
+ * @returns The records without them, or the same state when none is due.
230
+ */
231
+ export const dropFinished = (state, now) => {
232
+ const isDue = (record) => !isLive(record) && hasTtlPassed(record, now);
233
+ return Arr.some(state.records, isDue)
234
+ ? { ...state, records: Arr.filter(state.records, (record) => !isDue(record)) }
235
+ : state;
236
+ };
237
+ /**
238
+ * The unshielded coin ids some live transaction still accounts for.
239
+ *
240
+ * A final record accounts for none: a confirmed transaction's coins are spent on chain, and every other final state's
241
+ * coins are free. Read from the inputs each record keeps, so a record that never held its transaction still counts.
242
+ *
243
+ * @example
244
+ * const spokenFor = coveredUnshieldedIds(lifecycle);
245
+ *
246
+ * @param state The records.
247
+ * @returns Every such coin id, without repeats.
248
+ */
249
+ export const coveredUnshieldedIds = (state) => pipe(Arr.filter(state.records, isLive), Arr.flatMap((record) => record.inputs.unshielded), Arr.dedupe);
250
+ const SegmentsSchema = Schema.Array(Schema.Struct({ id: Schema.Number, success: Schema.Boolean }));
251
+ const RejectedVerdictSchema = Schema.Union(Schema.Struct({ status: Schema.Literal('FAILURE', 'PARTIAL_SUCCESS'), segments: SegmentsSchema }), Schema.Struct({ status: Schema.Literal('TTL_PASSED') }));
252
+ /** A state as stored: its tag, and whatever the state carries beside it. */
253
+ const WireStateSchema = Schema.Union(Schema.TaggedStruct('Balanced', {}), Schema.TaggedStruct('Finalized', {}), Schema.TaggedStruct('Submitted', {}), Schema.TaggedStruct('Confirmed', {}), Schema.TaggedStruct('Rejected', { verdict: RejectedVerdictSchema }), Schema.TaggedStruct('Orphaned', {
254
+ authoredFor: ProtocolVersion.ProtocolVersionSchema,
255
+ chainNow: ProtocolVersion.ProtocolVersionSchema,
256
+ }), Schema.TaggedStruct('Expired', {}), Schema.TaggedStruct('Reverted', {}));
257
+ const isWireState = Schema.is(Schema.typeSchema(WireStateSchema));
258
+ /** Builds each state with its own constructor, so a read state is the same value the transitions make. */
259
+ const StateSchema = Schema.transform(WireStateSchema, Schema.declare((value) => isWireState(value)), {
260
+ strict: true,
261
+ decode: (wire) => Match.valueTags(wire, {
262
+ Balanced: () => LifecycleState.Balanced(),
263
+ Finalized: () => LifecycleState.Finalized(),
264
+ Submitted: () => LifecycleState.Submitted(),
265
+ Confirmed: () => LifecycleState.Confirmed(),
266
+ Rejected: ({ verdict }) => LifecycleState.Rejected({ verdict }),
267
+ Orphaned: ({ authoredFor, chainNow }) => LifecycleState.Orphaned({ authoredFor, chainNow }),
268
+ Expired: () => LifecycleState.Expired(),
269
+ Reverted: () => LifecycleState.Reverted(),
270
+ }),
271
+ encode: (state) => state,
272
+ });
273
+ const InputsSchema = Schema.Struct({
274
+ unshielded: Schema.Array(Schema.String),
275
+ shielded: Schema.optionalWith(Schema.Array(Schema.String), { exact: true }),
276
+ });
277
+ /**
278
+ * A record as stored. Its identifiers, intent hashes, inputs and TTL may be absent only beside its transaction, which
279
+ * they are then read from: a store upgraded from `v1` never recorded them for a pending item.
280
+ */
281
+ const WireRecordSchema = Schema.Struct({
282
+ tx: Schema.optionalWith(Schema.String, { exact: true }),
283
+ /** What the trait said about the transaction that its bytes do not, when it said anything. */
284
+ txForm: Schema.optionalWith(Schema.String, { exact: true }),
285
+ protocolVersion: Schema.optionalWith(ProtocolVersion.ProtocolVersionSchema, { as: 'Option', exact: true }),
286
+ identifiers: Schema.optionalWith(Schema.Array(Schema.String), { exact: true }),
287
+ intentHashes: Schema.optionalWith(Schema.Array(Schema.String), { exact: true }),
288
+ inputs: Schema.optionalWith(InputsSchema, { exact: true }),
289
+ ttl: Schema.optionalWith(Schema.Date, { exact: true }),
290
+ createdAt: Schema.DateTimeUtc,
291
+ submittedAt: Schema.optionalWith(Schema.DateTimeUtc, { as: 'Option', exact: true }),
292
+ state: StateSchema,
293
+ });
294
+ /** The facts a record stored, each one it lacks read off its transaction by `trait`. A stored fact always wins. */
295
+ const factsOf = (wire, tx, trait) => ({
296
+ identifiers: wire.identifiers ?? trait.ids(tx),
297
+ intentHashes: wire.intentHashes ?? trait.intentHashes(tx),
298
+ inputs: wire.inputs ?? trait.inputs(tx),
299
+ ttl: wire.ttl ?? trait.ttl(tx, wire.createdAt),
300
+ });
301
+ /** The facts of a record that never held its transaction: all stored, since nothing else could supply them. */
302
+ const storedFactsOf = (wire) => wire.identifiers !== undefined &&
303
+ wire.intentHashes !== undefined &&
304
+ wire.inputs !== undefined &&
305
+ wire.ttl !== undefined
306
+ ? Option.some({
307
+ identifiers: wire.identifiers,
308
+ intentHashes: wire.intentHashes,
309
+ inputs: wire.inputs,
310
+ ttl: wire.ttl,
311
+ })
312
+ : Option.none();
313
+ const RecordSchema = (traits) => {
314
+ const DomainSchema = Schema.declare((value) => typeof value === 'object' && value !== null && 'state' in value && 'identifiers' in value);
315
+ /** The trait a record's transaction is read and written with: the one for its version, or the oldest without one. */
316
+ const traitOf = (protocolVersion, ast, actual) => Either.fromOption(traitForVersion(traits, protocolVersion), () => new ParseResult.Type(ast, actual, `No transaction trait is registered for protocol version ${Option.getOrElse(protocolVersion, () => 'unknown')}.`));
317
+ return Schema.asSchema(Schema.transformOrFail(WireRecordSchema, DomainSchema, {
318
+ strict: true,
319
+ decode: (wire, _options, ast) => {
320
+ const rest = {
321
+ protocolVersion: wire.protocolVersion,
322
+ createdAt: wire.createdAt,
323
+ submittedAt: wire.submittedAt,
324
+ state: wire.state,
325
+ };
326
+ return wire.tx === undefined
327
+ ? pipe(storedFactsOf(wire), Either.fromOption(() => new ParseResult.Type(ast, wire, 'A record that holds no transaction must carry its identifiers, intent hashes, inputs and TTL.')), Either.map((facts) => ({ ...facts, ...rest, tx: Option.none() })))
328
+ : pipe(traitOf(wire.protocolVersion, ast, wire), Either.flatMap((trait) => Either.try({
329
+ try: () => ({ trait, tx: trait.deserialize(Buffer.from(wire.tx ?? '', 'hex'), wire.txForm) }),
330
+ catch: (cause) => new ParseResult.Type(ast, wire, `Could not read the recorded transaction: ${String(cause)}`),
331
+ })), Either.map(({ trait, tx }) => ({ ...factsOf(wire, tx, trait), ...rest, tx: Option.some(tx) })));
332
+ },
333
+ encode: (record, _options, ast) => {
334
+ const rest = {
335
+ protocolVersion: record.protocolVersion,
336
+ identifiers: record.identifiers,
337
+ intentHashes: record.intentHashes,
338
+ inputs: record.inputs,
339
+ ttl: record.ttl,
340
+ createdAt: record.createdAt,
341
+ submittedAt: record.submittedAt,
342
+ state: record.state,
343
+ };
344
+ return Option.match(record.tx, {
345
+ onNone: () => Either.right(rest),
346
+ onSome: (tx) => pipe(traitOf(record.protocolVersion, ast, record), Either.flatMap((trait) => Either.try({
347
+ try: () => ({
348
+ tx: Buffer.from(trait.serialize(tx)).toString('hex'),
349
+ ...(trait.formOf === undefined ? {} : { txForm: trait.formOf(tx) }),
350
+ }),
351
+ catch: (cause) => new ParseResult.Type(ast, record, `Could not write the recorded transaction: ${String(cause)}`),
352
+ })), Either.map((written) => ({ ...rest, ...written }))),
353
+ });
354
+ },
355
+ }));
356
+ };
357
+ /**
358
+ * The stored shape in the current format version. Its own `fields` are the top-level members the format declares; any
359
+ * other member of a payload is an unknown field, carried rather than read.
360
+ */
361
+ const StoredStruct = (traits) => Schema.Struct({
362
+ version: Schema.Literal(SNAPSHOT_FORMAT_VERSION),
363
+ records: Schema.Array(RecordSchema(traits)),
364
+ });
365
+ /**
366
+ * Writes the records in the current stored format, with every top-level member a payload it was read from carried but
367
+ * this build does not declare.
368
+ *
369
+ * @example
370
+ * const stored = serialize(lifecycle, traits);
371
+ *
372
+ * @param state The records.
373
+ * @param traits The traits each record's transaction is written with, chosen by the version it was built for.
374
+ * @returns The records as a JSON string.
375
+ */
376
+ export const serialize = (state, traits) => {
377
+ const encoded = Schema.encodeSync(StoredStruct(traits))({
378
+ version: SNAPSHOT_FORMAT_VERSION,
379
+ records: state.records,
380
+ });
381
+ const written = SnapshotFormat.isJsonObject(encoded) ? encoded : {};
382
+ return JSON.stringify({
383
+ ...written,
384
+ ...SnapshotFormat.unknownFieldsOf(state.unknownFields ?? {}, (key) => Object.hasOwn(written, key)),
385
+ });
386
+ };
387
+ /**
388
+ * Reads records stored in any format version this build knows, upgrading an older one on the way.
389
+ *
390
+ * @remarks
391
+ * A record that holds its transaction but lacks a fact reads it off the transaction, with the trait registered for the
392
+ * version the record was stamped with, or the oldest trait when it carries no stamp. A version this build does not
393
+ * know is refused, never read as the current one.
394
+ * @example
395
+ * const lifecycle = deserialize(stored, traits);
396
+ *
397
+ * @param serialized The stored JSON string.
398
+ * @param traits The traits each record's transaction is read with, chosen by the version it was stamped with.
399
+ * @returns The records, or why the payload could not be read.
400
+ */
401
+ export const deserialize = (serialized, traits) => pipe(serialized, Schema.decodeUnknownEither(Schema.parseJson()), Either.flatMap(checkV1Store), Either.flatMap((parsed) => {
402
+ const json = upgradeSnapshotV1ToV2(parsed);
403
+ const schema = StoredStruct(traits);
404
+ return pipe(Schema.decodeUnknownEither(schema)(json), Either.map((data) => SnapshotFormat.withUnknownFields({ records: data.records }, SnapshotFormat.isJsonObject(json)
405
+ ? SnapshotFormat.unknownFieldsOf(json, (key) => Object.hasOwn(schema.fields, key))
406
+ : {})));
407
+ }));