@signerreach/reserve 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,385 @@
1
- # Temporary Holding Version
1
+ # reserve
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Experimental companion library to [SignerReach](https://github.com/signerreach/signerreach).
4
+ It is published to npm as an experimental `0.x` package so that it can be tried, and external
5
+ user demand has not yet been established. The project is being evaluated as a lightweight way
6
+ for TypeScript applications to check reserve and fee constraints before submitting supported
7
+ signer-change transactions.**
8
+
9
+ - [The problem](#the-problem)
10
+ - [What this project proposes](#what-this-project-proposes)
11
+ - [Scope and limitations](#scope-and-limitations)
12
+ - [Relationship to SignerReach](#relationship-to-signerreach)
13
+ - [Architecture](#architecture)
14
+ - [Install](#install)
15
+ - [Usage](#usage)
16
+ - [The rules, and how fees are modelled](#the-rules-and-how-fees-are-modelled)
17
+ - [What it does not do](#what-it-does-not-do)
18
+ - [Evidence and how much to trust it](#evidence-and-how-much-to-trust-it)
19
+ - [Known differences from the network](#known-differences-from-the-network)
20
+ - [Develop](#develop)
21
+ - [Status and licence](#status-and-licence)
22
+
23
+ ## The problem
24
+
25
+ On Stellar, an account must keep a minimum balance that grows with every entry it holds:
26
+ signers, trust lines, offers and data entries each add one base reserve, and sponsorship
27
+ moves reserves between accounts. A transaction that adds a signer can therefore carry every
28
+ signature it needs and still fail, because the account cannot afford the extra reserve. The
29
+ network includes such a transaction in a ledger, fails it with `op_low_reserve`, and still
30
+ charges its fee.
31
+
32
+ This is not hypothetical. On Testnet on 2026-11-20, a plan that SignerReach's checker had
33
+ called safe failed this way at ledger 5831809 and paid its fee
34
+ ([record](https://github.com/signerreach/signerreach/blob/main/docs/evidence/testnet-2026-11-20-reserve-gap/README.md)).
35
+
36
+ Whether a plan will be accepted depends on several figures that interact: the balance, the
37
+ minimum balance (sub-entries and sponsorship), selling liabilities, the fee, and the **order**
38
+ of the operations inside a transaction, since removing a signer before adding one can fit
39
+ where the reverse order does not. The arithmetic has confused people in public:
40
+ the Stellar documentation's sponsored-reserves formula was reported in 2026 to differ from
41
+ Stellar Core's by a selling-liabilities term
42
+ ([stellar-docs#2771](https://github.com/stellar/stellar-docs/issues/2771), closed), and a
43
+ Freighter user reported 0 XLM available after adding 2 XLM to an account with no trust lines
44
+ or offers ([freighter#1879](https://github.com/stellar/freighter/issues/1879), closed). This
45
+ README does not claim more about those two reports than that they were made.
46
+
47
+ ## What this project proposes
48
+
49
+ A small, dependency-free TypeScript function. Given an account's figures, read from one
50
+ ledger, and a plan of signer changes, it says for each transaction whether the network would
51
+ **accept** it, **reject** it before applying it without charging anything, or **include it and
52
+ fail it** while keeping the fee, together with the account that would result. It is meant to be
53
+ called before submitting, by wallets, bots and scripts that build signer changes.
54
+
55
+ That is a proposal, not an established need. No user has been identified, and whether the
56
+ check is worth having is what this project is being used to find out. What it can offer today
57
+ is a narrow model whose predictions have been compared with Testnet in 73 case runs (two
58
+ passes of 31 cases, one of 10, and a re-run of the one case that could not be used the first
59
+ time) and whose differences from the network are documented below.
60
+
61
+ ## Scope and limitations
62
+
63
+ Reserve checks balance, fee, and reserve constraints for a limited set of Stellar
64
+ classic-account signer changes. It does not determine whether a transaction has sufficient
65
+ signatures, whether its signer configuration is safe, or whether the account will retain
66
+ administrative access. For authorization and signer-availability analysis, use SignerReach.
67
+ Neither tool guarantees that a transaction will succeed when eventually submitted. Account
68
+ state and network conditions can change after a check.
69
+
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
74
+ [Evidence](#evidence-and-how-much-to-trust-it) and
75
+ [Known differences](#known-differences-from-the-network).
76
+
77
+ **Supported:** one classic account's native balance; `SetOptions` signer changes (add a
78
+ signer, change a signer's weight, remove a signer with weight 0) in transactions of 1 to 100
79
+ operations, with an optional fee bid.
80
+
81
+ ## Relationship to SignerReach
82
+
83
+ Reserve is a companion TypeScript library implementing the reserve-and-fee portion of the
84
+ SignerReach model. SignerReach focuses on authorization and future administrative access,
85
+ while Reserve focuses on account balance, fee, and reserve constraints. The two projects have
86
+ related but different responsibilities:
87
+
88
+ | | SignerReach | Reserve |
89
+ |---|---|---|
90
+ | Question | Will the account stay administrable after this plan, under the signers you say are available? | Can the account pay the fee and the reserve for this plan, in the order the network applies it? |
91
+ | Looks at | Signers, weights, thresholds, signatures, availability | Balance, minimum balance, selling liabilities, fee, order of operations |
92
+ | Language | Rust (a command-line tool) | TypeScript (a library) |
93
+ | Evidence | Its own Testnet and Mainnet records | Agreement with SignerReach's published binary, plus its own Testnet records |
94
+
95
+ They share rules R10 to R15 of
96
+ [SignerReach's specification](https://github.com/signerreach/signerreach/blob/main/docs/SPEC.md).
97
+ A change to one of those rules is made there first (see [CONTRIBUTING.md](CONTRIBUTING.md)).
98
+
99
+ ## Architecture
100
+
101
+ Reserve is a set of pure functions. It makes no network request, holds no key, signs and
102
+ submits nothing, and does not change the objects it is given. Everything it needs is passed in.
103
+
104
+ ```mermaid
105
+ flowchart LR
106
+ H["Your code reads an account from Horizon, from one ledger"] --> A["Account: balance, liabilities, sub-entries, sponsorship, base reserve, signers"]
107
+ P["Your plan: transactions of signer changes, with an optional fee bid"] --> C
108
+ A --> C["checkPlan"]
109
+ C --> R["Per transaction: accepted, failed, rejected or unknown, plus the account afterwards"]
110
+ R --> D["Your code decides whether to submit"]
111
+ ```
112
+
113
+ | File | Responsibility |
114
+ |---|---|
115
+ | `src/types.ts` | The data types: `Account`, `Transaction`, the four result types, `PlanResult`. |
116
+ | `src/account.ts` | The constants (1000 sub-entries, 20 signers, 100 stroops for each operation), `InputError`, `validateAccount`, `minimumBalance` and `available`. |
117
+ | `src/plan.ts` | `checkPlan`: evaluates a plan one transaction after another, in the order the network applies them. |
118
+ | `src/index.ts` | The public API. |
119
+
120
+ **What `checkPlan` does with each transaction.** It works on a copy of the account and, for
121
+ each transaction in turn:
122
+
123
+ 1. If the fee is below 100 stroops for each operation, it returns `unknown` and stops.
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
128
+ operation that cannot be applied makes the whole transaction `failed`: the fee stays
129
+ charged and none of its operations take effect. If every operation applies, the
130
+ transaction is `accepted` and its changes are kept.
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.
135
+
136
+ **Inputs are validated** and refused with an `InputError` if Stellar could not hold them:
137
+ negative amounts, liabilities above the balance, more than 1000 sub-entries or 20 signers, a
138
+ duplicated signer or the account's own key among the signers, a weight above 255, an empty
139
+ transaction, a fee outside 1 to 4294967295, or an amount that is not a `bigint`.
140
+
141
+ **How it is verified.** Each layer checks something the others do not:
142
+
143
+ | Layer | What it checks | Where |
144
+ |---|---|---|
145
+ | Rule tests | The rules, at their boundaries, with numbers worked out from the specification | `test/rules.test.ts` |
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` |
148
+ | Testnet tool | That predictions match what the network does, with each prediction written before the plan is submitted | `tools/testnet/`, `docs/evidence/` |
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` |
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` |
151
+
152
+ `tools/testnet/compare.mjs` contains a helper that builds an `Account` from a Horizon account
153
+ record. It is part of the Testnet tool, not of the library.
154
+
155
+ ## Install
156
+
157
+ ```
158
+ npm install @signerreach/reserve
159
+ ```
160
+
161
+ It has no dependencies. It is written in TypeScript and shipped compiled, with its type
162
+ declarations, as an ES module (`"type": "module"`), and it needs Node 22 or newer. From
163
+ CommonJS, load it with `await import("@signerreach/reserve")`.
164
+
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.
170
+
171
+ ## Usage
172
+
173
+ ```ts
174
+ import { available, checkPlan, minimumBalance, type Account } from "@signerreach/reserve";
175
+
176
+ const account: Account = {
177
+ accountId: "GA...OWNER",
178
+ balance: 20_000_100n, // stroops
179
+ sellingLiabilities: 0n,
180
+ subentryCount: 1,
181
+ numSponsoring: 0,
182
+ numSponsored: 0,
183
+ baseReserve: 5_000_000n,
184
+ signers: ["GB...B"],
185
+ };
186
+
187
+ minimumBalance(account); // 15000000n
188
+ available(account); // 5000100n
189
+
190
+ const result = checkPlan(account, [
191
+ { id: "add-c", operations: [{ key: "GC...C", weight: 1 }] },
192
+ ]);
193
+ result.allAccepted; // true
194
+ result.account.available; // 0n: nothing is left to spend
195
+
196
+ // One stroop less: the network would include the transaction, fail it, and keep the fee.
197
+ const short = checkPlan({ ...account, balance: 20_000_099n }, [
198
+ { id: "add-c", operations: [{ key: "GC...C", weight: 1 }] },
199
+ ]);
200
+ short.transactions[0]; // { outcome: "failed", reason: "low_reserve", shortfall: 1n, feeCharged: 100n, ... }
201
+ ```
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
+
216
+ (`examples/basic.ts` is this program, importing from the source tree instead of the package;
217
+ run it from a clone with `node examples/basic.ts`.)
218
+
219
+ Every amount is a `bigint` number of stroops. There are no floats anywhere, and a `number`
220
+ where an amount is expected is refused.
221
+
222
+ ## The rules, and how fees are modelled
223
+
224
+ These are rules R10 to R15 of the
225
+ [SignerReach specification](https://github.com/signerreach/signerreach/blob/main/docs/SPEC.md):
226
+
227
+ - `minimumBalance = (2 + subentries + sponsoring - sponsored) * baseReserve`
228
+ - `available = balance - minimumBalance - sellingLiabilities` (it can be negative)
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.
235
+ - **Failed transactions keep the fee (R12):** if it passes that check and then fails in an
236
+ operation, it is `failed`: the fee is charged and no operation takes effect.
237
+ - **Adding a signer (R11)** needs `available >= baseReserve`, checked after the 20-signer limit
238
+ and the 1000-sub-entry limit.
239
+ - **Changing the weight of an existing signer needs no reserve (R10).** Weight 0 removes the
240
+ signer and lowers the sub-entry count.
241
+ - **In order (R14):** operations apply one after another, so `[remove C, add D]` can fit where
242
+ `[add D, remove C]` does not.
243
+
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.
264
+
265
+ A fee bid of less than 100 stroops for each operation gives `unknown`: the network's minimum
266
+ fee is a setting that can change, so the library does not claim to know, and evaluation stops
267
+ at that transaction.
268
+
269
+ ## What it does not do
270
+
271
+ - **Authorization.** It does not check signatures, thresholds or whether anyone holds a key.
272
+ It assumes the plan is authorized. For that, use SignerReach.
273
+ - **Anything but signer changes.** Trust lines, offers, data entries, `createAccount`,
274
+ claimable balances, liquidity pools, sponsorship operations, fee bumps and Soroban fees are
275
+ not modelled. Each would need its own rule read from the stellar-core source, a Testnet run
276
+ at the boundary and a test before it could be added. (Trust lines, offers, data entries and
277
+ sponsorship appear in the Testnet records only as ways to put an account into a state before
278
+ the signer change is tested.)
279
+ - **Validate addresses.** Keys are compared as plain strings.
280
+ - **Fetch an account.** You give it the numbers. Reading them from Horizon is your code's job,
281
+ and the numbers must come from one ledger.
282
+ - **Say anything about the account now.** A balance can change between your check and the
283
+ submission.
284
+
285
+ ## Evidence and how much to trust it
286
+
287
+ Not every rule has the same level of evidence. This table says which is which.
288
+
289
+ | Rule or behaviour | Level of evidence |
290
+ |---|---|
291
+ | The reserve, fee and operation-order rules at their boundaries (R10 to R14) | **Observed on Testnet.** SignerReach ran seven cases on 2026-11-23 ([record](https://github.com/signerreach/signerreach/blob/main/docs/evidence/testnet-2026-11-23-reserve-boundaries/README.md)); this library ran 31 cases twice on 2026-11-27 ([run 1](docs/evidence/testnet-2026-11-27/README.md), [run 2](docs/evidence/testnet-2026-11-27-run-2/README.md)) |
292
+ | The 20-signer limit is checked before the reserve | **Observed on Testnet**, one case (`cap-21st-lowbal`), the same result in both runs |
293
+ | The 1000-sub-entry limit is checked before the reserve | **Observed on Testnet**, one case with less than a reserve available (`sub1000-low`, 2026-11-28). A second case with plenty of balance (`sub1000-rich`) was unusable the first time because of a fault in the tool, and matched when run again the same day ([re-run](docs/evidence/testnet-2026-11-28-tier3-rerun/README.md)). This was previously from the stellar-core source only |
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)) |
295
+ | Which of the 20-signer limit and the 1000-sub-entry limit is checked first | **Source inspection only.** Not tested on any network |
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 |
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 |
299
+
300
+ SignerReach's specification still lists some of the tier-3 rules as source-only; it has not
301
+ yet been updated to reflect these records.
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
+
306
+ **What the library's own Testnet runs showed.** Two runs of 31 cases each on 2026-11-27 at
307
+ protocol 30: **25 matched, 5 differed, 1 was an observation only, none unusable, the same in
308
+ both.** One pass of 10 tier-3 cases on 2026-11-28: **9 matched, none differed, 1 unusable**; the
309
+ unusable case was run again the same day and **matched**.
310
+ In every run each prediction was written before the plan was submitted. In run 2 and in tier 3
311
+ the account's balance also confirmed the fee of every transaction; run 1 did not record it.
312
+ These are repetitions on one network state with no surge pricing, not confirmation across
313
+ conditions.
314
+
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,
317
+ available balance and code. These are two implementations of the same rules by the same
318
+ author. Agreement is a consistency check between them. **It is not independent verification
319
+ against the network.**
320
+
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.
323
+
324
+ Known differences from the binary: for a fee below the minimum, the binary rejects the whole
325
+ input and evaluates nothing, while this library evaluates the earlier transactions and stops
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.
329
+
330
+ ## Known differences from the network
331
+
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
347
+ fee.** The network refused it at submission (`op_bad_signer`), with no ledger record after
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.
358
+
359
+ ## Develop
360
+
361
+ Node 22.18 or newer (it runs TypeScript directly).
362
+
363
+ ```
364
+ npm ci
365
+ npm run typecheck
366
+ npm test # 39 rule tests + 637 agreement cases
367
+ npm run build
368
+ npm run pack:check # packs it, installs it in a scratch project, uses it from JS and TS
369
+ node scripts/mutation-check.mjs
370
+ ```
371
+
372
+ To regenerate or re-check the vectors, you need the published binary. See
373
+ [vectors/README.md](vectors/README.md).
374
+
375
+ [tools/testnet](tools/testnet/README.md) runs the library's predictions against Stellar
376
+ Testnet and records whether the network agrees. Its records so far:
377
+ [run 1](docs/evidence/testnet-2026-11-27/README.md) and, with a corrected tool,
378
+ [run 2](docs/evidence/testnet-2026-11-27-run-2/README.md), both tiers 1 and 2;
379
+ [tier 3](docs/evidence/testnet-2026-11-28-tier3/README.md); and the
380
+ [re-run of its one unusable case](docs/evidence/testnet-2026-11-28-tier3-rerun/README.md).
381
+
382
+ ## Status and licence
383
+
384
+ Experimental. Version `0.1.1`, published to npm as `@signerreach/reserve`. Unaudited.
385
+ Apache-2.0. Not affiliated with the Stellar Development Foundation.
@@ -0,0 +1,23 @@
1
+ import type { Account, Stroops } from "./types.ts";
2
+ /** The most sub-entries an account can hold. */
3
+ export declare const SUB_ENTRY_LIMIT = 1000;
4
+ /** The most additional signers an account can hold. */
5
+ export declare const MAX_ADDITIONAL_SIGNERS = 20;
6
+ /** The fee assumed for each operation when a transaction gives none, in stroops. */
7
+ export declare const ASSUMED_FEE_PER_OPERATION: Stroops;
8
+ /** The largest amount Stellar can hold (a signed 64-bit integer). */
9
+ export declare const MAX_AMOUNT: Stroops;
10
+ /** The largest fee a transaction can carry (an unsigned 32-bit integer). */
11
+ export declare const MAX_FEE: Stroops;
12
+ /** The largest signer weight. */
13
+ export declare const MAX_WEIGHT = 255;
14
+ /** Thrown for input that Stellar could not hold, or that this library refuses to guess about. */
15
+ export declare class InputError extends Error {
16
+ constructor(message: string);
17
+ }
18
+ /** Refuses an account Stellar could not hold. Returns the account unchanged. */
19
+ export declare function validateAccount(account: Account): Account;
20
+ /** `(2 + subentries + sponsoring - sponsored) * baseReserve`. */
21
+ export declare function minimumBalance(account: Pick<Account, "subentryCount" | "numSponsoring" | "numSponsored" | "baseReserve">): Stroops;
22
+ /** `balance - minimumBalance - sellingLiabilities`. Negative when the account is below its minimum. */
23
+ export declare function available(account: Pick<Account, "balance" | "sellingLiabilities" | "subentryCount" | "numSponsoring" | "numSponsored" | "baseReserve">): Stroops;
@@ -0,0 +1,86 @@
1
+ /** The most sub-entries an account can hold. */
2
+ export const SUB_ENTRY_LIMIT = 1000;
3
+ /** The most additional signers an account can hold. */
4
+ export const MAX_ADDITIONAL_SIGNERS = 20;
5
+ /** The fee assumed for each operation when a transaction gives none, in stroops. */
6
+ export const ASSUMED_FEE_PER_OPERATION = 100n;
7
+ /** The largest amount Stellar can hold (a signed 64-bit integer). */
8
+ export const MAX_AMOUNT = 2n ** 63n - 1n;
9
+ /** The largest fee a transaction can carry (an unsigned 32-bit integer). */
10
+ export const MAX_FEE = 4294967295n;
11
+ /** The largest signer weight. */
12
+ export const MAX_WEIGHT = 255;
13
+ /** Thrown for input that Stellar could not hold, or that this library refuses to guess about. */
14
+ export class InputError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "InputError";
18
+ }
19
+ }
20
+ function isCount(value) {
21
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 4294967295;
22
+ }
23
+ /** Refuses an account Stellar could not hold. Returns the account unchanged. */
24
+ export function validateAccount(account) {
25
+ if (typeof account.accountId !== "string" || account.accountId === "") {
26
+ throw new InputError("accountId must be a non-empty string");
27
+ }
28
+ for (const [name, value] of [
29
+ ["balance", account.balance],
30
+ ["sellingLiabilities", account.sellingLiabilities],
31
+ ["baseReserve", account.baseReserve],
32
+ ]) {
33
+ if (typeof value !== "bigint") {
34
+ throw new InputError(`${name} must be a bigint number of stroops`);
35
+ }
36
+ if (value < 0n)
37
+ throw new InputError(`${name} is negative`);
38
+ if (value > MAX_AMOUNT)
39
+ throw new InputError(`${name} is more than a signed 64-bit integer`);
40
+ }
41
+ if (account.sellingLiabilities > account.balance) {
42
+ throw new InputError("the selling liabilities are more than the balance");
43
+ }
44
+ if (account.baseReserve < 1n)
45
+ throw new InputError("the base reserve is not above 0");
46
+ for (const [name, value] of [
47
+ ["subentryCount", account.subentryCount],
48
+ ["numSponsoring", account.numSponsoring],
49
+ ["numSponsored", account.numSponsored],
50
+ ]) {
51
+ if (!isCount(value))
52
+ throw new InputError(`${name} must be a whole number`);
53
+ }
54
+ if (account.subentryCount > SUB_ENTRY_LIMIT) {
55
+ throw new InputError("the sub-entry count is above 1000");
56
+ }
57
+ if (2 + account.subentryCount + account.numSponsoring - account.numSponsored < 0) {
58
+ throw new InputError("the sponsorship counts leave a negative number of reserved entries");
59
+ }
60
+ if (account.signers.length > MAX_ADDITIONAL_SIGNERS) {
61
+ throw new InputError("an account holds at most 20 additional signers");
62
+ }
63
+ if (account.subentryCount < account.signers.length) {
64
+ throw new InputError("the sub-entry count is below the number of additional signers");
65
+ }
66
+ const seen = new Set();
67
+ for (const key of account.signers) {
68
+ if (typeof key !== "string" || key === "")
69
+ throw new InputError("a signer key must be a non-empty string");
70
+ if (key === account.accountId)
71
+ throw new InputError("the account's own key is not an additional signer");
72
+ if (seen.has(key))
73
+ throw new InputError("a signer key is listed twice");
74
+ seen.add(key);
75
+ }
76
+ return account;
77
+ }
78
+ /** `(2 + subentries + sponsoring - sponsored) * baseReserve`. */
79
+ export function minimumBalance(account) {
80
+ const entries = 2 + account.subentryCount + account.numSponsoring - account.numSponsored;
81
+ return BigInt(entries) * account.baseReserve;
82
+ }
83
+ /** `balance - minimumBalance - sellingLiabilities`. Negative when the account is below its minimum. */
84
+ export function available(account) {
85
+ return account.balance - minimumBalance(account) - account.sellingLiabilities;
86
+ }
@@ -0,0 +1,3 @@
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
+ export { checkPlan } from "./plan.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/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { ASSUMED_FEE_PER_OPERATION, InputError, MAX_ADDITIONAL_SIGNERS, MAX_AMOUNT, MAX_FEE, MAX_WEIGHT, SUB_ENTRY_LIMIT, available, minimumBalance, validateAccount, } from "./account.js";
2
+ export { checkPlan } from "./plan.js";
package/dist/plan.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { Account, PlanResult, Transaction } from "./types.ts";
2
+ /**
3
+ * Evaluates a plan of signer changes against an account's balance, one
4
+ * transaction after another, in the order the network applies them.
5
+ *
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.
16
+ * - R12: a transaction that passes and then fails in an operation is included in
17
+ * a ledger and keeps its fee; none of its operations take effect.
18
+ * - R11, R10: adding a new signer needs one base reserve of available balance;
19
+ * changing the weight of an existing signer needs none.
20
+ * - R14: operations apply in order against the state earlier ones left.
21
+ *
22
+ * What it does not model: signatures and thresholds (it assumes the plan is
23
+ * authorized), any operation other than a signer change, fee bumps,
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`).
27
+ */
28
+ export declare function checkPlan(account: Account, transactions: readonly Transaction[]): PlanResult;
package/dist/plan.js ADDED
@@ -0,0 +1,232 @@
1
+ import { ASSUMED_FEE_PER_OPERATION, InputError, MAX_ADDITIONAL_SIGNERS, MAX_FEE, MAX_WEIGHT, SUB_ENTRY_LIMIT, available, minimumBalance, validateAccount, } from "./account.js";
2
+ function validateTransaction(tx, position) {
3
+ if (tx.operations.length === 0) {
4
+ throw new InputError(`transaction ${position}: a transaction needs at least one operation`);
5
+ }
6
+ if (tx.operations.length > 100) {
7
+ throw new InputError(`transaction ${position}: a transaction holds at most 100 operations`);
8
+ }
9
+ if (tx.fee !== undefined) {
10
+ if (typeof tx.fee !== "bigint") {
11
+ throw new InputError(`transaction ${position}: fee must be a bigint number of stroops`);
12
+ }
13
+ if (tx.fee < 1n || tx.fee > MAX_FEE) {
14
+ throw new InputError(`transaction ${position}: fee must be from 1 to 4294967295 stroops`);
15
+ }
16
+ }
17
+ for (const op of tx.operations) {
18
+ if (typeof op.key !== "string" || op.key === "") {
19
+ throw new InputError(`transaction ${position}: a signer key must be a non-empty string`);
20
+ }
21
+ if (!Number.isInteger(op.weight) || op.weight < 0 || op.weight > MAX_WEIGHT) {
22
+ throw new InputError(`transaction ${position}: a signer weight is a whole number from 0 to 255`);
23
+ }
24
+ }
25
+ }
26
+ function snapshot(account, balance, state) {
27
+ return {
28
+ balance,
29
+ sellingLiabilities: account.sellingLiabilities,
30
+ subentryCount: state.subentryCount,
31
+ numSponsoring: account.numSponsoring,
32
+ numSponsored: account.numSponsored,
33
+ baseReserve: account.baseReserve,
34
+ };
35
+ }
36
+ /**
37
+ * Applies one operation to `state` or says why it cannot be applied (R10, R11).
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).
41
+ */
42
+ function applyOperation(account, balance, state, op) {
43
+ const present = state.signers.has(op.key);
44
+ if (op.weight === 0) {
45
+ // R10: weight 0 removes a signer; for a key that is not a signer it changes nothing.
46
+ if (present) {
47
+ state.signers.delete(op.key);
48
+ state.subentryCount -= 1;
49
+ }
50
+ return undefined;
51
+ }
52
+ // R10: a key that is already a signer only changes weight and needs no reserve.
53
+ if (present)
54
+ return undefined;
55
+ // R11, in this order: signer limit, sub-entry limit, reserve.
56
+ if (state.signers.size >= MAX_ADDITIONAL_SIGNERS) {
57
+ return { reason: "too_many_signers", shortfall: 0n };
58
+ }
59
+ if (state.subentryCount >= SUB_ENTRY_LIMIT) {
60
+ return { reason: "too_many_subentries", shortfall: 0n };
61
+ }
62
+ const room = available(snapshot(account, balance, state));
63
+ if (room < account.baseReserve) {
64
+ return { reason: "low_reserve", shortfall: account.baseReserve - room };
65
+ }
66
+ state.signers.add(op.key);
67
+ state.subentryCount += 1;
68
+ return undefined;
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
+ }
107
+ /**
108
+ * Evaluates a plan of signer changes against an account's balance, one
109
+ * transaction after another, in the order the network applies them.
110
+ *
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.
121
+ * - R12: a transaction that passes and then fails in an operation is included in
122
+ * a ledger and keeps its fee; none of its operations take effect.
123
+ * - R11, R10: adding a new signer needs one base reserve of available balance;
124
+ * changing the weight of an existing signer needs none.
125
+ * - R14: operations apply in order against the state earlier ones left.
126
+ *
127
+ * What it does not model: signatures and thresholds (it assumes the plan is
128
+ * authorized), any operation other than a signer change, fee bumps,
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`).
132
+ */
133
+ export function checkPlan(account, transactions) {
134
+ validateAccount(account);
135
+ transactions.forEach((tx, i) => validateTransaction(tx, i));
136
+ const state = {
137
+ subentryCount: account.subentryCount,
138
+ signers: new Set(account.signers),
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;
144
+ const results = [];
145
+ let complete = true;
146
+ for (const [index, tx] of transactions.entries()) {
147
+ const assumedMinimum = ASSUMED_FEE_PER_OPERATION * BigInt(tx.operations.length);
148
+ const feeAssumed = tx.fee === undefined;
149
+ const fee = tx.fee ?? assumedMinimum;
150
+ const availableBefore = available(snapshot(account, balanceAtBid, state));
151
+ const base = { index, id: tx.id, fee, feeAssumed, availableBefore };
152
+ if (fee < assumedMinimum) {
153
+ results.push({ ...base, outcome: "unknown", reason: "fee_below_assumed_minimum", feeCharged: 0n });
154
+ complete = false;
155
+ break;
156
+ }
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)) {
164
+ results.push({
165
+ ...base,
166
+ outcome: "unknown",
167
+ reason: "fee_charge_changes_outcome",
168
+ feeCharged: 0n,
169
+ atLowestCharge: lowestOutcome,
170
+ atWholeBid: bidOutcome,
171
+ });
172
+ complete = false;
173
+ break;
174
+ }
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 });
216
+ break;
217
+ }
218
+ }
219
+ const final = snapshot(account, balanceAtBid, state);
220
+ return {
221
+ transactions: results,
222
+ account: {
223
+ balance: balanceAtBid,
224
+ subentryCount: state.subentryCount,
225
+ signers: [...state.signers],
226
+ minimumBalance: minimumBalance(final),
227
+ available: available(final),
228
+ },
229
+ complete,
230
+ allAccepted: complete && results.every((r) => r.outcome === "accepted"),
231
+ };
232
+ }
@@ -0,0 +1,150 @@
1
+ /** Every amount is a whole number of stroops (1 XLM = 10,000,000 stroops). No decimals, no floats. */
2
+ export type Stroops = bigint;
3
+ /** The balance side of one classic account at one moment. */
4
+ export interface Account {
5
+ /**
6
+ * The account's own G address. Used only to refuse a plan that names the
7
+ * account's own key as a signer. Keys are compared as plain strings; this
8
+ * library does not check that an address is well formed.
9
+ */
10
+ readonly accountId: string;
11
+ /** Native balance. */
12
+ readonly balance: Stroops;
13
+ /** Native selling liabilities (open offers). */
14
+ readonly sellingLiabilities: Stroops;
15
+ /** All sub-entries: additional signers, trust lines, offers and data entries. */
16
+ readonly subentryCount: number;
17
+ readonly numSponsoring: number;
18
+ readonly numSponsored: number;
19
+ /** The network's base reserve at the ledger the figures come from. */
20
+ readonly baseReserve: Stroops;
21
+ /** Keys of the account's additional signers (not the account's own key). */
22
+ readonly signers: readonly string[];
23
+ }
24
+ /** One signer change, as `SetOptions` makes it. Weight 0 removes the signer. */
25
+ export interface SignerOperation {
26
+ readonly key: string;
27
+ /** A whole number from 0 to 255. */
28
+ readonly weight: number;
29
+ }
30
+ export interface Transaction {
31
+ readonly id?: string;
32
+ /**
33
+ * The whole fee of the transaction in stroops, 1 to 4294967295. When absent,
34
+ * 100 stroops for each operation is assumed and the result says so.
35
+ */
36
+ readonly fee?: Stroops;
37
+ readonly operations: readonly SignerOperation[];
38
+ }
39
+ /** Why an operation cannot be applied (the transaction then fails but keeps its fee). */
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";
43
+ interface TransactionResultBase {
44
+ readonly index: number;
45
+ readonly id: string | undefined;
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
+ */
52
+ readonly fee: Stroops;
53
+ readonly feeAssumed: boolean;
54
+ /**
55
+ * `balance - minimumBalance - sellingLiabilities` before the transaction,
56
+ * with every earlier fee charged in full. May be negative.
57
+ */
58
+ readonly availableBefore: Stroops;
59
+ }
60
+ /** Applied. The fee was charged and every operation took effect. */
61
+ export interface AcceptedResult extends TransactionResultBase {
62
+ readonly outcome: "accepted";
63
+ readonly feeCharged: Stroops;
64
+ }
65
+ /**
66
+ * Included in a ledger, then failed in an operation: nothing took effect
67
+ * except that the fee was charged (`op_low_reserve` and the like).
68
+ */
69
+ export interface FailedResult extends TransactionResultBase {
70
+ readonly outcome: "failed";
71
+ readonly feeCharged: Stroops;
72
+ readonly reason: FailureReason;
73
+ /** Index of the operation that failed. */
74
+ readonly operationIndex: number;
75
+ /** For `low_reserve`: stroops short of one base reserve. Otherwise 0n. */
76
+ readonly shortfall: Stroops;
77
+ }
78
+ /**
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.
85
+ */
86
+ export interface RejectedResult extends TransactionResultBase {
87
+ readonly outcome: "rejected";
88
+ readonly feeCharged: 0n;
89
+ readonly reason: RejectionReason;
90
+ /** For `insufficient_balance`: `fee - availableBefore`. Otherwise 0n. */
91
+ readonly shortfall: Stroops;
92
+ /** For `own_key_as_signer`: the index of the first operation that names the key. */
93
+ readonly operationIndex?: number;
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
+ };
107
+ /**
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.
118
+ */
119
+ export type UnknownResult = FeeBelowMinimumResult | FeeChargeResult;
120
+ export interface FeeBelowMinimumResult extends TransactionResultBase {
121
+ readonly outcome: "unknown";
122
+ readonly reason: "fee_below_assumed_minimum";
123
+ readonly feeCharged: 0n;
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
+ }
132
+ export type TransactionResult = AcceptedResult | FailedResult | RejectedResult | UnknownResult;
133
+ /** The account after the transactions that were evaluated. */
134
+ export interface AccountAfter {
135
+ /** With every fee charged in full (the whole bid). */
136
+ readonly balance: Stroops;
137
+ readonly subentryCount: number;
138
+ readonly signers: readonly string[];
139
+ readonly minimumBalance: Stroops;
140
+ readonly available: Stroops;
141
+ }
142
+ export interface PlanResult {
143
+ readonly transactions: readonly TransactionResult[];
144
+ readonly account: AccountAfter;
145
+ /** False when evaluation stopped at an `unknown` transaction. */
146
+ readonly complete: boolean;
147
+ /** True only when `complete` and every transaction was accepted. */
148
+ readonly allAccepted: boolean;
149
+ }
150
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@signerreach/reserve",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "keywords": [
8
+ "stellar",
9
+ "signer",
10
+ "reserve",
11
+ "fee",
12
+ "multisig",
13
+ "typescript"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/signerreach/reserve.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/signerreach/reserve/issues"
21
+ },
22
+ "homepage": "https://github.com/signerreach/reserve#readme",
23
+ "engines": {
24
+ "node": ">=22"
25
+ },
26
+ "sideEffects": false,
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "LICENSE",
39
+ "README.md"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "typecheck": "tsc --noEmit",
46
+ "prebuild": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
47
+ "build": "tsc -p tsconfig.build.json",
48
+ "test": "node --test --test-reporter=spec \"test/**/*.test.ts\"",
49
+ "vectors": "node scripts/generate-vectors.mjs",
50
+ "vectors:check": "node scripts/generate-vectors.mjs --check",
51
+ "pack:check": "node scripts/pack-check.mjs",
52
+ "prepublishOnly": "npm run typecheck && npm run build && npm test && npm run pack:check"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "24.19.4",
56
+ "typescript": "5.9.3"
57
+ }
58
+ }