@arkade-os/swap 0.1.0-rc.13 → 0.1.0-rc.15

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 (53) hide show
  1. package/README.md +11 -0
  2. package/dist/advanced.cjs +1028 -1006
  3. package/dist/advanced.d.cts +145 -279
  4. package/dist/advanced.d.ts +145 -279
  5. package/dist/advanced.js +14 -8
  6. package/dist/{chunk-SC3SAY3X.js → chunk-4WPDXLXH.js} +501 -271
  7. package/dist/chunk-A3SHHRX4.js +104 -0
  8. package/dist/{chunk-KRXPQQJ7.js → chunk-BBP25BWH.js} +198 -218
  9. package/dist/{chunk-ZDFMD4FA.js → chunk-RX3WPV5D.js} +356 -584
  10. package/dist/errors-BcOgFV-F.d.ts +1559 -0
  11. package/dist/errors-n6IHTG-Z.d.cts +1559 -0
  12. package/dist/index.cjs +1406 -1331
  13. package/dist/index.d.cts +69 -186
  14. package/dist/index.d.ts +69 -186
  15. package/dist/index.js +102 -158
  16. package/dist/lockupContract-B_jNbjrG.d.ts +215 -0
  17. package/dist/lockupContract-ZsftgqMc.d.cts +215 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +227 -600
  20. package/dist/node/index.d.ts +227 -600
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +11 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer--1zVkNsV.d.ts +261 -0
  27. package/dist/offer-DsP1q6GE.d.cts +261 -0
  28. package/dist/protocol.cjs +747 -1012
  29. package/dist/protocol.d.cts +120 -255
  30. package/dist/protocol.d.ts +120 -255
  31. package/dist/protocol.js +146 -149
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BY6GUQiW.d.ts +2233 -0
  41. package/dist/repository-C32GKpR5.d.cts +2233 -0
  42. package/dist/{rfq-BWE8qkV2.d.ts → rfq-60PGpQ_x.d.cts} +178 -408
  43. package/dist/{rfq-BWE8qkV2.d.cts → rfq-60PGpQ_x.d.ts} +178 -408
  44. package/dist/{watch-D8Z78RAV.d.ts → watch-Cejw5cNQ.d.cts} +12 -30
  45. package/dist/{watch-C4ReJR5z.d.cts → watch-D8uzWrHc.d.ts} +12 -30
  46. package/package.json +2 -2
  47. package/dist/chunk-U7VWWTL6.js +0 -66
  48. package/dist/errors-LXMcNhNS.d.ts +0 -2222
  49. package/dist/errors-XUs8r0LT.d.cts +0 -2222
  50. package/dist/lockupContract-BhMebZCb.d.cts +0 -650
  51. package/dist/lockupContract-CAiN97fX.d.ts +0 -650
  52. package/dist/repository-BJLuVFQ0.d.ts +0 -3436
  53. package/dist/repository-DsR3b0JJ.d.cts +0 -3436
@@ -1,3 +1,7 @@
1
+ import {
2
+ collectAssetSwaps
3
+ } from "./chunk-A3SHHRX4.js";
4
+
1
5
  // src/store.ts
2
6
  import { hex } from "@scure/base";
3
7
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -5,7 +9,7 @@ import { contractPreimage } from "@arkade-os/sdk";
5
9
  var BTC_ASSET_ID = "btc";
6
10
  var byNewest = (a, b) => b.createdAt - a.createdAt;
