@hsuite/smart-engines-cli 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +56 -7
  2. package/dist/__tests__/helpers/fixtures-image-hygiene.d.ts +18 -0
  3. package/dist/__tests__/helpers/fixtures-image-hygiene.d.ts.map +1 -0
  4. package/dist/__tests__/helpers/fixtures-image-hygiene.js +42 -0
  5. package/dist/__tests__/helpers/fixtures-image-hygiene.js.map +1 -0
  6. package/dist/_lib/baas.d.ts +12 -17
  7. package/dist/_lib/baas.d.ts.map +1 -1
  8. package/dist/_lib/baas.js +13 -1
  9. package/dist/_lib/baas.js.map +1 -1
  10. package/dist/_lib/cluster-provisioning-report.d.ts +29 -0
  11. package/dist/_lib/cluster-provisioning-report.d.ts.map +1 -0
  12. package/dist/_lib/cluster-provisioning-report.js +35 -0
  13. package/dist/_lib/cluster-provisioning-report.js.map +1 -0
  14. package/dist/_lib/create-outcome.d.ts +43 -0
  15. package/dist/_lib/create-outcome.d.ts.map +1 -0
  16. package/dist/_lib/create-outcome.js +121 -0
  17. package/dist/_lib/create-outcome.js.map +1 -0
  18. package/dist/_lib/decimal-compare.d.ts +23 -0
  19. package/dist/_lib/decimal-compare.d.ts.map +1 -0
  20. package/dist/_lib/decimal-compare.js +69 -0
  21. package/dist/_lib/decimal-compare.js.map +1 -0
  22. package/dist/_lib/env.d.ts +6 -0
  23. package/dist/_lib/env.d.ts.map +1 -1
  24. package/dist/_lib/env.js +68 -1
  25. package/dist/_lib/env.js.map +1 -1
  26. package/dist/_lib/framework.js +2 -2
  27. package/dist/_lib/image-hygiene.d.ts +36 -0
  28. package/dist/_lib/image-hygiene.d.ts.map +1 -0
  29. package/dist/_lib/image-hygiene.js +233 -0
  30. package/dist/_lib/image-hygiene.js.map +1 -0
  31. package/dist/_lib/order-deadline.d.ts +35 -0
  32. package/dist/_lib/order-deadline.d.ts.map +1 -0
  33. package/dist/_lib/order-deadline.js +78 -0
  34. package/dist/_lib/order-deadline.js.map +1 -0
  35. package/dist/_lib/run-fn.d.ts +34 -0
  36. package/dist/_lib/run-fn.d.ts.map +1 -0
  37. package/dist/_lib/run-fn.js +15 -0
  38. package/dist/_lib/run-fn.js.map +1 -0
  39. package/dist/_lib/runtime-env.d.ts.map +1 -1
  40. package/dist/_lib/runtime-env.js +3 -0
  41. package/dist/_lib/runtime-env.js.map +1 -1
  42. package/dist/_lib/subscription-client.d.ts +123 -1
  43. package/dist/_lib/subscription-client.d.ts.map +1 -1
  44. package/dist/_lib/subscription-client.js +51 -41
  45. package/dist/_lib/subscription-client.js.map +1 -1
  46. package/dist/_lib/transport.d.ts +62 -0
  47. package/dist/_lib/transport.d.ts.map +1 -0
  48. package/dist/_lib/transport.js +120 -0
  49. package/dist/_lib/transport.js.map +1 -0
  50. package/dist/_lib/xrpl-login-signer.d.ts +39 -0
  51. package/dist/_lib/xrpl-login-signer.d.ts.map +1 -0
  52. package/dist/_lib/xrpl-login-signer.js +78 -0
  53. package/dist/_lib/xrpl-login-signer.js.map +1 -0
  54. package/dist/commands/app-lifecycle.d.ts.map +1 -1
  55. package/dist/commands/app-lifecycle.js +8 -2
  56. package/dist/commands/app-lifecycle.js.map +1 -1
  57. package/dist/commands/customer-scope.d.ts +48 -0
  58. package/dist/commands/customer-scope.d.ts.map +1 -0
  59. package/dist/commands/customer-scope.js +89 -0
  60. package/dist/commands/customer-scope.js.map +1 -0
  61. package/dist/commands/deploy.d.ts.map +1 -1
  62. package/dist/commands/deploy.js +11 -2
  63. package/dist/commands/deploy.js.map +1 -1
  64. package/dist/commands/personhood.d.ts +2 -2
  65. package/dist/commands/personhood.d.ts.map +1 -1
  66. package/dist/commands/personhood.js +12 -10
  67. package/dist/commands/personhood.js.map +1 -1
  68. package/dist/commands/redeploy.d.ts.map +1 -1
  69. package/dist/commands/redeploy.js +9 -2
  70. package/dist/commands/redeploy.js.map +1 -1
  71. package/dist/commands/subscribe.d.ts +52 -5
  72. package/dist/commands/subscribe.d.ts.map +1 -1
  73. package/dist/commands/subscribe.js +656 -70
  74. package/dist/commands/subscribe.js.map +1 -1
  75. package/dist/commands/topup.d.ts.map +1 -1
  76. package/dist/commands/topup.js +16 -1
  77. package/dist/commands/topup.js.map +1 -1
  78. package/dist/commands/transactions.d.ts +28 -31
  79. package/dist/commands/transactions.d.ts.map +1 -1
  80. package/dist/commands/transactions.js +36 -40
  81. package/dist/commands/transactions.js.map +1 -1
  82. package/dist/commands/upgrade.d.ts.map +1 -1
  83. package/dist/commands/upgrade.js +9 -1
  84. package/dist/commands/upgrade.js.map +1 -1
  85. package/dist/commands/verify.d.ts +23 -3
  86. package/dist/commands/verify.d.ts.map +1 -1
  87. package/dist/commands/verify.js +178 -34
  88. package/dist/commands/verify.js.map +1 -1
  89. package/dist/index.js +7 -4
  90. package/dist/index.js.map +1 -1
  91. package/package.json +2 -2
  92. package/dist/commands/governance.d.ts +0 -42
  93. package/dist/commands/governance.d.ts.map +0 -1
  94. package/dist/commands/governance.js +0 -144
  95. package/dist/commands/governance.js.map +0 -1
  96. package/dist/commands/hist-balance.d.ts +0 -52
  97. package/dist/commands/hist-balance.d.ts.map +0 -1
  98. package/dist/commands/hist-balance.js +0 -134
  99. package/dist/commands/hist-balance.js.map +0 -1
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.subscribeCommand = void 0;
7
7
  exports.runSubscribe = runSubscribe;
