@hsuite/smart-engines-cli 1.9.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 (62) 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/env.d.ts.map +1 -1
  7. package/dist/_lib/env.js +9 -7
  8. package/dist/_lib/env.js.map +1 -1
  9. package/dist/_lib/error-message.d.ts +7 -0
  10. package/dist/_lib/error-message.d.ts.map +1 -0
  11. package/dist/_lib/error-message.js +21 -0
  12. package/dist/_lib/error-message.js.map +1 -0
  13. package/dist/_lib/order-deadline.d.ts +23 -0
  14. package/dist/_lib/order-deadline.d.ts.map +1 -1
  15. package/dist/_lib/order-deadline.js +40 -6
  16. package/dist/_lib/order-deadline.js.map +1 -1
  17. package/dist/_lib/payment-guard.d.ts +59 -0
  18. package/dist/_lib/payment-guard.d.ts.map +1 -0
  19. package/dist/_lib/payment-guard.js +188 -0
  20. package/dist/_lib/payment-guard.js.map +1 -0
  21. package/dist/_lib/payment-lock.d.ts +27 -0
  22. package/dist/_lib/payment-lock.d.ts.map +1 -0
  23. package/dist/_lib/payment-lock.js +199 -0
  24. package/dist/_lib/payment-lock.js.map +1 -0
  25. package/dist/_lib/payment-record.d.ts +70 -0
  26. package/dist/_lib/payment-record.d.ts.map +1 -0
  27. package/dist/_lib/payment-record.js +78 -0
  28. package/dist/_lib/payment-record.js.map +1 -0
  29. package/dist/_lib/runtime-env.d.ts.map +1 -1
  30. package/dist/_lib/runtime-env.js +5 -0
  31. package/dist/_lib/runtime-env.js.map +1 -1
  32. package/dist/_lib/subscription-client.d.ts +40 -11
  33. package/dist/_lib/subscription-client.d.ts.map +1 -1
  34. package/dist/_lib/subscription-client.js +9 -0
  35. package/dist/_lib/subscription-client.js.map +1 -1
  36. package/dist/_lib/xrp-payment.d.ts +33 -0
  37. package/dist/_lib/xrp-payment.d.ts.map +1 -0
  38. package/dist/_lib/xrp-payment.js +99 -0
  39. package/dist/_lib/xrp-payment.js.map +1 -0
  40. package/dist/_lib/xrpl-login-signer.d.ts +16 -1
  41. package/dist/_lib/xrpl-login-signer.d.ts.map +1 -1
  42. package/dist/_lib/xrpl-login-signer.js +25 -1
  43. package/dist/_lib/xrpl-login-signer.js.map +1 -1
  44. package/dist/commands/faucet.d.ts +1 -1
  45. package/dist/commands/faucet.d.ts.map +1 -1
  46. package/dist/commands/faucet.js +2 -7
  47. package/dist/commands/faucet.js.map +1 -1
  48. package/dist/commands/subscribe.d.ts +17 -3
  49. package/dist/commands/subscribe.d.ts.map +1 -1
  50. package/dist/commands/subscribe.js +223 -107
  51. package/dist/commands/subscribe.js.map +1 -1
  52. package/dist/commands/topup.d.ts +19 -7
  53. package/dist/commands/topup.d.ts.map +1 -1
  54. package/dist/commands/topup.js +126 -14
  55. package/dist/commands/topup.js.map +1 -1
  56. package/dist/commands/upgrade.d.ts.map +1 -1
  57. package/dist/commands/upgrade.js +15 -4
  58. package/dist/commands/upgrade.js.map +1 -1
  59. package/dist/commands/verify.d.ts.map +1 -1
  60. package/dist/commands/verify.js +7 -1
  61. package/dist/commands/verify.js.map +1 -1
  62. package/package.json +2 -2
@@ -51,7 +51,9 @@ exports.renderReserveSurcharge = renderReserveSurcharge;
51
51
  * second subscription, no second deposit wallet).
52
52
  * 5. Render the deposit instructions.
