@hsuite/smart-engines-cli 1.8.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +1 -0
  2. package/dist/__tests__/helpers/xrpl-signing.d.ts +26 -0
  3. package/dist/__tests__/helpers/xrpl-signing.d.ts.map +1 -0
  4. package/dist/__tests__/helpers/xrpl-signing.js +39 -0
  5. package/dist/__tests__/helpers/xrpl-signing.js.map +1 -0
  6. package/dist/_lib/cluster-provisioning-report.d.ts +29 -0
  7. package/dist/_lib/cluster-provisioning-report.d.ts.map +1 -0
  8. package/dist/_lib/cluster-provisioning-report.js +35 -0
  9. package/dist/_lib/cluster-provisioning-report.js.map +1 -0
  10. package/dist/_lib/create-outcome.d.ts +43 -0
  11. package/dist/_lib/create-outcome.d.ts.map +1 -0
  12. package/dist/_lib/create-outcome.js +121 -0
  13. package/dist/_lib/create-outcome.js.map +1 -0
  14. package/dist/_lib/decimal-compare.d.ts +23 -0
  15. package/dist/_lib/decimal-compare.d.ts.map +1 -0
  16. package/dist/_lib/decimal-compare.js +69 -0
  17. package/dist/_lib/decimal-compare.js.map +1 -0
  18. package/dist/_lib/env.d.ts +6 -0
  19. package/dist/_lib/env.d.ts.map +1 -1
  20. package/dist/_lib/env.js +77 -8
  21. package/dist/_lib/env.js.map +1 -1
  22. package/dist/_lib/error-message.d.ts +7 -0
  23. package/dist/_lib/error-message.d.ts.map +1 -0
  24. package/dist/_lib/error-message.js +21 -0
  25. package/dist/_lib/error-message.js.map +1 -0
  26. package/dist/_lib/order-deadline.d.ts +58 -0
  27. package/dist/_lib/order-deadline.d.ts.map +1 -0
  28. package/dist/_lib/order-deadline.js +112 -0
  29. package/dist/_lib/order-deadline.js.map +1 -0
  30. package/dist/_lib/payment-guard.d.ts +59 -0
  31. package/dist/_lib/payment-guard.d.ts.map +1 -0
  32. package/dist/_lib/payment-guard.js +188 -0
  33. package/dist/_lib/payment-guard.js.map +1 -0
  34. package/dist/_lib/payment-lock.d.ts +27 -0
  35. package/dist/_lib/payment-lock.d.ts.map +1 -0
  36. package/dist/_lib/payment-lock.js +199 -0
  37. package/dist/_lib/payment-lock.js.map +1 -0
  38. package/dist/_lib/payment-record.d.ts +70 -0
  39. package/dist/_lib/payment-record.d.ts.map +1 -0
  40. package/dist/_lib/payment-record.js +78 -0
  41. package/dist/_lib/payment-record.js.map +1 -0
  42. package/dist/_lib/runtime-env.d.ts.map +1 -1
  43. package/dist/_lib/runtime-env.js +8 -0
  44. package/dist/_lib/runtime-env.js.map +1 -1
  45. package/dist/_lib/subscription-client.d.ts +136 -5
  46. package/dist/_lib/subscription-client.d.ts.map +1 -1
  47. package/dist/_lib/subscription-client.js +38 -41
  48. package/dist/_lib/subscription-client.js.map +1 -1
  49. package/dist/_lib/xrp-payment.d.ts +33 -0
  50. package/dist/_lib/xrp-payment.d.ts.map +1 -0
  51. package/dist/_lib/xrp-payment.js +99 -0
  52. package/dist/_lib/xrp-payment.js.map +1 -0
  53. package/dist/_lib/xrpl-login-signer.d.ts +54 -0
  54. package/dist/_lib/xrpl-login-signer.d.ts.map +1 -0
  55. package/dist/_lib/xrpl-login-signer.js +102 -0
  56. package/dist/_lib/xrpl-login-signer.js.map +1 -0
  57. package/dist/commands/app-lifecycle.d.ts.map +1 -1
  58. package/dist/commands/app-lifecycle.js +8 -2
  59. package/dist/commands/app-lifecycle.js.map +1 -1
  60. package/dist/commands/deploy.d.ts.map +1 -1
  61. package/dist/commands/deploy.js +8 -0
  62. package/dist/commands/deploy.js.map +1 -1
  63. package/dist/commands/faucet.d.ts +1 -1
  64. package/dist/commands/faucet.d.ts.map +1 -1
  65. package/dist/commands/faucet.js +2 -7
  66. package/dist/commands/faucet.js.map +1 -1
  67. package/dist/commands/personhood.d.ts +2 -2
  68. package/dist/commands/personhood.d.ts.map +1 -1
  69. package/dist/commands/personhood.js +11 -14
  70. package/dist/commands/personhood.js.map +1 -1
  71. package/dist/commands/redeploy.d.ts.map +1 -1
  72. package/dist/commands/redeploy.js +6 -0
  73. package/dist/commands/redeploy.js.map +1 -1
  74. package/dist/commands/subscribe.d.ts +68 -7
  75. package/dist/commands/subscribe.d.ts.map +1 -1
  76. package/dist/commands/subscribe.js +793 -91
  77. package/dist/commands/subscribe.js.map +1 -1
  78. package/dist/commands/topup.d.ts +19 -7
  79. package/dist/commands/topup.d.ts.map +1 -1
  80. package/dist/commands/topup.js +142 -15
  81. package/dist/commands/topup.js.map +1 -1
  82. package/dist/commands/transactions.d.ts +28 -31
  83. package/dist/commands/transactions.d.ts.map +1 -1
  84. package/dist/commands/transactions.js +36 -41
  85. package/dist/commands/transactions.js.map +1 -1
  86. package/dist/commands/upgrade.d.ts.map +1 -1
  87. package/dist/commands/upgrade.js +22 -3
  88. package/dist/commands/upgrade.js.map +1 -1
  89. package/dist/commands/verify.d.ts +19 -2
  90. package/dist/commands/verify.d.ts.map +1 -1
  91. package/dist/commands/verify.js +158 -23
  92. package/dist/commands/verify.js.map +1 -1
  93. package/dist/index.js +0 -4
  94. package/dist/index.js.map +1 -1
  95. package/package.json +2 -2
  96. package/dist/commands/governance.d.ts +0 -42
  97. package/dist/commands/governance.d.ts.map +0 -1
  98. package/dist/commands/governance.js +0 -155
  99. package/dist/commands/governance.js.map +0 -1
  100. package/dist/commands/hist-balance.d.ts +0 -52
  101. package/dist/commands/hist-balance.d.ts.map +0 -1
  102. package/dist/commands/hist-balance.js +0 -134
  103. 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
@@ -41,8 +51,21 @@ exports.runSubscribe = runSubscribe;
41
51
  * second subscription, no second deposit wallet).
42
52
  * 5. Render the deposit instructions.