7
11
  var getAssetSwapsOrThrow = async (repository) => {
8
- return (await repository.getAllSwaps()).filter(
12
+ return (await collectAssetSwaps(repository)).filter(
9
13
  (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
10
14
  // the payment hash instead — either marks a valid record
11
15
  (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
@@ -421,9 +425,7 @@ function decodeOffer(data) {
421
425
  }
422
426
  const need = (name) => {
423
427
  const v = fields[name];
424
- const len = FIELDS[name].width;
425
- if (!v || len !== void 0 && v.length !== len)
426
- throw new Error(`missing/invalid ${name}`);
428
+ if (!v) throw new Error(`missing/invalid ${name}`);
427
429
  return v;
428
430
  };
429
431
  const amount = need("wantAmount");
@@ -464,25 +466,18 @@ var OFFER_CONTRACT_LABEL = "Arkade swap offer";
464
466
  var OFFER_CONTRACT_KIND = "asset-swap-offer";
465
467
  async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
466
468
  const contractManager = await wallet.getContractManager();
467
- const client = await arkade.Arkade.connect({
468
- // Registration derives and persists; it never broadcasts and never
469
- // reads UTXOs, so the only thing the client needs off the server is the
470
- // info the caller already resolved. Handing that back — rather than a
471
- // provider built from a URL — is what lets `createOffer` take just a
472
- // wallet, and spares a second `/v1/info` round-trip.
473
- arkade: { getInfo: async () => info },
474
- identity: wallet.identity,
475
- // without this the row's `address` would be derived against the SDK's
476
- // default network while its script is right — a row that disagrees with
477
- // the address the user is about to fund
478
- network: networkFromArkadeInfo(info),
479
- contractManager
480
- });
469
+ const client = await derivingClient(wallet, info, contractManager);
481
470
  await contractManager.createContract(
482
471
  offerContractParams(client, binding, operatorPubkey, expectedPkScript)
483
472
  );
484
473
  await promoteOfferContract(contractManager, hex2.encode(expectedPkScript));
485
474
  }
475
+ var derivingClient = (wallet, info, contractManager) => arkade.Arkade.connect({
476
+ arkade: { getInfo: async () => info },
477
+ identity: wallet.identity,
478
+ network: networkFromArkadeInfo(info),
479
+ contractManager
480
+ });
486
481
  function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
487
482
  const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
488
483
  const contract = new arkade.ArkadeContract(client, program, args, keys);
@@ -503,12 +498,7 @@ async function restoreOfferCoverage(wallet, swaps) {
503
498
  wallet.getContractManager()
504
499
  ]);
505
500
  const operatorPubkey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
506
- const client = await arkade.Arkade.connect({
507
- arkade: { getInfo: async () => info },
508
- identity: wallet.identity,
509
- network: networkFromArkadeInfo(info),
510
- contractManager
511
- });
501
+ const client = await derivingClient(wallet, info, contractManager);
512
502
  const seen = /* @__PURE__ */ new Set();
513
503
  const covenants = [];
514
504
  for (const swap of live) {
@@ -549,47 +539,69 @@ function serverExitDelay(delay) {
549
539
  return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
550
540
  }
551
541
  async function createOffer(wallet, params) {
542
+ const derived = await deriveOffer(wallet, params);
543
+ await registerDerivedOffer(wallet, derived);
544
+ return {
545
+ offerHex: derived.offerHex,
546
+ extension: derived.extension,
547
+ address: derived.address,
548
+ swapPkScript: derived.swapPkScript
549
+ };
550
+ }
551
+ async function deriveOffer(wallet, params) {
552
552
  if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
553
553
  throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
554
554
  }
555
- const [info, makerAddress, makerPublicKey] = await Promise.all([
556
- // requireLive: this info binds signerPubkey into the covenant — a
557
- // snapshot could derive an address the operator no longer co-signs
558
- // for, so an unreachable operator fails the call instead (fail closed,
559
- // the same behaviour the pre-#734 caller-held provider had)
560
- wallet.getArkadeInfo({ requireLive: true }),
561
- wallet.getAddress(),
562
- wallet.identity.xOnlyPublicKey()
555
+ const [info, maker] = await Promise.all([
556
+ // requireLive: this binds signerPubkey into the covenant, and a snapshot could derive an
557
+ // address the operator no longer co-signs for — fail closed instead
558
+ params.info ?? wallet.getArkadeInfo({ requireLive: true }),
559
+ params.maker ?? (async () => {
560
+ const [address, publicKey] = await Promise.all([
561
+ wallet.getAddress(),
562
+ wallet.identity.xOnlyPublicKey()
563
+ ]);
564
+ return { pkScript: ArkAddress.decode(address).pkScript, publicKey };
565
+ })()
563
566
  ]);
564
567
  const operatorPubKey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
565
568
  const network = networkFromArkadeInfo(info);
566
569
  const emuKey = hex2.decode(
567
570
  toXOnlySignerHex(resolveEmulatorPubkey(network, params.emulatorPubkey))
568
571
  );
569
- const binding = {
572
+ const binding = Object.freeze({
570
573
  wantAmount: params.wantAmount,
571
574
  wantAsset: params.wantAsset,
572
575
  offerAsset: params.offerAsset,
573
- makerPkScript: ArkAddress.decode(makerAddress).pkScript,
574
- makerPublicKey,
576
+ makerPkScript: maker.pkScript,
577
+ makerPublicKey: maker.publicKey,
575
578
  emulatorPubkey: emuKey,
576
- // checked HERE, before the covenant is derived and registered below:
577
- // deferring it to `encodeOffer` leaves a registered contract behind for
578
- // an offer that then fails to encode. @see assertExitDelay
579
+ // checked before registration below. @see assertExitDelay
579
580
  exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
580
- };
581
+ });
581
582
  const script = offerContract(binding, operatorPubKey);
582
583
  const offer = { ...binding, swapPkScript: script.pkScript };
583
- await registerOfferContract(wallet, info, binding, operatorPubKey, script.pkScript);
584
584
  const payload = encodeOffer(offer);
585
- return {
585
+ return Object.freeze({
586
586
  offerHex: hex2.encode(payload),
587
587
  extension: { type: OFFER_PACKET_TYPE, payload },
588
588
  // the contract's .address() builds the address; assembling an ArkAddress
589
589
  // from tweakedPublicKey here would silently miss any future step it gains
590
590
  address: script.address(network.hrp, operatorPubKey).encode(),
591
- swapPkScript: script.pkScript
592
- };
591
+ swapPkScript: script.pkScript,
592
+ binding,
593
+ info,
594
+ operatorPubkey: operatorPubKey
595
+ });
596
+ }
597
+ async function registerDerivedOffer(wallet, derived) {
598
+ await registerOfferContract(
599
+ wallet,
600
+ derived.info,
601
+ derived.binding,
602
+ derived.operatorPubkey,
603
+ derived.swapPkScript
604
+ );
593
605
  }
594
606
  async function cancelOffer(wallet, offerHex, opts) {
595
607
  const { repository, fundingTxid, swapAddress } = opts;
@@ -617,7 +629,6 @@ async function cancelOffer(wallet, offerHex, opts) {
617
629
  }
618
630
  return txid;
619
631
  }
620
- var OFFER_COVENANT_MISMATCH = "rebuilt covenant does not match the offer's swapPkScript";
621
632
  var NoSpendableDepositError = class extends Error {
622
633
  name = "NoSpendableDepositError";
623
634
  constructor(options) {
@@ -627,7 +638,7 @@ var NoSpendableDepositError = class extends Error {
627
638
  var OfferCovenantMismatchError = class extends Error {
628
639
  constructor(swapPkScript, options) {
629
640
  super(
630
- `${OFFER_COVENANT_MISMATCH} \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt`,
641
+ "rebuilt covenant does not match the offer's swapPkScript \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt",
631
642
  options
632
643
  );
633
644
  this.swapPkScript = swapPkScript;
@@ -645,18 +656,13 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
645
656
  wallet.getArkadeBroadcaster()
646
657
  ]);
647
658
  const client = await arkade.Arkade.connect({
648
- // info the wallet already holds, plus its broadcast pair — the shape
649
- // `ArkadeServerProvider` describes, without a second `/v1/info`
650
659
  arkade: { getInfo: async () => info, ...broadcaster },
651
660
  indexer: reader,
652
661
  identity: wallet.identity,
653
- // registered offers resolve their VTXOs from the contract repository
654
- // instead of a direct indexer query; the indexer above stays as the
655
- // fallback for offers created before registration existed
662
+ // registered offers resolve VTXOs from the contract repository; the indexer is the fallback
663
+ // for offers created before registration existed
656
664
  contractManager
657
- // no `network`, unlike registerOfferContract: the row lookup is by
658
- // script and the payout script comes from wallet.getAddress(), so the
659
- // client's network (which only shapes address derivation) is unused here
665
+ // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
660
666
  });
661
667
  const operatorPubkey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
662
668
  const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
@@ -726,13 +732,9 @@ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
726
732
  indexer: new RestIndexerProvider(arkServerUrl),
727
733
  identity: wallet.identity,
728
734
  contractManager,
729
- // `fulfill` is a covenant path, so the emulator executes the arkade
730
- // script and finalizes with arkd. Without it the spend is built and then
731
- // refused at submission — there is no default to fall back on.
732
735
  emulator: typeof emulator === "string" ? new RestEmulatorProvider(emulator) : emulator,
733
- // Only reached for the client's own emulatorKey, which this fill never
734
- // derives against — the offer's own key is bound below. It still has to
735
- // resolve, and on a network with no pinned key it throws without this.
736
+ // only for the client's own emulatorKey, which this fill never derives against (the offer's
737
+ // key is bound below) — but it must still resolve on a network with no pinned key
736
738
  ...emulatorPubkey ? { emulatorPubkey } : {}
737
739
  });
738
740
  const serverKey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
@@ -807,13 +809,10 @@ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
807
809
  const { txid } = await fill.send();
808
810
  return txid;
809
811
  }
810
- var amountOfAsset = (assets, assetId) => {
811
- let total = BigInt(0);
812
- for (const a of assets ?? []) {
813
- if (a.assetId === assetId) total += BigInt(a.amount);
814
- }
815
- return total;
816
- };
812
+ var amountOfAsset = (assets, assetId) => (assets ?? []).reduce(
813
+ (total, a) => a.assetId === assetId ? total + BigInt(a.amount) : total,
814
+ BigInt(0)
815
+ );
817
816
 
818
817
  // src/lockupContract.ts
819
818
  import { hex as hex3 } from "@scure/base";
@@ -842,8 +841,8 @@ var LockupRegistrationFailed = class extends Error {
842
841
  /** The lockup address that was never registered — never fund it: nothing
843
842
  * is watching it. */
844
843
  address;
845
- /** The covenant the row would have been written from — the other half of
846
- * `registerLockupContract`, so the write is retryable without a quote. */
844
+ /** The covenant the row would have been written from, so the write is retryable without a
845
+ * quote. */
847
846
  script;
848
847
  constructor(script, address, cause) {
849
848
  super(`failed to register the lockup contract for ${address}`, { cause });
@@ -888,6 +887,28 @@ var ONCHAIN_CLAIM_VSIZE = 152;
888
887
  var newPreimage = () => crypto.getRandomValues(new Uint8Array(32));
889
888
  var paymentHashOf = (preimage) => hex4.encode(sha2562(preimage));
890
889
  var h160FromPaymentHash = (paymentHash) => ripemd160(hex4.decode(paymentHash));
890
+ var assertPreimageMatches = (preimage, preimageHash) => {
891
+ if (hex4.encode(ripemd160(sha2562(preimage))) !== hex4.encode(preimageHash)) {
892
+ throw new Error("preimage does not match the covenant's payment hash");
893
+ }
894
+ };
895
+ var gateError = (reason, message) => {
896
+ const error = new Error(message);
897
+ error.reason = reason;
898
+ return error;
899
+ };
900
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
901
+ async function pollUntil(probe, options, reason, message) {
902
+ const pollMs = options.pollMs ?? 5e3;
903
+ for (; ; ) {
904
+ const value = await probe();
905
+ if (value !== void 0) return value;
906
+ if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
907
+ throw gateError(reason, message);
908
+ }
909
+ await sleep(pollMs);
910
+ }
911
+ }
891
912
  var L1_NETWORKS = {
892
913
  bitcoin: btc.NETWORK,
893
914
  testnet: btc.TEST_NETWORK,
@@ -1043,29 +1064,24 @@ function extractPreimage(txHex, paymentHash) {
1043
1064
  }
1044
1065
  return null;
1045
1066
  }
1046
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1047
1067
  async function awaitOnchainFill(chain, htlc, minConfirmations, options = {}) {
1048
- const pollMs = options.pollMs ?? 5e3;
1049
- for (; ; ) {
1050
- const utxos = await chain.getScriptUtxos(htlc.pkScript);
1051
- const eligible = utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1);
1052
- if (eligible[0]) return eligible[0];
1053
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1054
- const error = new Error("HTLC was not filled before the deadline");
1055
- error.reason = "fill_timeout";
1056
- throw error;
1057
- }
1058
- await sleep(pollMs);
1059
- }
1068
+ return pollUntil(
1069
+ async () => {
1070
+ const utxos = await chain.getScriptUtxos(htlc.pkScript);
1071
+ return utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
1072
+ },
1073
+ options,
1074
+ "fill_timeout",
1075
+ "HTLC was not filled before the deadline"
1076
+ );
1060
1077
  }
1061
1078
  async function claimOnchainFill(chain, input) {
1062
1079
  const now = input.now ?? Math.floor(Date.now() / 1e3);
1063
1080
  if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
1064
- const error = new Error(
1081
+ throw gateError(
1082
+ "claim_window_closed",
1065
1083
  "refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
1066
1084
  );
1067
- error.reason = "claim_window_closed";
1068
- throw error;
1069
1085
  }
1070
1086
  const spend = await buildHtlcClaim(input);
1071
1087
  const txid = await chain.broadcast(spend.txHex);
@@ -1121,10 +1137,7 @@ async function sealWithEntropy(input, ephemeralKey, nonce) {
1121
1137
  const key = hkdf(sha2563, sharedX, ephemeralPub, HKDF_INFO, 32);
1122
1138
  if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
1123
1139
  const sealed = gcm(key, nonce, ephemeralPub).encrypt(input.preimage);
1124
- const ciphertext = new Uint8Array(33 + 12 + sealed.length);
1125
- ciphertext.set(ephemeralPub, 0);
1126
- ciphertext.set(nonce, 33);
1127
- ciphertext.set(sealed, 45);
1140
+ const ciphertext = concatBytes2(ephemeralPub, nonce, sealed);
1128
1141
  return {
1129
1142
  ciphertext: base64.encode(ciphertext),
1130
1143
  packet: base64.encode(
@@ -1183,7 +1196,7 @@ var claimPacketShape = (b64) => {
1183
1196
  kind: "packet",
1184
1197
  body: raw,
1185
1198
  needsArkadeScript: !hasArkadeScript,
1186
- ...pubkey ? { covclaimdPubkey: pubkey } : {}
1199
+ covclaimdPubkey: pubkey
1187
1200
  };
1188
1201
  } catch {
1189
1202
  return { kind: "ciphertext" };
@@ -1293,8 +1306,7 @@ var refusalMessage = (reason, detail) => {
1293
1306
  };
1294
1307
  var SwapRefusal = class extends Error {
1295
1308
  /** Literal-typed so the v2 error taxonomy's union discriminates on `name`
1296
- * — a `string` here collapses the discriminant for every member. Same value
1297
- * the constructor has always set, moved to a field initializer. */
1309
+ * — a `string` here collapses the discriminant for every member. */
1298
1310
  name = "SwapRefusal";
1299
1311
  reason;
1300
1312
  rfqId;
@@ -1358,9 +1370,7 @@ var arkadeSwapRequest = (input) => {
1358
1370
  pair,
1359
1371
  amount_side: input.amountSide ?? "from",
1360
1372
  amount: canonicalAssetAmount(input.amount),
1361
- // The pair names the assets; the profile names the trader. Both are
1362
- // covenant parameters, and the solver's `.strict()` schema refuses
1363
- // anything else — an undeclared key is `unsupported_payload`.
1373
+ // The solver's `.strict()` schema refuses any undeclared key as `unsupported_payload`.
1364
1374
  profile: {
1365
1375
  maker_pk_script: normalizeMakerPkScript(input.makerPkScript),
1366
1376
  maker_public_key: normalizeMakerPublicKey(input.makerPublicKey)
@@ -1410,11 +1420,6 @@ var normalizeMakerPublicKey = (value) => {
1410
1420
  return normalizeHexBytes(bytes, 32, "maker_public_key");
1411
1421
  };
1412
1422
  var MIN_HEADROOM_SECONDS = 90 * 60;
1413
- var gateError = (reason, message) => {
1414
- const error = new Error(message);
1415
- error.reason = reason;
1416
- return error;
1417
- };
1418
1423
  var assertFinite = (value, reason, label) => {
1419
1424
  if (value !== void 0 && !Number.isFinite(value)) {
1420
1425
  throw gateError(reason, `${label} is not a finite number (${String(value)})`);
@@ -1683,28 +1688,35 @@ var unilateralClaimDelay = (operatorExitDelaySeconds) => {
1683
1688
  };
1684
1689
  var unilateralRefundDelay = (claimDelay) => claimDelay;
1685
1690
  var unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
1691
+ var seconds = (value) => ({
1692
+ type: "seconds",
1693
+ value: BigInt(value)
1694
+ });
1695
+ var suiteVhtlc = (params, roles) => new VHTLC.ScriptV2({
1696
+ sender: roles.sender,
1697
+ receiver: roles.receiver,
1698
+ server: params.operatorPubkey,
1699
+ preimageHash: ripemd1602(hex5.decode(params.paymentHash)),
1700
+ refundLocktime: BigInt(params.refundLocktime),
1701
+ unilateralClaimDelay: seconds(params.claimDelay),
1702
+ unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1703
+ unilateralRefundWithoutReceiverDelay: seconds(
1704
+ roles.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1705
+ ),
1706
+ nonInteractiveParameters: {
1707
+ receiverPkScript: roles.receiverPkScript,
1708
+ senderPkScript: roles.senderPkScript,
1709
+ emulatorPubkey: params.emulatorPubkey,
1710
+ ...params.legacy !== void 0 && { legacy: params.legacy }
1711
+ }
1712
+ });
1686
1713
  function lightningSendContract(params) {
1687
- const seconds = (value) => ({
1688
- type: "seconds",
1689
- value: BigInt(value)
1690
- });
1691
- return new VHTLC.ScriptV2({
1714
+ return suiteVhtlc(params, {
1692
1715
  sender: params.senderPubkey,
1693
1716
  receiver: params.solverPubkey,
1694
- server: params.operatorPubkey,
1695
- preimageHash: ripemd1602(hex5.decode(params.paymentHash)),
1696
- refundLocktime: BigInt(params.refundLocktime),
1697
- unilateralClaimDelay: seconds(params.claimDelay),
1698
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1699
- unilateralRefundWithoutReceiverDelay: seconds(
1700
- params.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1701
- ),
1702
- nonInteractiveParameters: {
1703
- receiverPkScript: params.receiverPkScript,
1704
- senderPkScript: params.refundPkScript,
1705
- emulatorPubkey: params.emulatorPubkey,
1706
- ...params.legacy !== void 0 && { legacy: params.legacy }
1707
- }
1717
+ senderPkScript: params.refundPkScript,
1718
+ receiverPkScript: params.receiverPkScript,
1719
+ refundWithoutReceiverDelay: params.refundWithoutReceiverDelay
1708
1720
  });
1709
1721
  }
1710
1722
  function deriveLightningSend(input) {
@@ -1803,8 +1815,6 @@ async function requestLightningSend(wallet, transport, params) {
1803
1815
  rfqId,
1804
1816
  quote,
1805
1817
  address,
1806
- // What the lockup must carry: the quote's `from_amount` — the invoice
1807
- // PLUS the corridor's fee, never the bare invoice amount.
1808
1818
  fundAmount: quoteSats(quote.from_amount, "from_amount"),
1809
1819
  swapPkScript: derived.swapPkScript,
1810
1820
  script,
@@ -1844,7 +1854,16 @@ var assertArkadeFundable = (input) => {
1844
1854
  }
1845
1855
  };
1846
1856
  var quoteCarrierSats = (quote) => {
1847
- const published = quote.carrier_sats === void 0 ? 0n : BigInt(quote.carrier_sats);
1857
+ const raw = quote.carrier_sats;
1858
+ if (raw === void 0) return ASSET_CARRIER_SATS;
1859
+ const canonical = typeof raw === "number" ? Number.isSafeInteger(raw) && raw >= 0 : /^(0|[1-9][0-9]*)$/.test(raw);
1860
+ if (!canonical) {
1861
+ throw gateError(
1862
+ "carrier_malformed",
1863
+ `quote carrier_sats ${String(raw)} is not a non-negative integer`
1864
+ );
1865
+ }
1866
+ const published = BigInt(raw);
1848
1867
  return published > 0n ? published : ASSET_CARRIER_SATS;
1849
1868
  };
1850
1869
  async function requestArkadeSwap(wallet, transport, params) {
@@ -1926,6 +1945,18 @@ async function requestArkadeSwap(wallet, transport, params) {
1926
1945
  };
1927
1946
  }
1928
1947
  var l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
1948
+ var serverTerms = (info, emulatorPubkey) => {
1949
+ const network = networkFromArkadeInfo2(info);
1950
+ return {
1951
+ operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
1952
+ emulatorPubkey: toXOnly(
1953
+ hex5.decode(resolveEmulatorPubkey2(network, emulatorPubkey)),
1954
+ "emulator signer key"
1955
+ ),
1956
+ claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
1957
+ hrp: network.hrp
1958
+ };
1959
+ };
1929
1960
  var onchainSendRequest = (input) => ({
1930
1961
  v: 1,
1931
1962
  type: "rfq_request",
@@ -2045,18 +2076,11 @@ async function requestOnchainSend(wallet, transport, params) {
2045
2076
  })
2046
2077
  );
2047
2078
  assertQuotedAmount(quote, params.amountSide, params.amount);
2048
- const network = networkFromArkadeInfo2(info);
2049
2079
  const derived = deriveOnchainSend({
2050
2080
  quote,
2051
2081
  paymentHash,
2052
2082
  payoutPubkey: params.payoutPubkey,
2053
- operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
2054
- emulatorPubkey: toXOnly(
2055
- hex5.decode(resolveEmulatorPubkey2(network, params.emulatorPubkey)),
2056
- "emulator signer key"
2057
- ),
2058
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2059
- hrp: network.hrp,
2083
+ ...serverTerms(info, params.emulatorPubkey),
2060
2084
  l1Network: l1NetworkFromArk(info.network),
2061
2085
  refundAddress,
2062
2086
  senderPubkey
@@ -2161,40 +2185,16 @@ var assertReceivable = (input) => {
2161
2185
  }
2162
2186
  };
2163
2187
  function lightningReceiveContract(params) {
2164
- const seconds = (value) => ({
2165
- type: "seconds",
2166
- value: BigInt(value)
2167
- });
2168
- return new VHTLC.ScriptV2({
2188
+ return suiteVhtlc(params, {
2169
2189
  sender: params.solverPubkey,
2170
2190
  receiver: params.payoutPubkey,
2171
- server: params.operatorPubkey,
2172
- preimageHash: ripemd1602(hex5.decode(params.paymentHash)),
2173
- refundLocktime: BigInt(params.refundLocktime),
2174
- unilateralClaimDelay: seconds(params.claimDelay),
2175
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
2176
- unilateralRefundWithoutReceiverDelay: seconds(
2177
- unilateralRefundWithoutReceiverDelay(params.claimDelay)
2178
- ),
2179
- nonInteractiveParameters: {
2180
- receiverPkScript: params.payoutPkScript,
2181
- senderPkScript: params.solverRefundPkScript,
2182
- emulatorPubkey: params.emulatorPubkey,
2183
- ...params.legacy !== void 0 && { legacy: params.legacy }
2184
- }
2191
+ senderPkScript: params.solverRefundPkScript,
2192
+ receiverPkScript: params.payoutPkScript
2185
2193
  });
2186
2194
  }
2187
- function deriveLightningReceive(input) {
2188
- const { quote } = input;
2189
- const profile = quote.profile ?? {};
2190
- const refundLocktime = quote.refund_locktime;
2191
- const invoice = profile.invoice;
2192
- const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2193
- if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
2194
- throw new Error("lightning-receive quote is missing a binding field");
2195
- }
2195
+ var matchReceiveLockup = (input, refundLocktime, solverRefundPkScriptHex) => {
2196
2196
  const contractParams = {
2197
- solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
2197
+ solverPubkey: toXOnly(hex5.decode(input.quote.solver_pubkey), "solver key"),
2198
2198
  refundLocktime,
2199
2199
  operatorPubkey: input.operatorPubkey,
2200
2200
  paymentHash: input.paymentHash,
@@ -2205,11 +2205,27 @@ function deriveLightningReceive(input) {
2205
2205
  payoutPkScript: ArkAddress3.decode(input.payoutAddress).pkScript
2206
2206
  };
2207
2207
  const matched = matchQuotedLockup(
2208
- quote,
2208
+ input.quote,
2209
2209
  input.hrp,
2210
2210
  input.operatorPubkey,
2211
2211
  (legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
2212
2212
  );
2213
+ return { contractParams, matched };
2214
+ };
2215
+ function deriveLightningReceive(input) {
2216
+ const { quote } = input;
2217
+ const profile = quote.profile ?? {};
2218
+ const refundLocktime = quote.refund_locktime;
2219
+ const invoice = profile.invoice;
2220
+ const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2221
+ if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
2222
+ throw new Error("lightning-receive quote is missing a binding field");
2223
+ }
2224
+ const { contractParams, matched } = matchReceiveLockup(
2225
+ input,
2226
+ refundLocktime,
2227
+ solverRefundPkScriptHex
2228
+ );
2213
2229
  return {
2214
2230
  address: matched.address,
2215
2231
  swapPkScript: matched.script.pkScript,
@@ -2222,12 +2238,11 @@ function deriveLightningReceive(input) {
2222
2238
  }
2223
2239
  };
2224
2240
  }
2225
- async function requestLightningReceive(wallet, transport, params) {
2226
- const rfqId = params.rfqId ?? newRfqId();
2241
+ var provisionReceive = async (wallet, covclaimdPubkey, persistBefore) => {
2227
2242
  const secrets = await provisionClaimSecret(wallet);
2228
2243
  if (secrets.mustPersistPreimage) {
2229
2244
  console.warn(
2230
- "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before paying"
2245
+ `[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before ${persistBefore}`
2231
2246
  );
2232
2247
  }
2233
2248
  const preimage = secrets.preimage;
@@ -2237,10 +2252,12 @@ async function requestLightningReceive(wallet, transport, params) {
2237
2252
  wallet.getArkadeInfo({ requireLive: true }),
2238
2253
  wallet.getAddress()
2239
2254
  ]);
2240
- const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
2241
- preimage,
2242
- covclaimdPubkey: params.covclaimdPubkey
2243
- }) : void 0;
2255
+ const claimPacket = covclaimdPubkey ? await sealClaimPacket({ preimage, covclaimdPubkey }) : void 0;
2256
+ return { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket };
2257
+ };
2258
+ async function requestLightningReceive(wallet, transport, params) {
2259
+ const rfqId = params.rfqId ?? newRfqId();
2260
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "paying");
2244
2261
  const quote = await transport.requestQuote(
2245
2262
  lightningReceiveRequest({
2246
2263
  rfqId,
@@ -2253,19 +2270,12 @@ async function requestLightningReceive(wallet, transport, params) {
2253
2270
  })
2254
2271
  );
2255
2272
  assertQuotedAmount(quote, params.amountSide, params.amount);
2256
- const network = networkFromArkadeInfo2(info);
2257
2273
  const derived = deriveLightningReceive({
2258
2274
  quote,
2259
2275
  paymentHash,
2260
2276
  payoutPubkey,
2261
2277
  payoutAddress,
2262
- operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
2263
- emulatorPubkey: toXOnly(
2264
- hex5.decode(resolveEmulatorPubkey2(network, params.emulatorPubkey)),
2265
- "emulator signer key"
2266
- ),
2267
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2268
- hrp: network.hrp
2278
+ ...serverTerms(info, params.emulatorPubkey)
2269
2279
  });
2270
2280
  const now = Math.floor(Date.now() / 1e3);
2271
2281
  const { payDeadline } = verifyReceiveInvoice({
@@ -2308,26 +2318,11 @@ function deriveOnchainReceive(input) {
2308
2318
  if (refundLocktime === void 0 || claimPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || solverRefundPkScriptHex === void 0) {
2309
2319
  throw new Error("onchain-receive quote is missing a binding field");
2310
2320
  }
2311
- const contractParams = {
2312
- solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
2321
+ const { script, address } = matchReceiveLockup(
2322
+ input,
2313
2323
  refundLocktime,
2314
- operatorPubkey: input.operatorPubkey,
2315
- paymentHash: input.paymentHash,
2316
- claimDelay: input.claimDelay,
2317
- emulatorPubkey: input.emulatorPubkey,
2318
- solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
2319
- payoutPubkey: input.payoutPubkey,
2320
- payoutPkScript: ArkAddress3.decode(input.payoutAddress).pkScript
2321
- };
2322
- const { script, address } = matchQuotedLockup(
2323
- quote,
2324
- input.hrp,
2325
- input.operatorPubkey,
2326
- (legacy) => lightningReceiveContract({
2327
- ...contractParams,
2328
- ...legacy !== void 0 && { legacy }
2329
- })
2330
- );
2324
+ solverRefundPkScriptHex
2325
+ ).matched;
2331
2326
  const htlc = onchainHtlcScript(
2332
2327
  {
2333
2328
  paymentHash: input.paymentHash,
@@ -2350,23 +2345,7 @@ function deriveOnchainReceive(input) {
2350
2345
  }
2351
2346
  async function requestOnchainReceive(wallet, transport, params) {
2352
2347
  const rfqId = params.rfqId ?? newRfqId();
2353
- const secrets = await provisionClaimSecret(wallet);
2354
- if (secrets.mustPersistPreimage) {
2355
- console.warn(
2356
- "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
2357
- );
2358
- }
2359
- const preimage = secrets.preimage;
2360
- const paymentHash = hex5.encode(secrets.paymentHash);
2361
- const payoutPubkey = secrets.pubkey;
2362
- const [info, payoutAddress] = await Promise.all([
2363
- wallet.getArkadeInfo({ requireLive: true }),
2364
- wallet.getAddress()
2365
- ]);
2366
- const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
2367
- preimage,
2368
- covclaimdPubkey: params.covclaimdPubkey
2369
- }) : void 0;
2348
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "funding");
2370
2349
  const quote = await transport.requestQuote(
2371
2350
  onchainReceiveRequest({
2372
2351
  rfqId,
@@ -2380,20 +2359,13 @@ async function requestOnchainReceive(wallet, transport, params) {
2380
2359
  })
2381
2360
  );
2382
2361
  assertQuotedAmount(quote, params.amountSide, params.amount);
2383
- const network = networkFromArkadeInfo2(info);
2384
2362
  const derived = deriveOnchainReceive({
2385
2363
  quote,
2386
2364
  paymentHash,
2387
2365
  payoutPubkey,
2388
2366
  payoutAddress,
2389
2367
  refundPubkey: params.refundPubkey,
2390
- operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
2391
- emulatorPubkey: toXOnly(
2392
- hex5.decode(resolveEmulatorPubkey2(network, params.emulatorPubkey)),
2393
- "emulator signer key"
2394
- ),
2395
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2396
- hrp: network.hrp,
2368
+ ...serverTerms(info, params.emulatorPubkey),
2397
2369
  l1Network: l1NetworkFromArk(info.network)
2398
2370
  });
2399
2371
  assertFundable({
@@ -2447,6 +2419,8 @@ export {
2447
2419
  OFFER_CONTRACT_KIND,
2448
2420
  restoreOfferCoverage,
2449
2421
  createOffer,
2422
+ deriveOffer,
2423
+ registerDerivedOffer,
2450
2424
  cancelOffer,
2451
2425
  NoSpendableDepositError,
2452
2426
  OfferCovenantMismatchError,
@@ -2469,6 +2443,10 @@ export {
2469
2443
  ONCHAIN_CLAIM_VSIZE,
2470
2444
  newPreimage,
2471
2445
  paymentHashOf,
2446
+ assertPreimageMatches,
2447
+ gateError,
2448
+ sleep,
2449
+ pollUntil,
2472
2450
  L1_NETWORKS,
2473
2451
  l1ScriptForAddress,
2474
2452
  onchainHtlcScript,
@@ -2516,8 +2494,10 @@ export {
2516
2494
  lightningSendContract,
2517
2495
  deriveLightningSend,
2518
2496
  requestLightningSend,
2497
+ offerTermsFromQuote,
2519
2498
  verifyOfferAddress,
2520
2499
  assertArkadeFundable,
2500
+ quoteCarrierSats,
2521
2501
  requestArkadeSwap,
2522
2502
  l1NetworkFromArk,
2523
2503
  onchainSendRequest,