53
53
  * 6. AUTO-PAY the deposit from the dev wallet over the XRPL testnet (HST
54
- * Payment with a SendMax covering the 0.25% transfer fee). `--no-autopay`
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`
55
57
  * skips this and prints instructions for manual (XUMM) payment; re-running
56
58
  * `hsuite subscribe` afterwards resumes the saved entity. A RESUMED run first
57
59
  * asks GET /status and never pays a deposit the platform reports credited
@@ -82,11 +84,16 @@ const ora_1 = __importDefault(require("ora"));
82
84
  const smart_engines_sdk_1 = require("@hsuite/smart-engines-sdk");
83
85
  const env_1 = require("../_lib/env");
84
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");
85
91
  const create_outcome_1 = require("../_lib/create-outcome");
86
92
  const subscription_client_1 = require("../_lib/subscription-client");
87
93
  const subscription_env_1 = require("../_lib/subscription-env");
88
94
  const order_deadline_1 = require("../_lib/order-deadline");
89
95
  const xrpl_login_signer_1 = require("../_lib/xrpl-login-signer");
96
+ const xrp_payment_1 = require("../_lib/xrp-payment");
90
97
  /** Public XRPL testnet websocket endpoint (matches `hsuite init` + faucet). */
91
98
  const XRPL_TESTNET_WSS = 'wss://s.altnet.rippletest.net:51233';
92
99
  /**
@@ -105,11 +112,10 @@ function defaultXrplClientFactory(wss) {
105
112
  const { Client } = require('xrpl');
106
113
  return new Client(wss);
107
114
  }
108
- function defaultWalletSignFactory(seed) {
115
+ function defaultHashSignedTx(txBlob) {
109
116
  // eslint-disable-next-line @typescript-eslint/no-var-requires
110
- const { Wallet } = require('xrpl');
111
- const wallet = Wallet.fromSeed(seed);
112
- return (tx) => wallet.sign(tx).tx_blob;
117
+ const { hashes } = require('xrpl');
118
+ return hashes.hashSignedTx(txBlob);
113
119
  }
114
120
  /**
115
121
  * Default entity-create-intent signer (#3506 A3, MEDIUM-1 fix): the SAME
@@ -137,12 +143,21 @@ async function defaultIntentSignerFactory(address, seed) {
137
143
  * this and exits the process.
138
144
  */
139
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) {
140
153
  const env = (0, env_1.readEnv)(opts.env);
141
154
  const { address, seed } = (0, subscription_env_1.requireXrplCreds)(env);
142
155
  const tier = opts.tier;
143
156
  if (!VALID_TIERS.includes(tier)) {
144
157
  throw new Error(`unknown tier "${opts.tier}". Valid: ${VALID_TIERS.join(', ')}`);
145
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);
146
161
  const baseUrl = (0, subscription_env_1.requireValidatorUrl)(env, { gateway: opts.gateway });
147
162
  const client = (opts.clientFactory ??
148
163
  ((b) => new subscription_client_1.SubscriptionClient({ baseUrl: b, auth: { chain: 'xrpl', address, seed } })))(baseUrl);
@@ -185,38 +200,31 @@ async function runSubscribe(opts) {
185
200
  resumedFrom = `the unfinished create recorded in ${opts.env}`;
186
201
  }
187
202
  }
188
- let appId;
189
- let created;
190
- if (preexistingAppId) {
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'));
196
- }
197
- else {
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 () => {
198
206
  // #3506 A3 — every legitimate customer create carries a signed intent.
199
207
  // `GET /api/v3/discovery/network` is the PUBLIC, ingress-routed source of
200
208
  // the cluster's GenesisConfig.network — the exact value every responder
201
209
  // compares the intent's `network` field against (HIGH-2: genesis/status
202
210
  // 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) {
211
+ const discovered = await (0, smart_engines_sdk_1.fetchIntentNetwork)(baseUrl);
212
+ if (!discovered.ok) {
205
213
  // HIGH-1(a): a 404 means this cluster predates signed create intents
206
214
  // (#3635 + this endpoint haven't shipped there yet). Refuse BEFORE
207
215
  // creating anything — an old validator would otherwise silently strip
208
216
  // `creationIntent`, create a RANDOM-id entity, and the post-create
209
217
  // assert below would then throw, orphaning that entity + its pending
210
218
  // subscription on every retry.
211
- if (intentNetwork.status === 404) {
219
+ if (discovered.status === 404) {
212
220
  throw new Error('cannot build a signed entity-create intent: GET /api/v3/discovery/network ' +
213
221
  'was not found (404) — this cluster predates signed create intents; upgrade ' +
214
222
  'the cluster (ship #3635 + this endpoint) before running `hsuite subscribe`.');
215
223
  }
216
224
  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`);
