@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
@@ -1,266 +0,0 @@
1
- import { ProtocolVersion } from '@midnightntwrk/wallet-sdk-abstractions';
2
- import { DateTime, Either, Option, ParseResult, Schema } from 'effect';
3
- export type TransactionTrait<TTransaction> = {
4
- ids: (tx: TTransaction) => readonly string[];
5
- firstId: (tx: TTransaction) => string;
6
- areAllTxIdsIncluded: (tx: TTransaction, txIds: readonly string[]) => boolean;
7
- isOneIncludedInOther: (tx: TTransaction, otherTx: TTransaction) => boolean;
8
- hasTTLExpired: (tx: TTransaction, txCreationTime: DateTime.Utc, now: DateTime.Utc) => boolean;
9
- serialize: (tx: TTransaction) => Uint8Array;
10
- deserialize: (serialized: Uint8Array) => TTransaction;
11
- isTx: (tx: unknown) => tx is TTransaction;
12
- };
13
- export type HasTransactionTrait<TTransaction> = {
14
- txTrait: TransactionTrait<TTransaction>;
15
- };
16
- /**
17
- * The transaction traits a wallet can read pending transactions with, keyed by the protocol version range each one
18
- * serves.
19
- *
20
- * @remarks
21
- * A transaction's bytes, identifiers and TTL are only meaningful under the ledger version it was authored against, so
22
- * which trait applies is a property of the transaction rather than of the wallet holding it. Keeping that in the
23
- * shared {@link ProtocolVersion.Registry} means the boundary between two traits is the same boundary variant selection
24
- * and codec selection use.
25
- */
26
- export type VersionedTransactionTrait<TTransaction> = ProtocolVersion.Registry<TransactionTrait<TTransaction>>;
27
- export type HasVersionedTransactionTrait<TTransaction> = {
28
- txTraits: VersionedTransactionTrait<TTransaction>;
29
- };
30
- /** Registers one trait for every protocol version: the shape a wallet that speaks a single ledger version has. */
31
- export declare const singleTrait: <TTransaction>(trait: TransactionTrait<TTransaction>) => VersionedTransactionTrait<TTransaction>;
32
- /** The oldest registered trait: what an envelope that carries no version stamp is read with. */
33
- export declare const headTrait: <TTransaction>(traits: VersionedTransactionTrait<TTransaction>) => Option.Option<TransactionTrait<TTransaction>>;
34
- /**
35
- * The trait registered for a protocol version, or the oldest trait when nothing says which version applies.
36
- *
37
- * @remarks
38
- * Falling back to the oldest trait is the same convention snapshot restore uses for an envelope written before versions
39
- * were recorded: the only envelopes without a stamp are ones written before stamping existed, and those necessarily
40
- * predate every version boundary since.
41
- * @param traits The registered traits.
42
- * @param protocolVersion The version the transaction was authored for, when one is known.
43
- * @returns The trait to read with, or `Option.none()` when the version falls outside every registered range.
44
- */
45
- export declare const traitForVersion: <TTransaction>(traits: VersionedTransactionTrait<TTransaction>, protocolVersion: Option.Option<ProtocolVersion.ProtocolVersion>) => Option.Option<TransactionTrait<TTransaction>>;
46
- /** The registered trait that recognises a transaction object as its own, if any does. */
47
- export declare const recognisingTrait: <TTransaction>(traits: VersionedTransactionTrait<TTransaction>, tx: unknown) => Option.Option<TransactionTrait<TTransaction>>;
48
- /**
49
- * The trait to read an incoming transaction with: the one that recognises it, or the oldest as a last resort.
50
- *
51
- * @param traits The registered traits.
52
- * @param tx The transaction to place.
53
- * @returns The trait that owns `tx`, the oldest trait when none claims it, or `Option.none()` when nothing is
54
- * registered at all.
55
- */
56
- export declare const traitForTx: <TTransaction>(traits: VersionedTransactionTrait<TTransaction>, tx: TTransaction) => Option.Option<TransactionTrait<TTransaction>>;
57
- export type FailedTransactionResult = Readonly<{
58
- segments: ReadonlyArray<{
59
- id: number;
60
- success: boolean;
61
- }>;
62
- status: 'PARTIAL_SUCCESS' | 'FAILURE';
63
- }>;
64
- export type SuccessTransactionResult = Readonly<{
65
- segments: ReadonlyArray<{
66
- id: number;
67
- success: boolean;
68
- }>;
69
- status: 'SUCCESS';
70
- }>;
71
- /**
72
- * The verdict on a transaction a protocol upgrade left behind.
73
- *
74
- * @remarks
75
- * Deliberately not one of the indexer's statuses: the chain never reported anything about this transaction and never
76
- * will, because bytes authored under the previous protocol version cannot be included under the new one. Saying so in
77
- * its own arm keeps "the node rejected this" and "this can no longer be submitted at all" distinguishable.
78
- */
79
- export type OrphanedByForkResult = Readonly<{
80
- status: 'ORPHANED_BY_FORK';
81
- /** The protocol version the transaction was authored for. */
82
- authoredFor: ProtocolVersion.ProtocolVersion;
83
- /** The protocol version the chain had reached when the wallet gave up on it. */
84
- chainNow: ProtocolVersion.ProtocolVersion;
85
- }>;
86
- export type TransactionResult = FailedTransactionResult | SuccessTransactionResult | OrphanedByForkResult;
87
- export type PendingItem<TTransaction> = Readonly<{
88
- tx: TTransaction;
89
- creationTime: DateTime.Utc;
90
- /**
91
- * The protocol version the transaction was authored for, when the wallet had observed one.
92
- *
93
- * @remarks
94
- * `Option.none()` means the wallet never learned what version it was authored against — either the envelope predates
95
- * stamping, or no wallet had reported a version yet. That is not evidence the transaction was left behind, so such
96
- * an item is read with the oldest trait but never orphaned.
97
- */
98
- protocolVersion: Option.Option<ProtocolVersion.ProtocolVersion>;
99
- }>;
100
- export type CheckedItem<TTransaction> = PendingItem<TTransaction> & {
101
- result: TransactionResult;
102
- };
103
- export type PendingTransactionsItem<TTransaction> = PendingItem<TTransaction> | CheckedItem<TTransaction>;
104
- export type FailedTransactionItem<TTransaction> = PendingTransactionsItem<TTransaction> & {
105
- result: FailedTransactionResult;
106
- };
107
- export type OrphanedTransactionItem<TTransaction> = PendingTransactionsItem<TTransaction> & {
108
- result: OrphanedByForkResult;
109
- };
110
- /** An item the wallet has given up on, whether the chain rejected it or a protocol upgrade stranded it. */
111
- export type RejectedTransactionItem<TTransaction> = PendingTransactionsItem<TTransaction> & {
112
- result: FailedTransactionResult | OrphanedByForkResult;
113
- };
114
- /**
115
- * A transaction that has been balanced but not yet proven or submitted.
116
- *
117
- * Balancing reserves the coins a transaction will spend, and until the transaction is submitted nothing else records
118
- * that those coins are spoken for — so a transaction abandoned in between strands them. A reservation is that missing
119
- * record. It never holds the transaction itself: an unproven transaction carries key material and must not be
120
- * persisted.
121
- *
122
- * `identifiers` is what ties a reservation to the transaction that later arrives, and it is stable: proving and binding
123
- * both leave a transaction's identifiers unchanged. `intentHashes` is kept alongside because it is the value the ledger
124
- * stamps on the coins the transaction creates.
125
- */
126
- export type Reservation = Readonly<{
127
- identifiers: readonly string[];
128
- intentHashes: readonly string[];
129
- /** Ids of the coins this transaction reserved, per wallet, so each wallet can release its own. */
130
- inputs: Readonly<{
131
- unshielded: readonly string[];
132
- }>;
133
- /** The transaction's TTL: from this instant the ledger rejects it, so the reservation cannot still be valid. */
134
- ttl: Date;
135
- createdAt: DateTime.Utc;
136
- expired: boolean;
137
- }>;
138
- export type PendingTransactions<TTransaction> = Readonly<{
139
- all: ReadonlyArray<PendingTransactionsItem<TTransaction>>;
140
- reservations: ReadonlyArray<Reservation>;
141
- }>;
142
- /**
143
- * Records a balanced transaction, replacing any earlier reservation for the same spend.
144
- *
145
- * @example
146
- * const held = addReservation(state, { identifiers: tx.identifiers(), inputs: { unshielded: ids }, ttl });
147
- *
148
- * @param state - The pending transactions to add to
149
- * @param reservation - The record of what the balanced transaction booked
150
- * @returns The state with that reservation held, and any it replaces gone
151
- */
152
- export declare const addReservation: <TTransaction>(state: PendingTransactions<TTransaction>, reservation: Reservation) => PendingTransactions<TTransaction>;
153
- /**
154
- * Forgets every reservation holding one of `identifiers`.
155
- *
156
- * @example
157
- * const cleared = clearReservation(state, [...tx.identifiers()]);
158
- *
159
- * @param state - The pending transactions to clear from
160
- * @param identifiers - Identifiers of the spend whose record is finished with
161
- * @returns The state with those reservations gone; identifiers no reservation holds are ignored
162
- */
163
- export declare const clearReservation: <TTransaction>(state: PendingTransactions<TTransaction>, identifiers: readonly string[]) => PendingTransactions<TTransaction>;
164
- /**
165
- * Marks every reservation whose TTL `now` has passed. Marked rather than removed, mirroring how a failed transaction is
166
- * kept until a caller has acted on it: the coins still have to be released before the record is dropped.
167
- *
168
- * Passed, not reached: the ledger accepts an intent while its TTL is at or after the block's timestamp, so a
169
- * transaction is still perfectly valid at the instant its TTL names.
170
- *
171
- * Returns the state it was given when nothing reaches its expiry. This runs on a timer, so most visits change nothing,
172
- * and handing back the same value is what lets a caller publish only when something actually moved.
173
- *
174
- * @example
175
- * const swept = expireReservations(state, DateTime.unsafeNow());
176
- *
177
- * @param state - The pending transactions to sweep
178
- * @param now - The instant to expire against
179
- * @returns The state with newly expired reservations marked, or the same state when none is
180
- */
181
- export declare const expireReservations: <TTransaction>(state: PendingTransactions<TTransaction>, now: DateTime.Utc) => PendingTransactions<TTransaction>;
182
- /**
183
- * The unshielded coin ids some spend still accounts for.
184
- *
185
- * Every reservation's inputs, plus the inputs of every transaction being tracked. Both halves are needed: a reservation
186
- * covers a transaction that was balanced and never submitted, and registering a transaction drops the reservation
187
- * standing in for it, so from submission onwards only the tracked transaction says the coins are spoken for.
188
- *
189
- * @example
190
- * const spokenFor = coveredUnshieldedIds(pending, (tx) => ownInputIdsOf(tx));
191
- *
192
- * @param state - The reservations and tracked transactions to read
193
- * @param unshieldedInputsOf - How to name the unshielded coins a tracked transaction spends
194
- * @returns Every such coin id, without repeats
195
- */
196
- export declare const coveredUnshieldedIds: <TTransaction>(state: PendingTransactions<TTransaction>, unshieldedInputsOf: (tx: TTransaction) => readonly string[]) => readonly string[];
197
- /**
198
- * The reservations whose transactions can no longer be accepted, and whose coins are therefore free.
199
- *
200
- * Expiry marks a reservation rather than removing it, so this is what a caller reads to find the records it still has
201
- * to act on before dropping them.
202
- *
203
- * @example
204
- * const finished = allExpiredReservations(state);
205
- *
206
- * @param state - The pending transactions to read
207
- * @returns The marked reservations, in the order they were added; empty when none has expired
208
- */
209
- export declare const allExpiredReservations: <TTransaction>(state: PendingTransactions<TTransaction>) => ReadonlyArray<Reservation>;
210
- export declare const has: <TTransaction>(transactions: PendingTransactions<TTransaction>, transaction: TTransaction, traits: VersionedTransactionTrait<TTransaction>) => boolean;
211
- export declare const all: <TTransaction>(transactions: PendingTransactions<TTransaction>) => readonly TTransaction[];
212
- export declare const allFailed: <TTransaction>(transactions: PendingTransactions<TTransaction>) => ReadonlyArray<FailedTransactionItem<TTransaction>>;
213
- /** Transactions a protocol upgrade stranded: they were authored for a version the chain has moved past. */
214
- export declare const allOrphaned: <TTransaction>(transactions: PendingTransactions<TTransaction>) => ReadonlyArray<OrphanedTransactionItem<TTransaction>>;
215
- /**
216
- * Everything the wallet has given up on, in the order it was added: reported failures and orphaned transactions alike.
217
- * Both need the same treatment — unbook the coins, record the rejection — so both belong on one list.
218
- */
219
- export declare const allRejected: <TTransaction>(transactions: PendingTransactions<TTransaction>) => ReadonlyArray<RejectedTransactionItem<TTransaction>>;
220
- export declare const allPending: <TTransaction>(state: PendingTransactions<TTransaction>) => readonly PendingItem<TTransaction>[];
221
- export declare const empty: <TTransaction>() => PendingTransactions<TTransaction>;
222
- /**
223
- * Records a transaction as pending, stamped with the protocol version it was authored for.
224
- *
225
- * @param state The pending transactions.
226
- * @param tx The transaction to record.
227
- * @param now The time it was authored.
228
- * @param traits The traits pending transactions are read with.
229
- * @param protocolVersion The version the chain had reached when it was authored, when the wallet knew one.
230
- * @returns The pending transactions including `tx`, with any superseded entry from the same version epoch replaced.
231
- */
232
- export declare const addPendingTransaction: <TTransaction>(state: PendingTransactions<TTransaction>, tx: TTransaction, now: DateTime.Utc, traits: VersionedTransactionTrait<TTransaction>, protocolVersion: Option.Option<ProtocolVersion.ProtocolVersion>) => PendingTransactions<TTransaction>;
233
- export declare const clear: <TTransaction>(state: PendingTransactions<TTransaction>, tx: TTransaction, traits: VersionedTransactionTrait<TTransaction>) => PendingTransactions<TTransaction>;
234
- export declare const saveResult: <TTransaction>(state: PendingTransactions<TTransaction>, tx: TTransaction, result: TransactionResult, traits: VersionedTransactionTrait<TTransaction>) => PendingTransactions<TTransaction>;
235
- /**
236
- * Gives up on every unresolved transaction whose version epoch the chain has moved past.
237
- *
238
- * @remarks
239
- * The epochs are the registry's own ranges, so "the chain has moved past" means exactly "a different trait answers for
240
- * the chain now than answered for this transaction". A transaction authored under the previous protocol version can
241
- * never be included afterwards, so waiting for its TTL only delays the inevitable and holds its coins hostage
242
- * meanwhile.
243
- * @param state The pending transactions.
244
- * @param traits The traits pending transactions are read with, whose ranges define the epochs.
245
- * @param chainNow The protocol version the wallets have reached.
246
- * @returns The pending transactions with the stranded ones given an {@link OrphanedByForkResult}.
247
- */
248
- export declare const orphanBeyond: <TTransaction>(state: PendingTransactions<TTransaction>, traits: VersionedTransactionTrait<TTransaction>, chainNow: ProtocolVersion.ProtocolVersion) => PendingTransactions<TTransaction>;
249
- /**
250
- * The stored shape. Reservations arrived after the format was already in the field, so they are an optional member of
251
- * the version that was already there rather than a version of their own: a reader that predates them sees the version
252
- * it knows and ignores the member it does not, which is what keeps a store written here readable by an older package.
253
- *
254
- * A snapshot that omits them records no reservations, which is the truth about what the writer knew.
255
- */
256
- type Serialized<TTransaction> = Readonly<{
257
- version: 'v1';
258
- transactions: readonly PendingItem<TTransaction>[];
259
- reservations: readonly Reservation[];
260
- }>;
261
- export declare const SerializedSchema: <TTransaction>(traits: VersionedTransactionTrait<TTransaction>) => Schema.Schema<Serialized<TTransaction>, any>;
262
- export declare const serialize: <TTransaction>(state: PendingTransactions<TTransaction>, traits: VersionedTransactionTrait<TTransaction>) => string;
263
- export declare const deserialize: <TTransaction>(serialized: string, traits: VersionedTransactionTrait<TTransaction>) => Either.Either<PendingTransactions<TTransaction>, ParseResult.ParseError>;
264
- export declare const toSerialized: <TTransaction>(pendingTransactions: PendingTransactions<TTransaction>) => Serialized<TTransaction>;
265
- export declare const fromSerialized: <TTransaction>(serialized: Serialized<TTransaction>) => PendingTransactions<TTransaction>;
266
- export {};
@@ -1,302 +0,0 @@
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
- import { ProtocolVersion } from '@midnightntwrk/wallet-sdk-abstractions';
16
- import { Buffer } from 'buffer';
17
- import { Array as Arr, DateTime, Either, Option, Order, ParseResult, pipe, Schema } from 'effect';
18
- /** Registers one trait for every protocol version: the shape a wallet that speaks a single ledger version has. */
19
- export const singleTrait = (trait) => ({
20
- entries: [
21
- {
22
- range: ProtocolVersion.makeRange(ProtocolVersion.MinSupportedVersion, ProtocolVersion.MaxSupportedVersion),
23
- value: trait,
24
- },
25
- ],
26
- });
27
- /** The oldest registered trait: what an envelope that carries no version stamp is read with. */
28
- export const headTrait = (traits) => Option.fromNullable(traits.entries.at(0)).pipe(Option.map((entry) => entry.value));
29
- /**
30
- * The trait registered for a protocol version, or the oldest trait when nothing says which version applies.
31
- *
32
- * @remarks
33
- * Falling back to the oldest trait is the same convention snapshot restore uses for an envelope written before versions
34
- * were recorded: the only envelopes without a stamp are ones written before stamping existed, and those necessarily
35
- * predate every version boundary since.
36
- * @param traits The registered traits.
37
- * @param protocolVersion The version the transaction was authored for, when one is known.
38
- * @returns The trait to read with, or `Option.none()` when the version falls outside every registered range.
39
- */
40
- export const traitForVersion = (traits, protocolVersion) => Option.match(protocolVersion, {
41
- onNone: () => headTrait(traits),
42
- onSome: (version) => ProtocolVersion.select(traits, version),
43
- });
44
- /** The registered trait that recognises a transaction object as its own, if any does. */
45
- export const recognisingTrait = (traits, tx) => Option.fromNullable(traits.entries.find((entry) => entry.value.isTx(tx))).pipe(Option.map((entry) => entry.value));
46
- /**
47
- * The trait to read an incoming transaction with: the one that recognises it, or the oldest as a last resort.
48
- *
49
- * @param traits The registered traits.
50
- * @param tx The transaction to place.
51
- * @returns The trait that owns `tx`, the oldest trait when none claims it, or `Option.none()` when nothing is
52
- * registered at all.
53
- */
54
- export const traitForTx = (traits, tx) => Option.orElse(recognisingTrait(traits, tx), () => headTrait(traits));
55
- const traitOfItem = (traits, item) => traitForVersion(traits, item.protocolVersion);
56
- /** Two versions are in the same epoch when the registry answers them with the same trait. */
57
- const sameEpoch = (a, b) => Option.getEquivalence((left, right) => left === right)(a, b);
58
- const idsOf = (traits, tx) => traitForTx(traits, tx).pipe(Option.map((trait) => trait.ids(tx)), Option.getOrElse(() => []));
59
- /** A stored item's identifiers, read with the trait registered for the version it was stamped with. */
60
- const idsOfItem = (traits, item) => traitOfItem(traits, item).pipe(Option.map((trait) => trait.ids(item.tx)), Option.getOrElse(() => []));
61
- /** Whether a stored item is covered by the identifiers of an incoming transaction, each read with its own trait. */
62
- const isCoveredBy = (traits, item, txIds) => traitOfItem(traits, item).pipe(Option.map((trait) => trait.areAllTxIdsIncluded(item.tx, txIds)), Option.getOrElse(() => false));
63
- /** Two reservations, or a reservation and a transaction, are the same spend if they share any identifier. */
64
- const sharesIdentifier = (reservation, identifiers) => reservation.identifiers.some((id) => identifiers.includes(id));
65
- /**
66
- * Records a balanced transaction, replacing any earlier reservation for the same spend.
67
- *
68
- * @example
69
- * const held = addReservation(state, { identifiers: tx.identifiers(), inputs: { unshielded: ids }, ttl });
70
- *
71
- * @param state - The pending transactions to add to
72
- * @param reservation - The record of what the balanced transaction booked
73
- * @returns The state with that reservation held, and any it replaces gone
74
- */
75
- export const addReservation = (state, reservation) => ({
76
- ...state,
77
- reservations: Arr.append(Arr.filter(state.reservations, (existing) => !sharesIdentifier(existing, reservation.identifiers)), reservation),
78
- });
79
- /**
80
- * Forgets every reservation holding one of `identifiers`.
81
- *
82
- * @example
83
- * const cleared = clearReservation(state, [...tx.identifiers()]);
84
- *
85
- * @param state - The pending transactions to clear from
86
- * @param identifiers - Identifiers of the spend whose record is finished with
87
- * @returns The state with those reservations gone; identifiers no reservation holds are ignored
88
- */
89
- export const clearReservation = (state, identifiers) => ({
90
- ...state,
91
- reservations: Arr.filter(state.reservations, (reservation) => !sharesIdentifier(reservation, identifiers)),
92
- });
93
- /**
94
- * Marks every reservation whose TTL `now` has passed. Marked rather than removed, mirroring how a failed transaction is
95
- * kept until a caller has acted on it: the coins still have to be released before the record is dropped.
96
- *
97
- * Passed, not reached: the ledger accepts an intent while its TTL is at or after the block's timestamp, so a
98
- * transaction is still perfectly valid at the instant its TTL names.
99
- *
100
- * Returns the state it was given when nothing reaches its expiry. This runs on a timer, so most visits change nothing,
101
- * and handing back the same value is what lets a caller publish only when something actually moved.
102
- *
103
- * @example
104
- * const swept = expireReservations(state, DateTime.unsafeNow());
105
- *
106
- * @param state - The pending transactions to sweep
107
- * @param now - The instant to expire against
108
- * @returns The state with newly expired reservations marked, or the same state when none is
109
- */
110
- export const expireReservations = (state, now) => {
111
- const hasExpiry = (reservation) => !reservation.expired && reservation.ttl.getTime() < DateTime.toEpochMillis(now);
112
- return Arr.some(state.reservations, hasExpiry)
113
- ? {
114
- ...state,
115
- reservations: Arr.map(state.reservations, (reservation) => hasExpiry(reservation) ? { ...reservation, expired: true } : reservation),
116
- }
117
- : state;
118
- };
119
- /**
120
- * The unshielded coin ids some spend still accounts for.
121
- *
122
- * Every reservation's inputs, plus the inputs of every transaction being tracked. Both halves are needed: a reservation
123
- * covers a transaction that was balanced and never submitted, and registering a transaction drops the reservation
124
- * standing in for it, so from submission onwards only the tracked transaction says the coins are spoken for.
125
- *
126
- * @example
127
- * const spokenFor = coveredUnshieldedIds(pending, (tx) => ownInputIdsOf(tx));
128
- *
129
- * @param state - The reservations and tracked transactions to read
130
- * @param unshieldedInputsOf - How to name the unshielded coins a tracked transaction spends
131
- * @returns Every such coin id, without repeats
132
- */
133
- export const coveredUnshieldedIds = (state, unshieldedInputsOf) => pipe(Arr.appendAll(Arr.flatMap(state.reservations, (reservation) => reservation.inputs.unshielded), Arr.flatMap(state.all, (item) => unshieldedInputsOf(item.tx))), Arr.dedupe);
134
- /**
135
- * The reservations whose transactions can no longer be accepted, and whose coins are therefore free.
136
- *
137
- * Expiry marks a reservation rather than removing it, so this is what a caller reads to find the records it still has
138
- * to act on before dropping them.
139
- *
140
- * @example
141
- * const finished = allExpiredReservations(state);
142
- *
143
- * @param state - The pending transactions to read
144
- * @returns The marked reservations, in the order they were added; empty when none has expired
145
- */
146
- export const allExpiredReservations = (state) => Arr.filter(state.reservations, (reservation) => reservation.expired);
147
- export const has = (transactions, transaction, traits) => traitForTx(traits, transaction).pipe(Option.map((trait) => transactions.all.some((item) => trait.areAllTxIdsIncluded(transaction, idsOfItem(traits, item)))), Option.getOrElse(() => false));
148
- export const all = (transactions) => {
149
- return transactions.all.map((item) => item.tx);
150
- };
151
- const resultOf = (item) => 'result' in item ? Option.fromNullable(item.result) : Option.none();
152
- export const allFailed = (transactions) => {
153
- return transactions.all.filter((item) => 'result' in item && (item.result?.status === 'FAILURE' || item.result?.status === 'PARTIAL_SUCCESS'));
154
- };
155
- /** Transactions a protocol upgrade stranded: they were authored for a version the chain has moved past. */
156
- export const allOrphaned = (transactions) => {
157
- return transactions.all.filter((item) => 'result' in item && item.result?.status === 'ORPHANED_BY_FORK');
158
- };
159
- /**
160
- * Everything the wallet has given up on, in the order it was added: reported failures and orphaned transactions alike.
161
- * Both need the same treatment — unbook the coins, record the rejection — so both belong on one list.
162
- */
163
- export const allRejected = (transactions) => {
164
- return transactions.all.filter((item) => 'result' in item &&
165
- (item.result?.status === 'FAILURE' ||
166
- item.result?.status === 'PARTIAL_SUCCESS' ||
167
- item.result?.status === 'ORPHANED_BY_FORK'));
168
- };
169
- export const allPending = (state) => {
170
- return state.all.filter((item) => !('result' in item) || item.result === undefined);
171
- };
172
- export const empty = () => {
173
- return {
174
- all: [],
175
- reservations: [],
176
- };
177
- };
178
- /**
179
- * Records a transaction as pending, stamped with the protocol version it was authored for.
180
- *
181
- * @param state The pending transactions.
182
- * @param tx The transaction to record.
183
- * @param now The time it was authored.
184
- * @param traits The traits pending transactions are read with.
185
- * @param protocolVersion The version the chain had reached when it was authored, when the wallet knew one.
186
- * @returns The pending transactions including `tx`, with any superseded entry from the same version epoch replaced.
187
- */
188
- export const addPendingTransaction = (state, tx, now, traits, protocolVersion) => {
189
- const trait = traitForVersion(traits, protocolVersion);
190
- const item = { tx, creationTime: now, protocolVersion };
191
- // Whether one transaction supersedes another is a question only a single ledger version can answer — across a
192
- // version boundary the two were authored against different rules, so they are simply different transactions.
193
- const [rest, foundMatching] = pipe(state.all, Arr.partition((existing) => sameEpoch(traitOfItem(traits, existing), trait) &&
194
- Option.match(trait, {
195
- onNone: () => false,
196
- onSome: (found) => found.isOneIncludedInOther(tx, existing.tx),
197
- })));
198
- const idCount = (candidate) => Option.match(trait, { onNone: () => 0, onSome: (found) => found.ids(candidate.tx).length });
199
- const theBiggestMatchingTx = Arr.max(Arr.append(foundMatching, item), pipe(Order.number, Order.mapInput(idCount)));
200
- return {
201
- ...state,
202
- all: Arr.append(rest, theBiggestMatchingTx),
203
- // The transaction now stands for the spend its reservation was holding open, and carries the same identifiers.
204
- reservations: Arr.filter(state.reservations, (reservation) => !sharesIdentifier(reservation, idsOf(traits, tx))),
205
- };
206
- };
207
- export const clear = (state, tx, traits) => {
208
- const txIds = idsOf(traits, tx);
209
- return {
210
- ...state,
211
- all: Arr.filter(state.all, (item) => !isCoveredBy(traits, item, txIds)),
212
- // Whatever stopped tracking the transaction — a revert, or a spend that confirmed — also ends the reservation.
213
- reservations: Arr.filter(state.reservations, (reservation) => !sharesIdentifier(reservation, txIds)),
214
- };
215
- };
216
- export const saveResult = (state, tx, result, traits) => {
217
- const txIds = idsOf(traits, tx);
218
- return {
219
- ...state,
220
- all: Arr.map(state.all, (item) => (isCoveredBy(traits, item, txIds) ? { ...item, result } : item)),
221
- };
222
- };
223
- /**
224
- * Gives up on every unresolved transaction whose version epoch the chain has moved past.
225
- *
226
- * @remarks
227
- * The epochs are the registry's own ranges, so "the chain has moved past" means exactly "a different trait answers for
228
- * the chain now than answered for this transaction". A transaction authored under the previous protocol version can
229
- * never be included afterwards, so waiting for its TTL only delays the inevitable and holds its coins hostage
230
- * meanwhile.
231
- * @param state The pending transactions.
232
- * @param traits The traits pending transactions are read with, whose ranges define the epochs.
233
- * @param chainNow The protocol version the wallets have reached.
234
- * @returns The pending transactions with the stranded ones given an {@link OrphanedByForkResult}.
235
- */
236
- export const orphanBeyond = (state, traits, chainNow) => ({
237
- ...state,
238
- all: Arr.map(state.all, (item) => Option.isSome(resultOf(item))
239
- ? item
240
- : Option.match(item.protocolVersion, {
241
- onNone: () => item,
242
- onSome: (authoredFor) => hasEpochEnded(traits, authoredFor, chainNow)
243
- ? { ...item, result: { status: 'ORPHANED_BY_FORK', authoredFor, chainNow } }
244
- : item,
245
- })),
246
- });
247
- const hasEpochEnded = (traits, authoredFor, chainNow) => ProtocolVersion.selectEntry(traits, authoredFor).pipe(Option.map((entry) => chainNow >= entry.range[1]), Option.getOrElse(() => false));
248
- const ReservationSchema = Schema.Struct({
249
- identifiers: Schema.Array(Schema.String),
250
- intentHashes: Schema.Array(Schema.String),
251
- inputs: Schema.Struct({ unshielded: Schema.Array(Schema.String) }),
252
- ttl: Schema.Date,
253
- createdAt: Schema.DateTimeUtc,
254
- expired: Schema.Boolean,
255
- });
256
- const WireItemSchema = Schema.Struct({
257
- tx: Schema.String,
258
- creationTime: Schema.DateTimeUtc,
259
- // Additive: envelopes written before transactions were stamped simply omit it, and decode to `Option.none()`.
260
- protocolVersion: Schema.optionalWith(ProtocolVersion.ProtocolVersionSchema, { as: 'Option' }),
261
- });
262
- const PendingItemSchema = (traits) => {
263
- const TxSchema = Schema.declare((tx) => Option.isSome(recognisingTrait(traits, tx)));
264
- const DomainSchema = Schema.typeSchema(Schema.Struct({
265
- tx: TxSchema,
266
- creationTime: Schema.DateTimeUtc,
267
- protocolVersion: Schema.OptionFromSelf(ProtocolVersion.ProtocolVersionSchema),
268
- }));
269
- return Schema.asSchema(Schema.transformOrFail(WireItemSchema, DomainSchema, {
270
- strict: true,
271
- decode: (wire, _options, ast) => pipe(traitForVersion(traits, wire.protocolVersion), Either.fromOption(() => new ParseResult.Type(ast, wire, `No transaction trait is registered for protocol version ${Option.getOrElse(wire.protocolVersion, () => 'unknown')}.`)), Either.flatMap((trait) => Either.try({
272
- try: () => trait.deserialize(Buffer.from(wire.tx, 'hex')),
273
- catch: (cause) => new ParseResult.Type(ast, wire, `Could not read the pending transaction: ${String(cause)}`),
274
- })), Either.map((tx) => ({ tx, creationTime: wire.creationTime, protocolVersion: wire.protocolVersion }))),
275
- encode: (item, _options, ast) => pipe(traitForTx(traits, item.tx), Either.fromOption(() => new ParseResult.Type(ast, item, 'No transaction trait is registered.')), Either.flatMap((trait) => Either.try({
276
- try: () => Buffer.from(trait.serialize(item.tx)).toString('hex'),
277
- catch: (cause) => new ParseResult.Type(ast, item, `Could not write the pending transaction: ${String(cause)}`),
278
- })), Either.map((tx) => ({ tx, creationTime: item.creationTime, protocolVersion: item.protocolVersion }))),
279
- }));
280
- };
281
- export const SerializedSchema = (traits) => Schema.Struct({
282
- version: Schema.Literal('v1'),
283
- transactions: Schema.Array(PendingItemSchema(traits)),
284
- reservations: Schema.optionalWith(Schema.Array(ReservationSchema), { default: () => [] }),
285
- });
286
- export const serialize = (state, traits) => pipe(state, toSerialized, Schema.encodeSync(SerializedSchema(traits)), JSON.stringify);
287
- export const deserialize = (serialized, traits) => {
288
- return pipe(serialized, Schema.decodeUnknownEither(Schema.parseJson(SerializedSchema(traits))), Either.map((data) => fromSerialized(data)));
289
- };
290
- export const toSerialized = (pendingTransactions) => {
291
- return {
292
- version: 'v1',
293
- transactions: pendingTransactions.all,
294
- reservations: pendingTransactions.reservations,
295
- };
296
- };
297
- export const fromSerialized = (serialized) => {
298
- return {
299
- all: serialized.transactions,
300
- reservations: serialized.reservations,
301
- };
302
- };