@signerreach/reserve 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -67,9 +67,10 @@ administrative access. For authorization and signer-availability analysis, use S
67
67
  Neither tool guarantees that a transaction will succeed when eventually submitted. Account
68
68
  state and network conditions can change after a check.
69
69
 
70
- The model is narrow. It has been compared against Testnet observations, it differs from the
71
- network in two documented ways, and some of its rules rest on the stellar-core source alone.
72
- It does not claim to reproduce the network's behaviour in general. Details are in
70
+ The model is narrow. It has been compared against Testnet observations, some of its rules
71
+ rest on the stellar-core source alone, and the two differences from the network that the
72
+ first Testnet runs found were changed in 0.1.1 and **have not been run on Testnet since**. It
73
+ does not claim to reproduce the network's behaviour in general. Details are in
73
74
  [Evidence](#evidence-and-how-much-to-trust-it) and
74
75
  [Known differences](#known-differences-from-the-network).
75
76
 
@@ -91,7 +92,7 @@ related but different responsibilities:
91
92
  | Language | Rust (a command-line tool) | TypeScript (a library) |
92
93
  | Evidence | Its own Testnet and Mainnet records | Agreement with SignerReach's published binary, plus its own Testnet records |
93
94
 
94
- They share rules R10 to R14 of
95
+ They share rules R10 to R15 of
95
96
  [SignerReach's specification](https://github.com/signerreach/signerreach/blob/main/docs/SPEC.md).
96
97
  A change to one of those rules is made there first (see [CONTRIBUTING.md](CONTRIBUTING.md)).
97
98
 
@@ -120,12 +121,17 @@ flowchart LR
120
121
  each transaction in turn:
121
122
 
122
123
  1. If the fee is below 100 stroops for each operation, it returns `unknown` and stops.
123
- 2. If `available` is less than the fee bid, it returns `rejected` and charges nothing.
124
- 3. Otherwise it charges the fee, then applies the operations in order on a working copy. An
124
+ 2. If `available` is less than the whole fee bid, it returns `rejected` and charges nothing.
125
+ 3. If an operation names the account's own key, it returns `rejected` and charges nothing:
126
+ the network refuses it at submission.
127
+ 4. Otherwise it charges the fee, then applies the operations in order on a working copy. An
125
128
  operation that cannot be applied makes the whole transaction `failed`: the fee stays
126
129
  charged and none of its operations take effect. If every operation applies, the
127
130
  transaction is `accepted` and its changes are kept.
128
- 4. The next transaction sees the balance and sub-entries the previous one left.
131
+ 5. The network may charge less than the bid, down to 100 stroops for each operation, so steps
132
+ 2 to 4 are worked out twice, once with the whole bid charged and once with only 100 for
133
+ each operation charged. If the two differ, the result is `unknown` and evaluation stops.
134
+ 6. The next transaction sees the balance and sub-entries the previous one left.
129
135
 
130
136
  **Inputs are validated** and refused with an `InputError` if Stellar could not hold them:
131
137
  negative amounts, liabilities above the balance, more than 1000 sub-entries or 20 signers, a
@@ -137,8 +143,8 @@ transaction, a fee outside 1 to 4294967295, or an amount that is not a `bigint`.
137
143
  | Layer | What it checks | Where |
138
144
  |---|---|---|
139
145
  | Rule tests | The rules, at their boundaries, with numbers worked out from the specification | `test/rules.test.ts` |
140
- | Agreement vectors | That the library agrees with SignerReach's published binary, on 621 generated cases | `vectors/`, `test/vectors.test.ts` |
141
- | Bug injection | That the tests would notice a wrong rule: 23 deliberate bugs, all caught | `scripts/mutation-check.mjs` |
146
+ | Agreement vectors | That the library agrees with SignerReach's published binary, on 637 cases | `vectors/`, `test/vectors.test.ts` |
147
+ | Bug injection | That the tests would notice a wrong rule: 33 deliberate bugs, all caught | `scripts/mutation-check.mjs` |
142
148
  | Testnet tool | That predictions match what the network does, with each prediction written before the plan is submitted | `tools/testnet/`, `docs/evidence/` |
143
149
  | Package check | That the packed package installs and works: it is unpacked into a scratch project, used from JavaScript and type-checked from TypeScript (including a call that must be refused), and it fails if source, tests or anything unreviewed would be published | `scripts/pack-check.mjs` |
144
150
  | CI | The rule tests and agreement vectors on Node 22 and 24, the bug injection, the vectors regenerated from the published Linux binary, the package check on Node 22 and 24, and the Testnet tool's unit tests and dry run. The Testnet runs themselves are not run in CI | `.github/workflows/ci.yml` |
@@ -156,10 +162,11 @@ It has no dependencies. It is written in TypeScript and shipped compiled, with i
156
162
  declarations, as an ES module (`"type": "module"`), and it needs Node 22 or newer. From
157
163
  CommonJS, load it with `await import("@signerreach/reserve")`.
158
164
 
159
- It is a `0.x` release: the API may change between releases. The two differences from the
160
- network described under [Known differences](#known-differences-from-the-network) are **not
161
- fixed in 0.1.0**. Read them, and [Scope and limitations](#scope-and-limitations), before
162
- relying on it.
165
+ It is a `0.x` release: the API may change between releases. Version 0.1.1 changes two
166
+ results of 0.1.0 (see [Known differences](#known-differences-from-the-network)): an own-key
167
+ transaction is now `rejected` and not `failed`, and a transaction whose outcome depends on the
168
+ fee the network charges is now `unknown`. Read that section, and
169
+ [Scope and limitations](#scope-and-limitations), before relying on it.
163
170
 
164
171
  ## Usage
165
172
 
@@ -193,6 +200,19 @@ const short = checkPlan({ ...account, balance: 20_000_099n }, [
193
200
  short.transactions[0]; // { outcome: "failed", reason: "low_reserve", shortfall: 1n, feeCharged: 100n, ... }
194
201
  ```
195
202
 
203
+ A bid above 100 stroops for each operation can leave the answer open. Here the account can pay
204
+ a bid of 1000 for adding a signer only if the network charges less than the whole bid:
205
+
206
+ ```ts
207
+ const open = checkPlan({ ...account, balance: 20_000_500n }, [
208
+ { id: "add-c", fee: 1000n, operations: [{ key: "GC...C", weight: 1 }] },
209
+ ]);
210
+ open.transactions[0]; // { outcome: "unknown", reason: "fee_charge_changes_outcome",
211
+ // atLowestCharge: { outcome: "accepted" },
212
+ // atWholeBid: { outcome: "failed", reason: "low_reserve", operationIndex: 0 }, ... }
213
+ open.complete; // false
214
+ ```
215
+
196
216
  (`examples/basic.ts` is this program, importing from the source tree instead of the package;
197
217
  run it from a clone with `node examples/basic.ts`.)
198
218
 
@@ -201,13 +221,17 @@ where an amount is expected is refused.
201
221
 
202
222
  ## The rules, and how fees are modelled
203
223
 
204
- These are rules R10 to R14 of the
224
+ These are rules R10 to R15 of the
205
225
  [SignerReach specification](https://github.com/signerreach/signerreach/blob/main/docs/SPEC.md):
206
226
 
207
227
  - `minimumBalance = (2 + subentries + sponsoring - sponsored) * baseReserve`
208
228
  - `available = balance - minimumBalance - sellingLiabilities` (it can be negative)
209
- - **Fee first (R13):** if `available` is less than the fee bid, the transaction is `rejected`
210
- (`tx_insufficient_balance`). Nothing is charged and nothing changes.
229
+ - **Fee first (R13):** if `available` is less than the whole fee bid, the transaction is
230
+ `rejected` (`tx_insufficient_balance`). Nothing is charged and nothing changes.
231
+ - **The account's own key (R15):** an operation that names it as a signer, to add, re-weight or
232
+ remove it, is refused when the network validates the operation, at submission. It never
233
+ enters a ledger, so no fee is charged. The result is `rejected` with the reason
234
+ `own_key_as_signer`. This is checked after the fee has been found affordable.
211
235
  - **Failed transactions keep the fee (R12):** if it passes that check and then fails in an
212
236
  operation, it is `failed`: the fee is charged and no operation takes effect.
213
237
  - **Adding a signer (R11)** needs `available >= baseReserve`, checked after the 20-signer limit
@@ -217,23 +241,26 @@ These are rules R10 to R14 of the
217
241
  - **In order (R14):** operations apply one after another, so `[remove C, add D]` can fit where
218
242
  `[add D, remove C]` does not.
219
243
 
220
- **Fee bid and fee charged are different things.** A transaction states a fee *bid*. The model
221
- does two things with it:
222
-
223
- - *The check that the account can pay* is made against the **bid**. The Testnet runs observed
224
- this: a bid of 101 stroops with 100 available was rejected, and a bid of 1000 stroops was
225
- rejected with 999 available and accepted with exactly 1000.
226
- - *The amount charged* is modelled as the **bid**, which is **not** what the network did. In
227
- the three accepted cases whose bid was above the minimum (bids of 101 and 1000), the network
228
- charged 100 stroops, which is 100 for each operation, not the bid. The library therefore
229
- predicts a lower remaining balance than the network produced, by up to 900 stroops in those
230
- cases.
231
-
232
- In the cases observed this difference is conservative: the library predicted less balance than
233
- the account had, never more. **Surge pricing was not tested.** Under surge the network could
234
- charge more than 100 stroops for each operation, and whether the difference stays
235
- conservative then has not been checked. With no explicit fee, the model assumes 100 stroops for
236
- each operation, which matched what the network charged in every such case on Testnet.
244
+ **Fee bid and fee charged are different things (R13).** A transaction states a fee *bid*. The
245
+ model does two things with it:
246
+
247
+ - *The check that the account can pay* is made against the whole **bid**. The Testnet runs
248
+ observed this: a bid of 101 stroops with 100 available was rejected, and a bid of 1000
249
+ stroops was rejected with 999 available and accepted with exactly 1000.
250
+ - *The amount charged* is somewhere from **100 stroops for each operation up to the whole
251
+ bid**. In stellar-core the charge is the lower of the bid and the effective fee for each
252
+ operation, and the effective fee starts at the ledger's base fee and is raised only by surge
253
+ pricing. In the three accepted cases on Testnet whose bid was above the minimum (bids of 101
254
+ and 1000), the network charged 100 stroops for each operation. **Surge pricing was never
255
+ observed**, so no charge above 100 for each operation has been seen.
256
+
257
+ So each transaction is worked out twice, with the whole bid charged and with only 100 for each
258
+ operation charged, each against the balance that charge leaves. If both give the same outcome,
259
+ that is the result. If they differ, the result is `unknown` (`fee_charge_changes_outcome`),
260
+ evaluation stops, and the result says what each end gives. A plan is `allAccepted` only if it
261
+ works at every charge from the lowest to the whole bid. The balances in the result assume the
262
+ whole bid is charged. With no explicit fee, or a fee of exactly 100 for each operation, there
263
+ is one charge and nothing changes.
237
264
 
238
265
  A fee bid of less than 100 stroops for each operation gives `unknown`: the network's minimum
239
266
  fee is a setting that can change, so the library does not claim to know, and evaluation stops
@@ -267,12 +294,15 @@ Not every rule has the same level of evidence. This table says which is which.
267
294
  | The 1000th sub-entry is allowed; selling liabilities reduce the available balance by their amount; sponsorship moves the minimum by one reserve each way | **Observed on Testnet**, one exact-and-one-short pair of cases for each of the first two, and two pairs for sponsorship, one for each direction ([tier 3](docs/evidence/testnet-2026-11-28-tier3/README.md)) |
268
295
  | Which of the 20-signer limit and the 1000-sub-entry limit is checked first | **Source inspection only.** Not tested on any network |
269
296
  | Base reserves other than 5,000,000 stroops; sponsorship of more than one entry or of entries other than data entries | **Source inspection only.** Not tested on any network |
270
- | An explicit fee bid is the amount charged | **Contradicted by Testnet**: three cases, the same three in both runs (see below) |
271
- | The account's own key as a signer fails in a ledger and keeps the fee | **Contradicted by Testnet**: two cases (adding and removing the key), the same two in both runs (see below) |
297
+ | The charge is anywhere from 100 stroops for each operation to the whole bid (R13) | **Observed on Testnet only at the low end**: the network charged 100 for each operation in three cases (bids of 101 and 1000), the same in both runs. The upper end and everything between come from the stellar-core source. **Not observed:** a surge-priced ledger. Not re-run since 0.1.1 |
298
+ | The account's own key as a signer is refused at submission and costs nothing (R15) | **Observed on Testnet**: two cases (adding and removing the key), the same two in both runs, which showed that 0.1.0 predicted the opposite. 0.1.1 was changed to match, so those two runs are no longer an independent check of the new prediction. Not re-run since 0.1.1. The order of this check against the fee check is from the source only |
272
299
 
273
300
  SignerReach's specification still lists some of the tier-3 rules as source-only; it has not
274
301
  yet been updated to reflect these records.
275
302
 
303
+ The Testnet runs below were made with the predictions of 0.1.0. The 0.1.1 predictions for the
304
+ two differences were written after seeing those results.
305
+
276
306
  **What the library's own Testnet runs showed.** Two runs of 31 cases each on 2026-11-27 at
277
307
  protocol 30: **25 matched, 5 differed, 1 was an observation only, none unusable, the same in
278
308
  both.** One pass of 10 tier-3 cases on 2026-11-28: **9 matched, none differed, 1 unusable**; the
@@ -282,39 +312,49 @@ the account's balance also confirmed the fee of every transaction; run 1 did not
282
312
  These are repetitions on one network state with no surge pricing, not confirmation across
283
313
  conditions.
284
314
 
285
- **What agreement with SignerReach means.** `vectors/oracle.json` holds 621 cases generated by
286
- running the **published v0.1.2 binary**, and the library agrees with it on every result, fee,
315
+ **What agreement with SignerReach means.** `vectors/oracle.json` holds 637 cases generated by
316
+ running the **published v0.1.3 binary**, and the library agrees with it on every result, fee,
287
317
  available balance and code. These are two implementations of the same rules by the same
288
318
  author. Agreement is a consistency check between them. **It is not independent verification
289
319
  against the network.**
290
320
 
291
- **What the bug injection means.** 23 deliberate bugs injected into the rules were all caught
292
- (`node scripts/mutation-check.mjs`). Bugs outside those 23 may not be.
321
+ **What the bug injection means.** 33 deliberate bugs injected into the rules were all caught
322
+ (`node scripts/mutation-check.mjs`). Bugs outside those 33 may not be.
293
323
 
294
- Known difference from the binary: for a fee below the minimum, the binary rejects the whole
324
+ Known differences from the binary: for a fee below the minimum, the binary rejects the whole
295
325
  input and evaluates nothing, while this library evaluates the earlier transactions and stops
296
- at that one. Shortfall amounts are checked by the hand-written tests only, because the binary
297
- reports them in message text and not as a field.
326
+ at that one. After an undecided transaction the binary lists the later ones as not evaluated;
327
+ the library returns only the ones it evaluated. Shortfall amounts are checked by the
328
+ hand-written tests only, because the binary reports them in message text and not as a field.
298
329
 
299
330
  ## Known differences from the network
300
331
 
301
- Found by the Testnet run of 2026-11-27, and the same in both runs. They are **not fixed**.
302
- They are wrong in the library and in SignerReach's specification alike. Under this project's
303
- contribution rule (see [CONTRIBUTING.md](CONTRIBUTING.md)), a rule changes in SignerReach's
304
- specification, code and release first, and only then here, so that the library keeps agreeing
305
- with the published binary.
306
-
307
- 1. **An explicit fee bid is treated as the amount charged.** The network checks the bid, as
308
- the library does, but charged 100 stroops for each operation and not the bid (three cases,
309
- bids of 101 and 1000). The balance the library predicts afterwards is up to 900 stroops too
310
- low in those cases. In the cases observed that is the conservative direction: a later
311
- transaction in the same plan could be predicted rejected when the network would accept it.
312
- Surge pricing was not tested. With no explicit fee the difference did not arise.
313
- 2. **The account's own key named as a signer is predicted to fail in a ledger and keep its
332
+ The Testnet runs of 2026-11-27 found two differences between 0.1.0 and the network, the same
333
+ in both runs. Under this project's contribution rule (see [CONTRIBUTING.md](CONTRIBUTING.md)),
334
+ a rule changes in SignerReach's specification, code and release first, and only then here, so
335
+ that the library keeps agreeing with the published binary. SignerReach v0.1.3 changed both
336
+ rules, and this library follows it from 0.1.1.
337
+
338
+ 1. **An explicit fee bid was treated as the amount charged.** The network checks the bid but
339
+ charged 100 stroops for each operation, not the bid (three cases, bids of 101 and 1000). 0.1.0
340
+ therefore predicted a balance up to 900 stroops too low afterwards. **0.1.1:** the charge is
341
+ a range from 100 for each operation to the whole bid, and a transaction whose outcome
342
+ differs across the range is `unknown`. **A result can change:** a plan that bids above the
343
+ minimum and works only if the network charges less than the bid was `failed` or `rejected`
344
+ in 0.1.0 and is now `unknown`. A plan that works at every charge is still accepted, and one
345
+ that fails even at the lowest charge is still not.
346
+ 2. **The account's own key named as a signer was predicted to fail in a ledger and keep its
314
347
  fee.** The network refused it at submission (`op_bad_signer`), with no ledger record after
315
- twelve lookups and an unchanged balance, so no fee was charged. This was the same for adding
316
- and for removing the key, in both runs. The verdict, unsafe, is the same. The balance
317
- afterwards is not.
348
+ twelve lookups and an unchanged balance, so no fee was charged, for adding and for removing
349
+ the key, in both runs. **0.1.1:** it is `rejected` with the reason `own_key_as_signer` and
350
+ no fee, so a later transaction sees the balance without a fee taken. The verdict is the same
351
+ as before; the balance afterwards is not.
352
+
353
+ **What is still not known.** Neither change has been run on Testnet since it was made. The
354
+ upper end of the fee range, and every charge between the two ends, rests on the stellar-core
355
+ source: no surge-priced ledger was observed. Whether the own-key check comes before or after
356
+ the fee check, and before or after the authorization of later operations, is also from the
357
+ source only; it changes which reason is reported, not whether the transaction is refused.
318
358
 
319
359
  ## Develop
320
360
 
@@ -323,7 +363,7 @@ Node 22.18 or newer (it runs TypeScript directly).
323
363
  ```
324
364
  npm ci
325
365
  npm run typecheck
326
- npm test # 26 rule tests + 621 agreement cases
366
+ npm test # 39 rule tests + 637 agreement cases
327
367
  npm run build
328
368
  npm run pack:check # packs it, installs it in a scratch project, uses it from JS and TS
329
369
  node scripts/mutation-check.mjs
@@ -341,5 +381,5 @@ Testnet and records whether the network agrees. Its records so far:
341
381
 
342
382
  ## Status and licence
343
383
 
344
- Experimental. Version `0.1.0`, published to npm as `@signerreach/reserve`. Unaudited.
384
+ Experimental. Version `0.1.1`, published to npm as `@signerreach/reserve`. Unaudited.
345
385
  Apache-2.0. Not affiliated with the Stellar Development Foundation.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { ASSUMED_FEE_PER_OPERATION, InputError, MAX_ADDITIONAL_SIGNERS, MAX_AMOUNT, MAX_FEE, MAX_WEIGHT, SUB_ENTRY_LIMIT, available, minimumBalance, validateAccount, } from "./account.ts";
2
2
  export { checkPlan } from "./plan.ts";
3
- export type { Account, AccountAfter, AcceptedResult, FailedResult, FailureReason, PlanResult, RejectedResult, SignerOperation, Stroops, Transaction, TransactionResult, UnknownResult, } from "./types.ts";
3
+ export type { Account, AccountAfter, AcceptedResult, ChargeOutcome, FailedResult, FailureReason, FeeBelowMinimumResult, FeeChargeResult, PlanResult, RejectedResult, RejectionReason, SignerOperation, Stroops, Transaction, TransactionResult, UnknownResult, } from "./types.ts";
package/dist/plan.d.ts CHANGED
@@ -3,9 +3,16 @@ import type { Account, PlanResult, Transaction } from "./types.ts";
3
3
  * Evaluates a plan of signer changes against an account's balance, one
4
4
  * transaction after another, in the order the network applies them.
5
5
  *
6
- * What it models (rules R10 to R14 of the SignerReach specification):
7
- * - R13: before a transaction is applied, `available >= fee` must hold, else it
8
- * is rejected and nothing is charged.
6
+ * What it models (rules R10 to R15 of the SignerReach specification, v0.1.3):
7
+ * - R13: before a transaction is applied, `available >= fee` must hold, where
8
+ * `fee` is the whole bid, else it is rejected and nothing is charged. The
9
+ * network then charges the lower of the bid and its effective fee, anywhere
10
+ * from 100 stroops for each operation to the whole bid, so each transaction is
11
+ * worked out at both ends. If they give the same outcome, that is the result;
12
+ * if not, the result is `unknown` (`fee_charge_changes_outcome`) and
13
+ * evaluation stops. Balances in the result assume the whole bid is charged.
14
+ * - R15: an operation that names the account's own key is refused at submission,
15
+ * after the fee is found affordable and before any fee is charged.
9
16
  * - R12: a transaction that passes and then fails in an operation is included in
10
17
  * a ledger and keeps its fee; none of its operations take effect.
11
18
  * - R11, R10: adding a new signer needs one base reserve of available balance;
@@ -14,7 +21,8 @@ import type { Account, PlanResult, Transaction } from "./types.ts";
14
21
  *
15
22
  * What it does not model: signatures and thresholds (it assumes the plan is
16
23
  * authorized), any operation other than a signer change, fee bumps,
17
- * preconditions, and sponsorship operations. The network's minimum fee is not
18
- * known to it: a fee below 100 stroops for each operation gives `unknown`.
24
+ * preconditions, sponsorship operations, and surge pricing (never observed). The
25
+ * network's minimum fee is not known to it: a fee below 100 stroops for each
26
+ * operation gives `unknown` (`fee_below_assumed_minimum`).
19
27
  */
20
28
  export declare function checkPlan(account: Account, transactions: readonly Transaction[]): PlanResult;
package/dist/plan.js CHANGED
@@ -23,9 +23,9 @@ function validateTransaction(tx, position) {
23
23
  }
24
24
  }
25
25
  }
26
- function snapshot(account, state) {
26
+ function snapshot(account, balance, state) {
27
27
  return {
28
- balance: state.balance,
28
+ balance,
29
29
  sellingLiabilities: account.sellingLiabilities,
30
30
  subentryCount: state.subentryCount,
31
31
  numSponsoring: account.numSponsoring,
@@ -35,11 +35,11 @@ function snapshot(account, state) {
35
35
  }
36
36
  /**
37
37
  * Applies one operation to `state` or says why it cannot be applied (R10, R11).
38
- * The caller discards `state` when this returns a reason.
38
+ * `balance` is the balance after the fee. The caller discards `state` when this
39
+ * returns a reason. The account's own key is not handled here: it is refused
40
+ * before the fee is charged (R15).
39
41
  */
40
- function applyOperation(account, state, op) {
41
- if (op.key === account.accountId)
42
- return { reason: "bad_signer", shortfall: 0n };
42
+ function applyOperation(account, balance, state, op) {
43
43
  const present = state.signers.has(op.key);
44
44
  if (op.weight === 0) {
45
45
  // R10: weight 0 removes a signer; for a key that is not a signer it changes nothing.
@@ -59,7 +59,7 @@ function applyOperation(account, state, op) {
59
59
  if (state.subentryCount >= SUB_ENTRY_LIMIT) {
60
60
  return { reason: "too_many_subentries", shortfall: 0n };
61
61
  }
62
- const room = available(snapshot(account, state));
62
+ const room = available(snapshot(account, balance, state));
63
63
  if (room < account.baseReserve) {
64
64
  return { reason: "low_reserve", shortfall: account.baseReserve - room };
65
65
  }
@@ -67,13 +67,57 @@ function applyOperation(account, state, op) {
67
67
  state.subentryCount += 1;
68
68
  return undefined;
69
69
  }
70
+ /**
71
+ * One transaction against `balance`, in the order the network does it
72
+ * (R13, R15, R12): the whole bid must be affordable; an own-key operation is
73
+ * refused with no fee; then `charged` is taken and the operations apply.
74
+ */
75
+ function attempt(account, balance, state, tx, bid, charged) {
76
+ const room = available(snapshot(account, balance, state));
77
+ if (room < bid)
78
+ return { kind: "unaffordable", shortfall: bid - room };
79
+ const own = tx.operations.findIndex((op) => op.key === account.accountId);
80
+ if (own !== -1)
81
+ return { kind: "own_key", operationIndex: own };
82
+ const afterFee = balance - charged;
83
+ const working = { subentryCount: state.subentryCount, signers: new Set(state.signers) };
84
+ for (const [operationIndex, op] of tx.operations.entries()) {
85
+ const problem = applyOperation(account, afterFee, working, op);
86
+ if (problem)
87
+ return { kind: "failed", ...problem, operationIndex };
88
+ }
89
+ return { kind: "accepted", after: working };
90
+ }
91
+ /** The part of an attempt that the two ends of the fee range are compared on. */
92
+ function outcomeOf(a) {
93
+ switch (a.kind) {
94
+ case "accepted":
95
+ return { outcome: "accepted" };
96
+ case "unaffordable":
97
+ return { outcome: "rejected", reason: "insufficient_balance" };
98
+ case "own_key":
99
+ return { outcome: "rejected", reason: "own_key_as_signer", operationIndex: a.operationIndex };
100
+ case "failed":
101
+ return { outcome: "failed", reason: a.reason, operationIndex: a.operationIndex };
102
+ }
103
+ }
104
+ function sameOutcome(a, b) {
105
+ return JSON.stringify(a) === JSON.stringify(b);
106
+ }
70
107
  /**
71
108
  * Evaluates a plan of signer changes against an account's balance, one
72
109
  * transaction after another, in the order the network applies them.
73
110
  *
74
- * What it models (rules R10 to R14 of the SignerReach specification):
75
- * - R13: before a transaction is applied, `available >= fee` must hold, else it
76
- * is rejected and nothing is charged.
111
+ * What it models (rules R10 to R15 of the SignerReach specification, v0.1.3):
112
+ * - R13: before a transaction is applied, `available >= fee` must hold, where
113
+ * `fee` is the whole bid, else it is rejected and nothing is charged. The
114
+ * network then charges the lower of the bid and its effective fee, anywhere
115
+ * from 100 stroops for each operation to the whole bid, so each transaction is
116
+ * worked out at both ends. If they give the same outcome, that is the result;
117
+ * if not, the result is `unknown` (`fee_charge_changes_outcome`) and
118
+ * evaluation stops. Balances in the result assume the whole bid is charged.
119
+ * - R15: an operation that names the account's own key is refused at submission,
120
+ * after the fee is found affordable and before any fee is charged.
77
121
  * - R12: a transaction that passes and then fails in an operation is included in
78
122
  * a ledger and keeps its fee; none of its operations take effect.
79
123
  * - R11, R10: adding a new signer needs one base reserve of available balance;
@@ -82,71 +126,101 @@ function applyOperation(account, state, op) {
82
126
  *
83
127
  * What it does not model: signatures and thresholds (it assumes the plan is
84
128
  * authorized), any operation other than a signer change, fee bumps,
85
- * preconditions, and sponsorship operations. The network's minimum fee is not
86
- * known to it: a fee below 100 stroops for each operation gives `unknown`.
129
+ * preconditions, sponsorship operations, and surge pricing (never observed). The
130
+ * network's minimum fee is not known to it: a fee below 100 stroops for each
131
+ * operation gives `unknown` (`fee_below_assumed_minimum`).
87
132
  */
88
133
  export function checkPlan(account, transactions) {
89
134
  validateAccount(account);
90
135
  transactions.forEach((tx, i) => validateTransaction(tx, i));
91
136
  const state = {
92
- balance: account.balance,
93
137
  subentryCount: account.subentryCount,
94
138
  signers: new Set(account.signers),
95
139
  };
140
+ // The balance is tracked twice: with the whole of each bid charged, and with
141
+ // only the lowest charge taken. They differ only when a bid is above the minimum.
142
+ let balanceAtBid = account.balance;
143
+ let balanceAtLowest = account.balance;
96
144
  const results = [];
97
145
  let complete = true;
98
146
  for (const [index, tx] of transactions.entries()) {
99
147
  const assumedMinimum = ASSUMED_FEE_PER_OPERATION * BigInt(tx.operations.length);
100
148
  const feeAssumed = tx.fee === undefined;
101
149
  const fee = tx.fee ?? assumedMinimum;
102
- const availableBefore = available(snapshot(account, state));
150
+ const availableBefore = available(snapshot(account, balanceAtBid, state));
103
151
  const base = { index, id: tx.id, fee, feeAssumed, availableBefore };
104
152
  if (fee < assumedMinimum) {
105
153
  results.push({ ...base, outcome: "unknown", reason: "fee_below_assumed_minimum", feeCharged: 0n });
106
154
  complete = false;
107
155
  break;
108
156
  }
109
- // R13: checked before the transaction is applied; nothing is charged on failure.
110
- if (availableBefore < fee) {
157
+ // R13: the network charges between the lowest charge and the whole bid.
158
+ const lowest = assumedMinimum;
159
+ const atBid = attempt(account, balanceAtBid, state, tx, fee, fee);
160
+ const atLowest = attempt(account, balanceAtLowest, state, tx, fee, lowest);
161
+ const bidOutcome = outcomeOf(atBid);
162
+ const lowestOutcome = outcomeOf(atLowest);
163
+ if (!sameOutcome(bidOutcome, lowestOutcome)) {
111
164
  results.push({
112
165
  ...base,
113
- outcome: "rejected",
114
- reason: "insufficient_balance",
166
+ outcome: "unknown",
167
+ reason: "fee_charge_changes_outcome",
115
168
  feeCharged: 0n,
116
- shortfall: fee - availableBefore,
169
+ atLowestCharge: lowestOutcome,
170
+ atWholeBid: bidOutcome,
117
171
  });
118
- continue;
172
+ complete = false;
173
+ break;
119
174
  }
120
- // The fee is charged first, so the operations see the balance after it (R13).
121
- state.balance -= fee;
122
- const working = {
123
- balance: state.balance,
124
- subentryCount: state.subentryCount,
125
- signers: new Set(state.signers),
126
- };
127
- let failure;
128
- for (const [operationIndex, op] of tx.operations.entries()) {
129
- const problem = applyOperation(account, working, op);
130
- if (problem) {
131
- failure = { ...problem, operationIndex };
175
+ switch (atBid.kind) {
176
+ case "unaffordable":
177
+ // Refused before it is applied; nothing is charged.
178
+ results.push({
179
+ ...base,
180
+ outcome: "rejected",
181
+ reason: "insufficient_balance",
182
+ feeCharged: 0n,
183
+ shortfall: atBid.shortfall,
184
+ });
185
+ break;
186
+ case "own_key":
187
+ // R15: refused at submission, so no fee is charged either.
188
+ results.push({
189
+ ...base,
190
+ outcome: "rejected",
191
+ reason: "own_key_as_signer",
192
+ feeCharged: 0n,
193
+ shortfall: 0n,
194
+ operationIndex: atBid.operationIndex,
195
+ });
196
+ break;
197
+ case "failed":
198
+ // R12: included in a ledger, keeps its fee, no operation takes effect.
199
+ balanceAtBid -= fee;
200
+ balanceAtLowest -= lowest;
201
+ results.push({
202
+ ...base,
203
+ outcome: "failed",
204
+ feeCharged: fee,
205
+ reason: atBid.reason,
206
+ shortfall: atBid.shortfall,
207
+ operationIndex: atBid.operationIndex,
208
+ });
209
+ break;
210
+ case "accepted":
211
+ balanceAtBid -= fee;
212
+ balanceAtLowest -= lowest;
213
+ state.subentryCount = atBid.after.subentryCount;
214
+ state.signers = atBid.after.signers;
215
+ results.push({ ...base, outcome: "accepted", feeCharged: fee });
132
216
  break;
133
- }
134
- }
135
- if (failure) {
136
- // R12: included in a ledger, keeps its fee, no operation takes effect.
137
- results.push({ ...base, outcome: "failed", feeCharged: fee, ...failure });
138
- }
139
- else {
140
- state.subentryCount = working.subentryCount;
141
- state.signers = working.signers;
142
- results.push({ ...base, outcome: "accepted", feeCharged: fee });
143
217
  }
144
218
  }
145
- const final = snapshot(account, state);
219
+ const final = snapshot(account, balanceAtBid, state);
146
220
  return {
147
221
  transactions: results,
148
222
  account: {
149
- balance: state.balance,
223
+ balance: balanceAtBid,
150
224
  subentryCount: state.subentryCount,
151
225
  signers: [...state.signers],
152
226
  minimumBalance: minimumBalance(final),
package/dist/types.d.ts CHANGED
@@ -37,14 +37,24 @@ export interface Transaction {
37
37
  readonly operations: readonly SignerOperation[];
38
38
  }
39
39
  /** Why an operation cannot be applied (the transaction then fails but keeps its fee). */
40
- export type FailureReason = "bad_signer" | "too_many_signers" | "too_many_subentries" | "low_reserve";
40
+ export type FailureReason = "too_many_signers" | "too_many_subentries" | "low_reserve";
41
+ /** Why a transaction is refused before it is applied, so that no fee is charged. */
42
+ export type RejectionReason = "insufficient_balance" | "own_key_as_signer";
41
43
  interface TransactionResultBase {
42
44
  readonly index: number;
43
45
  readonly id: string | undefined;
44
- /** The fee that was used: the given one, or the assumed one. */
46
+ /**
47
+ * The fee that was used: the given one, or the assumed one. This is the whole
48
+ * bid. The network checks the whole bid against the available balance but may
49
+ * charge less, down to 100 stroops for each operation (R13); every balance in
50
+ * the result assumes the whole bid is charged.
51
+ */
45
52
  readonly fee: Stroops;
46
53
  readonly feeAssumed: boolean;
47
- /** `balance - minimumBalance - sellingLiabilities` before the transaction. May be negative. */
54
+ /**
55
+ * `balance - minimumBalance - sellingLiabilities` before the transaction,
56
+ * with every earlier fee charged in full. May be negative.
57
+ */
48
58
  readonly availableBefore: Stroops;
49
59
  }
50
60
  /** Applied. The fee was charged and every operation took effect. */
@@ -66,29 +76,63 @@ export interface FailedResult extends TransactionResultBase {
66
76
  readonly shortfall: Stroops;
67
77
  }
68
78
  /**
69
- * Refused before it is applied (`tx_insufficient_balance`): the fee is more
70
- * than the available balance. Nothing is charged and nothing changes.
79
+ * Refused before it is applied, and nothing is charged:
80
+ * - `insufficient_balance` (`tx_insufficient_balance`): the whole bid is more
81
+ * than the available balance.
82
+ * - `own_key_as_signer` (`op_bad_signer`): an operation names the account's own
83
+ * key as a signer. The network refuses it while validating the operation, at
84
+ * submission, so it never enters a ledger (R15). `shortfall` is 0n.
71
85
  */
72
86
  export interface RejectedResult extends TransactionResultBase {
73
87
  readonly outcome: "rejected";
74
88
  readonly feeCharged: 0n;
75
- readonly reason: "insufficient_balance";
76
- /** `fee - availableBefore`. */
89
+ readonly reason: RejectionReason;
90
+ /** For `insufficient_balance`: `fee - availableBefore`. Otherwise 0n. */
77
91
  readonly shortfall: Stroops;
92
+ /** For `own_key_as_signer`: the index of the first operation that names the key. */
93
+ readonly operationIndex?: number;
78
94
  }
95
+ /** What would happen to one transaction at one possible fee charge. */
96
+ export type ChargeOutcome = {
97
+ readonly outcome: "accepted";
98
+ } | {
99
+ readonly outcome: "rejected";
100
+ readonly reason: RejectionReason;
101
+ readonly operationIndex?: number;
102
+ } | {
103
+ readonly outcome: "failed";
104
+ readonly reason: FailureReason;
105
+ readonly operationIndex: number;
106
+ };
79
107
  /**
80
- * The library does not claim to know. Only one case: a fee below 100 stroops
81
- * for each operation, because the network's minimum fee is a setting that can
82
- * change. Evaluation stops here; later transactions are not evaluated.
108
+ * The library does not claim to know. Evaluation stops here; later transactions
109
+ * are not evaluated. Two cases:
110
+ *
111
+ * - `fee_below_assumed_minimum`: a fee below 100 stroops for each operation,
112
+ * because the network's minimum fee is a setting that can change.
113
+ * - `fee_charge_changes_outcome` (R13): the network checks the whole bid but
114
+ * charges the lower of the bid and its effective fee, anywhere from 100
115
+ * stroops for each operation up to the whole bid. The transaction comes out
116
+ * differently at the two ends, so which it is depends on the charge.
117
+ * `atLowestCharge` and `atWholeBid` say what each end gives.
83
118
  */
84
- export interface UnknownResult extends TransactionResultBase {
119
+ export type UnknownResult = FeeBelowMinimumResult | FeeChargeResult;
120
+ export interface FeeBelowMinimumResult extends TransactionResultBase {
85
121
  readonly outcome: "unknown";
86
122
  readonly reason: "fee_below_assumed_minimum";
87
123
  readonly feeCharged: 0n;
88
124
  }
125
+ export interface FeeChargeResult extends TransactionResultBase {
126
+ readonly outcome: "unknown";
127
+ readonly reason: "fee_charge_changes_outcome";
128
+ readonly feeCharged: 0n;
129
+ readonly atLowestCharge: ChargeOutcome;
130
+ readonly atWholeBid: ChargeOutcome;
131
+ }
89
132
  export type TransactionResult = AcceptedResult | FailedResult | RejectedResult | UnknownResult;
90
133
  /** The account after the transactions that were evaluated. */
91
134
  export interface AccountAfter {
135
+ /** With every fee charged in full (the whole bid). */
92
136
  readonly balance: Stroops;
93
137
  readonly subentryCount: number;
94
138
  readonly signers: readonly string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signerreach/reserve",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Experimental: check whether a Stellar classic account can pay the fee and the reserve for a plan of signer changes, in the order the network applies them.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",