@arkade-os/swap 0.1.0-rc.9 → 0.1.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.
- package/README.md +261 -252
- package/dist/advanced.cjs +6376 -3097
- package/dist/advanced.d.cts +325 -282
- package/dist/advanced.d.ts +325 -282
- package/dist/advanced.js +343 -34
- package/dist/chunk-A3SHHRX4.js +104 -0
- package/dist/chunk-FMRAV77W.js +3065 -0
- package/dist/{chunk-NS3K6BZG.js → chunk-HRMWBULL.js} +1746 -628
- package/dist/chunk-WKJFXXSR.js +3382 -0
- package/dist/index.cjs +6809 -3915
- package/dist/index.d.cts +71 -243
- package/dist/index.d.ts +71 -243
- package/dist/index.js +131 -167
- package/dist/lockupContract-D7BNjksX.d.ts +148 -0
- package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
- package/dist/node/index.cjs +61 -10
- package/dist/node/index.d.cts +307 -635
- package/dist/node/index.d.ts +307 -635
- package/dist/node/index.js +65 -10
- package/dist/nostr.cjs +427 -49
- package/dist/nostr.d.cts +59 -70
- package/dist/nostr.d.ts +59 -70
- package/dist/nostr.js +268 -36
- package/dist/offer-CcJfx5Fj.d.cts +269 -0
- package/dist/offer-DdB1M6FZ.d.ts +269 -0
- package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
- package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
- package/dist/protocol.cjs +5650 -4280
- package/dist/protocol.d.cts +258 -328
- package/dist/protocol.d.ts +258 -328
- package/dist/protocol.js +200 -224
- package/dist/repositories/realm/index.cjs +55 -11
- package/dist/repositories/realm/index.d.cts +18 -30
- package/dist/repositories/realm/index.d.ts +18 -30
- package/dist/repositories/realm/index.js +49 -12
- package/dist/repositories/sqlite/index.cjs +61 -10
- package/dist/repositories/sqlite/index.d.cts +7 -6
- package/dist/repositories/sqlite/index.d.ts +7 -6
- package/dist/repositories/sqlite/index.js +57 -11
- package/dist/repository-DmPzpbd7.d.ts +2342 -0
- package/dist/repository-DqdLVrVv.d.cts +2342 -0
- package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
- package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
- package/dist/watch-BonYT9af.d.cts +74 -0
- package/dist/watch-CmJQDtsy.d.ts +74 -0
- package/package.json +10 -10
- package/dist/chunk-JFKGMPMH.js +0 -3456
- package/dist/chunk-LLG7RD2T.js +0 -1499
- package/dist/chunk-U7VWWTL6.js +0 -66
- package/dist/errors-CNISbN0M.d.ts +0 -2218
- package/dist/errors-DwNhIP0N.d.cts +0 -2218
- package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
- package/dist/lockupContract-mIt4syse.d.cts +0 -664
- package/dist/repository-CGPLbjBe.d.ts +0 -3489
- package/dist/repository-DSGGq0ct.d.cts +0 -3489
- package/dist/watch-DWyVqyEN.d.cts +0 -96
- package/dist/watch-DmvHNX6T.d.ts +0 -96
package/dist/chunk-LLG7RD2T.js
DELETED
|
@@ -1,1499 +0,0 @@
|
|
|
1
|
-
// src/lockupContract.ts
|
|
2
|
-
import { hex } from "@scure/base";
|
|
3
|
-
import {
|
|
4
|
-
ArkAddress,
|
|
5
|
-
VHTLCV2ContractHandler
|
|
6
|
-
} from "@arkade-os/sdk";
|
|
7
|
-
var SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
|
|
8
|
-
var SWAP_LOCKUP_CONTRACT_LABEL = "Arkade RFQ swap lockup";
|
|
9
|
-
var SWAP_LOCKUP_CONTRACT_KIND = "rfq-swap-lockup";
|
|
10
|
-
var LockupContractMissing = class extends Error {
|
|
11
|
-
/** The lockup whose row is absent. */
|
|
12
|
-
address;
|
|
13
|
-
/** Its pkScript hex — the key the row would have been under. */
|
|
14
|
-
script;
|
|
15
|
-
constructor(address, script) {
|
|
16
|
-
super(
|
|
17
|
-
`no contract row for lockup ${address} (script ${script}); its covenant cannot be rebuilt from this wallet's contract store`
|
|
18
|
-
);
|
|
19
|
-
this.name = "LockupContractMissing";
|
|
20
|
-
this.address = address;
|
|
21
|
-
this.script = script;
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
var LockupRegistrationFailed = class extends Error {
|
|
25
|
-
/** The lockup address that was never registered — never fund it: nothing
|
|
26
|
-
* is watching it. */
|
|
27
|
-
address;
|
|
28
|
-
/** The covenant the row would have been written from — the other half of
|
|
29
|
-
* `registerLockupContract`, so the write is retryable without a quote. */
|
|
30
|
-
script;
|
|
31
|
-
constructor(script, address, cause) {
|
|
32
|
-
super(`failed to register the lockup contract for ${address}`, { cause });
|
|
33
|
-
this.name = "LockupRegistrationFailed";
|
|
34
|
-
this.address = address;
|
|
35
|
-
this.script = script;
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
async function registerLockupContract(contracts, script, address) {
|
|
39
|
-
try {
|
|
40
|
-
await contracts.createContract({
|
|
41
|
-
type: SWAP_LOCKUP_CONTRACT_TYPE,
|
|
42
|
-
params: VHTLCV2ContractHandler.serializeParams(script.options),
|
|
43
|
-
script: hex.encode(script.pkScript),
|
|
44
|
-
address,
|
|
45
|
-
label: SWAP_LOCKUP_CONTRACT_LABEL,
|
|
46
|
-
metadata: { genericallySpendable: false, kind: SWAP_LOCKUP_CONTRACT_KIND }
|
|
47
|
-
});
|
|
48
|
-
} catch (error) {
|
|
49
|
-
throw new LockupRegistrationFailed(script, address, error);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
async function lockupContractParams(contracts, lockupAddress) {
|
|
53
|
-
const script = hex.encode(ArkAddress.decode(lockupAddress).pkScript);
|
|
54
|
-
const [row] = await contracts.getContracts({ script });
|
|
55
|
-
if (!row) throw new LockupContractMissing(lockupAddress, script);
|
|
56
|
-
return row.params;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// src/onchainHtlc.ts
|
|
60
|
-
import { hex as hex2 } from "@scure/base";
|
|
61
|
-
import { sha256 } from "@noble/hashes/sha2.js";
|
|
62
|
-
import { ripemd160 } from "@noble/hashes/legacy.js";
|
|
63
|
-
import * as btc from "@scure/btc-signer";
|
|
64
|
-
var ONCHAIN_ORDER_MARGIN_SECONDS = 2 * 60 * 60;
|
|
65
|
-
var ONCHAIN_CLAIM_MARGIN_SECONDS = 90 * 60;
|
|
66
|
-
var MAX_MIN_CONFIRMATIONS = 6;
|
|
67
|
-
var LOCKTIME_THRESHOLD = 5e8;
|
|
68
|
-
var ONCHAIN_SECONDS_PER_BLOCK = 600;
|
|
69
|
-
var ONCHAIN_DUST_SATS = BigInt(330);
|
|
70
|
-
var ONCHAIN_CLAIM_VSIZE = 152;
|
|
71
|
-
var newPreimage = () => crypto.getRandomValues(new Uint8Array(32));
|
|
72
|
-
var paymentHashOf = (preimage) => hex2.encode(sha256(preimage));
|
|
73
|
-
var h160FromPaymentHash = (paymentHash) => ripemd160(hex2.decode(paymentHash));
|
|
74
|
-
var L1_NETWORKS = {
|
|
75
|
-
bitcoin: btc.NETWORK,
|
|
76
|
-
testnet: btc.TEST_NETWORK,
|
|
77
|
-
regtest: { ...btc.TEST_NETWORK, bech32: "bcrt" }
|
|
78
|
-
};
|
|
79
|
-
var l1ScriptForAddress = (address, network) => btc.OutScript.encode(btc.Address(L1_NETWORKS[network]).decode(address));
|
|
80
|
-
function onchainHtlcScript(params, network) {
|
|
81
|
-
if (params.claimKey.length !== 32 || params.refundKey.length !== 32) {
|
|
82
|
-
throw new Error("claimKey and refundKey must be 32-byte x-only keys");
|
|
83
|
-
}
|
|
84
|
-
if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0) {
|
|
85
|
-
throw new Error(
|
|
86
|
-
`refundLocktime must be a positive unix timestamp, got ${params.refundLocktime}`
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
if (params.refundLocktime < LOCKTIME_THRESHOLD) {
|
|
90
|
-
throw new Error(
|
|
91
|
-
`refundLocktime ${params.refundLocktime} is below LOCKTIME_THRESHOLD (${LOCKTIME_THRESHOLD}) and would be interpreted as a block height`
|
|
92
|
-
);
|
|
93
|
-
}
|
|
94
|
-
if (!Object.hasOwn(L1_NETWORKS, network)) {
|
|
95
|
-
throw new Error(
|
|
96
|
-
`unknown L1 network '${String(network)}' \u2014 expected one of ${Object.keys(L1_NETWORKS).join(", ")}`
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
const h160 = h160FromPaymentHash(params.paymentHash);
|
|
100
|
-
const claim = btc.Script.encode([
|
|
101
|
-
"SIZE",
|
|
102
|
-
32,
|
|
103
|
-
"EQUALVERIFY",
|
|
104
|
-
"HASH160",
|
|
105
|
-
h160,
|
|
106
|
-
"EQUALVERIFY",
|
|
107
|
-
params.claimKey,
|
|
108
|
-
"CHECKSIG"
|
|
109
|
-
]);
|
|
110
|
-
const refund = btc.Script.encode([
|
|
111
|
-
btc.ScriptNum().encode(BigInt(params.refundLocktime)),
|
|
112
|
-
"CHECKLOCKTIMEVERIFY",
|
|
113
|
-
"DROP",
|
|
114
|
-
params.refundKey,
|
|
115
|
-
"CHECKSIG"
|
|
116
|
-
]);
|
|
117
|
-
const payment = btc.p2tr(
|
|
118
|
-
btc.TAPROOT_UNSPENDABLE_KEY,
|
|
119
|
-
btc.taprootListToTree([{ script: claim }, { script: refund }]),
|
|
120
|
-
L1_NETWORKS[network],
|
|
121
|
-
true
|
|
122
|
-
);
|
|
123
|
-
const controlBlockFor = (leaf) => {
|
|
124
|
-
for (const [block, script] of payment.tapLeafScript ?? []) {
|
|
125
|
-
if (script.length - 1 === leaf.length && hex2.encode(script.subarray(0, leaf.length)) === hex2.encode(leaf)) {
|
|
126
|
-
return btc.TaprootControlBlock.encode(block);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
throw new Error("leaf missing from compiled taproot tree");
|
|
130
|
-
};
|
|
131
|
-
return {
|
|
132
|
-
address: payment.address,
|
|
133
|
-
pkScript: payment.script,
|
|
134
|
-
leaves: { claim, refund },
|
|
135
|
-
controlBlocks: { claim: controlBlockFor(claim), refund: controlBlockFor(refund) },
|
|
136
|
-
paymentHash: params.paymentHash,
|
|
137
|
-
refundLocktime: params.refundLocktime
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
var buildLeafSpend = async (input) => {
|
|
141
|
-
if (!Number.isFinite(input.feeRateSatVb) || input.feeRateSatVb <= 0) {
|
|
142
|
-
throw new Error(`feeRateSatVb must be positive, got ${input.feeRateSatVb}`);
|
|
143
|
-
}
|
|
144
|
-
const assemble = (payout2) => {
|
|
145
|
-
const tx2 = new btc.Transaction({ lockTime: input.lockTime ?? 0 });
|
|
146
|
-
tx2.addInput({
|
|
147
|
-
txid: input.utxo.txid,
|
|
148
|
-
index: input.utxo.vout,
|
|
149
|
-
witnessUtxo: { script: input.htlc.pkScript, amount: input.utxo.amount },
|
|
150
|
-
sequence: input.sequence
|
|
151
|
-
});
|
|
152
|
-
tx2.addOutput({ script: input.payoutPkScript, amount: payout2 });
|
|
153
|
-
return tx2;
|
|
154
|
-
};
|
|
155
|
-
const witness = (sig2) => [
|
|
156
|
-
sig2,
|
|
157
|
-
...input.stackAboveSig,
|
|
158
|
-
input.leaf,
|
|
159
|
-
input.controlBlock
|
|
160
|
-
];
|
|
161
|
-
const sizing = assemble(input.utxo.amount);
|
|
162
|
-
sizing.updateInput(0, { finalScriptWitness: witness(new Uint8Array(64)) }, true);
|
|
163
|
-
const fee = BigInt(Math.ceil(sizing.vsize * input.feeRateSatVb));
|
|
164
|
-
const payout = input.utxo.amount - fee;
|
|
165
|
-
if (payout < ONCHAIN_DUST_SATS) {
|
|
166
|
-
throw new Error(
|
|
167
|
-
`fee ${fee} leaves ${payout} sats from a ${input.utxo.amount} sat HTLC \u2014 below the ${ONCHAIN_DUST_SATS} sat dust limit`
|
|
168
|
-
);
|
|
169
|
-
}
|
|
170
|
-
const tx = assemble(payout);
|
|
171
|
-
const sighash = tx.preimageWitnessV1(
|
|
172
|
-
0,
|
|
173
|
-
[input.htlc.pkScript],
|
|
174
|
-
btc.SigHash.DEFAULT,
|
|
175
|
-
[input.utxo.amount],
|
|
176
|
-
void 0,
|
|
177
|
-
input.leaf,
|
|
178
|
-
192
|
|
179
|
-
);
|
|
180
|
-
const sig = await input.sign(sighash);
|
|
181
|
-
if (sig.length !== 64)
|
|
182
|
-
throw new Error(`sign() must return a 64-byte BIP340 signature, got ${sig.length}`);
|
|
183
|
-
tx.updateInput(0, { finalScriptWitness: witness(sig) }, true);
|
|
184
|
-
return { txHex: tx.hex, txid: tx.id, payoutAmount: payout };
|
|
185
|
-
};
|
|
186
|
-
var buildHtlcClaim = async (input) => {
|
|
187
|
-
if (paymentHashOf(input.preimage) !== input.htlc.paymentHash) {
|
|
188
|
-
throw new Error("preimage does not hash to the HTLC's payment hash");
|
|
189
|
-
}
|
|
190
|
-
return buildLeafSpend({
|
|
191
|
-
htlc: input.htlc,
|
|
192
|
-
utxo: input.utxo,
|
|
193
|
-
leaf: input.htlc.leaves.claim,
|
|
194
|
-
controlBlock: input.htlc.controlBlocks.claim,
|
|
195
|
-
stackAboveSig: [input.preimage],
|
|
196
|
-
payoutPkScript: input.payoutPkScript,
|
|
197
|
-
feeRateSatVb: input.feeRateSatVb,
|
|
198
|
-
sign: input.sign,
|
|
199
|
-
sequence: 4294967293
|
|
200
|
-
});
|
|
201
|
-
};
|
|
202
|
-
var buildHtlcRefund = (input) => buildLeafSpend({
|
|
203
|
-
htlc: input.htlc,
|
|
204
|
-
utxo: input.utxo,
|
|
205
|
-
leaf: input.htlc.leaves.refund,
|
|
206
|
-
controlBlock: input.htlc.controlBlocks.refund,
|
|
207
|
-
stackAboveSig: [],
|
|
208
|
-
payoutPkScript: input.payoutPkScript,
|
|
209
|
-
feeRateSatVb: input.feeRateSatVb,
|
|
210
|
-
sign: input.sign,
|
|
211
|
-
lockTime: input.htlc.refundLocktime,
|
|
212
|
-
// any value below 0xffffffff enables nLockTime enforcement
|
|
213
|
-
sequence: 4294967294
|
|
214
|
-
});
|
|
215
|
-
function extractPreimage(txHex, paymentHash) {
|
|
216
|
-
let raw;
|
|
217
|
-
try {
|
|
218
|
-
raw = btc.RawTx.decode(hex2.decode(txHex));
|
|
219
|
-
} catch {
|
|
220
|
-
return null;
|
|
221
|
-
}
|
|
222
|
-
for (const stack of raw.witnesses ?? []) {
|
|
223
|
-
for (const item of stack) {
|
|
224
|
-
if (item.length === 32 && hex2.encode(sha256(item)) === paymentHash) return item;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return null;
|
|
228
|
-
}
|
|
229
|
-
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
230
|
-
async function awaitOnchainFill(chain, htlc, minConfirmations, options = {}) {
|
|
231
|
-
const pollMs = options.pollMs ?? 5e3;
|
|
232
|
-
for (; ; ) {
|
|
233
|
-
const utxos = await chain.getScriptUtxos(htlc.pkScript);
|
|
234
|
-
const eligible = utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1);
|
|
235
|
-
if (eligible[0]) return eligible[0];
|
|
236
|
-
if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
|
|
237
|
-
const error = new Error("HTLC was not filled before the deadline");
|
|
238
|
-
error.reason = "fill_timeout";
|
|
239
|
-
throw error;
|
|
240
|
-
}
|
|
241
|
-
await sleep(pollMs);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
async function claimOnchainFill(chain, input) {
|
|
245
|
-
const now = input.now ?? Math.floor(Date.now() / 1e3);
|
|
246
|
-
if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
|
|
247
|
-
const error = new Error(
|
|
248
|
-
"refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
|
|
249
|
-
);
|
|
250
|
-
error.reason = "claim_window_closed";
|
|
251
|
-
throw error;
|
|
252
|
-
}
|
|
253
|
-
const spend = await buildHtlcClaim(input);
|
|
254
|
-
const txid = await chain.broadcast(spend.txHex);
|
|
255
|
-
return { txid, payoutAmount: spend.payoutAmount };
|
|
256
|
-
}
|
|
257
|
-
async function classifyOnchainHtlc(chain, input) {
|
|
258
|
-
const utxos = await chain.getScriptUtxos(input.htlc.pkScript);
|
|
259
|
-
const best = utxos.sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
|
|
260
|
-
if (!best) {
|
|
261
|
-
if (!input.funding) return { phase: "unfunded" };
|
|
262
|
-
const spend = await chain.getSpendingTx(
|
|
263
|
-
input.funding.txid,
|
|
264
|
-
input.funding.vout,
|
|
265
|
-
input.htlc.pkScript
|
|
266
|
-
);
|
|
267
|
-
if (!spend) return { phase: "unfunded" };
|
|
268
|
-
const preimage = extractPreimage(spend.txHex, input.htlc.paymentHash);
|
|
269
|
-
const txid = btc.Transaction.fromRaw(hex2.decode(spend.txHex), {
|
|
270
|
-
allowUnknownInputs: true,
|
|
271
|
-
allowUnknownOutputs: true
|
|
272
|
-
}).id;
|
|
273
|
-
return preimage ? { phase: "claimed", txid, preimage } : { phase: "swept", txid };
|
|
274
|
-
}
|
|
275
|
-
if (best.confirmations < input.minConfirmations)
|
|
276
|
-
return { phase: "awaiting_confirmations", utxo: best };
|
|
277
|
-
const mtp = await chain.getMtp();
|
|
278
|
-
if (mtp >= input.htlc.refundLocktime) return { phase: "refundable", utxo: best };
|
|
279
|
-
return { phase: "claimable", utxo: best };
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// src/claimPacket.ts
|
|
283
|
-
import { base64 } from "@scure/base";
|
|
284
|
-
import { concatBytes } from "@scure/btc-signer/utils.js";
|
|
285
|
-
import { gcm } from "@noble/ciphers/aes.js";
|
|
286
|
-
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
287
|
-
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
288
|
-
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
289
|
-
var HKDF_INFO = new TextEncoder().encode("covclaimd/preimage/v1");
|
|
290
|
-
async function sealClaimPacket(input) {
|
|
291
|
-
return sealWithEntropy(
|
|
292
|
-
input,
|
|
293
|
-
secp256k1.utils.randomSecretKey(),
|
|
294
|
-
crypto.getRandomValues(new Uint8Array(12))
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
async function sealWithEntropy(input, ephemeralKey, nonce) {
|
|
298
|
-
if (input.preimage.length !== 32) throw new Error("preimage must be 32 bytes");
|
|
299
|
-
if (input.covclaimdPubkey.length !== 33) {
|
|
300
|
-
throw new Error("covclaimd pubkey must be 33-byte compressed");
|
|
301
|
-
}
|
|
302
|
-
const ephemeralPub = secp256k1.getPublicKey(ephemeralKey, true);
|
|
303
|
-
const sharedX = secp256k1.getSharedSecret(ephemeralKey, input.covclaimdPubkey, true).subarray(1);
|
|
304
|
-
const key = hkdf(sha2562, sharedX, ephemeralPub, HKDF_INFO, 32);
|
|
305
|
-
if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
|
|
306
|
-
const sealed = gcm(key, nonce, ephemeralPub).encrypt(input.preimage);
|
|
307
|
-
const ciphertext = new Uint8Array(33 + 12 + sealed.length);
|
|
308
|
-
ciphertext.set(ephemeralPub, 0);
|
|
309
|
-
ciphertext.set(nonce, 33);
|
|
310
|
-
ciphertext.set(sealed, 45);
|
|
311
|
-
return {
|
|
312
|
-
ciphertext: base64.encode(ciphertext),
|
|
313
|
-
packet: base64.encode(
|
|
314
|
-
concatBytes(
|
|
315
|
-
tlv(TLV_CIPHERTEXT, ciphertext),
|
|
316
|
-
tlv(TLV_COVCLAIMD_PUBKEY, input.covclaimdPubkey)
|
|
317
|
-
)
|
|
318
|
-
)
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
var TLV_CIPHERTEXT = 1;
|
|
322
|
-
var TLV_ARKADE_SCRIPT = 2;
|
|
323
|
-
var TLV_COVCLAIMD_PUBKEY = 3;
|
|
324
|
-
var COMPRESSED_PUBKEY_LENGTH = 33;
|
|
325
|
-
var SEALED_CIPHERTEXT_LENGTH = 93;
|
|
326
|
-
var CLAIM_PACKET_TYPE = 4;
|
|
327
|
-
var tlv = (type, value) => Uint8Array.from([type, value.length >> 8 & 255, value.length & 255, ...value]);
|
|
328
|
-
var appendArkadeScript = (body, arkadeScript) => Uint8Array.from([...body, ...tlv(TLV_ARKADE_SCRIPT, arkadeScript)]);
|
|
329
|
-
var parseTlv = (data) => {
|
|
330
|
-
let ciphertextLength;
|
|
331
|
-
let hasArkadeScript = false;
|
|
332
|
-
let pubkey;
|
|
333
|
-
let offset = 0;
|
|
334
|
-
while (offset < data.length) {
|
|
335
|
-
if (offset + 3 > data.length) throw new Error("truncated TLV header");
|
|
336
|
-
const type = data[offset];
|
|
337
|
-
const length = data[offset + 1] << 8 | data[offset + 2];
|
|
338
|
-
offset += 3;
|
|
339
|
-
if (offset + length > data.length) {
|
|
340
|
-
throw new Error(`TLV type 0x${type.toString(16)} overruns the buffer`);
|
|
341
|
-
}
|
|
342
|
-
const value = data.subarray(offset, offset + length);
|
|
343
|
-
offset += length;
|
|
344
|
-
if (type === TLV_CIPHERTEXT) ciphertextLength = value.length;
|
|
345
|
-
else if (type === TLV_ARKADE_SCRIPT) hasArkadeScript = true;
|
|
346
|
-
else if (type === TLV_COVCLAIMD_PUBKEY) {
|
|
347
|
-
if (value.length !== COMPRESSED_PUBKEY_LENGTH) {
|
|
348
|
-
throw new Error(
|
|
349
|
-
`covclaimd_pub_key TLV is ${value.length} bytes, want ${COMPRESSED_PUBKEY_LENGTH}`
|
|
350
|
-
);
|
|
351
|
-
}
|
|
352
|
-
pubkey = value;
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
return { ciphertextLength, hasArkadeScript, pubkey };
|
|
356
|
-
};
|
|
357
|
-
var claimPacketShape = (b64) => {
|
|
358
|
-
try {
|
|
359
|
-
const raw = base64.decode(b64);
|
|
360
|
-
if (raw.length === SEALED_CIPHERTEXT_LENGTH) return { kind: "ciphertext" };
|
|
361
|
-
const { ciphertextLength, hasArkadeScript, pubkey } = parseTlv(raw);
|
|
362
|
-
if (ciphertextLength !== SEALED_CIPHERTEXT_LENGTH || pubkey === void 0) {
|
|
363
|
-
return { kind: "ciphertext" };
|
|
364
|
-
}
|
|
365
|
-
return {
|
|
366
|
-
kind: "packet",
|
|
367
|
-
body: raw,
|
|
368
|
-
needsArkadeScript: !hasArkadeScript,
|
|
369
|
-
...pubkey ? { covclaimdPubkey: pubkey } : {}
|
|
370
|
-
};
|
|
371
|
-
} catch {
|
|
372
|
-
return { kind: "ciphertext" };
|
|
373
|
-
}
|
|
374
|
-
};
|
|
375
|
-
|
|
376
|
-
// src/rfq.ts
|
|
377
|
-
import { hex as hex3 } from "@scure/base";
|
|
378
|
-
import { ripemd160 as ripemd1602 } from "@noble/hashes/legacy.js";
|
|
379
|
-
import {
|
|
380
|
-
ArkAddress as ArkAddress2,
|
|
381
|
-
VHTLC,
|
|
382
|
-
networkFromArkadeInfo,
|
|
383
|
-
resolveEmulatorPubkey,
|
|
384
|
-
toXOnly
|
|
385
|
-
} from "@arkade-os/sdk";
|
|
386
|
-
import {
|
|
387
|
-
provisionClaimSecret,
|
|
388
|
-
provisionRefundKey
|
|
389
|
-
} from "@arkade-os/sdk";
|
|
390
|
-
var solverHex = (value, field) => {
|
|
391
|
-
try {
|
|
392
|
-
return hex3.decode(value);
|
|
393
|
-
} catch {
|
|
394
|
-
throw new Error(`solver sent malformed hex for ${field}`);
|
|
395
|
-
}
|
|
396
|
-
};
|
|
397
|
-
var ARKADE_BTC = "arkade:BTC";
|
|
398
|
-
var LIGHTNING_BTC = "lightning:BTC";
|
|
399
|
-
var ONCHAIN_BTC = "onchain:BTC";
|
|
400
|
-
var arkadeAssetLeg = (id) => `arkade:${id.toString()}`;
|
|
401
|
-
var rfqPair = (from, to) => `${from}->${to}`;
|
|
402
|
-
var LIGHTNING_SEND_PAIR = rfqPair(ARKADE_BTC, LIGHTNING_BTC);
|
|
403
|
-
var LIGHTNING_RECEIVE_PAIR = rfqPair(LIGHTNING_BTC, ARKADE_BTC);
|
|
404
|
-
var ONCHAIN_SEND_PAIR = rfqPair(ARKADE_BTC, ONCHAIN_BTC);
|
|
405
|
-
var ONCHAIN_RECEIVE_PAIR = rfqPair(ONCHAIN_BTC, ARKADE_BTC);
|
|
406
|
-
var RFQ_TERMINAL_STATES = ["settled", "refused", "expired", "refunded", "stuck"];
|
|
407
|
-
var RFQ_REFUSAL_ERROR_CODES = [
|
|
408
|
-
"amount_side_unsupported",
|
|
409
|
-
"exact_out_unsupported",
|
|
410
|
-
"invalid_amount",
|
|
411
|
-
"invalid_payout_address",
|
|
412
|
-
"invalid_refund_address",
|
|
413
|
-
"invoice_amount_mismatch",
|
|
414
|
-
"invoice_cltv_too_large",
|
|
415
|
-
"invoice_malformed",
|
|
416
|
-
"invoice_missing_amount",
|
|
417
|
-
"invoice_missing_network",
|
|
418
|
-
"invoice_missing_payment_hash",
|
|
419
|
-
"invoice_missing_timestamp",
|
|
420
|
-
"invoice_mixed_case",
|
|
421
|
-
"invoice_sub_satoshi_amount",
|
|
422
|
-
"invoice_too_long",
|
|
423
|
-
"invoice_wrong_network"
|
|
424
|
-
];
|
|
425
|
-
var isRfqRefusalErrorCode = (value) => typeof value === "string" && RFQ_REFUSAL_ERROR_CODES.includes(value);
|
|
426
|
-
var REFUSAL_FIELDS = /* @__PURE__ */ new Set([
|
|
427
|
-
"amount",
|
|
428
|
-
"amount_side",
|
|
429
|
-
"profile.invoice",
|
|
430
|
-
"profile.payout_address",
|
|
431
|
-
"profile.refund_address"
|
|
432
|
-
]);
|
|
433
|
-
var REFUSAL_UNITS = /* @__PURE__ */ new Set(["blocks", "characters", "sats"]);
|
|
434
|
-
var safeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
435
|
-
var safeRefusalDetail = (detail) => {
|
|
436
|
-
if (!isRfqRefusalErrorCode(detail.errorCode)) return {};
|
|
437
|
-
return {
|
|
438
|
-
errorCode: detail.errorCode,
|
|
439
|
-
field: typeof detail.field === "string" && REFUSAL_FIELDS.has(detail.field) ? detail.field : void 0,
|
|
440
|
-
actual: safeInteger(detail.actual),
|
|
441
|
-
expected: safeInteger(detail.expected),
|
|
442
|
-
limit: safeInteger(detail.limit),
|
|
443
|
-
unit: typeof detail.unit === "string" && REFUSAL_UNITS.has(detail.unit) ? detail.unit : void 0
|
|
444
|
-
};
|
|
445
|
-
};
|
|
446
|
-
var refusalMessage = (reason, detail) => {
|
|
447
|
-
if (!detail.errorCode) return `solver refused: ${reason}`;
|
|
448
|
-
const where = detail.field ? ` at ${detail.field}` : "";
|
|
449
|
-
const unit = detail.unit ? ` ${detail.unit}` : "";
|
|
450
|
-
if (detail.actual !== void 0 && detail.limit !== void 0) {
|
|
451
|
-
return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, limit ${detail.limit})`;
|
|
452
|
-
}
|
|
453
|
-
if (detail.actual !== void 0 && detail.expected !== void 0) {
|
|
454
|
-
return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, expected ${detail.expected})`;
|
|
455
|
-
}
|
|
456
|
-
return `solver refused: ${reason} (${detail.errorCode}${where})`;
|
|
457
|
-
};
|
|
458
|
-
var SwapRefusal = class extends Error {
|
|
459
|
-
/** Literal-typed so the v2 error taxonomy's union discriminates on `name`
|
|
460
|
-
* — a `string` here collapses the discriminant for every member. Same value
|
|
461
|
-
* the constructor has always set, moved to a field initializer. */
|
|
462
|
-
name = "SwapRefusal";
|
|
463
|
-
reason;
|
|
464
|
-
rfqId;
|
|
465
|
-
errorCode;
|
|
466
|
-
field;
|
|
467
|
-
actual;
|
|
468
|
-
expected;
|
|
469
|
-
limit;
|
|
470
|
-
unit;
|
|
471
|
-
constructor(reason, rfqId, detail = {}) {
|
|
472
|
-
const safeDetail = safeRefusalDetail(detail);
|
|
473
|
-
super(refusalMessage(reason, safeDetail));
|
|
474
|
-
this.reason = reason;
|
|
475
|
-
this.rfqId = rfqId;
|
|
476
|
-
this.errorCode = safeDetail.errorCode;
|
|
477
|
-
this.field = safeDetail.field;
|
|
478
|
-
this.actual = safeDetail.actual;
|
|
479
|
-
this.expected = safeDetail.expected;
|
|
480
|
-
this.limit = safeDetail.limit;
|
|
481
|
-
this.unit = safeDetail.unit;
|
|
482
|
-
}
|
|
483
|
-
};
|
|
484
|
-
var AddressMismatch = class extends Error {
|
|
485
|
-
derived;
|
|
486
|
-
quoted;
|
|
487
|
-
constructor(derived, quoted) {
|
|
488
|
-
super("solver lockup address does not match local derivation \u2014 refusing to fund");
|
|
489
|
-
this.name = "AddressMismatch";
|
|
490
|
-
this.derived = derived;
|
|
491
|
-
this.quoted = quoted;
|
|
492
|
-
}
|
|
493
|
-
};
|
|
494
|
-
var newRfqId = () => hex3.encode(crypto.getRandomValues(new Uint8Array(32)));
|
|
495
|
-
var lightningSendRequest = (input) => ({
|
|
496
|
-
v: 1,
|
|
497
|
-
type: "rfq_request",
|
|
498
|
-
rfq_id: input.rfqId,
|
|
499
|
-
pair: LIGHTNING_SEND_PAIR,
|
|
500
|
-
amount_side: "to",
|
|
501
|
-
profile: {
|
|
502
|
-
invoice: input.invoice,
|
|
503
|
-
refund_address: input.refundAddress,
|
|
504
|
-
client_refund_pubkey: hex3.encode(input.senderPubkey)
|
|
505
|
-
}
|
|
506
|
-
});
|
|
507
|
-
var arkadeSwapRequest = (input) => {
|
|
508
|
-
if (!input.wantAsset && !input.offerAsset) {
|
|
509
|
-
throw new Error(
|
|
510
|
-
"set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC) \u2014 with neither set both legs are BTC, which is not a swap"
|
|
511
|
-
);
|
|
512
|
-
}
|
|
513
|
-
if (input.wantAsset && input.offerAsset) {
|
|
514
|
-
throw new Error(
|
|
515
|
-
"set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC) \u2014 asset->asset is nameable on the wire but no solver quotes it yet"
|
|
516
|
-
);
|
|
517
|
-
}
|
|
518
|
-
const pair = rfqPair(
|
|
519
|
-
input.offerAsset ? arkadeAssetLeg(input.offerAsset) : ARKADE_BTC,
|
|
520
|
-
input.wantAsset ? arkadeAssetLeg(input.wantAsset) : ARKADE_BTC
|
|
521
|
-
);
|
|
522
|
-
assertPairLength(pair);
|
|
523
|
-
return {
|
|
524
|
-
v: 1,
|
|
525
|
-
type: "rfq_request",
|
|
526
|
-
rfq_id: input.rfqId,
|
|
527
|
-
pair,
|
|
528
|
-
amount_side: input.amountSide,
|
|
529
|
-
amount: input.amount,
|
|
530
|
-
// The pair is the only place the asset ids appear. Repeating them here
|
|
531
|
-
// would be a key the solver's `.strict()` profile schema does not
|
|
532
|
-
// declare, and an undeclared key is `unsupported_payload` — a refusal,
|
|
533
|
-
// not an ignored extra. Empty, not absent: `profile` is required on
|
|
534
|
-
// every other request shape this wire carries.
|
|
535
|
-
profile: {}
|
|
536
|
-
};
|
|
537
|
-
};
|
|
538
|
-
var MIN_HEADROOM_SECONDS = 90 * 60;
|
|
539
|
-
var gateError = (reason, message) => {
|
|
540
|
-
const error = new Error(message);
|
|
541
|
-
error.reason = reason;
|
|
542
|
-
return error;
|
|
543
|
-
};
|
|
544
|
-
var assertFinite = (value, reason, label) => {
|
|
545
|
-
if (value !== void 0 && !Number.isFinite(value)) {
|
|
546
|
-
throw gateError(reason, `${label} is not a finite number (${String(value)})`);
|
|
547
|
-
}
|
|
548
|
-
};
|
|
549
|
-
var MAX_PAIR_LENGTH = 158;
|
|
550
|
-
var assertPairLength = (pair) => {
|
|
551
|
-
if (pair.length > MAX_PAIR_LENGTH) {
|
|
552
|
-
throw new Error(
|
|
553
|
-
`pair is ${pair.length} characters, over the wire's ${MAX_PAIR_LENGTH}-character limit`
|
|
554
|
-
);
|
|
555
|
-
}
|
|
556
|
-
};
|
|
557
|
-
var verifyLockupAddress = (quote, derivedAddress) => {
|
|
558
|
-
const quoted = quote.profile?.lockup_address;
|
|
559
|
-
const candidates = Array.isArray(derivedAddress) ? derivedAddress : [derivedAddress];
|
|
560
|
-
const matched = candidates.find((address) => address === quoted);
|
|
561
|
-
if (matched === void 0) throw new AddressMismatch(candidates, quoted);
|
|
562
|
-
return matched;
|
|
563
|
-
};
|
|
564
|
-
var LOCKUP_SHAPE_VARIANTS = [void 0, "preTimelockedRefund"];
|
|
565
|
-
var matchQuotedLockup = (quote, hrp, serverPubkey, build) => {
|
|
566
|
-
const candidates = LOCKUP_SHAPE_VARIANTS.map((legacy) => {
|
|
567
|
-
const script = build(legacy);
|
|
568
|
-
return { script, address: script.address(hrp, serverPubkey).encode(), legacy };
|
|
569
|
-
});
|
|
570
|
-
const matchedAddress = verifyLockupAddress(
|
|
571
|
-
quote,
|
|
572
|
-
candidates.map((candidate) => candidate.address)
|
|
573
|
-
);
|
|
574
|
-
return candidates.find((candidate) => candidate.address === matchedAddress);
|
|
575
|
-
};
|
|
576
|
-
var assertFundable = (input) => {
|
|
577
|
-
const fail = (reason, message) => {
|
|
578
|
-
throw gateError(reason, message);
|
|
579
|
-
};
|
|
580
|
-
if (input.quote.valid_until === void 0) {
|
|
581
|
-
fail("quote_malformed", "quote carries no valid_until");
|
|
582
|
-
}
|
|
583
|
-
assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
|
|
584
|
-
if (input.invoiceExpiresAt !== void 0 && input.now >= input.invoiceExpiresAt) {
|
|
585
|
-
fail("invoice_expired", "invoice expired");
|
|
586
|
-
}
|
|
587
|
-
if (input.now >= input.quote.valid_until)
|
|
588
|
-
fail("quote_expired", "quote expired \u2014 request a fresh one");
|
|
589
|
-
if (input.quote.refund_locktime !== void 0 && input.quote.refund_locktime - input.now < MIN_HEADROOM_SECONDS) {
|
|
590
|
-
fail("insufficient_headroom", "refund deadline headroom below 90 minutes");
|
|
591
|
-
}
|
|
592
|
-
if (input.maxFee) {
|
|
593
|
-
const { bps, sats, referenceRate } = input.maxFee;
|
|
594
|
-
if (bps === void 0 && sats === void 0) {
|
|
595
|
-
fail("max_fee_unbounded", "maxFee names neither bps nor sats");
|
|
596
|
-
}
|
|
597
|
-
if (bps !== void 0 && (!Number.isInteger(bps) || bps < 0 || bps > 1e4)) {
|
|
598
|
-
fail("max_fee_out_of_range", `maxFee.bps must be an integer in 0..10000, got ${bps}`);
|
|
599
|
-
}
|
|
600
|
-
if (sats !== void 0 && (!Number.isInteger(sats) || sats < 0)) {
|
|
601
|
-
fail("max_fee_out_of_range", `maxFee.sats must be a non-negative integer, got ${sats}`);
|
|
602
|
-
}
|
|
603
|
-
const legs = input.quote.pair.split("->");
|
|
604
|
-
const assetOf = (leg) => leg.slice(leg.indexOf(":") + 1);
|
|
605
|
-
const sameAsset = legs.length === 2 && assetOf(legs[0]) === assetOf(legs[1]);
|
|
606
|
-
if (!sameAsset && referenceRate === void 0) {
|
|
607
|
-
fail(
|
|
608
|
-
"fee_gate_unavailable",
|
|
609
|
-
`maxFee cannot gate ${input.quote.pair}: its legs name different assets, so from_amount - to_amount is not a fee. Supply maxFee.referenceRate (to-units per from-unit) from a source of your OWN \u2014 reading it off the solver's published feed would check the solver against its own number`
|
|
610
|
-
);
|
|
611
|
-
}
|
|
612
|
-
if (!sameAsset && (!Number.isFinite(referenceRate) || referenceRate <= 0)) {
|
|
613
|
-
fail(
|
|
614
|
-
"max_fee_out_of_range",
|
|
615
|
-
`maxFee.referenceRate must be a positive finite number, got ${referenceRate}`
|
|
616
|
-
);
|
|
617
|
-
}
|
|
618
|
-
const fee = sameAsset ? input.quote.from_amount - input.quote.to_amount : Math.ceil(
|
|
619
|
-
(input.quote.from_amount * referenceRate - input.quote.to_amount) / referenceRate
|
|
620
|
-
);
|
|
621
|
-
const allowed = Math.max(
|
|
622
|
-
sats ?? 0,
|
|
623
|
-
Math.floor(input.quote.from_amount * (bps ?? 0) / 1e4)
|
|
624
|
-
);
|
|
625
|
-
if (fee > allowed) {
|
|
626
|
-
fail("fee_too_high", `fee ${fee} exceeds the ${allowed} this client allows`);
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
if (input.onchain) {
|
|
630
|
-
const { htlcLocktime, minConfirmations, direction } = input.onchain;
|
|
631
|
-
if (!Number.isInteger(minConfirmations) || minConfirmations < 1 || minConfirmations > MAX_MIN_CONFIRMATIONS) {
|
|
632
|
-
fail(
|
|
633
|
-
"confirmations_out_of_range",
|
|
634
|
-
`min_confirmations must be 1..${MAX_MIN_CONFIRMATIONS}, got ${minConfirmations}`
|
|
635
|
-
);
|
|
636
|
-
}
|
|
637
|
-
const needed = minConfirmations * ONCHAIN_SECONDS_PER_BLOCK + ONCHAIN_CLAIM_MARGIN_SECONDS;
|
|
638
|
-
if (htlcLocktime - input.now <= needed) {
|
|
639
|
-
fail("claim_window_too_short", "L1 HTLC locktime leaves no safe claim window");
|
|
640
|
-
}
|
|
641
|
-
if (direction === "send") {
|
|
642
|
-
if (input.quote.refund_locktime === void 0 || htlcLocktime + ONCHAIN_ORDER_MARGIN_SECONDS > input.quote.refund_locktime) {
|
|
643
|
-
fail(
|
|
644
|
-
"timelock_order",
|
|
645
|
-
"L1 HTLC locktime + margin must fall before the Arkade refund locktime"
|
|
646
|
-
);
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
};
|
|
651
|
-
var expectQuote = (payload, rfqId, requestedPair) => {
|
|
652
|
-
const p = payload;
|
|
653
|
-
if (p?.type === "rfq_refusal") {
|
|
654
|
-
throw new SwapRefusal(p.reason ?? "unknown", p.rfq_id ?? rfqId, {
|
|
655
|
-
errorCode: p.error_code,
|
|
656
|
-
field: p.field,
|
|
657
|
-
actual: p.actual,
|
|
658
|
-
expected: p.expected,
|
|
659
|
-
limit: p.limit,
|
|
660
|
-
unit: p.unit
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
if (p?.type !== "rfq_quote" || p.rfq_id !== rfqId) {
|
|
664
|
-
throw new Error(`unexpected reply: ${p?.type ?? "no payload"}`);
|
|
665
|
-
}
|
|
666
|
-
if (requestedPair !== void 0 && p.pair !== requestedPair) {
|
|
667
|
-
throw new Error(
|
|
668
|
-
`solver quoted ${JSON.stringify(p.pair)}, not the requested ${requestedPair}`
|
|
669
|
-
);
|
|
670
|
-
}
|
|
671
|
-
return payload;
|
|
672
|
-
};
|
|
673
|
-
var pairOf = (payload) => typeof payload.pair === "string" ? payload.pair : void 0;
|
|
674
|
-
var httpTransport = (baseUrl, options = {}) => {
|
|
675
|
-
const fetchImpl = options.fetchImpl ?? fetch;
|
|
676
|
-
const readJson = async (response, what) => {
|
|
677
|
-
const body = await response.text();
|
|
678
|
-
try {
|
|
679
|
-
return JSON.parse(body);
|
|
680
|
-
} catch {
|
|
681
|
-
throw new Error(
|
|
682
|
-
`${what} returned HTTP ${response.status} with a non-JSON body: ${body.slice(0, 200)}`
|
|
683
|
-
);
|
|
684
|
-
}
|
|
685
|
-
};
|
|
686
|
-
return {
|
|
687
|
-
async requestQuote(payload) {
|
|
688
|
-
const response = await fetchImpl(`${baseUrl}/v1/swap`, {
|
|
689
|
-
method: "POST",
|
|
690
|
-
headers: { "content-type": "application/json" },
|
|
691
|
-
body: JSON.stringify(payload)
|
|
692
|
-
});
|
|
693
|
-
return expectQuote(
|
|
694
|
-
await readJson(response, "quote request"),
|
|
695
|
-
String(payload.rfq_id),
|
|
696
|
-
pairOf(payload)
|
|
697
|
-
);
|
|
698
|
-
},
|
|
699
|
-
async status(rfqId) {
|
|
700
|
-
const response = await fetchImpl(`${baseUrl}/v1/rfq/${rfqId}`, { method: "GET" });
|
|
701
|
-
if (response.status === 404) return null;
|
|
702
|
-
const payload = await readJson(response, "status request");
|
|
703
|
-
return payload?.type === "rfq_status" ? payload : null;
|
|
704
|
-
},
|
|
705
|
-
async close() {
|
|
706
|
-
}
|
|
707
|
-
};
|
|
708
|
-
};
|
|
709
|
-
var relayTransport = (relayUrl, options) => {
|
|
710
|
-
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
711
|
-
const Ctor = options.WebSocketCtor ?? WebSocket;
|
|
712
|
-
const pending = /* @__PURE__ */ new Map();
|
|
713
|
-
let sequence = 0;
|
|
714
|
-
const socketReady = new Promise((resolve, reject) => {
|
|
715
|
-
const ws = new Ctor(relayUrl);
|
|
716
|
-
ws.addEventListener("open", () => {
|
|
717
|
-
ws.send(
|
|
718
|
-
JSON.stringify({
|
|
719
|
-
op: "sub",
|
|
720
|
-
id: "s1",
|
|
721
|
-
filter: { recipient: options.clientPubkey }
|
|
722
|
-
})
|
|
723
|
-
);
|
|
724
|
-
resolve(ws);
|
|
725
|
-
});
|
|
726
|
-
ws.addEventListener("error", () => reject(new Error("relay connection failed")));
|
|
727
|
-
ws.addEventListener("message", (event) => {
|
|
728
|
-
let frame;
|
|
729
|
-
try {
|
|
730
|
-
frame = JSON.parse(String(event.data));
|
|
731
|
-
} catch {
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
if (frame.op !== "event") return;
|
|
735
|
-
const payload = frame.event?.payload;
|
|
736
|
-
const rfqId = payload?.rfq_id;
|
|
737
|
-
const settle = rfqId !== void 0 ? pending.get(rfqId) : void 0;
|
|
738
|
-
if (settle && rfqId !== void 0) {
|
|
739
|
-
pending.delete(rfqId);
|
|
740
|
-
settle(payload);
|
|
741
|
-
}
|
|
742
|
-
});
|
|
743
|
-
});
|
|
744
|
-
const roundTrip = async (payload, rfqId) => {
|
|
745
|
-
const ws = await socketReady;
|
|
746
|
-
const reply = new Promise((resolve, reject) => {
|
|
747
|
-
const timer = setTimeout(() => {
|
|
748
|
-
pending.delete(rfqId);
|
|
749
|
-
reject(new Error(`no reply within ${timeoutMs}ms`));
|
|
750
|
-
}, timeoutMs);
|
|
751
|
-
pending.set(rfqId, (p) => {
|
|
752
|
-
clearTimeout(timer);
|
|
753
|
-
resolve(p);
|
|
754
|
-
});
|
|
755
|
-
});
|
|
756
|
-
ws.send(
|
|
757
|
-
JSON.stringify({
|
|
758
|
-
op: "event",
|
|
759
|
-
event: {
|
|
760
|
-
id: `${options.clientPubkey}:${sequence += 1}`,
|
|
761
|
-
author: options.clientPubkey,
|
|
762
|
-
recipient: options.solverPubkey,
|
|
763
|
-
createdAtMs: Date.now(),
|
|
764
|
-
payload
|
|
765
|
-
}
|
|
766
|
-
})
|
|
767
|
-
);
|
|
768
|
-
return reply;
|
|
769
|
-
};
|
|
770
|
-
return {
|
|
771
|
-
async requestQuote(payload) {
|
|
772
|
-
return expectQuote(
|
|
773
|
-
await roundTrip(payload, String(payload.rfq_id)),
|
|
774
|
-
String(payload.rfq_id),
|
|
775
|
-
pairOf(payload)
|
|
776
|
-
);
|
|
777
|
-
},
|
|
778
|
-
async status(rfqId) {
|
|
779
|
-
const payload = await roundTrip(
|
|
780
|
-
{ v: 1, type: "rfq_status_request", rfq_id: rfqId },
|
|
781
|
-
rfqId
|
|
782
|
-
);
|
|
783
|
-
return payload?.type === "rfq_status" ? payload : null;
|
|
784
|
-
},
|
|
785
|
-
async close() {
|
|
786
|
-
try {
|
|
787
|
-
(await socketReady).close();
|
|
788
|
-
} catch {
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
};
|
|
792
|
-
};
|
|
793
|
-
var SEQUENCE_GRANULARITY_SECONDS = 512;
|
|
794
|
-
var SOLO_REFUND_HEADROOM_SECONDS = 8 * SEQUENCE_GRANULARITY_SECONDS;
|
|
795
|
-
var unilateralClaimDelay = (operatorExitDelaySeconds) => {
|
|
796
|
-
if (!Number.isFinite(operatorExitDelaySeconds) || operatorExitDelaySeconds < SEQUENCE_GRANULARITY_SECONDS) {
|
|
797
|
-
throw new Error(
|
|
798
|
-
`operator exit delay must be at least ${SEQUENCE_GRANULARITY_SECONDS}s of seconds, got ${operatorExitDelaySeconds}`
|
|
799
|
-
);
|
|
800
|
-
}
|
|
801
|
-
if (operatorExitDelaySeconds > 65535 * SEQUENCE_GRANULARITY_SECONDS - SOLO_REFUND_HEADROOM_SECONDS) {
|
|
802
|
-
throw new Error(
|
|
803
|
-
`operator exit delay ${operatorExitDelaySeconds}s exceeds what BIP68 can encode once the solo refund's headroom is stacked above it`
|
|
804
|
-
);
|
|
805
|
-
}
|
|
806
|
-
return Math.ceil(operatorExitDelaySeconds / SEQUENCE_GRANULARITY_SECONDS) * SEQUENCE_GRANULARITY_SECONDS;
|
|
807
|
-
};
|
|
808
|
-
var unilateralRefundDelay = (claimDelay) => claimDelay;
|
|
809
|
-
var unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
|
|
810
|
-
function lightningSendContract(params) {
|
|
811
|
-
const seconds = (value) => ({
|
|
812
|
-
type: "seconds",
|
|
813
|
-
value: BigInt(value)
|
|
814
|
-
});
|
|
815
|
-
return new VHTLC.ScriptV2({
|
|
816
|
-
sender: params.senderPubkey,
|
|
817
|
-
receiver: params.solverPubkey,
|
|
818
|
-
server: params.operatorPubkey,
|
|
819
|
-
preimageHash: ripemd1602(hex3.decode(params.paymentHash)),
|
|
820
|
-
refundLocktime: BigInt(params.refundLocktime),
|
|
821
|
-
unilateralClaimDelay: seconds(params.claimDelay),
|
|
822
|
-
unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
|
|
823
|
-
unilateralRefundWithoutReceiverDelay: seconds(
|
|
824
|
-
unilateralRefundWithoutReceiverDelay(params.claimDelay)
|
|
825
|
-
),
|
|
826
|
-
nonInteractiveParameters: {
|
|
827
|
-
receiverPkScript: params.receiverPkScript,
|
|
828
|
-
senderPkScript: params.refundPkScript,
|
|
829
|
-
emulatorPubkey: params.emulatorPubkey,
|
|
830
|
-
...params.legacy !== void 0 && { legacy: params.legacy }
|
|
831
|
-
}
|
|
832
|
-
});
|
|
833
|
-
}
|
|
834
|
-
function deriveLightningSend(input) {
|
|
835
|
-
const { quote } = input;
|
|
836
|
-
if (quote.refund_locktime === void 0) {
|
|
837
|
-
throw new Error("lightning-send quote is missing refund_locktime");
|
|
838
|
-
}
|
|
839
|
-
const receiverPkScriptHex = quote.profile?.receiver_pk_script;
|
|
840
|
-
if (receiverPkScriptHex === void 0) {
|
|
841
|
-
throw new Error("lightning-send quote is missing profile.receiver_pk_script");
|
|
842
|
-
}
|
|
843
|
-
const contractParams = {
|
|
844
|
-
solverPubkey: toXOnly(hex3.decode(quote.solver_pubkey), "solver key"),
|
|
845
|
-
refundLocktime: quote.refund_locktime,
|
|
846
|
-
operatorPubkey: input.operatorPubkey,
|
|
847
|
-
paymentHash: input.paymentHash,
|
|
848
|
-
claimDelay: input.claimDelay,
|
|
849
|
-
emulatorPubkey: input.emulatorPubkey,
|
|
850
|
-
senderPubkey: input.senderPubkey,
|
|
851
|
-
receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
|
|
852
|
-
refundPkScript: input.refundPkScript
|
|
853
|
-
};
|
|
854
|
-
const matched = matchQuotedLockup(
|
|
855
|
-
quote,
|
|
856
|
-
input.hrp,
|
|
857
|
-
input.operatorPubkey,
|
|
858
|
-
(legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
859
|
-
);
|
|
860
|
-
return {
|
|
861
|
-
address: matched.address,
|
|
862
|
-
swapPkScript: matched.script.pkScript,
|
|
863
|
-
script: matched.script,
|
|
864
|
-
contractParams: {
|
|
865
|
-
...contractParams,
|
|
866
|
-
...matched.legacy !== void 0 && { legacy: matched.legacy }
|
|
867
|
-
},
|
|
868
|
-
refundLocktime: quote.refund_locktime
|
|
869
|
-
};
|
|
870
|
-
}
|
|
871
|
-
async function requestLightningSend(wallet, transport, params) {
|
|
872
|
-
const rfqId = params.rfqId ?? newRfqId();
|
|
873
|
-
const secrets = await provisionRefundKey(wallet);
|
|
874
|
-
const senderPubkey = secrets.pubkey;
|
|
875
|
-
const refundAddress = secrets.address;
|
|
876
|
-
const info = await wallet.getArkadeInfo({ requireLive: true });
|
|
877
|
-
const quote = await transport.requestQuote(
|
|
878
|
-
lightningSendRequest({ rfqId, invoice: params.invoice.raw, refundAddress, senderPubkey })
|
|
879
|
-
);
|
|
880
|
-
if (quote.to_amount !== params.invoice.amountSats) {
|
|
881
|
-
throw new Error(
|
|
882
|
-
`quote to_amount ${quote.to_amount} does not match the invoice's ${params.invoice.amountSats}`
|
|
883
|
-
);
|
|
884
|
-
}
|
|
885
|
-
if (quote.from_amount < quote.to_amount) {
|
|
886
|
-
throw new Error(
|
|
887
|
-
`quote from_amount ${quote.from_amount} is below the invoice amount \u2014 a negative spread is not a quote`
|
|
888
|
-
);
|
|
889
|
-
}
|
|
890
|
-
const operatorPubkey = toXOnly(hex3.decode(info.signerPubkey), "ark signer key");
|
|
891
|
-
const network = networkFromArkadeInfo(info);
|
|
892
|
-
const derived = deriveLightningSend({
|
|
893
|
-
quote,
|
|
894
|
-
paymentHash: params.invoice.paymentHash,
|
|
895
|
-
senderPubkey,
|
|
896
|
-
refundPkScript: secrets.pkScript,
|
|
897
|
-
operatorPubkey,
|
|
898
|
-
emulatorPubkey: toXOnly(
|
|
899
|
-
hex3.decode(resolveEmulatorPubkey(network, params.emulatorPubkey)),
|
|
900
|
-
"emulator signer key"
|
|
901
|
-
),
|
|
902
|
-
claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
|
|
903
|
-
hrp: network.hrp
|
|
904
|
-
});
|
|
905
|
-
const { address, script, contractParams } = derived;
|
|
906
|
-
assertFundable({
|
|
907
|
-
quote,
|
|
908
|
-
invoiceExpiresAt: params.invoice.expiresAt,
|
|
909
|
-
now: Math.floor(Date.now() / 1e3)
|
|
910
|
-
});
|
|
911
|
-
await registerLockupContract(await wallet.getContractManager(), script, address);
|
|
912
|
-
return {
|
|
913
|
-
rfqId,
|
|
914
|
-
quote,
|
|
915
|
-
address,
|
|
916
|
-
// What the lockup must carry: the quote's `from_amount` — the invoice
|
|
917
|
-
// PLUS the corridor's fee, never the bare invoice amount.
|
|
918
|
-
fundAmount: quote.from_amount,
|
|
919
|
-
swapPkScript: derived.swapPkScript,
|
|
920
|
-
script,
|
|
921
|
-
refundAddress,
|
|
922
|
-
senderPubkey,
|
|
923
|
-
secrets,
|
|
924
|
-
contractParams
|
|
925
|
-
};
|
|
926
|
-
}
|
|
927
|
-
var l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
|
|
928
|
-
var onchainSendRequest = (input) => ({
|
|
929
|
-
v: 1,
|
|
930
|
-
type: "rfq_request",
|
|
931
|
-
rfq_id: input.rfqId,
|
|
932
|
-
pair: ONCHAIN_SEND_PAIR,
|
|
933
|
-
amount_side: input.amountSide,
|
|
934
|
-
amount: input.amount,
|
|
935
|
-
profile: {
|
|
936
|
-
payment_hash: input.paymentHash,
|
|
937
|
-
payout_pubkey: hex3.encode(input.payoutPubkey),
|
|
938
|
-
refund_address: input.refundAddress,
|
|
939
|
-
client_refund_pubkey: hex3.encode(input.senderPubkey)
|
|
940
|
-
}
|
|
941
|
-
});
|
|
942
|
-
var lightningReceiveRequest = (input) => ({
|
|
943
|
-
v: 1,
|
|
944
|
-
type: "rfq_request",
|
|
945
|
-
rfq_id: input.rfqId,
|
|
946
|
-
pair: LIGHTNING_RECEIVE_PAIR,
|
|
947
|
-
amount_side: input.amountSide,
|
|
948
|
-
amount: input.amount,
|
|
949
|
-
profile: {
|
|
950
|
-
payment_hash: input.paymentHash,
|
|
951
|
-
payout_address: input.payoutAddress,
|
|
952
|
-
payout_pubkey: hex3.encode(input.payoutPubkey),
|
|
953
|
-
...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket }
|
|
954
|
-
}
|
|
955
|
-
});
|
|
956
|
-
var onchainReceiveRequest = (input) => ({
|
|
957
|
-
v: 1,
|
|
958
|
-
type: "rfq_request",
|
|
959
|
-
rfq_id: input.rfqId,
|
|
960
|
-
pair: ONCHAIN_RECEIVE_PAIR,
|
|
961
|
-
amount_side: input.amountSide,
|
|
962
|
-
amount: input.amount,
|
|
963
|
-
profile: {
|
|
964
|
-
payment_hash: input.paymentHash,
|
|
965
|
-
...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket },
|
|
966
|
-
refund_pubkey: hex3.encode(input.refundPubkey),
|
|
967
|
-
payout_address: input.payoutAddress,
|
|
968
|
-
payout_pubkey: hex3.encode(input.payoutPubkey)
|
|
969
|
-
}
|
|
970
|
-
});
|
|
971
|
-
function deriveOnchainSend(input) {
|
|
972
|
-
const { quote } = input;
|
|
973
|
-
const profile = quote.profile ?? {};
|
|
974
|
-
const refundLocktime = quote.refund_locktime ?? profile.refund_locktime;
|
|
975
|
-
const htlcPubkey = profile.htlc_pubkey;
|
|
976
|
-
const htlcLocktime = profile.htlc_locktime;
|
|
977
|
-
const htlcAddress = profile.htlc_address;
|
|
978
|
-
const minConfirmations = profile.min_confirmations;
|
|
979
|
-
const receiverPkScriptHex = profile.receiver_pk_script;
|
|
980
|
-
if (refundLocktime === void 0 || htlcPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || receiverPkScriptHex === void 0) {
|
|
981
|
-
throw new Error("onchain-send quote is missing a binding field");
|
|
982
|
-
}
|
|
983
|
-
const contractParams = {
|
|
984
|
-
solverPubkey: toXOnly(hex3.decode(quote.solver_pubkey), "solver key"),
|
|
985
|
-
refundLocktime,
|
|
986
|
-
operatorPubkey: input.operatorPubkey,
|
|
987
|
-
paymentHash: input.paymentHash,
|
|
988
|
-
claimDelay: input.claimDelay,
|
|
989
|
-
emulatorPubkey: input.emulatorPubkey,
|
|
990
|
-
senderPubkey: input.senderPubkey,
|
|
991
|
-
receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
|
|
992
|
-
refundPkScript: ArkAddress2.decode(input.refundAddress).pkScript
|
|
993
|
-
};
|
|
994
|
-
const { script, address } = matchQuotedLockup(
|
|
995
|
-
quote,
|
|
996
|
-
input.hrp,
|
|
997
|
-
input.operatorPubkey,
|
|
998
|
-
(legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
999
|
-
);
|
|
1000
|
-
const htlcParams = {
|
|
1001
|
-
paymentHash: input.paymentHash,
|
|
1002
|
-
claimKey: input.payoutPubkey,
|
|
1003
|
-
refundKey: toXOnly(hex3.decode(htlcPubkey), "solver L1 htlc key"),
|
|
1004
|
-
refundLocktime: htlcLocktime
|
|
1005
|
-
};
|
|
1006
|
-
const htlc = onchainHtlcScript(htlcParams, input.l1Network);
|
|
1007
|
-
if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
|
|
1008
|
-
return {
|
|
1009
|
-
address,
|
|
1010
|
-
swapPkScript: script.pkScript,
|
|
1011
|
-
script,
|
|
1012
|
-
htlc,
|
|
1013
|
-
htlcParams,
|
|
1014
|
-
l1Network: input.l1Network,
|
|
1015
|
-
refundLocktime,
|
|
1016
|
-
htlcLocktime,
|
|
1017
|
-
minConfirmations
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
async function requestOnchainSend(wallet, transport, params) {
|
|
1021
|
-
const rfqId = params.rfqId ?? newRfqId();
|
|
1022
|
-
const secrets = await provisionClaimSecret(wallet, { preimage: params.preimage });
|
|
1023
|
-
if (secrets.mustPersistPreimage) {
|
|
1024
|
-
console.warn(
|
|
1025
|
-
"[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
|
|
1026
|
-
);
|
|
1027
|
-
}
|
|
1028
|
-
const paymentHash = hex3.encode(secrets.paymentHash);
|
|
1029
|
-
const senderPubkey = secrets.pubkey;
|
|
1030
|
-
const [info, refundAddress] = await Promise.all([
|
|
1031
|
-
wallet.getArkadeInfo({ requireLive: true }),
|
|
1032
|
-
wallet.getAddress()
|
|
1033
|
-
]);
|
|
1034
|
-
const quote = await transport.requestQuote(
|
|
1035
|
-
onchainSendRequest({
|
|
1036
|
-
rfqId,
|
|
1037
|
-
paymentHash,
|
|
1038
|
-
payoutPubkey: params.payoutPubkey,
|
|
1039
|
-
refundAddress,
|
|
1040
|
-
senderPubkey,
|
|
1041
|
-
amount: params.amount,
|
|
1042
|
-
amountSide: params.amountSide
|
|
1043
|
-
})
|
|
1044
|
-
);
|
|
1045
|
-
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
1046
|
-
const network = networkFromArkadeInfo(info);
|
|
1047
|
-
const derived = deriveOnchainSend({
|
|
1048
|
-
quote,
|
|
1049
|
-
paymentHash,
|
|
1050
|
-
payoutPubkey: params.payoutPubkey,
|
|
1051
|
-
operatorPubkey: toXOnly(hex3.decode(info.signerPubkey), "ark signer key"),
|
|
1052
|
-
emulatorPubkey: toXOnly(
|
|
1053
|
-
hex3.decode(resolveEmulatorPubkey(network, params.emulatorPubkey)),
|
|
1054
|
-
"emulator signer key"
|
|
1055
|
-
),
|
|
1056
|
-
claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
|
|
1057
|
-
hrp: network.hrp,
|
|
1058
|
-
l1Network: l1NetworkFromArk(info.network),
|
|
1059
|
-
refundAddress,
|
|
1060
|
-
senderPubkey
|
|
1061
|
-
});
|
|
1062
|
-
assertFundable({
|
|
1063
|
-
quote,
|
|
1064
|
-
now: Math.floor(Date.now() / 1e3),
|
|
1065
|
-
onchain: {
|
|
1066
|
-
htlcLocktime: derived.htlcLocktime,
|
|
1067
|
-
minConfirmations: derived.minConfirmations,
|
|
1068
|
-
direction: "send"
|
|
1069
|
-
}
|
|
1070
|
-
});
|
|
1071
|
-
await registerLockupContract(
|
|
1072
|
-
await wallet.getContractManager(),
|
|
1073
|
-
derived.script,
|
|
1074
|
-
derived.address
|
|
1075
|
-
);
|
|
1076
|
-
return {
|
|
1077
|
-
rfqId,
|
|
1078
|
-
quote,
|
|
1079
|
-
address: derived.address,
|
|
1080
|
-
fundAmount: quote.from_amount,
|
|
1081
|
-
swapPkScript: derived.swapPkScript,
|
|
1082
|
-
script: derived.script,
|
|
1083
|
-
refundAddress,
|
|
1084
|
-
htlc: derived.htlc,
|
|
1085
|
-
htlcParams: derived.htlcParams,
|
|
1086
|
-
l1Network: derived.l1Network,
|
|
1087
|
-
minConfirmations: derived.minConfirmations,
|
|
1088
|
-
refundLocktime: derived.refundLocktime,
|
|
1089
|
-
senderPubkey,
|
|
1090
|
-
secrets
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
var assertQuotedAmount = (quote, amountSide, amount) => {
|
|
1094
|
-
const quoted = amountSide === "from" ? quote.from_amount : quote.to_amount;
|
|
1095
|
-
if (quoted !== amount) {
|
|
1096
|
-
throw new Error(
|
|
1097
|
-
`quote ${amountSide === "from" ? "from_amount" : "to_amount"} ${quoted} does not match the requested ${amount} \u2014 not this trade's quote`
|
|
1098
|
-
);
|
|
1099
|
-
}
|
|
1100
|
-
if (quote.to_amount > quote.from_amount) {
|
|
1101
|
-
throw new Error("quote pays out more than it takes in \u2014 not a quote to fund");
|
|
1102
|
-
}
|
|
1103
|
-
};
|
|
1104
|
-
var MIN_CLAIM_WINDOW_SECONDS = 30 * 60;
|
|
1105
|
-
var verifyReceiveInvoice = (input) => {
|
|
1106
|
-
let decoded;
|
|
1107
|
-
try {
|
|
1108
|
-
decoded = input.decode(input.invoice);
|
|
1109
|
-
} catch (error) {
|
|
1110
|
-
throw gateError(
|
|
1111
|
-
"invoice_undecodable",
|
|
1112
|
-
`solver sent an undecodable invoice: ${error instanceof Error ? error.message : String(error)}`
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
assertFinite(decoded.expiresAt, "invoice_undecodable", "the decoded invoice expiry");
|
|
1116
|
-
assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
|
|
1117
|
-
if (decoded.paymentHash !== input.paymentHash) {
|
|
1118
|
-
throw gateError(
|
|
1119
|
-
"invoice_hash_mismatch",
|
|
1120
|
-
`solver's invoice pays ${decoded.paymentHash}, not this swap's ${input.paymentHash}`
|
|
1121
|
-
);
|
|
1122
|
-
}
|
|
1123
|
-
if (decoded.amountSats <= 0) {
|
|
1124
|
-
throw gateError("invoice_amount_mismatch", "solver's invoice names no amount");
|
|
1125
|
-
}
|
|
1126
|
-
if (decoded.amountSats !== input.quote.from_amount) {
|
|
1127
|
-
throw gateError(
|
|
1128
|
-
"invoice_amount_mismatch",
|
|
1129
|
-
`solver's invoice asks for ${decoded.amountSats}, not the quoted from_amount ${input.quote.from_amount}`
|
|
1130
|
-
);
|
|
1131
|
-
}
|
|
1132
|
-
return { payDeadline: Math.min(decoded.expiresAt, input.quote.valid_until) };
|
|
1133
|
-
};
|
|
1134
|
-
var assertReceivable = (input) => {
|
|
1135
|
-
assertFinite(input.payDeadline, "quote_malformed", "payDeadline");
|
|
1136
|
-
assertFinite(input.now, "invalid_gate_input", "now");
|
|
1137
|
-
assertFinite(input.minClaimWindowSeconds, "invalid_gate_input", "minClaimWindowSeconds");
|
|
1138
|
-
assertFinite(input.maxPayAmount, "invalid_gate_input", "maxPayAmount");
|
|
1139
|
-
const minClaimWindow = input.minClaimWindowSeconds ?? MIN_CLAIM_WINDOW_SECONDS;
|
|
1140
|
-
if (input.now >= input.payDeadline) {
|
|
1141
|
-
throw gateError("quote_expired", "quote or invoice already expired \u2014 request a fresh one");
|
|
1142
|
-
}
|
|
1143
|
-
if (input.quote.refund_locktime === void 0) {
|
|
1144
|
-
throw gateError("missing_refund_locktime", "receive quote carries no refund_locktime");
|
|
1145
|
-
}
|
|
1146
|
-
assertFinite(input.quote.refund_locktime, "quote_malformed", "quote refund_locktime");
|
|
1147
|
-
if (input.quote.refund_locktime - input.payDeadline < minClaimWindow) {
|
|
1148
|
-
throw gateError(
|
|
1149
|
-
"claim_window_too_short",
|
|
1150
|
-
`a payment at the deadline would leave under ${minClaimWindow}s to claim before the solver's refund opens`
|
|
1151
|
-
);
|
|
1152
|
-
}
|
|
1153
|
-
if (input.maxPayAmount !== void 0 && input.quote.from_amount > input.maxPayAmount) {
|
|
1154
|
-
throw gateError(
|
|
1155
|
-
"price_too_high",
|
|
1156
|
-
`quote asks ${input.quote.from_amount} sats, above the ${input.maxPayAmount} ceiling`
|
|
1157
|
-
);
|
|
1158
|
-
}
|
|
1159
|
-
};
|
|
1160
|
-
function lightningReceiveContract(params) {
|
|
1161
|
-
const seconds = (value) => ({
|
|
1162
|
-
type: "seconds",
|
|
1163
|
-
value: BigInt(value)
|
|
1164
|
-
});
|
|
1165
|
-
return new VHTLC.ScriptV2({
|
|
1166
|
-
sender: params.solverPubkey,
|
|
1167
|
-
receiver: params.payoutPubkey,
|
|
1168
|
-
server: params.operatorPubkey,
|
|
1169
|
-
preimageHash: ripemd1602(hex3.decode(params.paymentHash)),
|
|
1170
|
-
refundLocktime: BigInt(params.refundLocktime),
|
|
1171
|
-
unilateralClaimDelay: seconds(params.claimDelay),
|
|
1172
|
-
unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
|
|
1173
|
-
unilateralRefundWithoutReceiverDelay: seconds(
|
|
1174
|
-
unilateralRefundWithoutReceiverDelay(params.claimDelay)
|
|
1175
|
-
),
|
|
1176
|
-
nonInteractiveParameters: {
|
|
1177
|
-
receiverPkScript: params.payoutPkScript,
|
|
1178
|
-
senderPkScript: params.solverRefundPkScript,
|
|
1179
|
-
emulatorPubkey: params.emulatorPubkey,
|
|
1180
|
-
...params.legacy !== void 0 && { legacy: params.legacy }
|
|
1181
|
-
}
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
function deriveLightningReceive(input) {
|
|
1185
|
-
const { quote } = input;
|
|
1186
|
-
const profile = quote.profile ?? {};
|
|
1187
|
-
const refundLocktime = quote.refund_locktime;
|
|
1188
|
-
const invoice = profile.invoice;
|
|
1189
|
-
const solverRefundPkScriptHex = profile.solver_refund_pk_script;
|
|
1190
|
-
if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
|
|
1191
|
-
throw new Error("lightning-receive quote is missing a binding field");
|
|
1192
|
-
}
|
|
1193
|
-
const contractParams = {
|
|
1194
|
-
solverPubkey: toXOnly(hex3.decode(quote.solver_pubkey), "solver key"),
|
|
1195
|
-
refundLocktime,
|
|
1196
|
-
operatorPubkey: input.operatorPubkey,
|
|
1197
|
-
paymentHash: input.paymentHash,
|
|
1198
|
-
claimDelay: input.claimDelay,
|
|
1199
|
-
emulatorPubkey: input.emulatorPubkey,
|
|
1200
|
-
solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
|
|
1201
|
-
payoutPubkey: input.payoutPubkey,
|
|
1202
|
-
payoutPkScript: ArkAddress2.decode(input.payoutAddress).pkScript
|
|
1203
|
-
};
|
|
1204
|
-
const matched = matchQuotedLockup(
|
|
1205
|
-
quote,
|
|
1206
|
-
input.hrp,
|
|
1207
|
-
input.operatorPubkey,
|
|
1208
|
-
(legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
|
|
1209
|
-
);
|
|
1210
|
-
return {
|
|
1211
|
-
address: matched.address,
|
|
1212
|
-
swapPkScript: matched.script.pkScript,
|
|
1213
|
-
script: matched.script,
|
|
1214
|
-
invoice,
|
|
1215
|
-
refundLocktime,
|
|
1216
|
-
contractParams: {
|
|
1217
|
-
...contractParams,
|
|
1218
|
-
...matched.legacy !== void 0 && { legacy: matched.legacy }
|
|
1219
|
-
}
|
|
1220
|
-
};
|
|
1221
|
-
}
|
|
1222
|
-
async function requestLightningReceive(wallet, transport, params) {
|
|
1223
|
-
const rfqId = params.rfqId ?? newRfqId();
|
|
1224
|
-
const secrets = await provisionClaimSecret(wallet);
|
|
1225
|
-
if (secrets.mustPersistPreimage) {
|
|
1226
|
-
console.warn(
|
|
1227
|
-
"[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before paying"
|
|
1228
|
-
);
|
|
1229
|
-
}
|
|
1230
|
-
const preimage = secrets.preimage;
|
|
1231
|
-
const paymentHash = hex3.encode(secrets.paymentHash);
|
|
1232
|
-
const payoutPubkey = secrets.pubkey;
|
|
1233
|
-
const [info, payoutAddress] = await Promise.all([
|
|
1234
|
-
wallet.getArkadeInfo({ requireLive: true }),
|
|
1235
|
-
wallet.getAddress()
|
|
1236
|
-
]);
|
|
1237
|
-
const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
|
|
1238
|
-
preimage,
|
|
1239
|
-
covclaimdPubkey: params.covclaimdPubkey
|
|
1240
|
-
}) : void 0;
|
|
1241
|
-
const quote = await transport.requestQuote(
|
|
1242
|
-
lightningReceiveRequest({
|
|
1243
|
-
rfqId,
|
|
1244
|
-
paymentHash,
|
|
1245
|
-
payoutAddress,
|
|
1246
|
-
payoutPubkey,
|
|
1247
|
-
claimPacket: claimPacket?.packet,
|
|
1248
|
-
amount: params.amount,
|
|
1249
|
-
amountSide: params.amountSide
|
|
1250
|
-
})
|
|
1251
|
-
);
|
|
1252
|
-
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
1253
|
-
const network = networkFromArkadeInfo(info);
|
|
1254
|
-
const derived = deriveLightningReceive({
|
|
1255
|
-
quote,
|
|
1256
|
-
paymentHash,
|
|
1257
|
-
payoutPubkey,
|
|
1258
|
-
payoutAddress,
|
|
1259
|
-
operatorPubkey: toXOnly(hex3.decode(info.signerPubkey), "ark signer key"),
|
|
1260
|
-
emulatorPubkey: toXOnly(
|
|
1261
|
-
hex3.decode(resolveEmulatorPubkey(network, params.emulatorPubkey)),
|
|
1262
|
-
"emulator signer key"
|
|
1263
|
-
),
|
|
1264
|
-
claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
|
|
1265
|
-
hrp: network.hrp
|
|
1266
|
-
});
|
|
1267
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
1268
|
-
const { payDeadline } = verifyReceiveInvoice({
|
|
1269
|
-
invoice: derived.invoice,
|
|
1270
|
-
decode: params.decodeInvoice,
|
|
1271
|
-
paymentHash,
|
|
1272
|
-
quote
|
|
1273
|
-
});
|
|
1274
|
-
assertReceivable({ quote, payDeadline, now, maxPayAmount: params.maxPayAmount });
|
|
1275
|
-
await registerLockupContract(
|
|
1276
|
-
await wallet.getContractManager(),
|
|
1277
|
-
derived.script,
|
|
1278
|
-
derived.address
|
|
1279
|
-
);
|
|
1280
|
-
return {
|
|
1281
|
-
rfqId,
|
|
1282
|
-
quote,
|
|
1283
|
-
invoice: derived.invoice,
|
|
1284
|
-
payAmount: quote.from_amount,
|
|
1285
|
-
expectedAmount: quote.to_amount,
|
|
1286
|
-
invoiceExpiresAt: payDeadline,
|
|
1287
|
-
address: derived.address,
|
|
1288
|
-
swapPkScript: derived.swapPkScript,
|
|
1289
|
-
script: derived.script,
|
|
1290
|
-
payoutAddress,
|
|
1291
|
-
payoutPubkey,
|
|
1292
|
-
secrets,
|
|
1293
|
-
contractParams: derived.contractParams
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
function deriveOnchainReceive(input) {
|
|
1297
|
-
const { quote } = input;
|
|
1298
|
-
const profile = quote.profile ?? {};
|
|
1299
|
-
const refundLocktime = quote.refund_locktime;
|
|
1300
|
-
const claimPubkey = profile.claim_pubkey;
|
|
1301
|
-
const htlcLocktime = profile.htlc_locktime;
|
|
1302
|
-
const htlcAddress = profile.htlc_address;
|
|
1303
|
-
const minConfirmations = profile.min_confirmations;
|
|
1304
|
-
const solverRefundPkScriptHex = profile.solver_refund_pk_script;
|
|
1305
|
-
if (refundLocktime === void 0 || claimPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || solverRefundPkScriptHex === void 0) {
|
|
1306
|
-
throw new Error("onchain-receive quote is missing a binding field");
|
|
1307
|
-
}
|
|
1308
|
-
const contractParams = {
|
|
1309
|
-
solverPubkey: toXOnly(hex3.decode(quote.solver_pubkey), "solver key"),
|
|
1310
|
-
refundLocktime,
|
|
1311
|
-
operatorPubkey: input.operatorPubkey,
|
|
1312
|
-
paymentHash: input.paymentHash,
|
|
1313
|
-
claimDelay: input.claimDelay,
|
|
1314
|
-
emulatorPubkey: input.emulatorPubkey,
|
|
1315
|
-
solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
|
|
1316
|
-
payoutPubkey: input.payoutPubkey,
|
|
1317
|
-
payoutPkScript: ArkAddress2.decode(input.payoutAddress).pkScript
|
|
1318
|
-
};
|
|
1319
|
-
const { script, address } = matchQuotedLockup(
|
|
1320
|
-
quote,
|
|
1321
|
-
input.hrp,
|
|
1322
|
-
input.operatorPubkey,
|
|
1323
|
-
(legacy) => lightningReceiveContract({
|
|
1324
|
-
...contractParams,
|
|
1325
|
-
...legacy !== void 0 && { legacy }
|
|
1326
|
-
})
|
|
1327
|
-
);
|
|
1328
|
-
const htlc = onchainHtlcScript(
|
|
1329
|
-
{
|
|
1330
|
-
paymentHash: input.paymentHash,
|
|
1331
|
-
claimKey: toXOnly(hex3.decode(claimPubkey), "solver L1 claim key"),
|
|
1332
|
-
refundKey: input.refundPubkey,
|
|
1333
|
-
refundLocktime: htlcLocktime
|
|
1334
|
-
},
|
|
1335
|
-
input.l1Network
|
|
1336
|
-
);
|
|
1337
|
-
if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
|
|
1338
|
-
return {
|
|
1339
|
-
address,
|
|
1340
|
-
swapPkScript: script.pkScript,
|
|
1341
|
-
script,
|
|
1342
|
-
htlc,
|
|
1343
|
-
refundLocktime,
|
|
1344
|
-
htlcLocktime,
|
|
1345
|
-
minConfirmations
|
|
1346
|
-
};
|
|
1347
|
-
}
|
|
1348
|
-
async function requestOnchainReceive(wallet, transport, params) {
|
|
1349
|
-
const rfqId = params.rfqId ?? newRfqId();
|
|
1350
|
-
const secrets = await provisionClaimSecret(wallet);
|
|
1351
|
-
if (secrets.mustPersistPreimage) {
|
|
1352
|
-
console.warn(
|
|
1353
|
-
"[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
|
|
1354
|
-
);
|
|
1355
|
-
}
|
|
1356
|
-
const preimage = secrets.preimage;
|
|
1357
|
-
const paymentHash = hex3.encode(secrets.paymentHash);
|
|
1358
|
-
const payoutPubkey = secrets.pubkey;
|
|
1359
|
-
const [info, payoutAddress] = await Promise.all([
|
|
1360
|
-
wallet.getArkadeInfo({ requireLive: true }),
|
|
1361
|
-
wallet.getAddress()
|
|
1362
|
-
]);
|
|
1363
|
-
const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
|
|
1364
|
-
preimage,
|
|
1365
|
-
covclaimdPubkey: params.covclaimdPubkey
|
|
1366
|
-
}) : void 0;
|
|
1367
|
-
const quote = await transport.requestQuote(
|
|
1368
|
-
onchainReceiveRequest({
|
|
1369
|
-
rfqId,
|
|
1370
|
-
paymentHash,
|
|
1371
|
-
payoutAddress,
|
|
1372
|
-
payoutPubkey,
|
|
1373
|
-
refundPubkey: params.refundPubkey,
|
|
1374
|
-
claimPacket: claimPacket?.packet,
|
|
1375
|
-
amount: params.amount,
|
|
1376
|
-
amountSide: params.amountSide
|
|
1377
|
-
})
|
|
1378
|
-
);
|
|
1379
|
-
assertQuotedAmount(quote, params.amountSide, params.amount);
|
|
1380
|
-
const network = networkFromArkadeInfo(info);
|
|
1381
|
-
const derived = deriveOnchainReceive({
|
|
1382
|
-
quote,
|
|
1383
|
-
paymentHash,
|
|
1384
|
-
payoutPubkey,
|
|
1385
|
-
payoutAddress,
|
|
1386
|
-
refundPubkey: params.refundPubkey,
|
|
1387
|
-
operatorPubkey: toXOnly(hex3.decode(info.signerPubkey), "ark signer key"),
|
|
1388
|
-
emulatorPubkey: toXOnly(
|
|
1389
|
-
hex3.decode(resolveEmulatorPubkey(network, params.emulatorPubkey)),
|
|
1390
|
-
"emulator signer key"
|
|
1391
|
-
),
|
|
1392
|
-
claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
|
|
1393
|
-
hrp: network.hrp,
|
|
1394
|
-
l1Network: l1NetworkFromArk(info.network)
|
|
1395
|
-
});
|
|
1396
|
-
assertFundable({
|
|
1397
|
-
quote,
|
|
1398
|
-
now: Math.floor(Date.now() / 1e3),
|
|
1399
|
-
onchain: {
|
|
1400
|
-
htlcLocktime: derived.htlcLocktime,
|
|
1401
|
-
minConfirmations: derived.minConfirmations,
|
|
1402
|
-
direction: "receive"
|
|
1403
|
-
}
|
|
1404
|
-
});
|
|
1405
|
-
await registerLockupContract(
|
|
1406
|
-
await wallet.getContractManager(),
|
|
1407
|
-
derived.script,
|
|
1408
|
-
derived.address
|
|
1409
|
-
);
|
|
1410
|
-
return {
|
|
1411
|
-
rfqId,
|
|
1412
|
-
quote,
|
|
1413
|
-
address: derived.address,
|
|
1414
|
-
fundAmount: quote.from_amount,
|
|
1415
|
-
expectedAmount: quote.to_amount,
|
|
1416
|
-
swapPkScript: derived.swapPkScript,
|
|
1417
|
-
script: derived.script,
|
|
1418
|
-
htlc: derived.htlc,
|
|
1419
|
-
payoutAddress,
|
|
1420
|
-
payoutPubkey,
|
|
1421
|
-
secrets
|
|
1422
|
-
};
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
export {
|
|
1426
|
-
SWAP_LOCKUP_CONTRACT_TYPE,
|
|
1427
|
-
SWAP_LOCKUP_CONTRACT_LABEL,
|
|
1428
|
-
SWAP_LOCKUP_CONTRACT_KIND,
|
|
1429
|
-
LockupContractMissing,
|
|
1430
|
-
LockupRegistrationFailed,
|
|
1431
|
-
registerLockupContract,
|
|
1432
|
-
lockupContractParams,
|
|
1433
|
-
ONCHAIN_ORDER_MARGIN_SECONDS,
|
|
1434
|
-
ONCHAIN_CLAIM_MARGIN_SECONDS,
|
|
1435
|
-
MAX_MIN_CONFIRMATIONS,
|
|
1436
|
-
LOCKTIME_THRESHOLD,
|
|
1437
|
-
ONCHAIN_SECONDS_PER_BLOCK,
|
|
1438
|
-
ONCHAIN_DUST_SATS,
|
|
1439
|
-
ONCHAIN_CLAIM_VSIZE,
|
|
1440
|
-
newPreimage,
|
|
1441
|
-
paymentHashOf,
|
|
1442
|
-
L1_NETWORKS,
|
|
1443
|
-
l1ScriptForAddress,
|
|
1444
|
-
onchainHtlcScript,
|
|
1445
|
-
buildHtlcClaim,
|
|
1446
|
-
buildHtlcRefund,
|
|
1447
|
-
extractPreimage,
|
|
1448
|
-
awaitOnchainFill,
|
|
1449
|
-
claimOnchainFill,
|
|
1450
|
-
classifyOnchainHtlc,
|
|
1451
|
-
sealClaimPacket,
|
|
1452
|
-
SEALED_CIPHERTEXT_LENGTH,
|
|
1453
|
-
CLAIM_PACKET_TYPE,
|
|
1454
|
-
appendArkadeScript,
|
|
1455
|
-
claimPacketShape,
|
|
1456
|
-
ARKADE_BTC,
|
|
1457
|
-
LIGHTNING_BTC,
|
|
1458
|
-
ONCHAIN_BTC,
|
|
1459
|
-
arkadeAssetLeg,
|
|
1460
|
-
rfqPair,
|
|
1461
|
-
LIGHTNING_SEND_PAIR,
|
|
1462
|
-
LIGHTNING_RECEIVE_PAIR,
|
|
1463
|
-
ONCHAIN_SEND_PAIR,
|
|
1464
|
-
ONCHAIN_RECEIVE_PAIR,
|
|
1465
|
-
RFQ_TERMINAL_STATES,
|
|
1466
|
-
RFQ_REFUSAL_ERROR_CODES,
|
|
1467
|
-
isRfqRefusalErrorCode,
|
|
1468
|
-
SwapRefusal,
|
|
1469
|
-
AddressMismatch,
|
|
1470
|
-
newRfqId,
|
|
1471
|
-
lightningSendRequest,
|
|
1472
|
-
arkadeSwapRequest,
|
|
1473
|
-
assertPairLength,
|
|
1474
|
-
verifyLockupAddress,
|
|
1475
|
-
assertFundable,
|
|
1476
|
-
expectQuote,
|
|
1477
|
-
pairOf,
|
|
1478
|
-
httpTransport,
|
|
1479
|
-
relayTransport,
|
|
1480
|
-
unilateralClaimDelay,
|
|
1481
|
-
unilateralRefundDelay,
|
|
1482
|
-
unilateralRefundWithoutReceiverDelay,
|
|
1483
|
-
lightningSendContract,
|
|
1484
|
-
deriveLightningSend,
|
|
1485
|
-
requestLightningSend,
|
|
1486
|
-
l1NetworkFromArk,
|
|
1487
|
-
onchainSendRequest,
|
|
1488
|
-
lightningReceiveRequest,
|
|
1489
|
-
onchainReceiveRequest,
|
|
1490
|
-
deriveOnchainSend,
|
|
1491
|
-
requestOnchainSend,
|
|
1492
|
-
verifyReceiveInvoice,
|
|
1493
|
-
assertReceivable,
|
|
1494
|
-
lightningReceiveContract,
|
|
1495
|
-
deriveLightningReceive,
|
|
1496
|
-
requestLightningReceive,
|
|
1497
|
-
deriveOnchainReceive,
|
|
1498
|
-
requestOnchainReceive
|
|
1499
|
-
};
|