43
53
  * 6. AUTO-PAY the deposit from the dev wallet over the XRPL testnet (HST
44
- * Payment with a SendMax covering the 0.25% transfer fee). `--no-autopay`
45
- * skips this and prints instructions for manual (XUMM) payment.
54
+ * Payment with a SendMax covering the 0.25% transfer fee; with
55
+ * `--pay-with xrp`, an XRP Payment of the quoted drops carrying the order's
56
+ * Destination Tag, #3699 PR2). `--no-autopay`
57
+ * skips this and prints instructions for manual (XUMM) payment; re-running
58
+ * `hsuite subscribe` afterwards resumes the saved entity. A RESUMED run first
59
+ * asks GET /status and never pays a deposit the platform reports credited
60
+ * (deposit_confirmed / active), nor on an answer that cannot confirm the
61
+ * deposit is still owed (a failed read, `not_found`) (#3411). That read is
62
+ * ADVISORY, not a guarantee: only the cluster that holds the deposit account
63
+ * verifies on read, so another cluster can still answer `pending_deposit` for
64
+ * a payment sent a minute ago. The LEDGER is the source of truth every cluster
65
+ * agrees on, so before paying the CLI reads the deposit account's HST trust-line
66
+ * balance and refuses when it already holds what the quote asks (#3771). After a
67
+ * payment whose outcome is unknown, or that already validated, the error says so
68
+ * and points at `--no-autopay`, which can never pay.
46
69
  * 7. Poll GET /api/v3/subscription/status/:entityId until the deposit is
47
70
  * confirmed and ready to mint (status in { deposit_confirmed, pending_mint,
48
71
  * minting, active }; the real confirmed status is `deposit_confirmed`).
@@ -58,9 +81,19 @@ exports.runSubscribe = runSubscribe;
58
81
  const commander_1 = require("commander");
59
82
  const chalk_1 = __importDefault(require("chalk"));
60
83
  const ora_1 = __importDefault(require("ora"));
84
+ const smart_engines_sdk_1 = require("@hsuite/smart-engines-sdk");
61
85
  const env_1 = require("../_lib/env");
86
+ const decimal_compare_1 = require("../_lib/decimal-compare");
87
+ const payment_record_1 = require("../_lib/payment-record");
88
+ const payment_lock_1 = require("../_lib/payment-lock");
89
+ const error_message_1 = require("../_lib/error-message");
90
+ const payment_guard_1 = require("../_lib/payment-guard");
91
+ const create_outcome_1 = require("../_lib/create-outcome");
62
92
  const subscription_client_1 = require("../_lib/subscription-client");
63
93
  const subscription_env_1 = require("../_lib/subscription-env");
94
+ const order_deadline_1 = require("../_lib/order-deadline");
95
+ const xrpl_login_signer_1 = require("../_lib/xrpl-login-signer");
96
+ const xrp_payment_1 = require("../_lib/xrp-payment");
64
97
  /** Public XRPL testnet websocket endpoint (matches `hsuite init` + faucet). */
65
98
  const XRPL_TESTNET_WSS = 'wss://s.altnet.rippletest.net:51233';
66
99
  /**
@@ -79,11 +112,28 @@ function defaultXrplClientFactory(wss) {
79
112
  const { Client } = require('xrpl');
80
113
  return new Client(wss);
81
114
  }
82
- function defaultWalletSignFactory(seed) {
115
+ function defaultHashSignedTx(txBlob) {
83
116
  // eslint-disable-next-line @typescript-eslint/no-var-requires
84
- const { Wallet } = require('xrpl');
85
- const wallet = Wallet.fromSeed(seed);
86
- return (tx) => wallet.sign(tx).tx_blob;
117
+ const { hashes } = require('xrpl');
118
+ return hashes.hashSignedTx(txBlob);
119
+ }
120
+ /**
121
+ * Default entity-create-intent signer (#3506 A3, MEDIUM-1 fix): the SAME
122
+ * identity `authenticate()` logs in as — `XRPL_ADDRESS` + `deriveKeypair(seed)`
123
+ * via {@link buildXrplLoginSigner} — NEVER `xrpl.Wallet.fromSeed` /
124
+ * `createXrplWeb3Signer`. See `xrpl-login-signer.ts`'s doc-comment for why
125
+ * those two derivations can disagree (xrpl@4.6.0 forces ed25519 regardless of
126
+ * the seed's actual algorithm) and why that breaks the validator's
127
+ * intent-owner binding (#3635).
128
+ */
129
+ async function defaultIntentSignerFactory(address, seed) {
130
+ const loginSigner = await (0, xrpl_login_signer_1.buildXrplLoginSigner)(address, seed);
131
+ return {
132
+ chain: 'xrpl',
133
+ walletAddress: loginSigner.address,
134
+ publicKey: loginSigner.publicKey,
135
+ signFn: loginSigner.signFn,
136
+ };
87
137
  }
88
138
  /**
89
139
  * Pure orchestration body — exported for unit tests.
@@ -93,12 +143,21 @@ function defaultWalletSignFactory(seed) {
93
143
  * this and exits the process.
94
144
  */
95
145
  async function runSubscribe(opts) {
146
+ // #3917 item 3 — one paying run per env file: the guard that stops a second payment reads the
147
+ // env file's record and asks the ledger long before this run writes its own, so two runs on one
148
+ // env file could both pass it. The lock is the env file's, shared with `hsuite topup`.
149
+ return (0, payment_lock_1.withPaymentLock)(opts.env, 'hsuite subscribe', () => runSubscribeLocked(opts));
150
+ }
151
+ /** The body of {@link runSubscribe}, run while it holds the env file's payment lock. */
152
+ async function runSubscribeLocked(opts) {
96
153
  const env = (0, env_1.readEnv)(opts.env);
97
154
  const { address, seed } = (0, subscription_env_1.requireXrplCreds)(env);
98
155
  const tier = opts.tier;
99
156
  if (!VALID_TIERS.includes(tier)) {
100
157
  throw new Error(`unknown tier "${opts.tier}". Valid: ${VALID_TIERS.join(', ')}`);
101
158
  }
159
+ // #3699 PR2 — parsed before anything is sent: an unknown asset is a mistake, not a default.
160
+ const payWith = (0, xrp_payment_1.parsePayWith)(opts.payWith);
102
161
  const baseUrl = (0, subscription_env_1.requireValidatorUrl)(env, { gateway: opts.gateway });
103
162
  const client = (opts.clientFactory ??
104
163
  ((b) => new subscription_client_1.SubscriptionClient({ baseUrl: b, auth: { chain: 'xrpl', address, seed } })))(baseUrl);
@@ -106,6 +165,13 @@ async function runSubscribe(opts) {
106
165
  // session by signing a challenge before any call.
107
166
  await client.authenticate();
108
167
  const sleep = opts.sleep ?? defaultSleep;
168
+ // What THIS run was started with, repeated in every "run this next" hint below (see Invocation).
169
+ const inv = {
170
+ neverPay: opts.autopay === false,
171
+ tier,
172
+ ...(opts.gateway ? { gateway: opts.gateway } : {}),
173
+ ...(opts.appName ? { appName: opts.appName } : {}),
174
+ };
109
175
  const appName = opts.appName ?? env.get('APP_NAME') ?? 'Smart App Showcase';
110
176
  // A DNS-safe name is required by the create DTO (the entityId is derived by
111
177
  // the DKG ceremony, not from this name; the name is the display label).
@@ -120,13 +186,126 @@ async function runSubscribe(opts) {
120
186
  // An explicit --app-id / a previously-written SUBSCRIPTION_APP_ID short-
121
187
  // circuits create (re-running `subscribe` to finish paying/minting an
122
188
  // already-created entity), so a resumed run does not fork a second entity.
123
- const preexistingAppId = opts.appId ?? env.get('SUBSCRIPTION_APP_ID');
189
+ // `||`, not `??`: an EMPTY `--app-id ""` falls back to the saved id instead of
190
+ // forking a second entity beside it.
191
+ let preexistingAppId = opts.appId || env.get('SUBSCRIPTION_APP_ID');
192
+ let resumedFrom = opts.appId ? '--app-id' : `SUBSCRIPTION_APP_ID in ${opts.env}`;
193
+ if (!preexistingAppId) {
194
+ // #3766 — an earlier create may have left no verdict (a timeout, a dropped connection, a
195
+ // gateway 5xx after the work was done). Ask the platform before creating anything: if that
196
+ // entity exists, it is THE entity to resume, never a reason to create a second one.
197
+ const adopted = await reconcileUnfinishedCreate(client, env, opts.env, inv);
198
+ if (adopted) {
199
+ preexistingAppId = adopted;
200
+ resumedFrom = `the unfinished create recorded in ${opts.env}`;
201
+ }
202
+ }
203
+ // #3506 A3 / A2c — the cluster's network every intent is signed for, fetched ONCE and only when a
204
+ // run actually signs (a fresh create, or the deposit request of a resumed run).
205
+ const resolveIntentNetwork = async () => {
206
+ // #3506 A3 — every legitimate customer create carries a signed intent.
207
+ // `GET /api/v3/discovery/network` is the PUBLIC, ingress-routed source of
208
+ // the cluster's GenesisConfig.network — the exact value every responder
209
+ // compares the intent's `network` field against (HIGH-2: genesis/status
210
+ // is NOT on the ingress allow-list and 404s through the gateway).
211
+ const discovered = await (0, smart_engines_sdk_1.fetchIntentNetwork)(baseUrl);
212
+ if (!discovered.ok) {
213
+ // HIGH-1(a): a 404 means this cluster predates signed create intents
214
+ // (#3635 + this endpoint haven't shipped there yet). Refuse BEFORE
215
+ // creating anything — an old validator would otherwise silently strip
216
+ // `creationIntent`, create a RANDOM-id entity, and the post-create
217
+ // assert below would then throw, orphaning that entity + its pending
218
+ // subscription on every retry.
219
+ if (discovered.status === 404) {
220
+ throw new Error('cannot build a signed entity-create intent: GET /api/v3/discovery/network ' +
221
+ 'was not found (404) — this cluster predates signed create intents; upgrade ' +
222
+ 'the cluster (ship #3635 + this endpoint) before running `hsuite subscribe`.');
223
+ }
224
+ throw new Error('cannot build a signed entity-create intent: GET /api/v3/discovery/network ' +
225
+ `failed (status ${discovered.status}) — refusing to create without a verified network`);
226
+ }
227
+ const network = discovered.network;
228
+ // #3506 A3 LOW-1 (lying/misconfigured gateway, mainnet-only guard):
229
+ // `HSUITE_NETWORK` records which HSUITE CLUSTER `VALIDATOR_URL`/
230
+ // `SMART_HOST_URL` were resolved from (`hsuite init`, see `init.ts:
231
+ // 165-168`) — it is NOT the XRPL chain/faucet network (that's
232
+ // `XRPL_NETWORK`), and it is NOT the same value as the cluster's own
233
+ // `GenesisConfig.network` either: that value is derived server-side from
234
+ // `request.network || HEDERA_NETWORK || 'testnet'`
235
+ // (`genesis-bootstrap.service.ts:892`), so a devnet-cluster user (or one
236
+ // with `HSUITE_NETWORK` unset) LEGITIMATELY sees a discovered "testnet"
237
+ // — there is no separate "devnet" GenesisConfig label today. Refusing on
238
+ // every disagreement would therefore reject genuinely honest devnet
239
+ // onboarding. What must never happen regardless of `HSUITE_NETWORK` is
240
+ // silently signing a MAINNET intent: only refuse when the discovered
241
+ // network is mainnet and the operator has not explicitly confirmed
242
+ // `HSUITE_NETWORK=mainnet` — a compromised/misrouted gateway cannot
243
+ // trick a devnet/testnet/unset-configured user into a real-value mainnet
244
+ // signature. Compared case-insensitively (both sides normalised).
245
+ const hsuiteNetwork = env.get('HSUITE_NETWORK');
246
+ const normalizedDiscovered = network.toLowerCase();
247
+ const normalizedConfigured = hsuiteNetwork?.toLowerCase();
248
+ if (normalizedDiscovered === 'mainnet' && normalizedConfigured !== 'mainnet') {
249
+ throw new Error(`cluster-reported network "${network}" is mainnet, but the configured ` +
250
+ `HSUITE_NETWORK is "${hsuiteNetwork ?? '(unset)'}" — refusing to sign a MAINNET ` +
251
+ 'entity-create intent unless HSUITE_NETWORK=mainnet (possible lying or ' +
252
+ 'misconfigured gateway)');
253
+ }
254
+ return network;
255
+ };
256
+ let networkOnce;
257
+ const intentNetwork = () => (networkOnce ??= resolveIntentNetwork());
258
+ let signerOnce;
259
+ const intentSigner = () => (signerOnce ??= Promise.resolve((opts.intentSignerFactory ?? defaultIntentSignerFactory)(address, seed)));
260
+ // #3506 A2c — the deposit wallet of the subscription is created under the DEVELOPER's own signed
261
+ // intent too: this wallet signs the canonical `subscription` deposit rule, built HERE from the
262
+ // cluster's reported deposit token (the validator rebuilds it from the signed message and refuses
263
+ // any difference), bound to the smart-app `forAppId`. Valid ~10 minutes: signed right before it is
264
+ // sent, and signed afresh for every send.
265
+ const signDepositIntent = async (forAppId) => {
266
+ const network = await intentNetwork();
267
+ const tokenId = await client.depositTokenId('xrpl');
268
+ if (!tokenId) {
269
+ throw new Error('cannot build a signed deposit-wallet intent: GET /api/v3/subscription/config reports no ' +
270
+ 'deposit token for xrpl — this cluster predates payer-signed deposit wallets (#3506 A2c); ' +
271
+ 'upgrade the cluster before running `hsuite subscribe`.');
272
+ }
273
+ const { proof } = await (0, smart_engines_sdk_1.signDepositWalletIntent)(await intentSigner(), {
274
+ network,
275
+ depositType: 'subscription',
276
+ chain: 'xrpl',
277
+ tokenId,
278
+ appId: forAppId,
279
+ });
280
+ return proof;
281
+ };
124
282
  let appId;
125
283
  let created;
126
284
  if (preexistingAppId) {
127
285
  appId = preexistingAppId;
286
+ // Say so: the platform's stored subscription decides the tier and the amount,
287
+ // so the --tier / --app-name this run was started with have no effect on it.
288
+ console.log(chalk_1.default.gray(` resuming smart-app entity ${appId} (from ${resumedFrom}) — ` +
289
+ 'it keeps the tier and name it was created with; --tier and --app-name are ignored'));
128
290
  }
129
291
  else {
292
+ const network = await intentNetwork();
293
+ // The developer authors the rule CLIENT-SIDE (the wallet signs its hash) —
294
+ // the standard default, byte-identical to what the validator would
295
+ // otherwise synthesize server-side for the same deployment path.
296
+ const validatorRules = (0, smart_engines_sdk_1.buildDefaultSmartAppValidatorRules)();
297
+ const { proof: creationIntent, entityId: expectedEntityId } = await (0, smart_engines_sdk_1.signEntityCreateIntent)(await intentSigner(), {
298
+ network,
299
+ entityType: 'smart-app',
300
+ chain: 'xrpl',
301
+ rule: validatorRules,
302
+ });
303
+ // #3506 A2c — and the deposit wallet's intent, bound to the entityId the app intent derives.
304
+ const depositCreationIntent = await signDepositIntent(expectedEntityId);
305
+ // #3766 — record the create as PENDING before the request leaves: it is a long synchronous
306
+ // ceremony and this client gives up first, so "no answer" must not be mistaken for "nothing
307
+ // was created". Refuses (nothing sent) when the record cannot be kept.
308
+ recordPendingCreate(opts.env, expectedEntityId, (0, create_outcome_1.pendingCreateDeadline)(creationIntent.message));
130
309
  try {
131
310
  created = await client.createApp({
132
311
  name: appName,
@@ -140,17 +319,61 @@ async function runSubscribe(opts) {
140
319
  },
141
320
  tier,
142
321
  networks: ['testnet'],
143
- // validatorRules omitted (optional) — the factory synthesizes the
144
- // canonical security-first default for the standard deployment path.
322
+ // #3506 A3 — the EXACT rule the client hashed, plus the signed proof
323
+ // binding this create to it (and to a leader-independent entityId).
324
+ validatorRules,
325
+ creationIntent,
326
+ depositCreationIntent,
327
+ // #3699 PR2 — priced in XRP when asked; omitted (= HSUITE) otherwise, as ever.
328
+ ...(payWith === 'xrp' ? { paymentAsset: 'XRP' } : {}),
145
329
  });
146
330
  }
147
331
  catch (err) {
148
- throw new Error(`smart-app entity creation failed: ${err.message}`);
332
+ if ((0, create_outcome_1.createWasRefused)(err) || (0, create_outcome_1.createNeverSent)(err)) {
333
+ // The platform rejected the request, or it never left this machine: nothing was created,
334
+ // so nothing is pending and the next run creates normally.
335
+ clearPendingCreate(opts.env);
336
+ throw new Error(`smart-app entity creation failed: ${(0, error_message_1.errorMessage)(err)}`, { cause: err });
337
+ }
338
+ throw new Error(`smart-app entity creation failed: ${(0, error_message_1.errorMessage)(err)}${unknownCreateNote(expectedEntityId, opts.env, inv)}`, { cause: err });
339
+ }
340
+ if (!created?.appId) {
341
+ // The platform answered (even with an empty 2xx body), but without the entity: it may well
342
+ // exist at `expectedEntityId`.
343
+ throw new Error('create returned no appId (DKG entityId) — server contract violation' +
344
+ unknownCreateNote(expectedEntityId, opts.env, inv));
149
345
  }
150
- if (!created.appId) {
151
- throw new Error('create returned no appId (DKG entityId) — server contract violation');
346
+ // #3506 A3 / #3636 crypto review — defence in depth: never trust the
347
+ // server's returned id alone. A mismatch means the entity was NOT created
348
+ // at the id the signed intent derives; treat the response as untrusted and
349
+ // stop here — do NOT continue into the deposit / subscription steps below.
350
+ try {
351
+ (0, smart_engines_sdk_1.assertCreatedEntityMatchesIntent)(created.appId, expectedEntityId);
352
+ }
353
+ catch (err) {
354
+ // The create DID answer — with an id the intent does not authorize. It is not "unknown"
355
+ // any more, so it stays no longer pending (and is never resumed).
356
+ clearPendingCreate(opts.env);
357
+ // HIGH-1(b): the server DID create something — at `created.appId` — it
358
+ // is just not the id the signed intent authorizes. That entity (and any
359
+ // subscription minted against it) is now ORPHANED: unaffiliated with
360
+ // this wallet's signed intent. Name it explicitly so the operator can
361
+ // investigate/reclaim it rather than silently losing track of it, and
362
+ // do NOT blindly retry (a retry signs a NEW intent/nonce and, against a
363
+ // cluster with this defect, may orphan yet another entity).
364
+ throw new Error(`entity-create intent mismatch — the create is UNTRUSTED and will NOT be used. ` +
365
+ `The server created an ORPHANED entity at appId "${created.appId}" (a subscription ` +
366
+ `may exist on it, unaffiliated with your wallet). Do NOT retry blindly. Record ` +
367
+ `"${created.appId}" and investigate the cluster (bug, stale validator missing ` +
368
+ `#3635, or compromise) before creating again. Original error: ${(0, error_message_1.errorMessage)(err)}`);
152
369
  }
153
370
  appId = created.appId;
371
+ // #3754 — record the entity BEFORE any further step (deposit instructions,
372
+ // payment, mint). Every one of them can fail, and a failed payment used to
373
+ // throw before the end-of-run `upsertEnv`, leaving only the `hsuite init`
374
+ // placeholder in the env file — so the retry created a SECOND DKG entity,
375
+ // subscription, order and funded deposit account.
376
+ persistCreatedEntity(opts.env, appId, inv);
154
377
  }
155
378
  // Step 2: obtain the HST deposit instructions for THIS entityId. createApp
156
379
  // normally returns them (the subscription was created alongside the entity).
@@ -162,68 +385,166 @@ async function runSubscribe(opts) {
162
385
  let deposit = created?.depositInstructions;
163
386
  let subscriptionId = created?.subscriptionId;
164
387
  if (!deposit) {
388
+ const requestBody = {
389
+ appId,
390
+ developerAccountId: address,
391
+ chain: 'xrpl',
392
+ appName,
393
+ selectedTier: tier,
394
+ selectedNetworks: ['xrpl'],
395
+ ...(payWith === 'xrp' ? { paymentAsset: 'XRP' } : {}),
396
+ };
165
397
  try {
166
- requested = await client.request({
167
- appId,
168
- developerAccountId: address,
169
- chain: 'xrpl',
170
- appName,
171
- selectedTier: tier,
172
- selectedNetworks: ['xrpl'],
173
- });
398
+ // #3506 A2c — the request creates the deposit wallet only when this node has none. A RESUMED
399
+ // run almost always asks about a wallet that exists (the idempotent replay), so it first asks
400
+ // WITHOUT an intent: no discovery call, no signature. Only the validator's answer that a wallet
401
+ // would have to be created (`deposit_intent_required`) makes it sign, once, afresh.
402
+ try {
403
+ requested = await client.request(requestBody);
404
+ }
405
+ catch (err) {
406
+ if (!(0, smart_engines_sdk_1.isDepositIntentRequiredError)(err))
407
+ throw err;
408
+ requested = await client.request({
409
+ ...requestBody,
410
+ depositCreationIntent: await signDepositIntent(appId),
411
+ });
412
+ }
174
413
  }
175
414
  catch (err) {
176
- throw new Error(`subscription request failed: ${err.message}`);
415
+ throw new Error(`subscription request failed: ${(0, error_message_1.errorMessage)(err)}${unpaidNote(appId, opts.env, inv)}`, {
416
+ cause: err,
417
+ });
177
418
  }
178
419
  deposit = requested.depositInstructions;
179
420
  subscriptionId = subscriptionId ?? requested.subscriptionId;
180
421
  }
181
- if (!deposit) {
422
+ // #3411 — a RESUMED run asks the platform where the subscription stands
423
+ // BEFORE it pays anything. `GET /status` verifies a pending deposit on read
424
+ // (`checkSubscriptionStatus`), so it is fresher than the idempotent `request`
425
+ // replay above, which only echoes the stored row: a deposit paid by hand a
426
+ // moment ago (the `--no-autopay` flow) or by a previous run whose poll timed
427
+ // out can already show as credited here. ADVISORY, not a guarantee: deposit
428
+ // accounts are not replicated, so only the cluster that holds this one
429
+ // verifies on read — through the gateway another cluster answers from the
430
+ // replicated row and can still say `pending_deposit` for a payment sent a
431
+ // minute ago. An answer that cannot confirm the deposit is still owed (a failed
432
+ // read, `not_found`) blocks the payment rather than risk paying twice.
433
+ const standing = preexistingAppId
434
+ ? await readStandingBeforePaying(client, appId, opts.env, inv)
435
+ : undefined;
436
+ const creditedAs = [standing?.status, requested?.status].find(isReadyToMint);
437
+ if (!deposit && standing) {
182
438
  // No deposit instructions. On a RESUME of an already-active subscription
183
439
  // (--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
- }
440
+ // this is EXPECTED — not a contract violation. If the subscription is
441
+ // already provisioned, skip deposit+pay+mint and go straight to accepting
442
+ // the brokered sell offer so the NFT lands on the dev wallet.
443
+ const alreadyProvisioned = Boolean(standing.subscriptionNftSerial) ||
444
+ Boolean(standing.chainNfts?.xrpl?.nftId) ||
445
+ (standing.status ?? '').toLowerCase() === 'active';
446
+ if (alreadyProvisioned) {
447
+ // NFT coordinates can lag the 'active' status by a few ledgers.
448
+ const status = standing.subscriptionNftSerial || standing.chainNfts?.xrpl?.nftId
449
+ ? standing
450
+ : await pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) || Boolean(s.chainNfts?.xrpl?.nftId), opts.nftPollAttempts ?? 24);
451
+ (0, payment_guard_1.clearPendingPayment)(opts.env, appId, payment_record_1.PENDING_PAYMENT_KEY); // active: whatever was paid has been credited
452
+ const nftAccepted = await acceptSubscriptionNft(opts, address, seed, sleep, status);
453
+ return {
454
+ appId,
455
+ subscriptionId: status.subscriptionId ?? subscriptionId,
456
+ nftSerial: status.subscriptionNftSerial,
457
+ tier,
458
+ status: status.status,
459
+ depositPaid: true,
460
+ nftAccepted,
461
+ };
208
462
  }
209
- throw new Error('no depositInstructions for the created entity — server contract violation');
210
463
  }
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
- };
464
+ // Set once THIS run's deposit payment validated; every later failure then
465
+ // says so (see `afterDeposit`).
466
+ let paid;
467
+ const afterDeposit = async (step) => {
468
+ try {
469
+ return await step();
470
+ }
471
+ catch (err) {
472
+ throw paid ? paidThenFailed(err, paid, appId, opts.env, inv) : err;
473
+ }
474
+ };
475
+ if (creditedAs) {
476
+ // Credited, so there is nothing left to pay — however the run was started
477
+ // (`--no-autopay` only governs PAYING): carry on to mint + accept. This is
478
+ // what makes `--no-autopay`, pay by hand, re-run `hsuite subscribe` safe.
479
+ console.log(chalk_1.default.yellow(` deposit already credited (status=${creditedAs}) — not paying again`));
480
+ }
481
+ else {
482
+ if (!deposit) {
483
+ throw new Error(preexistingAppId
484
+ ? `no depositInstructions returned for saved entity ${appId} — usually because the node that ` +
485
+ 'answered holds no deposit-account record for it (deposit accounts are not replicated ' +
486
+ `between clusters), so it cannot say what to pay${unpaidNote(appId, opts.env, inv)} ` +
487
+ 'Try again in a minute: a retry can reach a node that has it.'
488
+ : 'no depositInstructions for the created entity — server contract violation');
489
+ }
490
+ // #3699 D8 / #3765 — never put an expired quote in front of a payer, on EITHER path:
491
+ // requote first if the deadline has already passed, then show / pay the NEW amount and tag.
492
+ // (A manual payer used to be shown whatever the replay re-attached, expired or not.)
493
+ try {
494
+ deposit = await (0, order_deadline_1.ensureUnexpiredQuote)(client, deposit);
495
+ }
496
+ catch (err) {
497
+ throw new Error(`could not requote the expired quote for order ${deposit.orderId ?? 'n/a'}: ` +
498
+ `${(0, error_message_1.errorMessage)(err)}${unpaidNote(appId, opts.env, inv)}`, { cause: err });
499
+ }
500
+ // #3699 PR2 — `--pay-with xrp` is only ever answered with an order priced in XRP. A validator that
501
+ // hands HST instructions to an XRP request (or an older one that ignores the asset) would have this run
502
+ // pay HST, the asset the builder did not ask to pay in: refuse HERE, before anything is signed.
503
+ if (payWith === 'xrp' && !(0, xrp_payment_1.xrpPaymentOf)(deposit)) {
504
+ throw new Error('asked to pay in XRP, but the validator priced this subscription in HSUITE (no XRP payment ' +
505
+ `instruction came back) — nothing was paid${unpaidNote(appId, opts.env, inv)} ` +
506
+ 'Re-run without --pay-with to pay in HSUITE.');
507
+ }
508
+ // #3699 PR2 — an XRP instruction is paid exactly as given: check it pays THIS deposit account before
509
+ // it is shown or signed.
510
+ const instructedXrp = (0, xrp_payment_1.xrpPaymentOf)(deposit);
511
+ if (instructedXrp) {
512
+ try {
513
+ (0, xrp_payment_1.assertXrpPaymentConsistent)(deposit, instructedXrp);
514
+ }
515
+ catch (err) {
516
+ throw new Error(`${(0, error_message_1.errorMessage)(err)}${unpaidNote(appId, opts.env, inv)}`, { cause: err });
517
+ }
518
+ }
519
+ // A resumed entity keeps the tier it was created with, which this run's
520
+ // --tier says nothing about: print the tier only for an entity created now.
521
+ renderDepositInstructions(deposit, preexistingAppId ? undefined : tier, appId);
522
+ // Step 3: auto-pay the deposit from the dev wallet (unless --no-autopay).
523
+ if (opts.autopay === false) {
524
+ renderManualPaymentHint(deposit);
525
+ return {
526
+ appId,
527
+ subscriptionId,
528
+ tier,
529
+ status: standing?.status ?? requested?.status ?? 'pending_deposit',
530
+ depositPaid: false,
531
+ nftAccepted: false,
532
+ };
533
+ }
534
+ try {
535
+ paid = await payDeposit(opts, address, seed, deposit, appId);
536
+ }
537
+ catch (err) {
538
+ // #3754 — the entity exists whether or not this payment did (it is already
539
+ // saved above). Say so, and how to resume it, so a failed payment never
540
+ // reads as "start over".
541
+ throw paymentFailure(err, { appId, subscriptionId, deposit, address, envPath: opts.env, inv });
542
+ }
543
+ console.log(chalk_1.default.gray(` deposit payment validated${paid.hash ? ` (tx ${paid.hash})` : ''}`));
223
544
  }
224
- await payDeposit(opts, address, seed, deposit);
225
545
  // Step 3: poll /status until the deposit is confirmed and ready to mint.
226
- await pollStatus(client, appId, sleep, opts, (s) => isReadyToMint(s.status));
546
+ await afterDeposit(() => pollStatus(client, appId, sleep, opts, (s) => isReadyToMint(s.status)));
547
+ (0, payment_guard_1.clearPendingPayment)(opts.env, appId, payment_record_1.PENDING_PAYMENT_KEY); // credited: the platform has counted the payment this CLI recorded
227
548
  // Step 4: POST /mint — kicks off the async NFT mint. Tolerate a non-2xx here
228
549
  // (the server may still be finalizing); the status poll below is the source of
229
550
  // truth for whether the NFT actually minted.
@@ -234,18 +555,18 @@ async function runSubscribe(opts) {
234
555
  }
235
556
  }
236
557
  catch (err) {
237
- console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${err.message}`));
558
+ console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${(0, error_message_1.errorMessage)(err)}`));
238
559
  }
239
560
  // Step 5: poll until the NFT serial is set OR the minted NFT coordinates
240
561
  // appear on /status (the NFT mints asynchronously via the mint subscriber).
241
562
  // The 2-of-3 issuer MPC mint + offer creation take ~15-25s, so poll ~24×5s
242
563
  // (~120s) before giving up. Bounded by attempt count (not wall-clock) so the
243
564
  // injected-`sleep` unit tests stay fast.
244
- const status = await pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) ||
565
+ const status = await afterDeposit(() => pollStatus(client, appId, sleep, opts, (s) => Boolean(s.subscriptionNftSerial) ||
245
566
  Boolean(s.chainNfts?.xrpl?.nftId) ||
246
- (s.status ?? '').toLowerCase() === 'active', opts.nftPollAttempts ?? 24);
567
+ (s.status ?? '').toLowerCase() === 'active', opts.nftPollAttempts ?? 24));
247
568
  // 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);