225
+ `failed (status ${discovered.status}) — refusing to create without a verified network`);
218
226
  }
219
- const network = intentNetwork.network;
227
+ const network = discovered.network;
220
228
  // #3506 A3 LOW-1 (lying/misconfigured gateway, mainnet-only guard):
221
229
  // `HSUITE_NETWORK` records which HSUITE CLUSTER `VALIDATOR_URL`/
222
230
  // `SMART_HOST_URL` were resolved from (`hsuite init`, see `init.ts:
@@ -243,17 +251,57 @@ async function runSubscribe(opts) {
243
251
  'entity-create intent unless HSUITE_NETWORK=mainnet (possible lying or ' +
244
252
  'misconfigured gateway)');
245
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
+ };
282
+ let appId;
283
+ let created;
284
+ if (preexistingAppId) {
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'));
290
+ }
291
+ else {
292
+ const network = await intentNetwork();
246
293
  // The developer authors the rule CLIENT-SIDE (the wallet signs its hash) —
247
294
  // the standard default, byte-identical to what the validator would
248
295
  // otherwise synthesize server-side for the same deployment path.
249
296
  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, {
297
+ const { proof: creationIntent, entityId: expectedEntityId } = await (0, smart_engines_sdk_1.signEntityCreateIntent)(await intentSigner(), {
252
298
  network,
253
299
  entityType: 'smart-app',
254
300
  chain: 'xrpl',
255
301
  rule: validatorRules,
256
302
  });
303
+ // #3506 A2c — and the deposit wallet's intent, bound to the entityId the app intent derives.
304
+ const depositCreationIntent = await signDepositIntent(expectedEntityId);
257
305
  // #3766 — record the create as PENDING before the request leaves: it is a long synchronous
258
306
  // ceremony and this client gives up first, so "no answer" must not be mistaken for "nothing
259
307
  // was created". Refuses (nothing sent) when the record cannot be kept.
@@ -275,6 +323,9 @@ async function runSubscribe(opts) {
275
323
  // binding this create to it (and to a leader-independent entityId).
276
324
  validatorRules,
277
325
  creationIntent,
326
+ depositCreationIntent,
327
+ // #3699 PR2 — priced in XRP when asked; omitted (= HSUITE) otherwise, as ever.
328
+ ...(payWith === 'xrp' ? { paymentAsset: 'XRP' } : {}),
278
329
  });
279
330
  }
280
331
  catch (err) {
@@ -282,9 +333,9 @@ async function runSubscribe(opts) {
282
333
  // The platform rejected the request, or it never left this machine: nothing was created,
283
334
  // so nothing is pending and the next run creates normally.
284
335
  clearPendingCreate(opts.env);
285
- throw new Error(`smart-app entity creation failed: ${errorMessage(err)}`, { cause: err });
336
+ throw new Error(`smart-app entity creation failed: ${(0, error_message_1.errorMessage)(err)}`, { cause: err });
286
337
  }
287
- throw new Error(`smart-app entity creation failed: ${errorMessage(err)}${unknownCreateNote(expectedEntityId, opts.env, inv)}`, { cause: err });
338
+ throw new Error(`smart-app entity creation failed: ${(0, error_message_1.errorMessage)(err)}${unknownCreateNote(expectedEntityId, opts.env, inv)}`, { cause: err });
288
339
  }
289
340
  if (!created?.appId) {
290
341
  // The platform answered (even with an empty 2xx body), but without the entity: it may well
@@ -314,7 +365,7 @@ async function runSubscribe(opts) {
314
365
  `The server created an ORPHANED entity at appId "${created.appId}" (a subscription ` +
315
366
  `may exist on it, unaffiliated with your wallet). Do NOT retry blindly. Record ` +
316
367
  `"${created.appId}" and investigate the cluster (bug, stale validator missing ` +
317
- `#3635, or compromise) before creating again. Original error: ${errorMessage(err)}`);
368
+ `#3635, or compromise) before creating again. Original error: ${(0, error_message_1.errorMessage)(err)}`);
318
369
  }