8
+ exports.renderReserveSurcharge = renderReserveSurcharge;
8
9
  /**
9
10
  * `hsuite subscribe` — Onboard a smart-app the CANONICAL, MINT-FIRST way:
10
11
  * create the smart-app's DKG ENTITY first, mint the builder subscription NFT
@@ -34,6 +35,15 @@ exports.runSubscribe = runSubscribe;
34
35
  * `{ appId: entityId, depositInstructions, subscriptionId }`. THIS replaces
35
36
  * the old random-id + standalone `subscription/request`. From here the
36
37
  * `entityId` is THE appId for everything downstream.
38
+ * The entity is SAVED (SUBSCRIPTION_APP_ID + APP_ID) the moment the create is
39
+ * verified — before any deposit/payment step — so a failed payment leaves it
40
+ * recorded and a re-run RESUMES it instead of creating a second one (#3754).
41
+ * The create itself is recorded as PENDING (SUBSCRIPTION_PENDING_CREATE) before
42
+ * the request leaves: a create whose outcome is unknown (a timeout, a dropped
43
+ * connection, a gateway 5xx after the work was done) is reconciled by the next
44
+ * run — it asks the platform whether that entity exists and RESUMES it if so,
45
+ * and creates a fresh one only when the platform shows none AND the earlier
46
+ * signed intent can no longer complete (#3766).
37
47
  * 4. Ensure deposit instructions: the createApp response normally carries them.
38
48
  * If a node deferred deposit-account creation, fall back to the idempotent
39
49
  * POST /api/v3/subscription/request { appId: entityId, … } (same retry/503
@@ -42,7 +52,18 @@ exports.runSubscribe = runSubscribe;
42
52
  * 5. Render the deposit instructions.
43
53
  * 6. AUTO-PAY the deposit from the dev wallet over the XRPL testnet (HST
44
54
  * Payment with a SendMax covering the 0.25% transfer fee). `--no-autopay`
45
- * skips this and prints instructions for manual (XUMM) payment.
55
+ * skips this and prints instructions for manual (XUMM) payment; re-running
56
+ * `hsuite subscribe` afterwards resumes the saved entity. A RESUMED run first
57
+ * asks GET /status and never pays a deposit the platform reports credited
58
+ * (deposit_confirmed / active), nor on an answer that cannot confirm the
59
+ * deposit is still owed (a failed read, `not_found`) (#3411). That read is
60
+ * ADVISORY, not a guarantee: only the cluster that holds the deposit account
61
+ * verifies on read, so another cluster can still answer `pending_deposit` for
62
+ * a payment sent a minute ago. The LEDGER is the source of truth every cluster
63
+ * agrees on, so before paying the CLI reads the deposit account's HST trust-line
64
+ * balance and refuses when it already holds what the quote asks (#3771). After a
65
+ * payment whose outcome is unknown, or that already validated, the error says so
66
+ * and points at `--no-autopay`, which can never pay.
46
67
  * 7. Poll GET /api/v3/subscription/status/:entityId until the deposit is
47
68
  * confirmed and ready to mint (status in { deposit_confirmed, pending_mint,
48
69
  * minting, active }; the real confirmed status is `deposit_confirmed`).
@@ -58,9 +79,14 @@ exports.runSubscribe = runSubscribe;
58
79
  const commander_1 = require("commander");
59
80
  const chalk_1 = __importDefault(require("chalk"));
60
81
  const ora_1 = __importDefault(require("ora"));
82
+ const smart_engines_sdk_1 = require("@hsuite/smart-engines-sdk");
61
83
  const env_1 = require("../_lib/env");
84
+ const decimal_compare_1 = require("../_lib/decimal-compare");
85
+ const create_outcome_1 = require("../_lib/create-outcome");
62
86
  const subscription_client_1 = require("../_lib/subscription-client");
63
87
  const subscription_env_1 = require("../_lib/subscription-env");
88
+ const order_deadline_1 = require("../_lib/order-deadline");
89
+ const xrpl_login_signer_1 = require("../_lib/xrpl-login-signer");
64
90
  /** Public XRPL testnet websocket endpoint (matches `hsuite init` + faucet). */
65
91
  const XRPL_TESTNET_WSS = 'wss://s.altnet.rippletest.net:51233';