569
+ const nftAccepted = await afterDeposit(() => acceptSubscriptionNft(opts, address, seed, sleep, status));
249
570
  return {
250
571
  appId,
251
572
  subscriptionId: status.subscriptionId ?? subscriptionId,
@@ -272,6 +593,234 @@ function toDnsSafeName(name) {
272
593
  .replace(/-+$/g, '');
273
594
  return slug.length > 0 ? slug : 'smart-app';
274
595
  }
596
+ /** `value` as one shell word: left as is when it is plain, else single-quoted. */
597
+ function shellQuote(value) {
598
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
599
+ }
600
+ /**
601
+ * The command that resumes `appId`, ready to paste: the entity AND the env file it
602
+ * is saved in. `--no-autopay` makes it unable to pay, so it is what to run after a
603
+ * payment that may already have gone through — it still mints and accepts the NFT
604
+ * as soon as the platform credits the deposit.
605
+ */
606
+ function resumeCommand(appId, envPath, flags = {}) {
607
+ return (`hsuite subscribe --app-id ${shellQuote(appId)} --env ${shellQuote(envPath)}` +
608
+ (flags.gateway ? ` --gateway ${shellQuote(flags.gateway)}` : '') +
609
+ (flags.neverPay ? ' --no-autopay' : ''));
610
+ }
611
+ /** {@link resumeCommand}'s flags for a run started as `inv`; `neverPay` forces the can-never-pay form. */
612
+ function resumeFlags(inv, neverPay = false) {
613
+ return { neverPay: neverPay || inv.neverPay, ...(inv.gateway ? { gateway: inv.gateway } : {}) };
614
+ }
615
+ /** The tail of a failure that happens after the entity is saved but BEFORE any payment. */
616
+ function unpaidNote(appId, envPath, inv) {
617
+ return (` — smart-app entity ${appId} is saved and NOTHING has been paid. Re-run ` +
618
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it (that will NOT create a second entity).`);
619
+ }
620
+ /** The error for a payment that did not go through (or may not have) — see {@link PaymentOutcomeUnknownError}. */
621
+ function paymentFailure(err, ctx) {
622
+ const entity = `smart-app entity ${ctx.appId} (subscription ${ctx.subscriptionId ?? 'n/a'}, ` +
623
+ `order ${ctx.deposit.orderId ?? 'n/a'})`;
624
+ if (err instanceof DepositAlreadyOnLedgerError) {
625
+ return new Error(`${(0, error_message_1.errorMessage)(err)} (the order is covered at ${err.threshold} HST) — it looks paid, but the platform has not ` +
626
+ `credited it yet. NOT paying again. ${entity} is saved. Give the platform about a minute, then run ` +
627
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it mints and ` +
628
+ 'accepts the NFT once the platform credits the deposit. If that balance is NOT a payment for this ' +
629
+ 'order, the same command prints what to pay by hand.', { cause: err });
630
+ }
631
+ if (err instanceof payment_guard_1.RecordedPaymentLandedError) {
632
+ return new Error(`${(0, error_message_1.errorMessage)(err)} (validated tesSUCCESS) — it looks paid, but the platform has not credited it ` +
633
+ `yet. NOT paying again, whatever the quote asks now. ${entity} is saved. Give the platform about a ` +
634
+ `minute, then run \`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot ` +
635
+ 'pay, and it mints and accepts the NFT once the platform credits the deposit. If the platform ' +
636
+ 'instead reports the order underpaid, the same command prints what to pay by hand.', { cause: err });
637
+ }
638
+ if (err instanceof payment_guard_1.PaymentOutcomeUnknownError) {
639
+ return new Error(`${(0, error_message_1.errorMessage)(err)} — the payment was submitted but its outcome is UNKNOWN: it may still ` +
640
+ `validate. ${entity} is saved. BEFORE re-running, check whether ${ctx.address} already sent ` +
641
+ `HST to ${ctx.deposit.walletAddress} (an XRPL testnet explorer shows it): re-running can pay ` +
642
+ 'AGAIN. If it did go through, wait about a minute and run ' +
643
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it ` +
644
+ 'mints and accepts the NFT once the platform credits the deposit.', { cause: err });
645
+ }
646
+ return new Error(`${(0, error_message_1.errorMessage)(err)} — ${entity} is NOT orphaned. Fix the cause, then re-run ` +
647
+ `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv))}\` to resume it — that will NOT create a second entity.`, { cause: err });
648
+ }
649
+ /** The error for a step that failed AFTER this run's deposit payment validated. */
650
+ function paidThenFailed(err, receipt, appId, envPath, inv) {
651
+ return new Error(`${(0, error_message_1.errorMessage)(err)} — the deposit payment${receipt.hash ? ` (tx ${receipt.hash})` : ''} WAS validated ` +
652
+ 'on the ledger: do NOT pay again. Give the platform about a minute to credit it, then run ' +
653
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv, true))}\` — it cannot pay, and it finishes minting ` +
654
+ 'and accepting the NFT.', { cause: err });
655
+ }
656
+ /**
657
+ * Ask the platform where a RESUMED subscription stands before anything is paid
658
+ * (#3411). Throws — with nothing paid — when it cannot be read, or when the node
659
+ * that answered has no such subscription (`hasSubscription: false`, `not_found`:
660
+ * a cluster that has not replicated it yet, or one that does not recognise this
661
+ * wallet as its owner). Neither answer shows the deposit is still owed, and
662
+ * paying on a "don't know" is how a deposit gets paid twice.
663
+ */
664
+ async function readStandingBeforePaying(client, appId, envPath, inv) {
665
+ let standing;
666
+ try {
667
+ standing = await client.status(appId);
668
+ }
669
+ catch (err) {
670
+ throw new Error(`could not read where subscription ${appId} stands (${(0, error_message_1.errorMessage)(err)})${unpaidNote(appId, envPath, inv)}`, { cause: err });
671
+ }
672
+ if (standing.hasSubscription === false) {
673
+ throw new Error(`the platform that answered has no subscription for smart-app entity ${appId} that this wallet ` +
674
+ `owns (status=${standing.status ?? 'unknown'}) — the cluster may not have replicated it yet, or ` +
675
+ `the entity belongs to another wallet${unpaidNote(appId, envPath, inv)} Try again in a minute.`);
676
+ }
677
+ return standing;
678
+ }
679
+ /**
680
+ * Save a freshly created (or adopted, see {@link reconcileUnfinishedCreate}) entity as
681
+ * `SUBSCRIPTION_APP_ID` (+ `APP_ID` — the same pair the end-of-run write and the
682
+ * `--no-autopay` path produce) so a re-run RESUMES it instead of creating a second one (#3754),
683
+ * and then clears the pending-create record: the create has its verdict now (#3766).
684
+ *
685
+ * Fails loud, and BEFORE any payment, when the file cannot be written: an entity
686
+ * the CLI cannot keep track of must not be paid for, and the error carries the id
687
+ * so the developer can resume it explicitly with `--app-id`.
688
+ */
689
+ function persistCreatedEntity(envPath, appId, inv) {
690
+ try {
691
+ (0, env_1.upsertEnv)(envPath, { SUBSCRIPTION_APP_ID: appId, APP_ID: appId });
692
+ }
693
+ catch (err) {
694
+ throw new Error(`smart-app entity ${appId} was created but could not be saved to ${envPath} ` +
695
+ `(${(0, error_message_1.errorMessage)(err)}). Nothing has been paid. Re-run ` +
696
+ `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it.`, { cause: err });
697
+ }
698
+ // The create has its verdict now: it is no longer pending.
699
+ clearPendingCreate(envPath);
700
+ }
701
+ /**
702
+ * The command that retries a `subscribe` WITHOUT naming an entity: it reconciles an unfinished
703
+ * create first (#3766) and, if that earlier create is dead, creates a fresh entity — so it repeats
704
+ * the tier, name and gateway this run was started with, and `--no-autopay`.
705
+ */
706
+ function rerunCommand(envPath, inv) {
707
+ return (`hsuite subscribe --env ${shellQuote(envPath)} --tier ${shellQuote(inv.tier)}` +
708
+ (inv.appName ? ` --app-name ${shellQuote(inv.appName)}` : '') +
709
+ (inv.gateway ? ` --gateway ${shellQuote(inv.gateway)}` : '') +
710
+ (inv.neverPay ? ' --no-autopay' : ''));
711
+ }
712
+ /**
713
+ * Record the create of `entityId` as pending BEFORE it is sent (#3766). Fails loud — with
714
+ * nothing sent — when the file cannot be written: a create this CLI cannot keep track of is
715
+ * exactly the one it would orphan.
716
+ */
717
+ function recordPendingCreate(envPath, entityId, until) {
718
+ try {
719
+ (0, env_1.upsertEnv)(envPath, { [create_outcome_1.PENDING_CREATE_KEY]: (0, create_outcome_1.formatPendingCreate)({ appId: entityId, until }) });
720
+ }
721
+ catch (err) {
722
+ throw new Error(`cannot record the create of smart-app entity ${entityId} in ${envPath} (${(0, error_message_1.errorMessage)(err)}) — ` +
723
+ 'refusing to send it: a create this CLI cannot keep track of could be orphaned. ' +
724
+ 'Nothing was created and nothing has been paid.', { cause: err });
725
+ }
726
+ }
727
+ /**
728
+ * Forget the pending create. Best effort: a record that survives is only ever PROBED by the next
729
+ * run (never trusted), and is ignored outright once SUBSCRIPTION_APP_ID is set — so a failed
730
+ * removal can cost a delay, never an orphan.
731
+ */
732
+ function clearPendingCreate(envPath) {
733
+ try {
734
+ (0, env_1.removeEnvKeys)(envPath, [create_outcome_1.PENDING_CREATE_KEY]);
735
+ }
736
+ catch {
737
+ // see above
738
+ }
739
+ }
740
+ /** The tail of a failure that leaves a create's outcome unknown: the entity may exist (#3766). */
741
+ function unknownCreateNote(expectedEntityId, envPath, inv) {
742
+ return (` — its outcome is UNKNOWN: the platform may still have created smart-app entity ${expectedEntityId} ` +
743
+ '(the create is a long ceremony and this client may have given up before it finished). Nothing has ' +
744
+ `been paid. Re-run \`${rerunCommand(envPath, inv)}\`: it asks the platform whether ${expectedEntityId} ` +
745
+ 'exists and RESUMES it if it does — it will not create a second one.');
746
+ }
747
+ /** How to get unstuck when the CLI cannot settle a recorded create by itself. */
748
+ function forgetPendingHint(envPath) {
749
+ return (`If you are sure the earlier create never reached the platform, delete the ${create_outcome_1.PENDING_CREATE_KEY} ` +
750
+ `line from ${envPath} and re-run.`);
751
+ }
752
+ /**
753
+ * Settle an earlier create that ended without a verdict (#3766), before this run creates
754
+ * anything. Asks the platform about the recorded entity:
755
+ * - it EXISTS → adopt it (saved as SUBSCRIPTION_APP_ID) and resume it: the earlier create did
756
+ * complete, and a second entity would orphan it;
757
+ * - it does not, but the earlier create may still be completing (or the answer is not a plain
758
+ * "no") → refuse: creating now could leave TWO entities;
759
+ * - it does not and the signed intent has run out (its `exp` plus a grace) → the earlier create
760
+ * is dead; carry on and create a fresh entity;
761
+ * - the platform cannot be asked, or the record is not one this CLI wrote → refuse (nothing created).
762
+ *
763
+ * @returns the entity id to resume, or `undefined` to create a fresh one.
764
+ */
765
+ async function reconcileUnfinishedCreate(client, env, envPath, inv) {
766
+ const raw = env.get(create_outcome_1.PENDING_CREATE_KEY);
767
+ if (!raw)
768
+ return undefined;
769
+ const pending = (0, create_outcome_1.parsePendingCreate)(raw);
770
+ if (!pending) {
771
+ // Fail closed: a record this CLI did not write cannot say whether an earlier create is still
772
+ // outstanding, and ignoring it is how a second entity gets created.
773
+ throw new Error(`${create_outcome_1.PENDING_CREATE_KEY} in ${envPath} is not a record this CLI wrote (${JSON.stringify(raw)}), so it ` +
774
+ 'cannot tell whether an earlier create is still outstanding — nothing has been created or paid now. ' +
775
+ forgetPendingHint(envPath));
776
+ }
777
+ const earlier = `an earlier \`hsuite subscribe\` asked the platform to create smart-app entity ${pending.appId} ` +
778
+ 'and never got an answer';
779
+ let standing;
780
+ try {
781
+ standing = await client.status(pending.appId);
782
+ }
783
+ catch (err) {
784
+ throw new Error(`${earlier}, and the platform could not be asked whether it exists (${(0, error_message_1.errorMessage)(err)}) — ` +
785
+ `nothing has been created or paid now. Re-run \`${rerunCommand(envPath, inv)}\` in a minute. ` +
786
+ forgetPendingHint(envPath), { cause: err });
787
+ }
788
+ if (standing.hasSubscription === true) {
789
+ console.log(chalk_1.default.yellow(` the earlier create DID complete: smart-app entity ${pending.appId} exists — resuming it, not creating another`));
790
+ persistCreatedEntity(envPath, pending.appId, inv);
791
+ return pending.appId;
792
+ }
793
+ if (standing.hasSubscription === false && Date.now() >= pending.until) {
794
+ 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`));
795
+ return undefined;
796
+ }
797
+ throw new Error(`${earlier}. The platform does not show it (yet), and that create may still be completing (its signed ` +
798
+ `intent should have run out by ${new Date(pending.until).toISOString()}) — creating another entity now ` +
799
+ 'could leave two entities. Re-run ' +
800
+ `\`${rerunCommand(envPath, inv)}\` after that time; sooner, the moment the platform shows ` +
801
+ `${pending.appId}, it is resumed. ${forgetPendingHint(envPath)}`);
802
+ }
803
+ /**
804
+ * Write the end-of-run env updates. A failure is REPORTED, not thrown: by now the
805
+ * entity is created and saved ({@link persistCreatedEntity}), the deposit paid and
806
+ * the NFT minted, and an error after "subscription active" would read as the whole
807
+ * run having failed. The values are printed so they can be added by hand.
808
+ *
809
+ * @returns whether the file was written.
810
+ */
811
+ function saveEnv(envPath, updates) {
812
+ try {
813
+ (0, env_1.upsertEnv)(envPath, updates);
814
+ return true;
815
+ }
816
+ catch (err) {
817
+ console.log(chalk_1.default.yellow(`\n could not write ${envPath} (${(0, error_message_1.errorMessage)(err)}) — add these by hand:`));
818
+ for (const [key, value] of Object.entries(updates)) {
819
+ console.log(chalk_1.default.yellow(` ${key}=${value}`));
820
+ }
821
+ return false;
822
+ }
823
+ }
275
824
  /**
276
825
  * Pay the HST deposit from the dev wallet over the XRPL testnet.
277
826
  *
@@ -281,18 +830,53 @@ function toDnsSafeName(name) {
281
830
  * submit a `Payment` of `amount` whole HST with a `SendMax` of
282
831
  * `amount × 1.004` to cover the 0.25% HST transfer fee.
283
832
  *
284
- * Requires tesSUCCESS. Always disconnects.
833
+ * #3699 PR1a — when `deposit.destinationTag` is present (the validator wired
834
+ * a price-locked SubscriptionOrder), the Payment carries it as
835
+ * `DestinationTag` so PR1b's `account_tx` matcher (keyed on the tag, never
836
+ * bare `Amount` — the XRPL partial-payment protection) can find this
837
+ * payment. Omitted entirely, not sent as `0`/`undefined`, when absent (older
838
+ * server / order creation unavailable) — unchanged from pre-#3699 behavior.
839
+ *
840
+ * #3771 — BEFORE anything is signed or submitted, the deposit account's HST balance is read from
841
+ * the ledger and the payment is refused ({@link DepositAlreadyOnLedgerError}) when the account
842
+ * already holds what the quote asks, or when that balance cannot be read at all.
843
+ *
844
+ * #3917 item 3 — and BEFORE that, the payment an earlier run recorded for this entity (its signed
845
+ * hash, written before it was submitted) is looked up on the ledger: delivered → refused
846
+ * ({@link RecordedPaymentLandedError}); still able to land → refused as unknown
847
+ * ({@link PaymentOutcomeUnknownError}); failed or past its `LastLedgerSequence` without landing →
848
+ * it delivered nothing, and this run pays. The hash of the payment THIS run signs is recorded
849
+ * before it is submitted (and a payment that cannot be recorded is not submitted).
850
+ *
851
+ * Requires tesSUCCESS. Always disconnects. A thrown wait for the verdict (the
852
+ * blob is already out) surfaces as {@link PaymentOutcomeUnknownError}; a `tec*` /
853
+ * `tem*` verdict is a plain failure — nothing was delivered.
285
854
  */