319
370
  appId = created.appId;
320
371
  // #3754 — record the entity BEFORE any further step (deposit instructions,
@@ -334,18 +385,34 @@ async function runSubscribe(opts) {
334
385
  let deposit = created?.depositInstructions;
335
386
  let subscriptionId = created?.subscriptionId;
336
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
+ };
337
397
  try {
338
- requested = await client.request({
339
- appId,
340
- developerAccountId: address,
341
- chain: 'xrpl',
342
- appName,
343
- selectedTier: tier,
344
- selectedNetworks: ['xrpl'],
345
- });
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
+ }
346
413
  }
347
414
  catch (err) {
348
- throw new Error(`subscription request failed: ${errorMessage(err)}${unpaidNote(appId, opts.env, inv)}`, {
415
+ throw new Error(`subscription request failed: ${(0, error_message_1.errorMessage)(err)}${unpaidNote(appId, opts.env, inv)}`, {
349
416
  cause: err,
350
417
  });
351
418
  }
@@ -381,6 +448,7 @@ async function runSubscribe(opts) {
381
448
  const status = standing.subscriptionNftSerial || standing.chainNfts?.xrpl?.nftId
382
449
  ? standing
383
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
384
452
  const nftAccepted = await acceptSubscriptionNft(opts, address, seed, sleep, status);
385
453
  return {
386
454
  appId,
@@ -427,7 +495,26 @@ async function runSubscribe(opts) {
427
495
  }
428
496
  catch (err) {
429
497
  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 });
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
+ }
431
518
  }
432
519
  // A resumed entity keeps the tier it was created with, which this run's
433
520
  // --tier says nothing about: print the tier only for an entity created now.
@@ -445,7 +532,7 @@ async function runSubscribe(opts) {
445
532
  };
446
533
  }
447
534
  try {
448
- paid = await payDeposit(opts, address, seed, deposit);
535
+ paid = await payDeposit(opts, address, seed, deposit, appId);
449
536
  }
450
537
  catch (err) {
451
538
  // #3754 — the entity exists whether or not this payment did (it is already
@@ -457,6 +544,7 @@ async function runSubscribe(opts) {
457
544
  }
458
545
  // Step 3: poll /status until the deposit is confirmed and ready to mint.
459
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
460
548
  // Step 4: POST /mint — kicks off the async NFT mint. Tolerate a non-2xx here
461
549
  // (the server may still be finalizing); the status poll below is the source of
462
550
  // truth for whether the NFT actually minted.
@@ -467,7 +555,7 @@ async function runSubscribe(opts) {
467
555
  }
468
556
  }