66
92
  /**
@@ -85,6 +111,24 @@ function defaultWalletSignFactory(seed) {
85
111
  const wallet = Wallet.fromSeed(seed);
86
112
  return (tx) => wallet.sign(tx).tx_blob;
87
113
  }
114
+ /**
115
+ * Default entity-create-intent signer (#3506 A3, MEDIUM-1 fix): the SAME
116
+ * identity `authenticate()` logs in as — `XRPL_ADDRESS` + `deriveKeypair(seed)`
117
+ * via {@link buildXrplLoginSigner} — NEVER `xrpl.Wallet.fromSeed` /
118
+ * `createXrplWeb3Signer`. See `xrpl-login-signer.ts`'s doc-comment for why
119
+ * those two derivations can disagree (xrpl@4.6.0 forces ed25519 regardless of
120
+ * the seed's actual algorithm) and why that breaks the validator's
121
+ * intent-owner binding (#3635).
122
+ */
123
+ async function defaultIntentSignerFactory(address, seed) {
124
+ const loginSigner = await (0, xrpl_login_signer_1.buildXrplLoginSigner)(address, seed);
125
+ return {
126
+ chain: 'xrpl',
127
+ walletAddress: loginSigner.address,
128
+ publicKey: loginSigner.publicKey,
129
+ signFn: loginSigner.signFn,
130
+ };
131
+ }
88
132
  /**
89
133
  * Pure orchestration body — exported for unit tests.
90
134
  *
@@ -106,6 +150,13 @@ async function runSubscribe(opts) {
106
150
  // session by signing a challenge before any call.
107
151
  await client.authenticate();
108
152
  const sleep = opts.sleep ?? defaultSleep;
153
+ // What THIS run was started with, repeated in every "run this next" hint below (see Invocation).
154
+ const inv = {
155
+ neverPay: opts.autopay === false,
156
+ tier,
157
+ ...(opts.gateway ? { gateway: opts.gateway } : {}),
158
+ ...(opts.appName ? { appName: opts.appName } : {}),
159
+ };
109
160
  const appName = opts.appName ?? env.get('APP_NAME') ?? 'Smart App Showcase';
110
161
  // A DNS-safe name is required by the create DTO (the entityId is derived by
111
162
  // the DKG ceremony, not from this name; the name is the display label).
@@ -120,13 +171,93 @@ async function runSubscribe(opts) {
120
171
  // An explicit --app-id / a previously-written SUBSCRIPTION_APP_ID short-
121
172
  // circuits create (re-running `subscribe` to finish paying/minting an
122
173
  // already-created entity), so a resumed run does not fork a second entity.
123
- const preexistingAppId = opts.appId ?? env.get('SUBSCRIPTION_APP_ID');
174
+ // `||`, not `??`: an EMPTY `--app-id ""` falls back to the saved id instead of
175
+ // forking a second entity beside it.
176
+ let preexistingAppId = opts.appId || env.get('SUBSCRIPTION_APP_ID');
177
+ let resumedFrom = opts.appId ? '--app-id' : `SUBSCRIPTION_APP_ID in ${opts.env}`;
178
+ if (!preexistingAppId) {
179
+ // #3766 — an earlier create may have left no verdict (a timeout, a dropped connection, a
180
+ // gateway 5xx after the work was done). Ask the platform before creating anything: if that
181
+ // entity exists, it is THE entity to resume, never a reason to create a second one.
182
+ const adopted = await reconcileUnfinishedCreate(client, env, opts.env, inv);
183
+ if (adopted) {
184
+ preexistingAppId = adopted;
185
+ resumedFrom = `the unfinished create recorded in ${opts.env}`;
186
+ }
187
+ }
124
188
  let appId;
125
189
  let created;
126
190
  if (preexistingAppId) {
127
191
  appId = preexistingAppId;
192
+ // Say so: the platform's stored subscription decides the tier and the amount,
193
+ // so the --tier / --app-name this run was started with have no effect on it.
194
+ console.log(chalk_1.default.gray(` resuming smart-app entity ${appId} (from ${resumedFrom}) — ` +
195
+ 'it keeps the tier and name it was created with; --tier and --app-name are ignored'));
128
196
  }
129
197
  else {
198
+ // #3506 A3 — every legitimate customer create carries a signed intent.
199
+ // `GET /api/v3/discovery/network` is the PUBLIC, ingress-routed source of
200
+ // the cluster's GenesisConfig.network — the exact value every responder
201
+ // compares the intent's `network` field against (HIGH-2: genesis/status
202
+ // is NOT on the ingress allow-list and 404s through the gateway).
203
+ const intentNetwork = await (0, smart_engines_sdk_1.fetchIntentNetwork)(baseUrl);
204
+ if (!intentNetwork.ok) {
205
+ // HIGH-1(a): a 404 means this cluster predates signed create intents
206
+ // (#3635 + this endpoint haven't shipped there yet). Refuse BEFORE
207
+ // creating anything — an old validator would otherwise silently strip
208
+ // `creationIntent`, create a RANDOM-id entity, and the post-create
209
+ // assert below would then throw, orphaning that entity + its pending
210
+ // subscription on every retry.
211
+ if (intentNetwork.status === 404) {
212
+ throw new Error('cannot build a signed entity-create intent: GET /api/v3/discovery/network ' +
213
+ 'was not found (404) — this cluster predates signed create intents; upgrade ' +
214
+ 'the cluster (ship #3635 + this endpoint) before running `hsuite subscribe`.');
215
+ }
216
+ throw new Error('cannot build a signed entity-create intent: GET /api/v3/discovery/network ' +
217
+ `failed (status ${intentNetwork.status}) — refusing to create without a verified network`);
218
+ }
219
+ const network = intentNetwork.network;
220
+ // #3506 A3 LOW-1 (lying/misconfigured gateway, mainnet-only guard):
221
+ // `HSUITE_NETWORK` records which HSUITE CLUSTER `VALIDATOR_URL`/
222
+ // `SMART_HOST_URL` were resolved from (`hsuite init`, see `init.ts:
223
+ // 165-168`) — it is NOT the XRPL chain/faucet network (that's
224
+ // `XRPL_NETWORK`), and it is NOT the same value as the cluster's own
225
+ // `GenesisConfig.network` either: that value is derived server-side from
226
+ // `request.network || HEDERA_NETWORK || 'testnet'`
227
+ // (`genesis-bootstrap.service.ts:892`), so a devnet-cluster user (or one
228
+ // with `HSUITE_NETWORK` unset) LEGITIMATELY sees a discovered "testnet"
229
+ // — there is no separate "devnet" GenesisConfig label today. Refusing on
230
+ // every disagreement would therefore reject genuinely honest devnet
231
+ // onboarding. What must never happen regardless of `HSUITE_NETWORK` is
232
+ // silently signing a MAINNET intent: only refuse when the discovered
233
+ // network is mainnet and the operator has not explicitly confirmed
234
+ // `HSUITE_NETWORK=mainnet` — a compromised/misrouted gateway cannot
235
+ // trick a devnet/testnet/unset-configured user into a real-value mainnet
236
+ // signature. Compared case-insensitively (both sides normalised).
237
+ const hsuiteNetwork = env.get('HSUITE_NETWORK');
238
+ const normalizedDiscovered = network.toLowerCase();
239
+ const normalizedConfigured = hsuiteNetwork?.toLowerCase();
240
+ if (normalizedDiscovered === 'mainnet' && normalizedConfigured !== 'mainnet') {
241
+ throw new Error(`cluster-reported network "${network}" is mainnet, but the configured ` +
242
+ `HSUITE_NETWORK is "${hsuiteNetwork ?? '(unset)'}" — refusing to sign a MAINNET ` +
243
+ 'entity-create intent unless HSUITE_NETWORK=mainnet (possible lying or ' +
244
+ 'misconfigured gateway)');
245
+ }
246
+ // The developer authors the rule CLIENT-SIDE (the wallet signs its hash) —
247
+ // the standard default, byte-identical to what the validator would
248
+ // otherwise synthesize server-side for the same deployment path.
249
+ const validatorRules = (0, smart_engines_sdk_1.buildDefaultSmartAppValidatorRules)();
250
+ const intentSigner = await (opts.intentSignerFactory ?? defaultIntentSignerFactory)(address, seed);
251
+ const { proof: creationIntent, entityId: expectedEntityId } = await (0, smart_engines_sdk_1.signEntityCreateIntent)(intentSigner, {
252
+ network,
253
+ entityType: 'smart-app',
254
+ chain: 'xrpl',
255
+ rule: validatorRules,
256
+ });
257
+ // #3766 — record the create as PENDING before the request leaves: it is a long synchronous
258
+ // ceremony and this client gives up first, so "no answer" must not be mistaken for "nothing
259
+ // was created". Refuses (nothing sent) when the record cannot be kept.
260
+ recordPendingCreate(opts.env, expectedEntityId, (0, create_outcome_1.pendingCreateDeadline)(creationIntent.message));
130
261
  try {
131
262
  created = await client.createApp({
132
263
  name: appName,
@@ -140,17 +271,58 @@ async function runSubscribe(opts) {
140
271
  },
141
272
  tier,
142
273
  networks: ['testnet'],
143
- // validatorRules omitted (optional) — the factory synthesizes the
144
- // canonical security-first default for the standard deployment path.
274
+ // #3506 A3 — the EXACT rule the client hashed, plus the signed proof
275
+ // binding this create to it (and to a leader-independent entityId).
276
+ validatorRules,
277
+ creationIntent,
145
278
  });
146
279
  }
147
280
  catch (err) {
148
- throw new Error(`smart-app entity creation failed: ${err.message}`);
281
+ if ((0, create_outcome_1.createWasRefused)(err) || (0, create_outcome_1.createNeverSent)(err)) {
282
+ // The platform rejected the request, or it never left this machine: nothing was created,
283
+ // so nothing is pending and the next run creates normally.
284
+ clearPendingCreate(opts.env);
285
+ throw new Error(`smart-app entity creation failed: ${errorMessage(err)}`, { cause: err });
286
+ }
287
+ throw new Error(`smart-app entity creation failed: ${errorMessage(err)}${unknownCreateNote(expectedEntityId, opts.env, inv)}`, { cause: err });
149
288
  }
150
- if (!created.appId) {
151
- throw new Error('create returned no appId (DKG entityId) — server contract violation');
289
+ if (!created?.appId) {
290
+ // The platform answered (even with an empty 2xx body), but without the entity: it may well
291
+ // exist at `expectedEntityId`.
292
+ throw new Error('create returned no appId (DKG entityId) — server contract violation' +
293
+ unknownCreateNote(expectedEntityId, opts.env, inv));
294
+ }
295
+ // #3506 A3 / #3636 crypto review — defence in depth: never trust the
296
+ // server's returned id alone. A mismatch means the entity was NOT created
297
+ // at the id the signed intent derives; treat the response as untrusted and
298
+ // stop here — do NOT continue into the deposit / subscription steps below.
299
+ try {
300
+ (0, smart_engines_sdk_1.assertCreatedEntityMatchesIntent)(created.appId, expectedEntityId);
301
+ }
302
+ catch (err) {
303
+ // The create DID answer — with an id the intent does not authorize. It is not "unknown"
304
+ // any more, so it stays no longer pending (and is never resumed).
305
+ clearPendingCreate(opts.env);
306
+ // HIGH-1(b): the server DID create something — at `created.appId` — it
307
+ // is just not the id the signed intent authorizes. That entity (and any
308
+ // subscription minted against it) is now ORPHANED: unaffiliated with
309
+ // this wallet's signed intent. Name it explicitly so the operator can
310
+ // investigate/reclaim it rather than silently losing track of it, and
311
+ // do NOT blindly retry (a retry signs a NEW intent/nonce and, against a
312
+ // cluster with this defect, may orphan yet another entity).
313
+ throw new Error(`entity-create intent mismatch — the create is UNTRUSTED and will NOT be used. ` +
314
+ `The server created an ORPHANED entity at appId "${created.appId}" (a subscription ` +
315
+ `may exist on it, unaffiliated with your wallet). Do NOT retry blindly. Record ` +
316
+ `"${created.appId}" and investigate the cluster (bug, stale validator missing ` +
317
+ `#3635, or compromise) before creating again. Original error: ${errorMessage(err)}`);
152
318
  }
153
319
  appId = created.appId;
320
+ // #3754 — record the entity BEFORE any further step (deposit instructions,
321
+ // payment, mint). Every one of them can fail, and a failed payment used to
322
+ // throw before the end-of-run `upsertEnv`, leaving only the `hsuite init`
323
+ // placeholder in the env file — so the retry created a SECOND DKG entity,
324
+ // subscription, order and funded deposit account.
325
+ persistCreatedEntity(opts.env, appId, inv);
154
326
  }
155
327
  // Step 2: obtain the HST deposit instructions for THIS entityId. createApp
156
328
  // normally returns them (the subscription was created alongside the entity).
@@ -173,57 +345,118 @@ async function runSubscribe(opts) {
173
345
  });
174
346
  }
175
347
  catch (err) {
176
- throw new Error(`subscription request failed: ${err.message}`);
348
+ throw new Error(`subscription request failed: ${errorMessage(err)}${unpaidNote(appId, opts.env, inv)}`, {
349
+ cause: err,
350
+ });
177
351
  }
178
352
  deposit = requested.depositInstructions;
179
353
  subscriptionId = subscriptionId ?? requested.subscriptionId;
180
354
  }
181
- if (!deposit) {
355
+ // #3411 — a RESUMED run asks the platform where the subscription stands
356
+ // BEFORE it pays anything. `GET /status` verifies a pending deposit on read
357
+ // (`checkSubscriptionStatus`), so it is fresher than the idempotent `request`
358
+ // replay above, which only echoes the stored row: a deposit paid by hand a
359
+ // moment ago (the `--no-autopay` flow) or by a previous run whose poll timed
360
+ // out can already show as credited here. ADVISORY, not a guarantee: deposit
361
+ // accounts are not replicated, so only the cluster that holds this one
362
+ // verifies on read — through the gateway another cluster answers from the
363
+ // replicated row and can still say `pending_deposit` for a payment sent a
364
+ // minute ago. An answer that cannot confirm the deposit is still owed (a failed
365
+ // read, `not_found`) blocks the payment rather than risk paying twice.
366
+ const standing = preexistingAppId
367
+ ? await readStandingBeforePaying(client, appId, opts.env, inv)
368
+ : undefined;
369
+ const creditedAs = [standing?.status, requested?.status].find(isReadyToMint);
370
+ if (!deposit && standing) {
182
371
  // No deposit instructions. On a RESUME of an already-active subscription
183
372
  // (--app-id / SUBSCRIPTION_APP_ID, deposit long paid, NFT possibly minted),
184
- // this is EXPECTED — not a contract violation. Check /status: if the
185
- // subscription is already provisioned, skip deposit+pay+mint and go straight
186
- // to accepting the brokered sell offer so the NFT lands on the dev wallet.
187
- if (preexistingAppId) {
188
- const existing = await client.status(appId);
189
- const alreadyProvisioned = Boolean(existing.subscriptionNftSerial) ||
190
- Boolean(existing.chainNfts?.xrpl?.nftId) ||
191
- (existing.status ?? '').toLowerCase() === 'active';
192
- if (alreadyProvisioned) {
193
- // NFT coordinates can lag the 'active' status by a few ledgers.
194
- const status = existing.subscriptionNftSerial || existing.chainNfts?.xrpl?.nftId
195
- ? existing
196
- : await pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) || Boolean(s.chainNfts?.xrpl?.nftId), opts.nftPollAttempts ?? 24);
197
- const nftAccepted = await acceptSubscriptionNft(opts, address, seed, sleep, status);
198
- return {
199
- appId,
200
- subscriptionId: status.subscriptionId ?? subscriptionId,
201
- nftSerial: status.subscriptionNftSerial,
202
- tier,
203
- status: status.status,
204
- depositPaid: true,
205
- nftAccepted,
206
- };
207
- }
373
+ // this is EXPECTED — not a contract violation. If the subscription is
374
+ // already provisioned, skip deposit+pay+mint and go straight to accepting
375
+ // the brokered sell offer so the NFT lands on the dev wallet.
376
+ const alreadyProvisioned = Boolean(standing.subscriptionNftSerial) ||
377
+ Boolean(standing.chainNfts?.xrpl?.nftId) ||
378
+ (standing.status ?? '').toLowerCase() === 'active';
379
+ if (alreadyProvisioned) {
380
+ // NFT coordinates can lag the 'active' status by a few ledgers.
381
+ const status = standing.subscriptionNftSerial || standing.chainNfts?.xrpl?.nftId
382
+ ? standing
383
+ : await pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) || Boolean(s.chainNfts?.xrpl?.nftId), opts.nftPollAttempts ?? 24);
384
+ const nftAccepted = await acceptSubscriptionNft(opts, address, seed, sleep, status);
385
+ return {
386
+ appId,
387
+ subscriptionId: status.subscriptionId ?? subscriptionId,
388
+ nftSerial: status.subscriptionNftSerial,
389
+ tier,
390
+ status: status.status,
391
+ depositPaid: true,
392
+ nftAccepted,
393
+ };
208
394
  }
209
- throw new Error('no depositInstructions for the created entity — server contract violation');
210
- }
211
- renderDepositInstructions(deposit, tier, appId);
212
- // Step 3: auto-pay the deposit from the dev wallet (unless --no-autopay).
213
- if (opts.noAutopay) {
214
- renderManualPaymentHint(deposit);
215
- return {
216
- appId,
217
- subscriptionId,
218
- tier,
219
- status: requested?.status ?? 'pending_deposit',
220
- depositPaid: false,
221
- nftAccepted: false,
222
- };
223
395
  }
224
- await payDeposit(opts, address, seed, deposit);
396
+ // Set once THIS run's deposit payment validated; every later failure then
397
+ // says so (see `afterDeposit`).
398
+ let paid;
399
+ const afterDeposit = async (step) => {
400
+ try {
401
+ return await step();
402
+ }
403
+ catch (err) {
404
+ throw paid ? paidThenFailed(err, paid, appId, opts.env, inv) : err;
405
+ }
406
+ };
407
+ if (creditedAs) {
408
+ // Credited, so there is nothing left to pay — however the run was started
409
+ // (`--no-autopay` only governs PAYING): carry on to mint + accept. This is
410
+ // what makes `--no-autopay`, pay by hand, re-run `hsuite subscribe` safe.
411
+ console.log(chalk_1.default.yellow(` deposit already credited (status=${creditedAs}) — not paying again`));
412
+ }
413
+ else {
414
+ if (!deposit) {
415
+ throw new Error(preexistingAppId
416
+ ? `no depositInstructions returned for saved entity ${appId} — usually because the node that ` +
417
+ 'answered holds no deposit-account record for it (deposit accounts are not replicated ' +
418
+ `between clusters), so it cannot say what to pay${unpaidNote(appId, opts.env, inv)} ` +
419
+ 'Try again in a minute: a retry can reach a node that has it.'
420
+ : 'no depositInstructions for the created entity — server contract violation');
421
+ }
422
+ // #3699 D8 / #3765 — never put an expired quote in front of a payer, on EITHER path:
423
+ // requote first if the deadline has already passed, then show / pay the NEW amount and tag.
424
+ // (A manual payer used to be shown whatever the replay re-attached, expired or not.)
425
+ try {
426
+ deposit = await (0, order_deadline_1.ensureUnexpiredQuote)(client, deposit);
427
+ }
428
+ catch (err) {
429
+ throw new Error(`could not requote the expired quote for order ${deposit.orderId ?? 'n/a'}: ` +
430
+ `${errorMessage(err)}${unpaidNote(appId, opts.env, inv)}`, { cause: err });
431
+ }
432
+ // A resumed entity keeps the tier it was created with, which this run's
433
+ // --tier says nothing about: print the tier only for an entity created now.
434
+ renderDepositInstructions(deposit, preexistingAppId ? undefined : tier, appId);
435
+ // Step 3: auto-pay the deposit from the dev wallet (unless --no-autopay).
436
+ if (opts.autopay === false) {
437
+ renderManualPaymentHint(deposit);
438
+ return {
439
+ appId,
440
+ subscriptionId,
441
+ tier,
442
+ status: standing?.status ?? requested?.status ?? 'pending_deposit',
443
+ depositPaid: false,
444
+ nftAccepted: false,
445
+ };
446
+ }
447
+ try {
448
+ paid = await payDeposit(opts, address, seed, deposit);
449
+ }
450
+ catch (err) {
451
+ // #3754 — the entity exists whether or not this payment did (it is already
452
+ // saved above). Say so, and how to resume it, so a failed payment never
453
+ // reads as "start over".
454
+ throw paymentFailure(err, { appId, subscriptionId, deposit, address, envPath: opts.env, inv });
455
+ }
456
+ console.log(chalk_1.default.gray(` deposit payment validated${paid.hash ? ` (tx ${paid.hash})` : ''}`));
457
+ }
225
458
  // Step 3: poll /status until the deposit is confirmed and ready to mint.
226
- await pollStatus(client, appId, sleep, opts, (s) => isReadyToMint(s.status));
459
+ await afterDeposit(() => pollStatus(client, appId, sleep, opts, (s) => isReadyToMint(s.status)));
227
460
  // Step 4: POST /mint — kicks off the async NFT mint. Tolerate a non-2xx here
228
461
  // (the server may still be finalizing); the status poll below is the source of
229
462
  // truth for whether the NFT actually minted.
@@ -234,18 +467,18 @@ async function runSubscribe(opts) {
234
467
  }
235
468
  }
236
469
  catch (err) {
237
- console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${err.message}`));
470
+ console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${errorMessage(err)}`));
238
471
  }
239
472
  // Step 5: poll until the NFT serial is set OR the minted NFT coordinates
240
473
  // appear on /status (the NFT mints asynchronously via the mint subscriber).
241
474
  // The 2-of-3 issuer MPC mint + offer creation take ~15-25s, so poll ~24×5s
242
475
  // (~120s) before giving up. Bounded by attempt count (not wall-clock) so the
243
476
  // injected-`sleep` unit tests stay fast.
244
- const status = await pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) ||
477
+ const status = await afterDeposit(() => pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) ||
245
478
  Boolean(s.chainNfts?.xrpl?.nftId) ||
246
- (s.status ?? '').toLowerCase() === 'active', opts.nftPollAttempts ?? 24);
479
+ (s.status ?? '').toLowerCase() === 'active', opts.nftPollAttempts ?? 24));
247
480
  // Step 6: accept the brokered sell offer so the NFT lands on the dev wallet.
248
- const nftAccepted = await acceptSubscriptionNft(opts, address, seed, sleep, status);
481
+ const nftAccepted = await afterDeposit(() => acceptSubscriptionNft(opts, address, seed, sleep, status));
249
482
  return {
250
483
  appId,
251
484
  subscriptionId: status.subscriptionId ?? subscriptionId,
@@ -272,6 +505,255 @@ function toDnsSafeName(name) {
272
505
  .replace(/-+$/g, '');
273
506
  return slug.length > 0 ? slug : 'smart-app';
274
507
  }
508
+ /**
509
+ * A printable reason for whatever was thrown. An `Error` gives its message (its
510
+ * name when the message is empty); a thrown string is itself; anything else is
511
+ * JSON — never "undefined" and never "[object Object]".
512
+ */
513
+ function errorMessage(err) {
514
+ if (err instanceof Error)
515
+ return err.message || err.name;
516
+ if (typeof err === 'string')
517
+ return err;
518
+ try {
519
+ return JSON.stringify(err) ?? String(err);
520
+ }
521
+ catch {
522
+ return String(err);
523
+ }
524
+ }
525
+ /** `value` as one shell word: left as is when it is plain, else single-quoted. */
526
+ function shellQuote(value) {
527
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
528
+ }
529
+ /**
530
+ * The command that resumes `appId`, ready to paste: the entity AND the env file it
531
+ * is saved in. `--no-autopay` makes it unable to pay, so it is what to run after a
532
+ * payment that may already have gone through — it still mints and accepts the NFT
533
+ * as soon as the platform credits the deposit.
534
+ */
535
+ function resumeCommand(appId, envPath, flags = {}) {
536
+ return (`hsuite subscribe --app-id ${shellQuote(appId)} --env ${shellQuote(envPath)}` +
537
+ (flags.gateway ? ` --gateway ${shellQuote(flags.gateway)}` : '') +
538
+ (flags.neverPay ? ' --no-autopay' : ''));
539
+ }
540
+ /** {@link resumeCommand}'s flags for a run started as `inv`; `neverPay` forces the can-never-pay form. */
541
+ function resumeFlags(inv, neverPay = false) {
542
+ return { neverPay: neverPay || inv.neverPay, ...(inv.gateway ? { gateway: inv.gateway } : {}) };
543
+ }
544
+ /** The tail of a failure that happens after the entity is saved but BEFORE any payment. */
545
+ function unpaidNote(appId, envPath, inv) {
546
+ return (` — smart-app entity ${appId} is saved and NOTHING has been paid. Re-run ` +
547
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it (that will NOT create a second entity).`);
548
+ }
549
+ /**
550
+ * The deposit payment left this process but no verdict came back (a timeout, a
551
+ * dropped websocket …): it may still validate. A plain "fix the cause and re-run"
552
+ * would invite a second payment, so it gets its own message (see `paymentFailure`).
553
+ */
554
+ class PaymentOutcomeUnknownError extends Error {
555
+ constructor(cause) {
556
+ super(errorMessage(cause), { cause });
557
+ this.name = 'PaymentOutcomeUnknownError';
558
+ }
559
+ }
560
+ /** The error for a payment that did not go through (or may not have) — see {@link PaymentOutcomeUnknownError}. */
561
+ function paymentFailure(err, ctx) {
562
+ const entity = `smart-app entity ${ctx.appId} (subscription ${ctx.subscriptionId ?? 'n/a'}, ` +
563
+ `order ${ctx.deposit.orderId ?? 'n/a'})`;
564
+ if (err instanceof DepositAlreadyOnLedgerError) {
565
+ return new Error(`${errorMessage(err)} (the order is covered at ${err.threshold} HST) — it looks paid, but the platform has not ` +
566
+ `credited it yet. NOT paying again. ${entity} is saved. Give the platform about a minute, then run ` +
567
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it mints and ` +
568
+ 'accepts the NFT once the platform credits the deposit. If that balance is NOT a payment for this ' +
569
+ 'order, the same command prints what to pay by hand.', { cause: err });
570
+ }
571
+ if (err instanceof PaymentOutcomeUnknownError) {
572
+ return new Error(`${errorMessage(err)} — the payment was submitted but its outcome is UNKNOWN: it may still ` +
573
+ `validate. ${entity} is saved. BEFORE re-running, check whether ${ctx.address} already sent ` +
574
+ `HST to ${ctx.deposit.walletAddress} (an XRPL testnet explorer shows it): re-running can pay ` +
575
+ 'AGAIN. If it did go through, wait about a minute and run ' +
576
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it ` +
577
+ 'mints and accepts the NFT once the platform credits the deposit.', { cause: err });
578
+ }
579
+ return new Error(`${errorMessage(err)} — ${entity} is NOT orphaned. Fix the cause, then re-run ` +
580
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv))}\` to resume it — that will NOT create a second entity.`, { cause: err });
581
+ }
582
+ /** The error for a step that failed AFTER this run's deposit payment validated. */
583
+ function paidThenFailed(err, receipt, appId, envPath, inv) {
584
+ return new Error(`${errorMessage(err)} — the deposit payment${receipt.hash ? ` (tx ${receipt.hash})` : ''} WAS validated ` +
585
+ 'on the ledger: do NOT pay again. Give the platform about a minute to credit it, then run ' +
586
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv, true))}\` — it cannot pay, and it finishes minting ` +
587
+ 'and accepting the NFT.', { cause: err });
588
+ }
589
+ /**
590
+ * Ask the platform where a RESUMED subscription stands before anything is paid
591
+ * (#3411). Throws — with nothing paid — when it cannot be read, or when the node
592
+ * that answered has no such subscription (`hasSubscription: false`, `not_found`:
593
+ * a cluster that has not replicated it yet, or one that does not recognise this
594
+ * wallet as its owner). Neither answer shows the deposit is still owed, and
595
+ * paying on a "don't know" is how a deposit gets paid twice.
596
+ */
597
+ async function readStandingBeforePaying(client, appId, envPath, inv) {
598
+ let standing;
599
+ try {
600
+ standing = await client.status(appId);
601
+ }
602
+ catch (err) {
603
+ throw new Error(`could not read where subscription ${appId} stands (${errorMessage(err)})${unpaidNote(appId, envPath, inv)}`, { cause: err });
604
+ }
605
+ if (standing.hasSubscription === false) {
606
+ throw new Error(`the platform that answered has no subscription for smart-app entity ${appId} that this wallet ` +
607
+ `owns (status=${standing.status ?? 'unknown'}) — the cluster may not have replicated it yet, or ` +
608
+ `the entity belongs to another wallet${unpaidNote(appId, envPath, inv)} Try again in a minute.`);
609
+ }
610
+ return standing;
611
+ }
612
+ /**
613
+ * Save a freshly created (or adopted, see {@link reconcileUnfinishedCreate}) entity as
614
+ * `SUBSCRIPTION_APP_ID` (+ `APP_ID` — the same pair the end-of-run write and the
615
+ * `--no-autopay` path produce) so a re-run RESUMES it instead of creating a second one (#3754),
616
+ * and then clears the pending-create record: the create has its verdict now (#3766).
617
+ *
618
+ * Fails loud, and BEFORE any payment, when the file cannot be written: an entity
619
+ * the CLI cannot keep track of must not be paid for, and the error carries the id
620
+ * so the developer can resume it explicitly with `--app-id`.
621
+ */
622
+ function persistCreatedEntity(envPath, appId, inv) {
623
+ try {
624
+ (0, env_1.upsertEnv)(envPath, { SUBSCRIPTION_APP_ID: appId, APP_ID: appId });
625
+ }
626
+ catch (err) {
627
+ throw new Error(`smart-app entity ${appId} was created but could not be saved to ${envPath} ` +
628
+ `(${errorMessage(err)}). Nothing has been paid. Re-run ` +
629
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it.`, { cause: err });
630
+ }
631
+ // The create has its verdict now: it is no longer pending.
632
+ clearPendingCreate(envPath);
633
+ }
634
+ /**
635
+ * The command that retries a `subscribe` WITHOUT naming an entity: it reconciles an unfinished
636
+ * create first (#3766) and, if that earlier create is dead, creates a fresh entity — so it repeats
637
+ * the tier, name and gateway this run was started with, and `--no-autopay`.
638
+ */
639
+ function rerunCommand(envPath, inv) {
640
+ return (`hsuite subscribe --env ${shellQuote(envPath)} --tier ${shellQuote(inv.tier)}` +
641
+ (inv.appName ? ` --app-name ${shellQuote(inv.appName)}` : '') +
642
+ (inv.gateway ? ` --gateway ${shellQuote(inv.gateway)}` : '') +
643
+ (inv.neverPay ? ' --no-autopay' : ''));
644
+ }
645
+ /**
646
+ * Record the create of `entityId` as pending BEFORE it is sent (#3766). Fails loud — with
647
+ * nothing sent — when the file cannot be written: a create this CLI cannot keep track of is
648
+ * exactly the one it would orphan.
649
+ */
650
+ function recordPendingCreate(envPath, entityId, until) {
651
+ try {
652
+ (0, env_1.upsertEnv)(envPath, { [create_outcome_1.PENDING_CREATE_KEY]: (0, create_outcome_1.formatPendingCreate)({ appId: entityId, until }) });
653
+ }
654
+ catch (err) {
655
+ throw new Error(`cannot record the create of smart-app entity ${entityId} in ${envPath} (${errorMessage(err)}) — ` +
656
+ 'refusing to send it: a create this CLI cannot keep track of could be orphaned. ' +
657
+ 'Nothing was created and nothing has been paid.', { cause: err });
658
+ }
659
+ }
660
+ /**
661
+ * Forget the pending create. Best effort: a record that survives is only ever PROBED by the next
662
+ * run (never trusted), and is ignored outright once SUBSCRIPTION_APP_ID is set — so a failed
663
+ * removal can cost a delay, never an orphan.
664
+ */
665
+ function clearPendingCreate(envPath) {
666
+ try {
667
+ (0, env_1.removeEnvKeys)(envPath, [create_outcome_1.PENDING_CREATE_KEY]);
668
+ }
669
+ catch {
670
+ // see above
671
+ }
672
+ }
673
+ /** The tail of a failure that leaves a create's outcome unknown: the entity may exist (#3766). */
674
+ function unknownCreateNote(expectedEntityId, envPath, inv) {
675
+ return (` — its outcome is UNKNOWN: the platform may still have created smart-app entity ${expectedEntityId} ` +
676
+ '(the create is a long ceremony and this client may have given up before it finished). Nothing has ' +
677
+ `been paid. Re-run \`${rerunCommand(envPath, inv)}\`: it asks the platform whether ${expectedEntityId} ` +
678
+ 'exists and RESUMES it if it does — it will not create a second one.');
679
+ }
680
+ /** How to get unstuck when the CLI cannot settle a recorded create by itself. */
681
+ function forgetPendingHint(envPath) {
682
+ return (`If you are sure the earlier create never reached the platform, delete the ${create_outcome_1.PENDING_CREATE_KEY} ` +
683
+ `line from ${envPath} and re-run.`);
684
+ }
685
+ /**
686
+ * Settle an earlier create that ended without a verdict (#3766), before this run creates
687
+ * anything. Asks the platform about the recorded entity:
688
+ * - it EXISTS → adopt it (saved as SUBSCRIPTION_APP_ID) and resume it: the earlier create did
689
+ * complete, and a second entity would orphan it;
690
+ * - it does not, but the earlier create may still be completing (or the answer is not a plain
691
+ * "no") → refuse: creating now could leave TWO entities;
692
+ * - it does not and the signed intent has run out (its `exp` plus a grace) → the earlier create
693
+ * is dead; carry on and create a fresh entity;
694
+ * - the platform cannot be asked, or the record is not one this CLI wrote → refuse (nothing created).
695
+ *
696
+ * @returns the entity id to resume, or `undefined` to create a fresh one.
697
+ */
698
+ async function reconcileUnfinishedCreate(client, env, envPath, inv) {
699
+ const raw = env.get(create_outcome_1.PENDING_CREATE_KEY);
700
+ if (!raw)
701
+ return undefined;
702
+ const pending = (0, create_outcome_1.parsePendingCreate)(raw);
703
+ if (!pending) {
704
+ // Fail closed: a record this CLI did not write cannot say whether an earlier create is still
705
+ // outstanding, and ignoring it is how a second entity gets created.
706
+ throw new Error(`${create_outcome_1.PENDING_CREATE_KEY} in ${envPath} is not a record this CLI wrote (${JSON.stringify(raw)}), so it ` +
707
+ 'cannot tell whether an earlier create is still outstanding — nothing has been created or paid now. ' +
708
+ forgetPendingHint(envPath));
709
+ }
710
+ const earlier = `an earlier \`hsuite subscribe\` asked the platform to create smart-app entity ${pending.appId} ` +
711
+ 'and never got an answer';
712
+ let standing;
713
+ try {
714
+ standing = await client.status(pending.appId);
715
+ }
716
+ catch (err) {
717
+ throw new Error(`${earlier}, and the platform could not be asked whether it exists (${errorMessage(err)}) — ` +
718
+ `nothing has been created or paid now. Re-run \`${rerunCommand(envPath, inv)}\` in a minute. ` +
719
+ forgetPendingHint(envPath), { cause: err });
720
+ }
721
+ if (standing.hasSubscription === true) {
722
+ console.log(chalk_1.default.yellow(` the earlier create DID complete: smart-app entity ${pending.appId} exists — resuming it, not creating another`));
723
+ persistCreatedEntity(envPath, pending.appId, inv);
724
+ return pending.appId;
725
+ }
726
+ if (standing.hasSubscription === false && Date.now() >= pending.until) {
727
+ console.log(chalk_1.default.yellow(` the earlier create of ${pending.appId} never completed and its signed intent has run out — creating a fresh entity`));
728
+ return undefined;
729
+ }
730
+ throw new Error(`${earlier}. The platform does not show it (yet), and that create may still be completing (its signed ` +
731
+ `intent should have run out by ${new Date(pending.until).toISOString()}) — creating another entity now ` +
732
+ 'could leave two entities. Re-run ' +
733
+ `\`${rerunCommand(envPath, inv)}\` after that time; sooner, the moment the platform shows ` +
734
+ `${pending.appId}, it is resumed. ${forgetPendingHint(envPath)}`);
735
+ }
736
+ /**
737
+ * Write the end-of-run env updates. A failure is REPORTED, not thrown: by now the
738
+ * entity is created and saved ({@link persistCreatedEntity}), the deposit paid and
739
+ * the NFT minted, and an error after "subscription active" would read as the whole
740
+ * run having failed. The values are printed so they can be added by hand.
741
+ *
742
+ * @returns whether the file was written.
743
+ */
744
+ function saveEnv(envPath, updates) {
745
+ try {
746
+ (0, env_1.upsertEnv)(envPath, updates);
747
+ return true;
748
+ }
749
+ catch (err) {
750
+ console.log(chalk_1.default.yellow(`\n could not write ${envPath} (${errorMessage(err)}) — add these by hand:`));
751
+ for (const [key, value] of Object.entries(updates)) {
752
+ console.log(chalk_1.default.yellow(` ${key}=${value}`));
753
+ }
754
+ return false;
755
+ }
756
+ }
275
757
  /**
276
758
  * Pay the HST deposit from the dev wallet over the XRPL testnet.
277
759
  *
@@ -281,7 +763,20 @@ function toDnsSafeName(name) {
281
763
  * submit a `Payment` of `amount` whole HST with a `SendMax` of
282
764
  * `amount × 1.004` to cover the 0.25% HST transfer fee.
283
765
  *
284
- * Requires tesSUCCESS. Always disconnects.
766
+ * #3699 PR1a — when `deposit.destinationTag` is present (the validator wired
767
+ * a price-locked SubscriptionOrder), the Payment carries it as
768
+ * `DestinationTag` so PR1b's `account_tx` matcher (keyed on the tag, never
769
+ * bare `Amount` — the XRPL partial-payment protection) can find this
770
+ * payment. Omitted entirely, not sent as `0`/`undefined`, when absent (older
771
+ * server / order creation unavailable) — unchanged from pre-#3699 behavior.
772
+ *
773
+ * #3771 — BEFORE anything is signed or submitted, the deposit account's HST balance is read from
774
+ * the ledger and the payment is refused ({@link DepositAlreadyOnLedgerError}) when the account
775
+ * already holds what the quote asks, or when that balance cannot be read at all.
776
+ *
777
+ * Requires tesSUCCESS. Always disconnects. A thrown wait for the verdict (the
778
+ * blob is already out) surfaces as {@link PaymentOutcomeUnknownError}; a `tec*` /
779
+ * `tem*` verdict is a plain failure — nothing was delivered.
285
780
  */
286
781
  async function payDeposit(opts, address, seed, deposit) {
287
782
  if (deposit.chain !== 'xrpl') {
@@ -292,7 +787,11 @@ async function payDeposit(opts, address, seed, deposit) {
292
787
  const client = (opts.xrplClientFactory ?? defaultXrplClientFactory)(XRPL_TESTNET_WSS);
293
788
  await client.connect();
294
789
  try {
295
- const issuer = await resolveHstIssuer(client, deposit.walletAddress);
790
+ const { issuer, balance } = await readDepositHstLine(client, deposit.walletAddress);
791
+ // #3771 — the LEDGER is the one source of truth every cluster agrees on: a deposit
792
+ // account that already holds what this quote asks has been paid, whatever a replica's
793
+ // `/status` still says. Nothing is signed or submitted past this point on a refusal.
794
+ refuseIfAlreadyOnLedger(deposit, balance);
296
795
  const value = deposit.amount;
297
796
  const sendMax = (Number(value) * HST_TRANSFER_FEE_MULTIPLIER).toFixed(6);
298
797
  const tx = {
@@ -301,34 +800,96 @@ async function payDeposit(opts, address, seed, deposit) {
301
800
  Destination: deposit.walletAddress,
302
801
  Amount: { currency: 'HST', issuer, value },
303
802
  SendMax: { currency: 'HST', issuer, value: sendMax },
803
+ ...(deposit.destinationTag !== undefined ? { DestinationTag: deposit.destinationTag } : {}),
304
804
  };
305
805
  const prepared = await client.autofill(tx);
306
806
  const txBlob = walletSign(prepared);
307
- const result = await client.submitAndWait(txBlob);
807
+ let result;
808
+ try {
809
+ result = await client.submitAndWait(txBlob);
810
+ }
811
+ catch (err) {
812
+ // The blob has left this process: the ledger may still validate it.
813
+ throw new PaymentOutcomeUnknownError(err);
814
+ }
308
815
  const code = result.result?.meta?.TransactionResult;
816
+ if (code === undefined) {
817
+ // No verdict in the answer: not a failure the ledger reported.
818
+ throw new PaymentOutcomeUnknownError(new Error('deposit Payment came back with no transaction result'));
819
+ }
309
820
  if (code !== 'tesSUCCESS') {
310
- throw new Error(`deposit Payment failed: ${code ?? 'unknown result'}`);
821
+ throw new Error(`deposit Payment failed: ${code}`);
311
822
  }
823
+ return { hash: result.result?.hash };
312
824
  }
313
825
  finally {
314
- await client.disconnect();
826
+ // A failing disconnect (a dead socket) must not replace the error that got us here — above all
827
+ // not a refusal to pay twice, or a payment whose outcome is unknown.
828
+ await client.disconnect().catch(() => undefined);
315
829
  }
316
830
  }
317
831
  /**
318
- * Resolve the HST issuer from the deposit account's trust lines.
832
+ * Read the deposit account's HST trust line: the HST issuer and what the account holds.
319
833
  *
320
834
  * The deposit account holds an HST trust line whose peer (`account`) is the HST
321
835
  * issuer. We query `account_lines` on the deposit wallet and return the peer of
322
- * the line whose `currency` is 'HST'.
836
+ * the line whose `currency` is 'HST', and that line's `balance` — what the
837
+ * account holds, as the LEDGER reports it (#3771).
323
838
  */
324
- async function resolveHstIssuer(client, depositWallet) {
839
+ async function readDepositHstLine(client, depositWallet) {
840
+ // No `ledger_index`: the server's default view answers (rippled: the open ledger, which also
841
+ // shows a payment that has not validated yet — the safe side for "is it already paid?").
325
842
  const res = await client.request({ command: 'account_lines', account: depositWallet });
326
843
  const lines = res.result?.lines ?? [];
327
844
  const hst = lines.find((l) => l?.currency === 'HST');
328
845
  if (!hst?.account) {
329
846
  throw new Error(`could not resolve HST issuer: deposit account ${depositWallet} has no HST trust line`);
330
847
  }
331
- return hst.account;
848
+ return { issuer: hst.account, balance: String(hst.balance ?? '') };
849
+ }
850
+ /**
851
+ * The deposit account already holds what the quote asks, but the platform has not credited it
852
+ * (#3771). Thrown INSTEAD of paying: the payment is on the ledger already.
853
+ */
854
+ class DepositAlreadyOnLedgerError extends Error {
855
+ threshold;
856
+ constructor(depositWallet, balance, threshold) {
857
+ super(`deposit account ${depositWallet} already holds ${balance} HST on the ledger`);
858
+ this.threshold = threshold;
859
+ this.name = 'DepositAlreadyOnLedgerError';
860
+ }
861
+ }
862
+ /**
863
+ * Refuse to pay when the deposit account's ledger balance already covers the quote (#3771).
864
+ *
865
+ * `GET /status` is only authoritative on the cluster that holds the deposit account, so a
866
+ * resumed run that reaches another cluster can read `pending_deposit` for a payment sent a
867
+ * minute ago, and pay AGAIN. The ledger has no such lag.
868
+ *
869
+ * The threshold is what the quote ASKS, except for a REQUOTED order, which asks only for the
870
+ * REMAINDER (the total at the new rate minus what the platform already counted): the account
871
+ * then still holds the earlier, short payment, so the remainder alone would refuse a payment
872
+ * that is genuinely owed. `hsuiteDue` is the whole base price, so the larger of the two is the
873
+ * balance that means "paid in full" either way.
874
+ *
875
+ * FAILS CLOSED: a balance (or a quote `amount`) that cannot be read as a number is an error,
876
+ * never a "carry on and pay". An unreadable `hsuiteDue` is ignored — the threshold stays the
877
+ * `amount`, which is the safe direction. (XRPL HST is whole-unit, so `amount` and `hsuiteDue`
878
+ * share one scale; `payDeposit` pays XRPL deposits only.)
879
+ */
880
+ function refuseIfAlreadyOnLedger(deposit, balance) {
881
+ let threshold = deposit.amount;
882
+ if (deposit.hsuiteDue !== undefined && (0, decimal_compare_1.compareDecimals)(deposit.hsuiteDue, threshold) === 1) {
883
+ threshold = deposit.hsuiteDue;
884
+ }
885
+ const held = (0, decimal_compare_1.compareDecimals)(balance, threshold);
886
+ if (held === undefined) {
887
+ throw new Error(`could not read the HST balance of deposit account ${deposit.walletAddress} ` +
888
+ `(the ledger said ${JSON.stringify(balance)}, the quote asks ${deposit.amount}) — ` +
889
+ 'refusing to pay without knowing the account does not already hold it');
890
+ }
891
+ if (held >= 0)
892
+ throw new DepositAlreadyOnLedgerError(deposit.walletAddress, balance, threshold);
332
893
  }
333
894
  /**
334
895
  * Ready-to-mint check.
@@ -505,13 +1066,35 @@ async function findSellOfferIndexByNftId(client, nftId, recipient) {
505
1066
  const match = offers.find((o) => o?.destination === recipient) ?? offers[0];
506
1067
  return match?.nft_offer_index;
507
1068
  }
1069
+ /** `tier` is omitted for a RESUMED entity: it keeps the tier it was created with, not this run's `--tier`. */
508
1070
  function renderDepositInstructions(d, tier, appId) {
509
1071
  console.log(chalk_1.default.bold.green(`\n Subscription requested: ${appId}`));
510
1072
  console.log(chalk_1.default.bold.yellow('\n Deposit required to mint your subscription NFT:'));
511
- console.log(chalk_1.default.gray(` tier: ${tier}`));
1073
+ if (tier)
1074
+ console.log(chalk_1.default.gray(` tier: ${tier}`));
512
1075
  console.log(chalk_1.default.gray(` chain: ${d.chain}`));
513
1076
  console.log(chalk_1.default.gray(` amount: ${d.amount} HST (token ${d.tokenId})`));
514
- console.log(chalk_1.default.gray(` to: ${d.walletAddress}\n`));
1077
+ renderReserveSurcharge(d);
1078
+ console.log(chalk_1.default.gray(` to: ${d.walletAddress}`));
1079
+ // #3765 — the order is matched by DestinationTag, so a payment that omits it (by hand, from a
1080
+ // wallet whose "destination tag" field was left empty) is not attributed to this order.
1081
+ // `!== undefined`, not truthiness: 0 is a valid tag.
1082
+ if (d.destinationTag !== undefined) {
1083
+ console.log(chalk_1.default.gray(` tag: ${d.destinationTag} (Destination Tag — REQUIRED on the payment)`));
1084
+ }
1085
+ (0, order_deadline_1.renderOrderDeadline)(d);
1086
+ console.log('');
1087
+ }
1088
+ /**
1089
+ * #3022 — show the reserve surcharge as its own line item. It is already inside
1090
+ * `amount`; the user still makes ONE HST payment.
1091
+ */
1092
+ function renderReserveSurcharge(d) {
1093
+ if (!d.reserveSurcharge)
1094
+ return;
1095
+ const xrp = Number(d.reserveSurcharge.xrpOutlayDrops) / 1_000_000;
1096
+ console.log(chalk_1.default.gray(` base: ${d.baseAmount ?? '?'} HST`));
1097
+ console.log(chalk_1.default.gray(` reserve surcharge: ${d.reserveSurcharge.hstAmount} HST (XRPL account reserve, ${xrp} XRP at ${d.reserveSurcharge.xrpPriceInHst} HST/XRP)`));
515
1098
  }
516
1099
  function renderManualPaymentHint(d) {
517
1100
  const xummDeeplink = buildXummDeeplink(d);
@@ -526,7 +1109,8 @@ function buildXummDeeplink(d) {
526
1109
  // Minimal Xumm deeplink shape; full IssuedCurrency requires a JSON payload
527
1110
  // pushed through https://xumm.app/sign — for the CLI we surface the raw tx
528
1111
  // params so the user can paste them into their wallet.
529
- return `xumm://xrpl/send?to=${encodeURIComponent(d.walletAddress)}&amount=${encodeURIComponent(d.amount)}&token=${encodeURIComponent(d.tokenId)}`;
1112
+ const tag = d.destinationTag !== undefined ? `&dt=${encodeURIComponent(String(d.destinationTag))}` : '';
1113
+ return `xumm://xrpl/send?to=${encodeURIComponent(d.walletAddress)}&amount=${encodeURIComponent(d.amount)}&token=${encodeURIComponent(d.tokenId)}${tag}`;
530
1114
  }
531
1115
  exports.subscribeCommand = new commander_1.Command('subscribe')
532
1116
  .description('Subscribe a smart-app: create DKG entity → auto-pay deposit → mint → accept subscription NFT (mint-first)')
@@ -554,7 +1138,7 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
554
1138
  result = await runSubscribe(opts);
555
1139
  }
556
1140
  catch (err) {
557
- spinner.fail(err.message);
1141
+ spinner.fail(errorMessage(err));
558
1142
  process.exit(1);
559
1143
  }
560
1144
  if (!result.depositPaid) {
@@ -563,8 +1147,9 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
563
1147
  SUBSCRIPTION_APP_ID: result.appId,
564
1148
  APP_ID: result.appId,
565
1149
  };
566
- (0, env_1.upsertEnv)(opts.env, updates);
567
- console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID to ${opts.env}`));
1150
+ if (saveEnv(opts.env, updates)) {
1151
+ console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID to ${opts.env}`));
1152
+ }
568
1153
  console.log(chalk_1.default.yellow('\n Pay the deposit, then re-run `hsuite subscribe` to mint + accept the NFT.\n'));
569
1154
  return;
570
1155
  }
@@ -589,8 +1174,9 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
589
1174
  if (result.nftSerial !== undefined) {
590
1175
  updates.SUBSCRIPTION_NFT_SERIAL = String(result.nftSerial);
591
1176
  }
592
- (0, env_1.upsertEnv)(opts.env, updates);
593
- console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID${result.nftSerial !== undefined ? ' + SUBSCRIPTION_NFT_SERIAL' : ''} to ${opts.env}`));
1177
+ if (saveEnv(opts.env, updates)) {
1178
+ console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID${result.nftSerial !== undefined ? ' + SUBSCRIPTION_NFT_SERIAL' : ''} to ${opts.env}`));
1179
+ }
594
1180
  console.log(chalk_1.default.bold.green('\n ✓ subscribed\n'));
595
1181
  });
596
1182
  //# sourceMappingURL=subscribe.js.map