286
- async function payDeposit(opts, address, seed, deposit) {
855
+ async function payDeposit(opts, address, seed, deposit, appId) {
287
856
  if (deposit.chain !== 'xrpl') {
288
857
  throw new Error(`auto-pay only supports XRPL deposits (got chain=${deposit.chain}); ` +
289
858
  'use --no-autopay and pay manually');
290
859
  }
291
- const walletSign = (opts.walletSignFactory ?? defaultWalletSignFactory)(seed);
860
+ const walletSign = (opts.walletSignFactory ?? xrpl_login_signer_1.buildXrplTxSigner)(seed);
292
861
  const client = (opts.xrplClientFactory ?? defaultXrplClientFactory)(XRPL_TESTNET_WSS);
293
862
  await client.connect();
294
863
  try {
295
- const issuer = await resolveHstIssuer(client, deposit.walletAddress);
864
+ // #3917 item 3 — what became of the payment an earlier run SENT decides first; the balance
865
+ // below cannot tell whose HST it holds, so a requote at a higher price used to be paid again.
866
+ await (0, payment_guard_1.refuseIfRecordedPaymentMayLand)(client, opts.env, appId, payment_record_1.PENDING_PAYMENT_KEY);
867
+ // #3699 PR2 — an order priced in XRP is paid in XRP: the quoted drops, with the order's tag. The HST
868
+ // line of the deposit account says nothing about it (the platform converts the XRP into HST inside the
869
+ // account), so the HST-balance guard below does not apply; the recorded-payment guard above, which asks
870
+ // the ledger what became of the payment an earlier run sent, is what stops a second payment.
871
+ const xrpPay = (0, xrp_payment_1.xrpPaymentOf)(deposit);
872
+ if (xrpPay) {
873
+ return await signRecordAndSubmit(client, walletSign, opts, (0, xrp_payment_1.buildXrpPaymentTx)(address, xrpPay), appId);
874
+ }
875
+ const { issuer, balance } = await readDepositHstLine(client, deposit.walletAddress);
876
+ // #3771 — the LEDGER is the one source of truth every cluster agrees on: a deposit
877
+ // account that already holds what this quote asks has been paid, whatever a replica's
878
+ // `/status` still says. Nothing is signed or submitted past this point on a refusal.
879
+ refuseIfAlreadyOnLedger(deposit, balance);
296
880
  const value = deposit.amount;
297
881
  const sendMax = (Number(value) * HST_TRANSFER_FEE_MULTIPLIER).toFixed(6);
298
882
  const tx = {
@@ -301,34 +885,113 @@ async function payDeposit(opts, address, seed, deposit) {
301
885
  Destination: deposit.walletAddress,
302
886
  Amount: { currency: 'HST', issuer, value },
303
887
  SendMax: { currency: 'HST', issuer, value: sendMax },
888
+ ...(deposit.destinationTag !== undefined ? { DestinationTag: deposit.destinationTag } : {}),
304
889
  };
305
- const prepared = await client.autofill(tx);
306
- const txBlob = walletSign(prepared);
307
- const result = await client.submitAndWait(txBlob);
308
- const code = result.result?.meta?.TransactionResult;
309
- if (code !== 'tesSUCCESS') {
310
- throw new Error(`deposit Payment failed: ${code ?? 'unknown result'}`);
311
- }
890
+ return await signRecordAndSubmit(client, walletSign, opts, tx, appId);
312
891
  }
313
892
  finally {
314
- await client.disconnect();
893
+ // A failing disconnect (a dead socket) must not replace the error that got us here — above all
894
+ // not a refusal to pay twice, or a payment whose outcome is unknown.
895
+ await client.disconnect().catch(() => undefined);
315
896
  }
316
897
  }
317
898
  /**
318
- * Resolve the HST issuer from the deposit account's trust lines.
899
+ * Autofill, sign, RECORD and submit a deposit Payment, and require `tesSUCCESS` (shared by the HST and the
900
+ * XRP deposit). The signed hash is recorded BEFORE the blob leaves this process (as the pending create is,
901
+ * #3766): from here on a crash, a timeout or a requote cannot make a later run forget it may already have
902
+ * paid. A thrown wait for the verdict (the blob is out) is {@link PaymentOutcomeUnknownError}; a `tec*` /
903
+ * `tem*` verdict is a plain failure: nothing was delivered.
904
+ */
905
+ async function signRecordAndSubmit(client, walletSign, opts, tx, appId) {
906
+ const prepared = await client.autofill(tx);
907
+ const txBlob = walletSign(prepared);
908
+ (0, payment_guard_1.recordPendingPayment)(opts.env, {
909
+ appId,
910
+ txHash: (opts.hashSignedTx ?? defaultHashSignedTx)(txBlob),
911
+ ...(typeof prepared.LastLedgerSequence === 'number'
912
+ ? { lastLedgerSequence: prepared.LastLedgerSequence }
913
+ : {}),
914
+ }, payment_record_1.PENDING_PAYMENT_KEY);
915
+ let result;
916
+ try {
917
+ result = await client.submitAndWait(txBlob);
918
+ }
919
+ catch (err) {
920
+ // The blob has left this process: the ledger may still validate it.
921
+ throw new payment_guard_1.PaymentOutcomeUnknownError(err);
922
+ }
923
+ const code = result.result?.meta?.TransactionResult;
924
+ if (code === undefined) {
925
+ // No verdict in the answer: not a failure the ledger reported.
926
+ throw new payment_guard_1.PaymentOutcomeUnknownError(new Error('deposit Payment came back with no transaction result'));
927
+ }
928
+ if (code !== 'tesSUCCESS') {
929
+ throw new Error(`deposit Payment failed: ${code}`);
930
+ }
931
+ return { hash: result.result?.hash };
932
+ }
933
+ /**
934
+ * Read the deposit account's HST trust line: the HST issuer and what the account holds.
319
935
  *
320
936
  * The deposit account holds an HST trust line whose peer (`account`) is the HST
321
937
  * issuer. We query `account_lines` on the deposit wallet and return the peer of
322
- * the line whose `currency` is 'HST'.
938
+ * the line whose `currency` is 'HST', and that line's `balance` — what the
939
+ * account holds, as the LEDGER reports it (#3771).
323
940
  */
324
- async function resolveHstIssuer(client, depositWallet) {
941
+ async function readDepositHstLine(client, depositWallet) {
942
+ // No `ledger_index`: the server's default view answers (rippled: the open ledger, which also
943
+ // shows a payment that has not validated yet — the safe side for "is it already paid?").
325
944
  const res = await client.request({ command: 'account_lines', account: depositWallet });
326
945
  const lines = res.result?.lines ?? [];
327
946
  const hst = lines.find((l) => l?.currency === 'HST');
328
947
  if (!hst?.account) {
329
948
  throw new Error(`could not resolve HST issuer: deposit account ${depositWallet} has no HST trust line`);
330
949
  }
331
- return hst.account;
950
+ return { issuer: hst.account, balance: String(hst.balance ?? '') };
951
+ }
952
+ /**
953
+ * The deposit account already holds what the quote asks, but the platform has not credited it
954
+ * (#3771). Thrown INSTEAD of paying: the payment is on the ledger already.
955
+ */
956
+ class DepositAlreadyOnLedgerError extends Error {
957
+ threshold;
958
+ constructor(depositWallet, balance, threshold) {
959
+ super(`deposit account ${depositWallet} already holds ${balance} HST on the ledger`);
960
+ this.threshold = threshold;
961
+ this.name = 'DepositAlreadyOnLedgerError';
962
+ }
963
+ }
964
+ /**
965
+ * Refuse to pay when the deposit account's ledger balance already covers the quote (#3771).
966
+ *
967
+ * `GET /status` is only authoritative on the cluster that holds the deposit account, so a
968
+ * resumed run that reaches another cluster can read `pending_deposit` for a payment sent a
969
+ * minute ago, and pay AGAIN. The ledger has no such lag.
970
+ *
971
+ * The threshold is what the quote ASKS, except for a REQUOTED order, which asks only for the
972
+ * REMAINDER (the total at the new rate minus what the platform already counted): the account
973
+ * then still holds the earlier, short payment, so the remainder alone would refuse a payment
974
+ * that is genuinely owed. `hsuiteDue` is the whole base price, so the larger of the two is the
975
+ * balance that means "paid in full" either way.
976
+ *
977
+ * FAILS CLOSED: a balance (or a quote `amount`) that cannot be read as a number is an error,
978
+ * never a "carry on and pay". An unreadable `hsuiteDue` is ignored — the threshold stays the
979
+ * `amount`, which is the safe direction. (XRPL HST is whole-unit, so `amount` and `hsuiteDue`
980
+ * share one scale; `payDeposit` pays XRPL deposits only.)
981
+ */
982
+ function refuseIfAlreadyOnLedger(deposit, balance) {
983
+ let threshold = deposit.amount;
984
+ if (deposit.hsuiteDue !== undefined && (0, decimal_compare_1.compareDecimals)(deposit.hsuiteDue, threshold) === 1) {
985
+ threshold = deposit.hsuiteDue;
986
+ }
987
+ const held = (0, decimal_compare_1.compareDecimals)(balance, threshold);
988
+ if (held === undefined) {
989
+ throw new Error(`could not read the HST balance of deposit account ${deposit.walletAddress} ` +
990
+ `(the ledger said ${JSON.stringify(balance)}, the quote asks ${deposit.amount}) — ` +
991
+ 'refusing to pay without knowing the account does not already hold it');
992
+ }
993
+ if (held >= 0)
994
+ throw new DepositAlreadyOnLedgerError(deposit.walletAddress, balance, threshold);
332
995
  }
333
996
  /**
334
997
  * Ready-to-mint check.
@@ -404,7 +1067,7 @@ async function acceptSubscriptionNft(opts, address, seed, sleep, status) {
404
1067
  // Explicit override wins; otherwise use the issuer the status now exposes.
405
1068
  const issuer = opts.nftIssuer ?? xrplNft?.issuerAddress;
406
1069
  const client = (opts.xrplClientFactory ?? defaultXrplClientFactory)(XRPL_TESTNET_WSS);
407
- const walletSign = (opts.walletSignFactory ?? defaultWalletSignFactory)(seed);
1070
+ const walletSign = (opts.walletSignFactory ?? xrpl_login_signer_1.buildXrplTxSigner)(seed);
408
1071
  const attempts = opts.acceptAttempts ?? 10;
409
1072
  const retryMs = opts.acceptRetryMs ?? opts.pollIntervalMs ?? 5000;
410
1073
  await client.connect();
@@ -505,17 +1168,46 @@ async function findSellOfferIndexByNftId(client, nftId, recipient) {
505
1168
  const match = offers.find((o) => o?.destination === recipient) ?? offers[0];
506
1169
  return match?.nft_offer_index;
507
1170
  }
1171
+ /** `tier` is omitted for a RESUMED entity: it keeps the tier it was created with, not this run's `--tier`. */
508
1172
  function renderDepositInstructions(d, tier, appId) {
509
1173
  console.log(chalk_1.default.bold.green(`\n Subscription requested: ${appId}`));
510
1174
  console.log(chalk_1.default.bold.yellow('\n Deposit required to mint your subscription NFT:'));
511
- console.log(chalk_1.default.gray(` tier: ${tier}`));
1175
+ if (tier)
1176
+ console.log(chalk_1.default.gray(` tier: ${tier}`));
512
1177
  console.log(chalk_1.default.gray(` chain: ${d.chain}`));
1178
+ const xrpPay = (0, xrp_payment_1.xrpPaymentOf)(d);
1179
+ if (xrpPay) {
1180
+ // #3699 PR2 — priced in XRP: what to SEND is the XRP payment; the HST lines say what it becomes.
1181
+ (0, xrp_payment_1.renderXrpPayment)(d, xrpPay);
1182
+ renderReserveSurcharge(d);
1183
+ (0, order_deadline_1.renderOrderDeadline)(d);
1184
+ console.log('');
1185
+ return;
1186
+ }
513
1187
  console.log(chalk_1.default.gray(` amount: ${d.amount} HST (token ${d.tokenId})`));
514
- console.log(chalk_1.default.gray(` to: ${d.walletAddress}\n`));
1188
+ renderReserveSurcharge(d);
1189
+ console.log(chalk_1.default.gray(` to: ${d.walletAddress}`));
1190
+ (0, order_deadline_1.renderDestinationTag)(d); // #3765
1191
+ (0, order_deadline_1.renderOrderDeadline)(d);
1192
+ console.log('');
1193
+ }
1194
+ /**
1195
+ * #3022 — show the reserve surcharge as its own line item. It is already inside
1196
+ * `amount`; the user still makes ONE HST payment.
1197
+ */
1198
+ function renderReserveSurcharge(d) {
1199
+ if (!d.reserveSurcharge)
1200
+ return;
1201
+ const xrp = Number(d.reserveSurcharge.xrpOutlayDrops) / 1_000_000;
1202
+ console.log(chalk_1.default.gray(` base: ${d.baseAmount ?? '?'} HST`));
1203
+ console.log(chalk_1.default.gray(` reserve surcharge: ${d.reserveSurcharge.hstAmount} HST (XRPL account reserve, ${xrp} XRP at ${d.reserveSurcharge.xrpPriceInHst} HST/XRP)`));
515
1204
  }
516
1205
  function renderManualPaymentHint(d) {
517
1206
  const xummDeeplink = buildXummDeeplink(d);
518
1207
  console.log(chalk_1.default.cyan(' --no-autopay: pay the deposit manually, then re-run `hsuite subscribe`.'));
1208
+ if ((0, xrp_payment_1.xrpPaymentOf)(d)) {
1209
+ console.log(chalk_1.default.cyan(' Send the XRP amount above with the Destination Tag — without the tag it is not matched to your order.'));
1210
+ }
519
1211
  console.log(chalk_1.default.cyan(' XUMM deeplink:'));
520
1212
  console.log(chalk_1.default.cyan(` ${xummDeeplink}\n`));
521
1213
  }
@@ -523,10 +1215,14 @@ function buildXummDeeplink(d) {
523
1215
  if (d.chain !== 'xrpl') {
524
1216
  return `(no deeplink: chain=${d.chain})`;
525
1217
  }
1218
+ // #3699 PR2 — an XRP order is paid in plain XRP (drops converted to XRP in the link), tag included.
1219
+ const xrpPay = (0, xrp_payment_1.xrpPaymentOf)(d);
1220
+ if (xrpPay)
1221
+ return (0, xrp_payment_1.xrpSendDeeplink)(xrpPay);
526
1222
  // Minimal Xumm deeplink shape; full IssuedCurrency requires a JSON payload
527
1223
  // pushed through https://xumm.app/sign — for the CLI we surface the raw tx
528
1224
  // 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)}`;
1225
+ return (0, order_deadline_1.xummSendDeeplink)(d);
530
1226
  }
531
1227
  exports.subscribeCommand = new commander_1.Command('subscribe')
532
1228
  .description('Subscribe a smart-app: create DKG entity → auto-pay deposit → mint → accept subscription NFT (mint-first)')
@@ -535,7 +1231,11 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
535
1231
  .option('--tier <tier>', 'Subscription tier (builder|growth|scale|enterprise)', 'builder')
536
1232
  .option('--app-id <id>', 'Resume an already-created entity by its appId (defaults to SUBSCRIPTION_APP_ID env). When unset, subscribe CREATES the DKG entity and uses its entityId.')
537
1233
  .option('--app-name <name>', 'Smart-app display name')
538
- .option('--no-autopay', 'Skip auto-paying the HST deposit; print instructions for manual (XUMM) payment')
1234
+ .option('--no-autopay', 'Skip auto-paying the deposit; print instructions for manual (XUMM) payment')
1235
+ .option('--pay-with <asset>', 'Asset to pay the subscription in: hsuite (default) or xrp. With xrp the validator quotes the price in XRP ' +
1236
+ '(the HST/XRP market plus a buffer) and the deposit is an XRP payment of the quoted amount with the order\'s ' +
1237
+ 'Destination Tag; the platform converts it into HST inside the deposit account. A validator with XRP ' +
1238
+ 'payments off or no HST/XRP market refuses, and nothing is created.')
539
1239
  .option('--nft-issuer <address>', 'Optional override for the XRPL subscription-NFT issuer. No longer required: the /status response now exposes chainNfts.xrpl (nftId + issuerAddress) and the offer is resolved from it automatically. Defaults to SUBSCRIPTION_NFT_ISSUER env.')
540
1240
  .action(async (opts) => {
541
1241
  console.log(chalk_1.default.bold.cyan('\n hsuite subscribe\n'));
@@ -554,7 +1254,7 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
554
1254
  result = await runSubscribe(opts);
555
1255
  }
556
1256
  catch (err) {
557
- spinner.fail(err.message);
1257
+ spinner.fail((0, error_message_1.errorMessage)(err));
558
1258
  process.exit(1);
559
1259
  }
560
1260
  if (!result.depositPaid) {
@@ -563,8 +1263,9 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
563
1263
  SUBSCRIPTION_APP_ID: result.appId,
564
1264
  APP_ID: result.appId,
565
1265
  };
566
- (0, env_1.upsertEnv)(opts.env, updates);
567
- console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID to ${opts.env}`));
1266
+ if (saveEnv(opts.env, updates)) {
1267
+ console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID to ${opts.env}`));
1268
+ }
568
1269
  console.log(chalk_1.default.yellow('\n Pay the deposit, then re-run `hsuite subscribe` to mint + accept the NFT.\n'));
569
1270
  return;
570
1271
  }
@@ -589,8 +1290,9 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
589
1290
  if (result.nftSerial !== undefined) {
590
1291
  updates.SUBSCRIPTION_NFT_SERIAL = String(result.nftSerial);
591
1292
  }
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}`));
1293
+ if (saveEnv(opts.env, updates)) {
1294
+ console.log(chalk_1.default.gray(`\n wrote SUBSCRIPTION_APP_ID${result.nftSerial !== undefined ? ' + SUBSCRIPTION_NFT_SERIAL' : ''} to ${opts.env}`));
1295
+ }
594
1296
  console.log(chalk_1.default.bold.green('\n ✓ subscribed\n'));
595
1297
  });
596
1298
  //# sourceMappingURL=subscribe.js.map