469
557
  catch (err) {
470
- console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${errorMessage(err)}`));
558
+ console.log(chalk_1.default.yellow(` mint HTTP error (tolerated, will poll status): ${(0, error_message_1.errorMessage)(err)}`));
471
559
  }
472
560
  // Step 5: poll until the NFT serial is set OR the minted NFT coordinates
473
561
  // appear on /status (the NFT mints asynchronously via the mint subscriber).
@@ -505,23 +593,6 @@ function toDnsSafeName(name) {
505
593
  .replace(/-+$/g, '');
506
594
  return slug.length > 0 ? slug : 'smart-app';
507
595
  }
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
596
  /** `value` as one shell word: left as is when it is plain, else single-quoted. */
526
597
  function shellQuote(value) {
527
598
  return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
@@ -546,42 +617,38 @@ function unpaidNote(appId, envPath, inv) {
546
617
  return (` — smart-app entity ${appId} is saved and NOTHING has been paid. Re-run ` +
547
618
  `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it (that will NOT create a second entity).`);
548
619
  }
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
620
  /** The error for a payment that did not go through (or may not have) — see {@link PaymentOutcomeUnknownError}. */
561
621
  function paymentFailure(err, ctx) {
562
622
  const entity = `smart-app entity ${ctx.appId} (subscription ${ctx.subscriptionId ?? 'n/a'}, ` +
563
623
  `order ${ctx.deposit.orderId ?? 'n/a'})`;
564
624
  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 ` +
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 ` +
566
626
  `credited it yet. NOT paying again. ${entity} is saved. Give the platform about a minute, then run ` +
567
627
  `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it mints and ` +
568
628
  'accepts the NFT once the platform credits the deposit. If that balance is NOT a payment for this ' +
569
629
  'order, the same command prints what to pay by hand.', { cause: err });
570
630
  }
571
- if (err instanceof PaymentOutcomeUnknownError) {
572
- return new Error(`${errorMessage(err)} — the payment was submitted but its outcome is UNKNOWN: it may still ` +
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 ` +
573
640
  `validate. ${entity} is saved. BEFORE re-running, check whether ${ctx.address} already sent ` +
574
641
  `HST to ${ctx.deposit.walletAddress} (an XRPL testnet explorer shows it): re-running can pay ` +
575
642
  'AGAIN. If it did go through, wait about a minute and run ' +
576
643
  `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv, true))}\` — it cannot pay, and it ` +
577
644
  'mints and accepts the NFT once the platform credits the deposit.', { cause: err });
578
645
  }
579
- return new Error(`${errorMessage(err)} — ${entity} is NOT orphaned. Fix the cause, then re-run ` +
646
+ return new Error(`${(0, error_message_1.errorMessage)(err)} — ${entity} is NOT orphaned. Fix the cause, then re-run ` +
580
647
  `\`${resumeCommand(ctx.appId, ctx.envPath, resumeFlags(ctx.inv))}\` to resume it — that will NOT create a second entity.`, { cause: err });
581
648
  }
582
649
  /** The error for a step that failed AFTER this run's deposit payment validated. */
583
650
  function paidThenFailed(err, receipt, appId, envPath, inv) {
584
- return new Error(`${errorMessage(err)} — the deposit payment${receipt.hash ? ` (tx ${receipt.hash})` : ''} WAS validated ` +
651
+ return new Error(`${(0, error_message_1.errorMessage)(err)} — the deposit payment${receipt.hash ? ` (tx ${receipt.hash})` : ''} WAS validated ` +
585
652
  'on the ledger: do NOT pay again. Give the platform about a minute to credit it, then run ' +
586
653
  `\`${resumeCommand(appId, envPath, resumeFlags(inv, true))}\` — it cannot pay, and it finishes minting ` +
587
654
  'and accepting the NFT.', { cause: err });
@@ -600,7 +667,7 @@ async function readStandingBeforePaying(client, appId, envPath, inv) {
600
667
  standing = await client.status(appId);
601
668
  }
602
669
  catch (err) {
603
- throw new Error(`could not read where subscription ${appId} stands (${errorMessage(err)})${unpaidNote(appId, envPath, inv)}`, { cause: err });
670
+ throw new Error(`could not read where subscription ${appId} stands (${(0, error_message_1.errorMessage)(err)})${unpaidNote(appId, envPath, inv)}`, { cause: err });
604
671
  }
605
672
  if (standing.hasSubscription === false) {
606
673
  throw new Error(`the platform that answered has no subscription for smart-app entity ${appId} that this wallet ` +
@@ -625,7 +692,7 @@ function persistCreatedEntity(envPath, appId, inv) {
625
692
  }
626
693
  catch (err) {
627
694
  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 ` +
695
+ `(${(0, error_message_1.errorMessage)(err)}). Nothing has been paid. Re-run ` +
629
696
  `\`${resumeCommand(appId, envPath, resumeFlags(inv))}\` to resume it.`, { cause: err });
630
697
  }
631
698
  // The create has its verdict now: it is no longer pending.
@@ -652,7 +719,7 @@ function recordPendingCreate(envPath, entityId, until) {
652
719
  (0, env_1.upsertEnv)(envPath, { [create_outcome_1.PENDING_CREATE_KEY]: (0, create_outcome_1.formatPendingCreate)({ appId: entityId, until }) });
653
720
  }
654
721
  catch (err) {
655
- throw new Error(`cannot record the create of smart-app entity ${entityId} in ${envPath} (${errorMessage(err)}) — ` +
722
+ throw new Error(`cannot record the create of smart-app entity ${entityId} in ${envPath} (${(0, error_message_1.errorMessage)(err)}) — ` +
656
723
  'refusing to send it: a create this CLI cannot keep track of could be orphaned. ' +
657
724
  'Nothing was created and nothing has been paid.', { cause: err });
658
725
  }
@@ -714,7 +781,7 @@ async function reconcileUnfinishedCreate(client, env, envPath, inv) {
714
781
  standing = await client.status(pending.appId);
715
782
  }
716
783
  catch (err) {
717
- throw new Error(`${earlier}, and the platform could not be asked whether it exists (${errorMessage(err)}) — ` +
784
+ throw new Error(`${earlier}, and the platform could not be asked whether it exists (${(0, error_message_1.errorMessage)(err)}) — ` +
718
785
  `nothing has been created or paid now. Re-run \`${rerunCommand(envPath, inv)}\` in a minute. ` +
719
786
  forgetPendingHint(envPath), { cause: err });
720
787
  }
@@ -747,7 +814,7 @@ function saveEnv(envPath, updates) {
747
814
  return true;
748
815
  }
749
816
  catch (err) {
750
- console.log(chalk_1.default.yellow(`\n could not write ${envPath} (${errorMessage(err)}) — add these by hand:`));
817
+ console.log(chalk_1.default.yellow(`\n could not write ${envPath} (${(0, error_message_1.errorMessage)(err)}) — add these by hand:`));
751
818
  for (const [key, value] of Object.entries(updates)) {
752
819
  console.log(chalk_1.default.yellow(` ${key}=${value}`));
753
820
  }
@@ -774,19 +841,37 @@ function saveEnv(envPath, updates) {
774
841
  * the ledger and the payment is refused ({@link DepositAlreadyOnLedgerError}) when the account
775
842
  * already holds what the quote asks, or when that balance cannot be read at all.
776
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
+ *
777
851
  * Requires tesSUCCESS. Always disconnects. A thrown wait for the verdict (the
778
852
  * blob is already out) surfaces as {@link PaymentOutcomeUnknownError}; a `tec*` /
779
853
  * `tem*` verdict is a plain failure — nothing was delivered.
780
854
  */
781
- async function payDeposit(opts, address, seed, deposit) {
855
+ async function payDeposit(opts, address, seed, deposit, appId) {
782
856
  if (deposit.chain !== 'xrpl') {
783
857
  throw new Error(`auto-pay only supports XRPL deposits (got chain=${deposit.chain}); ` +
784
858
  'use --no-autopay and pay manually');
785
859
  }
786
- const walletSign = (opts.walletSignFactory ?? defaultWalletSignFactory)(seed);
860
+ const walletSign = (opts.walletSignFactory ?? xrpl_login_signer_1.buildXrplTxSigner)(seed);
787
861
  const client = (opts.xrplClientFactory ?? defaultXrplClientFactory)(XRPL_TESTNET_WSS);
788
862
  await client.connect();
789
863
  try {
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
+ }
790
875
  const { issuer, balance } = await readDepositHstLine(client, deposit.walletAddress);
791
876
  // #3771 — the LEDGER is the one source of truth every cluster agrees on: a deposit
792
877
  // account that already holds what this quote asks has been paid, whatever a replica's
@@ -802,25 +887,7 @@ async function payDeposit(opts, address, seed, deposit) {
802
887
  SendMax: { currency: 'HST', issuer, value: sendMax },
803
888
  ...(deposit.destinationTag !== undefined ? { DestinationTag: deposit.destinationTag } : {}),
804
889
  };
805
- const prepared = await client.autofill(tx);
806
- const txBlob = walletSign(prepared);
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
- }
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
- }
820
- if (code !== 'tesSUCCESS') {
821
- throw new Error(`deposit Payment failed: ${code}`);
822
- }
823
- return { hash: result.result?.hash };
890
+ return await signRecordAndSubmit(client, walletSign, opts, tx, appId);
824
891
  }
825
892
  finally {
826
893
  // A failing disconnect (a dead socket) must not replace the error that got us here — above all
@@ -828,6 +895,41 @@ async function payDeposit(opts, address, seed, deposit) {
828
895
  await client.disconnect().catch(() => undefined);
829
896
  }
830
897
  }
898
+ /**
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
+ }
831
933
  /**
832
934
  * Read the deposit account's HST trust line: the HST issuer and what the account holds.
833
935
  *
@@ -965,7 +1067,7 @@ async function acceptSubscriptionNft(opts, address, seed, sleep, status) {
965
1067
  // Explicit override wins; otherwise use the issuer the status now exposes.
966
1068
  const issuer = opts.nftIssuer ?? xrplNft?.issuerAddress;
967
1069
  const client = (opts.xrplClientFactory ?? defaultXrplClientFactory)(XRPL_TESTNET_WSS);
968
- const walletSign = (opts.walletSignFactory ?? defaultWalletSignFactory)(seed);
1070
+ const walletSign = (opts.walletSignFactory ?? xrpl_login_signer_1.buildXrplTxSigner)(seed);
969
1071
  const attempts = opts.acceptAttempts ?? 10;
970
1072
  const retryMs = opts.acceptRetryMs ?? opts.pollIntervalMs ?? 5000;
971
1073
  await client.connect();
@@ -1073,15 +1175,19 @@ function renderDepositInstructions(d, tier, appId) {
1073
1175
  if (tier)
1074
1176
  console.log(chalk_1.default.gray(` tier: ${tier}`));
1075
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
+ }
1076
1187
  console.log(chalk_1.default.gray(` amount: ${d.amount} HST (token ${d.tokenId})`));
1077
1188
  renderReserveSurcharge(d);
1078
1189
  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
- }
1190
+ (0, order_deadline_1.renderDestinationTag)(d); // #3765
1085
1191
  (0, order_deadline_1.renderOrderDeadline)(d);
1086
1192
  console.log('');
1087
1193
  }
@@ -1099,6 +1205,9 @@ function renderReserveSurcharge(d) {
1099
1205
  function renderManualPaymentHint(d) {
1100
1206
  const xummDeeplink = buildXummDeeplink(d);
1101
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
+ }
1102
1211
  console.log(chalk_1.default.cyan(' XUMM deeplink:'));
1103
1212
  console.log(chalk_1.default.cyan(` ${xummDeeplink}\n`));
1104
1213
  }
@@ -1106,11 +1215,14 @@ function buildXummDeeplink(d) {
1106
1215
  if (d.chain !== 'xrpl') {
1107
1216
  return `(no deeplink: chain=${d.chain})`;
1108
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);
1109
1222
  // Minimal Xumm deeplink shape; full IssuedCurrency requires a JSON payload
1110
1223
  // pushed through https://xumm.app/sign — for the CLI we surface the raw tx
1111
1224
  // params so the user can paste them into their wallet.
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}`;
1225
+ return (0, order_deadline_1.xummSendDeeplink)(d);
1114
1226
  }
1115
1227
  exports.subscribeCommand = new commander_1.Command('subscribe')
1116
1228
  .description('Subscribe a smart-app: create DKG entity → auto-pay deposit → mint → accept subscription NFT (mint-first)')
@@ -1119,7 +1231,11 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
1119
1231
  .option('--tier <tier>', 'Subscription tier (builder|growth|scale|enterprise)', 'builder')
1120
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.')
1121
1233
  .option('--app-name <name>', 'Smart-app display name')
1122
- .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.')
1123
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.')
1124
1240
  .action(async (opts) => {
1125
1241
  console.log(chalk_1.default.bold.cyan('\n hsuite subscribe\n'));
@@ -1138,7 +1254,7 @@ exports.subscribeCommand = new commander_1.Command('subscribe')
1138
1254
  result = await runSubscribe(opts);
1139
1255
  }
1140
1256
  catch (err) {
1141
- spinner.fail(errorMessage(err));
1257
+ spinner.fail((0, error_message_1.errorMessage)(err));
1142
1258
  process.exit(1);
1143
1259
  }
1144
1260
  if (!result.depositPaid) {