@ninsei-labs/sdk 0.58.0 → 0.60.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/CHANGELOG.md +16 -0
- package/README.md +59 -26
- package/THIRD_PARTY_NOTICES.md +7 -4
- package/assets/vendors/MANIFEST.json +1 -1
- package/assets/vendors/sdk/sdk-browser.js +4 -6
- package/engine/core/config.js +2 -2
- package/engine/core/deployments.generated.js +17 -0
- package/engine/monero/scan.js +56 -8
- package/index.d.ts +152 -41
- package/package.json +4 -4
- package/src/index.mjs +4 -4
- package/src/predictEscrow.mjs +25 -0
- package/src/public/networks.d.ts +9 -0
- package/src/public/networks.mjs +1 -0
- package/src/public/xmr.d.ts +8 -0
- package/src/public/xmr.mjs +1 -1
- package/src/quotePolicy.mjs +44 -11
- package/src/quotes.mjs +20 -16
- package/src/record.mjs +4 -0
- package/src/relayFirmClient.mjs +18 -0
- package/src/swaps.mjs +498 -93
- package/src/sweep.mjs +9 -2
- package/src/version.mjs +1 -1
- package/src/witness-slice.mjs +84 -0
- package/src/xmr-arrival.mjs +244 -121
package/src/swaps.mjs
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// order and halves -> server -> watching the Monero address. A lock without a recovery file is a lock with nothing
|
|
6
6
|
// to open it with if the browser is lost, so the confirmation stands BEFORE anything that locks funds.
|
|
7
7
|
import { SdkError } from "./errors.mjs";
|
|
8
|
-
import {
|
|
8
|
+
import { quoteLifeVerdict } from "./quotePolicy.mjs";
|
|
9
9
|
import { SDK_VERSION } from "./version.mjs";
|
|
10
10
|
import * as engine from "./engine.mjs";
|
|
11
11
|
// The name is NOT `record`: inside start there is a variable with that name, and referencing the module before it
|
|
@@ -15,6 +15,7 @@ import * as recordModule from "./record.mjs";
|
|
|
15
15
|
// The order: our own side is built by the engine's builder, the counterparty's side is verified and accepted, and
|
|
16
16
|
// the joint address is assembled from the halves. There are no formulas of our own in the core - see order.mjs.
|
|
17
17
|
import { buildOwnSideFromHalvesKnown, contextOf, halfHex, norm, normalizeCounterpartyView, orderStepChunked } from "./order.mjs";
|
|
18
|
+
import { predictEscrow } from "./predictEscrow.mjs";
|
|
18
19
|
// Locking the funds: sending goes through the already-finished step (`lock.send`), the wallet is an adapter from outside.
|
|
19
20
|
import * as lock from "./lock.mjs";
|
|
20
21
|
import * as flow from "./swap-flow.mjs";
|
|
@@ -268,6 +269,11 @@ export const recordInputOf = (request, xmrNetwork = null) => {
|
|
|
268
269
|
// tie the created escrow to the provider node's record, and without it the node cannot take the ETH
|
|
269
270
|
// (sdk/src/swap-flow.mjs: quoteId: quote.id -> swap.orderQuoteId).
|
|
270
271
|
orderQuoteId: pass(quote.id),
|
|
272
|
+
// THE PENDING-FUNDING IDENTITY. A retry without the relay answer still has to prove that the record it found
|
|
273
|
+
// belongs to the same order; the salt alone is not enough, so the chain, the factory and the predicted escrow
|
|
274
|
+
// are stored beside it.
|
|
275
|
+
chainId: pass((request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)),
|
|
276
|
+
factory: pass((request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)),
|
|
271
277
|
// WHERE TO WITHDRAW XMR: part of the record, not a detail of the screen - the progress screen exports the file by it.
|
|
272
278
|
receiveAddress: pass(request.receiveTo),
|
|
273
279
|
// WHAT THE PERSON SAW: the maker, its spread, the fee, the rate and the quote signature. Screen data, but it must
|
|
@@ -321,33 +327,79 @@ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null
|
|
|
321
327
|
return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
|
|
322
328
|
}
|
|
323
329
|
|
|
324
|
-
// A PENDING FUNDING IS RESUMED ONLY FOR THE SAME
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
|
|
330
|
+
// A PENDING FUNDING IS RESUMED ONLY FOR THE SAME ORDER, NOT MERELY THE SAME NONCE. The quote nonce is the maker's
|
|
331
|
+
// value and a second offer can reuse it. The identity is the client's salt together with the chain, the factory and
|
|
332
|
+
// the predicted escrow: those four values are the order the record was built for. A record that names no predicted
|
|
333
|
+
// escrow cannot prove it is the same order and is not resumed.
|
|
334
|
+
const pendingSalt = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
|
|
335
|
+
const pendingAddress = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
|
|
336
|
+
function pendingFundingIdentity(swap) {
|
|
337
|
+
const escrow = swap && swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
|
|
338
|
+
const order = swap && swap.order && typeof swap.order === "object" ? swap.order : {};
|
|
339
|
+
const quote = swap && swap.quote && typeof swap.quote === "object" ? swap.quote : {};
|
|
340
|
+
return {
|
|
341
|
+
salt: pendingSalt(escrow.salt ?? (swap && swap.recoverySalt)),
|
|
342
|
+
chainId: Number(order.chainId ?? quote.chainId ?? (swap && swap.chainId) ?? escrow.chainId),
|
|
343
|
+
factory: pendingAddress(order.factory ?? quote.factory ?? (swap && swap.factory) ?? escrow.factory),
|
|
344
|
+
escrow: pendingAddress(escrow.address ?? (swap && swap.predictedEscrow)),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// THE PENDING ROW CAN BE FOUND WITHOUT ITS ESCROW. A reloaded retry has the salt, chain and factory, but it has
|
|
349
|
+
// no request escrow; the address must be predicted from the signed quote before the row can prove it is the same
|
|
350
|
+
// order. This base match only selects a row that *might* be resumed; it never authorises a send.
|
|
351
|
+
function samePendingBase(swap, identity = {}) {
|
|
352
|
+
if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
|
|
353
|
+
const recorded = pendingFundingIdentity(swap);
|
|
354
|
+
const wanted = {
|
|
355
|
+
salt: pendingSalt(identity.salt),
|
|
356
|
+
chainId: Number(identity.chainId),
|
|
357
|
+
factory: pendingAddress(identity.factory),
|
|
358
|
+
};
|
|
359
|
+
if (!wanted.salt || !wanted.factory || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
|
|
360
|
+
// Records written before the identity gained chain/factory still have the salt. They may be matched on what they
|
|
361
|
+
// have, but the caller still has to name the same predicted address; a partial record is never a free pass.
|
|
362
|
+
if (recorded.salt !== wanted.salt) return false;
|
|
363
|
+
if (recorded.factory && recorded.factory !== wanted.factory) return false;
|
|
364
|
+
if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function samePendingFunding(swap, identity = {}) {
|
|
328
369
|
if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
|
|
329
|
-
const
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
370
|
+
const recorded = pendingFundingIdentity(swap);
|
|
371
|
+
const wanted = {
|
|
372
|
+
salt: pendingSalt(identity.salt),
|
|
373
|
+
chainId: Number(identity.chainId),
|
|
374
|
+
factory: pendingAddress(identity.factory),
|
|
375
|
+
escrow: pendingAddress(identity.escrow),
|
|
376
|
+
};
|
|
377
|
+
if (!wanted.salt || !wanted.factory || !wanted.escrow || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
|
|
378
|
+
if (recorded.salt !== wanted.salt || recorded.escrow !== wanted.escrow) return false;
|
|
379
|
+
// A RECORD WRITTEN BEFORE THE IDENTITY FIELDS STILL HAS ONE OPINION: its salt and its escrow address. Missing
|
|
380
|
+
// chain/factory fields are wildcards only for that old shape; a record that carries them must match them exactly.
|
|
381
|
+
if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
|
|
382
|
+
if (recorded.factory && recorded.factory !== wanted.factory) return false;
|
|
383
|
+
return true;
|
|
336
384
|
}
|
|
337
385
|
|
|
338
386
|
/**
|
|
339
387
|
* WHAT A PENDING RECORD MEANS FOR THIS START.
|
|
340
388
|
* `salt-required` is the expensive branch made loud: a caller that knows only the nonce of a pending record cannot
|
|
341
|
-
* prove it is the same order, and falling through would build a second deposit. The caller must bring the
|
|
342
|
-
*
|
|
389
|
+
* prove it is the same order, and falling through would build a second deposit. The caller must bring the full
|
|
390
|
+
* identity (salt, chain, factory, predicted escrow), not guess.
|
|
343
391
|
*/
|
|
344
|
-
export function pendingFundingVerdict(swap,
|
|
392
|
+
export function pendingFundingVerdict(swap, identity = {}) {
|
|
345
393
|
const pending = Boolean(swap && (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true)));
|
|
346
394
|
if (!pending) return "not-pending";
|
|
347
|
-
const
|
|
348
|
-
const
|
|
349
|
-
if (
|
|
350
|
-
|
|
395
|
+
const salt = pendingSalt(identity.salt);
|
|
396
|
+
const quoteId = String(identity.quoteId === undefined || identity.quoteId === null ? "" : identity.quoteId);
|
|
397
|
+
if (!salt) {
|
|
398
|
+
// THE QUOTE ID CAN SELECT THE RECORD, BUT IT CANNOT PROVE THE ORDER. Only a record that the caller named by the
|
|
399
|
+
// same quote id is this branch; an unrelated pending record must not block a new start.
|
|
400
|
+
return !quoteId || String(swap.orderQuoteId || "") === quoteId ? "salt-required" : "different";
|
|
401
|
+
}
|
|
402
|
+
return samePendingFunding(swap, identity) ? "resume" : "different";
|
|
351
403
|
}
|
|
352
404
|
|
|
353
405
|
// THE RECORD OF A SALE, FOUND BY ITS ESCROW. `sellWatch` is called from a reloaded page with the address in hand,
|
|
@@ -364,7 +416,7 @@ function swapByEscrow(store, escrow) {
|
|
|
364
416
|
return null;
|
|
365
417
|
}
|
|
366
418
|
|
|
367
|
-
export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, now = null, evmBlock = null, store = engine.store,
|
|
419
|
+
export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, fetchImpl = null, now = null, sleep = null, evmBlock = null, store = engine.store,
|
|
368
420
|
// THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
|
|
369
421
|
// no server step and no route table to consult.
|
|
370
422
|
config = null,
|
|
@@ -382,6 +434,43 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
382
434
|
// substitute your own. Otherwise the lock step could not be checked beyond predicting the address - and "the address
|
|
383
435
|
// from the receipt" would remain an argument on trust, not a verified property.
|
|
384
436
|
const reader = typeof call === "function" ? call : engine.evm.readContract;
|
|
437
|
+
// A RELOADED RETRY DOES NOT CARRY THE ESCROW. It still carries the signed order quote and the order terms, so the
|
|
438
|
+
// same factory predict() the send would use can name the address before the pending row is compared. A missing
|
|
439
|
+
// quote or a failed read is a refusal by name, never permission to send a second deposit.
|
|
440
|
+
const predictedEscrowForRetry = async (request) => {
|
|
441
|
+
const quote = request && request.orderQuote;
|
|
442
|
+
const order = request && request.order;
|
|
443
|
+
if (!quote || typeof quote !== "object" || !quote.signature) return null;
|
|
444
|
+
const factory = (order && order.factory) || quote.factory;
|
|
445
|
+
if (!factory) return null;
|
|
446
|
+
const lockerHalf = {
|
|
447
|
+
commitHalfLocker: (order && order.commitHalfLocker) ?? quote.commitHalfLocker,
|
|
448
|
+
edPointLocker: (order && order.edPointLocker) ?? quote.edPointLocker,
|
|
449
|
+
edViewPointLocker: (order && order.edViewPointLocker) ?? quote.edViewPointLocker,
|
|
450
|
+
};
|
|
451
|
+
if (!lockerHalf.commitHalfLocker || !lockerHalf.edPointLocker || !lockerHalf.edViewPointLocker) return null;
|
|
452
|
+
try {
|
|
453
|
+
return await predictEscrow({ quote, order, call: reader });
|
|
454
|
+
} catch (error) {
|
|
455
|
+
// A RETRY MUST NOT REPORT A CHAIN READ AS A MISSING ARGUMENT. The caller already brought the signed quote;
|
|
456
|
+
// "bring an escrow" cannot fix a factory that did not answer. A coded refusal keeps its own identity; a bare
|
|
457
|
+
// transport/decode failure becomes the factory check that could not be made.
|
|
458
|
+
if (error instanceof SdkError) throw error;
|
|
459
|
+
throw new SdkError("quote-factory-unchecked", { step: "factory", why: "predict-failed" });
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
// THE INSTANCE TRANSPORT IS THE DEFAULT, NOT BACKGROUND MAGIC. A per-call `fetch` still wins; otherwise every
|
|
463
|
+
// network read made by this client (height probes, relay quote/claim, witness verification) uses `fetchImpl`.
|
|
464
|
+
const withDefaultFetch = (request) => (fetchImpl && request && typeof request === "object"
|
|
465
|
+
&& typeof request.fetch !== "function" ? { ...request, fetch: fetchImpl } : request);
|
|
466
|
+
// THE SLOT CLOCK IS A SEAM. A real caller uses wall time and a timer; a check can advance both, so a 15-30 s
|
|
467
|
+
// slot is exercised without making the suite wait for it.
|
|
468
|
+
const clockMs = () => {
|
|
469
|
+
const value = typeof now === "function" ? Number(now()) : Date.now();
|
|
470
|
+
return Number.isFinite(value) ? value : Date.now();
|
|
471
|
+
};
|
|
472
|
+
const sleepFor = typeof sleep === "function" ? sleep
|
|
473
|
+
: (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
385
474
|
// ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
|
|
386
475
|
// wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
|
|
387
476
|
// timestamp is the chain's clock, not the device's.
|
|
@@ -422,7 +511,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
422
511
|
const listed = Array.isArray(request.xmrNodes) ? request.xmrNodes
|
|
423
512
|
: (config && typeof config.nodesFor === "function" ? config.nodesFor(moneroNetwork) : []);
|
|
424
513
|
return startHeightFromNodes({ nodes: listed, network: moneroNetwork,
|
|
425
|
-
fetchImpl: request.fetchImpl || (typeof fetch === "function" ? fetch : null) });
|
|
514
|
+
fetchImpl: request.fetchImpl || fetchImpl || (typeof fetch === "function" ? fetch : null) });
|
|
426
515
|
}
|
|
427
516
|
const records = () => {
|
|
428
517
|
const state = store.loadState();
|
|
@@ -432,12 +521,14 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
432
521
|
// A START THAT ENDED WITH A SENT TRANSACTION AND NO RECEIPT IS RESUMED, NOT RESENT. The transaction hash and the
|
|
433
522
|
// predicted escrow are kept on the record; a retry of the same quote reads that receipt instead of building a
|
|
434
523
|
// second side and sending a second deposit.
|
|
435
|
-
const pendingFundingOf = (
|
|
436
|
-
const
|
|
437
|
-
const
|
|
438
|
-
|
|
524
|
+
const pendingFundingOf = (identity) => {
|
|
525
|
+
const salt = pendingSalt(identity && identity.salt);
|
|
526
|
+
const quoteId = String(identity && identity.quoteId !== undefined && identity.quoteId !== null ? identity.quoteId : "");
|
|
527
|
+
// WITHOUT EITHER HANDLE NOTHING CAN SELECT A RECORD. With a quote id the loop below can still name the record and
|
|
528
|
+
// refuse it as salt-required instead of silently starting a second deposit.
|
|
529
|
+
if (!salt && !quoteId) return null;
|
|
439
530
|
for (const swap of records()) {
|
|
440
|
-
const verdict = pendingFundingVerdict(swap,
|
|
531
|
+
const verdict = pendingFundingVerdict(swap, identity);
|
|
441
532
|
if (verdict === "salt-required") {
|
|
442
533
|
throw new SdkError("bad-input", { field: "recoverySalt", why: "required-for-pending-funding" });
|
|
443
534
|
}
|
|
@@ -701,13 +792,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
701
792
|
|
|
702
793
|
// THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
|
|
703
794
|
// want to run both itself. The watch uses exactly these, so there is one decision, not two.
|
|
704
|
-
verifyArrival: (request) => xmrArrival.verifyArrival(request),
|
|
795
|
+
verifyArrival: (request) => xmrArrival.verifyArrival(withDefaultFetch(request)),
|
|
705
796
|
/**
|
|
706
797
|
* SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
|
|
707
798
|
* slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
|
|
708
799
|
* `ready` or refunds. It exists so the protocol can be exercised before an independent operator serves it.
|
|
709
800
|
*/
|
|
710
|
-
verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(request),
|
|
801
|
+
verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(withDefaultFetch(request)),
|
|
711
802
|
assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
|
|
712
803
|
|
|
713
804
|
/**
|
|
@@ -731,7 +822,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
731
822
|
* arrival check and the real refund.
|
|
732
823
|
*/
|
|
733
824
|
async refundIfXmrMissing(request = {}, deps = {}) {
|
|
734
|
-
const verify = typeof deps.verify === "function" ? deps.verify
|
|
825
|
+
const verify = typeof deps.verify === "function" ? deps.verify
|
|
826
|
+
: (request) => xmrArrival.verifyArrival(withDefaultFetch(request));
|
|
735
827
|
const refund = typeof deps.refund === "function" ? deps.refund : actions.refund;
|
|
736
828
|
const nowOf = typeof deps.now === "function" ? deps.now : () => Math.floor(Date.now() / 1000);
|
|
737
829
|
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
@@ -836,10 +928,60 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
836
928
|
|
|
837
929
|
// RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
|
|
838
930
|
// reusing its hash is the only way to learn the escrow without a second payment.
|
|
839
|
-
const
|
|
840
|
-
const
|
|
931
|
+
const explicitSalt = request.recoverySalt;
|
|
932
|
+
const rawSaltForResume = request.recoverySalt || (request.order && request.order.salt) ||
|
|
841
933
|
(request.orderQuote && request.orderQuote.salt) || null;
|
|
842
|
-
|
|
934
|
+
// THE SALT THAT MATCHES THE PENDING ROW IS THE CANONICAL ONE. A caller may pass a number or a bigint
|
|
935
|
+
// (`StartRequest.recoverySalt` allows all three); the record holds hex, so the raw value would miss the row
|
|
936
|
+
// after a reload and start a second deposit. Canonicalise once, before the identity lookup.
|
|
937
|
+
let saltForResume = null;
|
|
938
|
+
try {
|
|
939
|
+
saltForResume = rawSaltForResume === null || rawSaltForResume === undefined || rawSaltForResume === ""
|
|
940
|
+
? null : recoverySaltOf(rawSaltForResume);
|
|
941
|
+
} catch {
|
|
942
|
+
// AN INVALID SALT THE CALLER NAMED IS A REFUSAL, NOT "NO SALT". Falling through to the salt-less path
|
|
943
|
+
// would hide a malformed input behind a different diagnosis; an absent salt is the only case that may.
|
|
944
|
+
if (explicitSalt !== undefined && explicitSalt !== null && String(explicitSalt).trim() !== "") {
|
|
945
|
+
throw new SdkError("bad-input", { field: "recoverySalt", why: "unreadable" });
|
|
946
|
+
}
|
|
947
|
+
saltForResume = null;
|
|
948
|
+
}
|
|
949
|
+
const resumeIdentity = {
|
|
950
|
+
salt: saltForResume,
|
|
951
|
+
// THE QUOTE ID IS ONLY A SELECTOR. It lets a salt-less retry name the pending row and be refused loudly, but
|
|
952
|
+
// it never replaces the salt/chain/factory/escrow proof below.
|
|
953
|
+
quoteId: (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null,
|
|
954
|
+
chainId: (request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)
|
|
955
|
+
?? (request.quote && request.quote.chainId),
|
|
956
|
+
factory: (request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)
|
|
957
|
+
?? (request.quote && request.quote.factory),
|
|
958
|
+
escrow: request.escrow || request.predictedEscrow || (request.quote && request.quote.escrow)
|
|
959
|
+
|| (request.orderQuote && request.orderQuote.escrow) || null,
|
|
960
|
+
};
|
|
961
|
+
// A RELOADED RETRY HAS NO ESCROW FIELD. Find the pending row by the part it does have, then let the factory
|
|
962
|
+
// predict the address from the same signed terms the send uses. If that address cannot be named, the retry is
|
|
963
|
+
// refused by name; it must not fall through to a new deposit.
|
|
964
|
+
let pendingRecord = null;
|
|
965
|
+
if (records().some((swap) => samePendingBase(swap, resumeIdentity))) {
|
|
966
|
+
const predicted = await predictedEscrowForRetry(request);
|
|
967
|
+
if (!predicted) {
|
|
968
|
+
throw new SdkError("bad-input", { field: "escrow", why: "required-for-pending-funding" });
|
|
969
|
+
}
|
|
970
|
+
const named = pendingAddress(resumeIdentity.escrow);
|
|
971
|
+
if (resumeIdentity.escrow && !named) {
|
|
972
|
+
throw new SdkError("bad-input", { field: "escrow", why: "unreadable" });
|
|
973
|
+
}
|
|
974
|
+
if (named && named !== pendingAddress(predicted)) {
|
|
975
|
+
throw new SdkError("bad-input", { field: "escrow", why: "escrow-mismatch" });
|
|
976
|
+
}
|
|
977
|
+
resumeIdentity.escrow = predicted;
|
|
978
|
+
pendingRecord = pendingFundingOf(resumeIdentity);
|
|
979
|
+
if (!pendingRecord) {
|
|
980
|
+
throw new SdkError("bad-input", { field: "escrow", why: "pending-funding-unresolved" });
|
|
981
|
+
}
|
|
982
|
+
} else {
|
|
983
|
+
pendingRecord = pendingFundingOf(resumeIdentity);
|
|
984
|
+
}
|
|
843
985
|
if (pendingRecord) {
|
|
844
986
|
const resumed = await resumePendingFunding(pendingRecord, request);
|
|
845
987
|
if (resumed) return resumed;
|
|
@@ -1094,8 +1236,20 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1094
1236
|
// THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
|
|
1095
1237
|
const nowMs = typeof now === "function" ? Number(now()) : Date.now();
|
|
1096
1238
|
const nowSec = Math.floor(nowMs / 1000);
|
|
1097
|
-
|
|
1098
|
-
|
|
1239
|
+
// THE PREPARATION WAS ALREADY PAID FOR AT THE ANSWER. This check runs after the proof, the record and the
|
|
1240
|
+
// chain reads; requiring START_PREP_SEC again would refuse a quote that the answer accepted and spent those
|
|
1241
|
+
// seconds on. Only the next-block margin remains between here and the send.
|
|
1242
|
+
const life = quoteLifeVerdict({ validUntil: until, nowSec, side: "ask", prepSec: 0 });
|
|
1243
|
+
if (!life.ok) {
|
|
1244
|
+
throw new SdkError("quote-expired", {
|
|
1245
|
+
validUntil: Number.isFinite(until) ? until : null,
|
|
1246
|
+
now: Number.isFinite(nowSec) ? nowSec : null,
|
|
1247
|
+
remainingSec: life.remainingSec,
|
|
1248
|
+
marginSec: life.marginSec,
|
|
1249
|
+
prepSec: life.prepSec,
|
|
1250
|
+
confirmBySec: life.confirmBySec,
|
|
1251
|
+
step: "lock",
|
|
1252
|
+
});
|
|
1099
1253
|
}
|
|
1100
1254
|
}
|
|
1101
1255
|
lockRequest.quote = request.orderQuote || null;
|
|
@@ -1200,17 +1354,21 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1200
1354
|
const wantExpect = request.expect !== undefined && request.expect !== null;
|
|
1201
1355
|
const wantWallet = request.wallet !== undefined && request.wallet !== null;
|
|
1202
1356
|
if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
|
|
1203
|
-
|
|
1204
|
-
|
|
1357
|
+
// THE RECORD IS READ ONCE. It supplies the escrow for the auto ready-mark and the joint Monero address for
|
|
1358
|
+
// the result; `request.address` was never part of the public watch request.
|
|
1359
|
+
const record = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
|
|
1360
|
+
const storedSwap = record;
|
|
1361
|
+
const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
|
|
1362
|
+
if (wantExpect && !escrowAddress) throw new SdkError("bad-input", { field: "escrow" });
|
|
1205
1363
|
const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
|
|
1206
1364
|
const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
|
|
1207
1365
|
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
|
|
1208
1366
|
// THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
|
|
1209
1367
|
const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
|
|
1210
1368
|
? Math.trunc(Number(request.minConfirmations)) : limitOf("xmrConfirmations", 10);
|
|
1211
|
-
// THE CLIENT-SIDE CHECK IS
|
|
1212
|
-
//
|
|
1213
|
-
//
|
|
1369
|
+
// THE CLIENT-SIDE CHECK IS THE WATCH: it needs the joint address, the joint view secret and the joint spend
|
|
1370
|
+
// public key - all of which the client has and the backend no longer needs. Without them the wait is refused
|
|
1371
|
+
// by name (`bad-input`/`verify`); the retired service answer is not a fallback.
|
|
1214
1372
|
const verifyRequest = request.verify && typeof request.verify === "object"
|
|
1215
1373
|
? { ...request.verify,
|
|
1216
1374
|
nodes: Array.isArray(request.verify.nodes) ? request.verify.nodes
|
|
@@ -1233,6 +1391,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1233
1391
|
// the spend public key. Without them there is nothing to wait on: a named refusal, not a request to the
|
|
1234
1392
|
// page's own origin and not a fallback to a retired backend.
|
|
1235
1393
|
if (!verifyRequest) throw new SdkError("bad-input", { field: "verify", why: "required" });
|
|
1394
|
+
// THE JOINT MONERO ADDRESS IS THE ONE THE CLIENT CHECKS, NOT THE ESCROW. `verify.address` is the joint address;
|
|
1395
|
+
// the record's `moneroAddress` is the same value after a reload. The EVM escrow never leaves this method as
|
|
1396
|
+
// the XMR address, and it is the only address the auto ready-mark may receive.
|
|
1397
|
+
const moneroAddress = typeof verifyRequest.address === "string" && verifyRequest.address
|
|
1398
|
+
? verifyRequest.address
|
|
1399
|
+
: (record && record.escrow && record.escrow.moneroAddress) || null;
|
|
1400
|
+
if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
|
|
1236
1401
|
const started = Date.now();
|
|
1237
1402
|
// --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
|
|
1238
1403
|
// A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
|
|
@@ -1247,9 +1412,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1247
1412
|
// A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
|
|
1248
1413
|
// durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
|
|
1249
1414
|
// must not start failing where it did not before.
|
|
1250
|
-
let record = null;
|
|
1251
|
-
try { record = engine.swap.getSwap(id, store); } catch { record = null; }
|
|
1252
|
-
const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
|
|
1253
1415
|
// FROM THE ESCROW'S BIRTH HEIGHT when the record knows it: the event cannot be older than the funding, and
|
|
1254
1416
|
// walking the whole chain every tick is a cost with no answer behind it.
|
|
1255
1417
|
const fromBlock = blockBoundaryOf(record && record.escrow
|
|
@@ -1298,7 +1460,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1298
1460
|
let last = null;
|
|
1299
1461
|
for (;;) {
|
|
1300
1462
|
await readDeclineLogs();
|
|
1301
|
-
last = { address:
|
|
1463
|
+
last = { address: moneroAddress, expectedXmr: request.expectedXmr ?? null, status: null };
|
|
1302
1464
|
// THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
|
|
1303
1465
|
// to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
|
|
1304
1466
|
const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
|
|
@@ -1311,7 +1473,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1311
1473
|
// holds the view key), so it is not consulted when the client verifies. A disagreement or locked money
|
|
1312
1474
|
// throws its own code above and closes the button; one operator / few confirmations name a WAITING state.
|
|
1313
1475
|
if (verifyRequest) {
|
|
1314
|
-
const verdict = await xmrArrival.verifyArrival({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) });
|
|
1476
|
+
const verdict = await xmrArrival.verifyArrival(withDefaultFetch({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) }));
|
|
1315
1477
|
last.verify = verdict;
|
|
1316
1478
|
if (!verdict.seen) {
|
|
1317
1479
|
if (Date.now() - started >= timeoutMs) {
|
|
@@ -1328,7 +1490,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1328
1490
|
source: "client" };
|
|
1329
1491
|
if (wantExpect && wantWallet) {
|
|
1330
1492
|
verified.marked = await actions.markReady(
|
|
1331
|
-
{ escrow:
|
|
1493
|
+
{ escrow: escrowAddress, expect: request.expect, onStep: request.onStep }, request.wallet);
|
|
1332
1494
|
} else {
|
|
1333
1495
|
verified.next = "mark-ready";
|
|
1334
1496
|
}
|
|
@@ -1339,8 +1501,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1339
1501
|
|
|
1340
1502
|
/**
|
|
1341
1503
|
* START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
|
|
1342
|
-
* the record keeps the one-time address, the escrow, our half, the
|
|
1343
|
-
*
|
|
1504
|
+
* the record keeps the one-time address, the escrow, our half, the order expectations and the relay origin, so a
|
|
1505
|
+
* reload can continue with `get` + `sellWatch` + `sellClaim`. The optional `claimSender` is a legacy
|
|
1506
|
+
* single-sender fallback; `claimViaRelay` takes the client's ordered list at claim time. This method sends nothing.
|
|
1344
1507
|
*/
|
|
1345
1508
|
async startSell(request) {
|
|
1346
1509
|
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
@@ -1377,12 +1540,41 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1377
1540
|
|| String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
|
|
1378
1541
|
const requestedSender = request.claimSender === undefined || request.claimSender === null
|
|
1379
1542
|
|| String(request.claimSender).trim() === "" ? null : addressTextOf(request.claimSender, "claimSender");
|
|
1543
|
+
const requestedList = request.claimSenders === undefined || request.claimSenders === null
|
|
1544
|
+
? null : request.claimSenders;
|
|
1545
|
+
if (requestedList !== null && !Array.isArray(requestedList)) {
|
|
1546
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
|
|
1547
|
+
}
|
|
1548
|
+
if (requestedList && requestedList.length === 0) {
|
|
1549
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1550
|
+
}
|
|
1551
|
+
if (requestedList && requestedSender) {
|
|
1552
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
|
|
1553
|
+
}
|
|
1380
1554
|
if (requestedSender && requestedSender === dealMaker) {
|
|
1381
1555
|
throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
|
|
1382
1556
|
}
|
|
1383
1557
|
if (requestedSender && quoteKeyOwner && requestedSender === quoteKeyOwner) {
|
|
1384
1558
|
throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
|
|
1385
1559
|
}
|
|
1560
|
+
const offerSender = offer.claimSender === undefined || offer.claimSender === null
|
|
1561
|
+
|| String(offer.claimSender).trim() === "" ? null : addressTextOf(offer.claimSender, "offer.claimSender");
|
|
1562
|
+
// THE STORED LIST IS BUILT HERE, ONCE. The relay's published claimSender is the default first sender; a caller
|
|
1563
|
+
// that brings its own ordered list owns the order. The scalar remains a one-element fallback for older callers.
|
|
1564
|
+
const explicitSenders = requestedList || (requestedSender ? [requestedSender] : null);
|
|
1565
|
+
const rawSenders = explicitSenders || (offerSender ? [offerSender] : []);
|
|
1566
|
+
const claimSenders = [];
|
|
1567
|
+
for (const raw of rawSenders) {
|
|
1568
|
+
if (raw === undefined || raw === null || String(raw).trim() === "") {
|
|
1569
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1570
|
+
}
|
|
1571
|
+
const sender = addressTextOf(raw, "claimSenders");
|
|
1572
|
+
if (sender === dealMaker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
|
|
1573
|
+
if (quoteKeyOwner && sender === quoteKeyOwner) {
|
|
1574
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
|
|
1575
|
+
}
|
|
1576
|
+
if (!claimSenders.includes(sender)) claimSenders.push(sender);
|
|
1577
|
+
}
|
|
1386
1578
|
// THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
|
|
1387
1579
|
// one-time address and escrow; a second record would be a second promise about one deal.
|
|
1388
1580
|
const quoteId = quote.id || quote.nonce || null;
|
|
@@ -1399,9 +1591,21 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1399
1591
|
|| !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
|
|
1400
1592
|
throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
|
|
1401
1593
|
}
|
|
1402
|
-
const
|
|
1403
|
-
|
|
1404
|
-
|
|
1594
|
+
const storedList = Array.isArray(existing.claimSenders) ? existing.claimSenders : null;
|
|
1595
|
+
// THE OLD SCALAR IS NOT A PIN. A reload may name another sender or bring the ordered list at claim time; the
|
|
1596
|
+
// record keeps the latest list and its first sender for callers that still use the scalar. An offer-only
|
|
1597
|
+
// sender fills a record that has no list; it never replaces a list the client already chose.
|
|
1598
|
+
if (explicitSenders && claimSenders.length && (!storedList || storedList.length !== claimSenders.length
|
|
1599
|
+
|| storedList.some((value, index) => String(value).toLowerCase() !== claimSenders[index]))) {
|
|
1600
|
+
existing.claimSenders = claimSenders;
|
|
1601
|
+
existing.claimSender = claimSenders[0];
|
|
1602
|
+
try { engine.swap.saveSwap(existing, store); }
|
|
1603
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1604
|
+
} else if (!explicitSenders && !storedList && claimSenders.length) {
|
|
1605
|
+
existing.claimSenders = claimSenders;
|
|
1606
|
+
existing.claimSender = claimSenders[0];
|
|
1607
|
+
try { engine.swap.saveSwap(existing, store); }
|
|
1608
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1405
1609
|
}
|
|
1406
1610
|
// THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
|
|
1407
1611
|
// a resumed offer naming another origin is a different offer; one that now names the same origin fills a
|
|
@@ -1416,11 +1620,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1416
1620
|
try { engine.swap.saveSwap(existing, store); }
|
|
1417
1621
|
catch { throw new SdkError("storage-unavailable", { step: "save-relay" }); }
|
|
1418
1622
|
}
|
|
1419
|
-
if (requestedSender && !storedSender) {
|
|
1420
|
-
existing.claimSender = requestedSender;
|
|
1421
|
-
try { engine.swap.saveSwap(existing, store); }
|
|
1422
|
-
catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
|
|
1423
|
-
}
|
|
1424
1623
|
const storedWindow = existing.readyWindow || existing.sellWindow || null;
|
|
1425
1624
|
if (offerWindow && storedWindow) {
|
|
1426
1625
|
const a = readReadyWindow(storedWindow, { side: "bid", field: "readyWindow" });
|
|
@@ -1438,6 +1637,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1438
1637
|
xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
|
|
1439
1638
|
claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
|
|
1440
1639
|
claimSender: existing.claimSender || null,
|
|
1640
|
+
claimSenders: Array.isArray(existing.claimSenders) ? existing.claimSenders : [],
|
|
1441
1641
|
readyWindow: existing.readyWindow || existing.sellWindow || null,
|
|
1442
1642
|
resumed: true, next: "send-xmr" };
|
|
1443
1643
|
}
|
|
@@ -1507,9 +1707,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1507
1707
|
swap.orderQuote = offer.orderQuote || null;
|
|
1508
1708
|
swap.quote = quote;
|
|
1509
1709
|
swap.claimTip = quote.claimTip || null;
|
|
1510
|
-
// THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping
|
|
1710
|
+
// THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping the list means a reload cannot silently
|
|
1511
1711
|
// send the half to a different node than the one the client selected.
|
|
1512
|
-
if (
|
|
1712
|
+
if (claimSenders.length) {
|
|
1713
|
+
swap.claimSenders = claimSenders;
|
|
1714
|
+
swap.claimSender = claimSenders[0];
|
|
1715
|
+
}
|
|
1513
1716
|
swap.expect = {
|
|
1514
1717
|
chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
|
|
1515
1718
|
readyBy: order.readyBy, t1: order.t1, salt: order.salt,
|
|
@@ -1546,6 +1749,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1546
1749
|
return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
|
|
1547
1750
|
xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
|
|
1548
1751
|
claimSender: swap.claimSender || null,
|
|
1752
|
+
claimSenders: Array.isArray(swap.claimSenders) ? swap.claimSenders : [],
|
|
1549
1753
|
readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
|
|
1550
1754
|
},
|
|
1551
1755
|
|
|
@@ -1573,15 +1777,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1573
1777
|
* CLAIM THE ETH ON A SELL WITHOUT A WALLET.
|
|
1574
1778
|
*
|
|
1575
1779
|
* The seller holds XMR and no ETH, so the escrow pays the signed `claimTip` to whoever submits the claim.
|
|
1576
|
-
*
|
|
1577
|
-
* the
|
|
1578
|
-
*
|
|
1579
|
-
*
|
|
1580
|
-
*
|
|
1581
|
-
*
|
|
1582
|
-
* never name the deal's maker. `relayUrl` is only a restatement of the stored origin: a different one is refused
|
|
1583
|
-
* rather than obeyed. A vanished answer is `claim-unknown` (the claim may have been sent), never success; only a
|
|
1584
|
-
* real txid returns.
|
|
1780
|
+
* `claimSenders` is the client's ordered list: the relay's own sender first, then the listed makers. The SDK
|
|
1781
|
+
* sends the half to one sender at a time through `POST /v1/claims/{sender}/{escrow}`; a refusal moves on at once,
|
|
1782
|
+
* a txid or unknown answer is followed by reading the escrow for the rest of that sender's 15-30 s slot, and
|
|
1783
|
+
* only `claimed` on chain is success. An exhausted list returns `state: "claim-yourself"` with the time left
|
|
1784
|
+
* before `t1`. The deal's maker and its quote-key owner are refused before the half leaves the client. This
|
|
1785
|
+
* method never creates or uses a wallet and never signs a chain transaction; `sellClaim` remains that path.
|
|
1585
1786
|
*/
|
|
1586
1787
|
async claimViaRelay(request = {}) {
|
|
1587
1788
|
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
@@ -1617,35 +1818,47 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1617
1818
|
}
|
|
1618
1819
|
}
|
|
1619
1820
|
}
|
|
1821
|
+
const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
|
|
1822
|
+
|| String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
|
|
1620
1823
|
const storedSenderRaw = swap.claimSender === undefined || swap.claimSender === null
|
|
1621
1824
|
|| String(swap.claimSender).trim() === "" ? null : swap.claimSender;
|
|
1622
1825
|
const requestedSenderRaw = request.claimSender === undefined || request.claimSender === null
|
|
1623
1826
|
|| String(request.claimSender).trim() === "" ? null : request.claimSender;
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1827
|
+
// THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; the old scalar and the stored value are
|
|
1828
|
+
// only one-element fallbacks for callers written before the list existed. Neither is a pin: the next sender is
|
|
1829
|
+
// tried when this one refuses or its slot ends.
|
|
1830
|
+
if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
|
|
1831
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
|
|
1628
1832
|
}
|
|
1629
|
-
const
|
|
1630
|
-
if (
|
|
1631
|
-
|
|
1632
|
-
const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
|
|
1633
|
-
|| String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
|
|
1634
|
-
if (quoteKeyOwner && sender === quoteKeyOwner) {
|
|
1635
|
-
throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
|
|
1833
|
+
const explicitList = Array.isArray(request.claimSenders) ? request.claimSenders : null;
|
|
1834
|
+
if (explicitList && explicitList.length === 0) {
|
|
1835
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1636
1836
|
}
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
swap.claimSender = requestedSender;
|
|
1640
|
-
try { engine.swap.saveSwap(swap, store); }
|
|
1641
|
-
catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
|
|
1837
|
+
if (explicitList && requestedSenderRaw) {
|
|
1838
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
|
|
1642
1839
|
}
|
|
1840
|
+
const rawSenders = explicitList || (requestedSenderRaw ? [requestedSenderRaw] : null)
|
|
1841
|
+
|| (Array.isArray(swap.claimSenders) ? swap.claimSenders : null)
|
|
1842
|
+
|| (storedSenderRaw ? [storedSenderRaw] : []);
|
|
1843
|
+
if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
|
|
1844
|
+
const senders = [];
|
|
1845
|
+
for (const raw of rawSenders) {
|
|
1846
|
+
if (raw === undefined || raw === null || String(raw).trim() === "") {
|
|
1847
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1848
|
+
}
|
|
1849
|
+
const sender = addressTextOf(raw, "claimSenders");
|
|
1850
|
+
if (sender === maker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
|
|
1851
|
+
if (quoteKeyOwner && sender === quoteKeyOwner) {
|
|
1852
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
|
|
1853
|
+
}
|
|
1854
|
+
if (!senders.includes(sender)) senders.push(sender);
|
|
1855
|
+
}
|
|
1856
|
+
if (!senders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
|
|
1643
1857
|
if (escrowRecord.address === undefined || escrowRecord.address === null || escrowRecord.address === "") {
|
|
1644
1858
|
throw new SdkError("bad-input", { field: "escrow", why: "not-in-record" });
|
|
1645
1859
|
}
|
|
1646
1860
|
const escrow = addressTextOf(escrowRecord.address, "escrow");
|
|
1647
1861
|
const halfClaimer = halfTextOf(escrowRecord.half);
|
|
1648
|
-
|
|
1649
1862
|
// THE ORIGIN IS THE QUOTE'S, NOT THE CALLER'S. The record stores the relay that answered; a request may
|
|
1650
1863
|
// repeat it (with a trailing slash), but may not choose another one after the quote.
|
|
1651
1864
|
if (swap.relayUrl === undefined || swap.relayUrl === null || swap.relayUrl === "") {
|
|
@@ -1657,14 +1870,196 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1657
1870
|
throw new SdkError("bad-input", { field: "relayUrl", why: "foreign-relay" });
|
|
1658
1871
|
}
|
|
1659
1872
|
}
|
|
1873
|
+
// A LIST IS NOT A PIN. It is saved only as the fallback for a reload whose caller no longer has the relay's
|
|
1874
|
+
// answer; a later request that brings its own order ignores it.
|
|
1875
|
+
if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
|
|
1876
|
+
|| swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
|
|
1877
|
+
swap.claimSenders = senders;
|
|
1878
|
+
swap.claimSender = senders[0];
|
|
1879
|
+
try { engine.swap.saveSwap(swap, store); }
|
|
1880
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1881
|
+
}
|
|
1660
1882
|
|
|
1661
1883
|
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
|
|
1662
|
-
? Number(request.timeoutMs) : 20_000;
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1884
|
+
? Math.min(120_000, Number(request.timeoutMs)) : 20_000;
|
|
1885
|
+
// ONE SENDER AT A TIME, EACH WITH ITS OWN SLOT. Refusal moves on immediately; an accepted/unknown answer is
|
|
1886
|
+
// followed by reading the escrow until it says claimed or the slot ends. A txid alone is never success.
|
|
1887
|
+
const slotMs = Number.isFinite(Number(request.slotMs)) && Number(request.slotMs) > 0
|
|
1888
|
+
? Math.min(30_000, Math.max(15_000, Number(request.slotMs))) : 20_000;
|
|
1889
|
+
// A POLL UNDER 250 ms only burns chain reads, and a timeout above two minutes would hide a stuck sender
|
|
1890
|
+
// behind a wait the caller does not expect.
|
|
1891
|
+
const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
|
|
1892
|
+
? Math.min(slotMs, Math.max(250, Number(request.pollMs))) : 2_000;
|
|
1893
|
+
const readStatus = async () => {
|
|
1894
|
+
try { return await flow.orderStatus(escrow, { call: reader }); }
|
|
1895
|
+
catch (error) {
|
|
1896
|
+
// AN UNREAD ESCROW IS NOT AN OPEN ONE. The caller must not be told to claim a sale whose state we could
|
|
1897
|
+
// not read; the half may already have landed. This is the same unknown state as a lost relay answer.
|
|
1898
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "escrow-unread",
|
|
1899
|
+
detail: String((error && error.message) || error).slice(0, 160) });
|
|
1900
|
+
}
|
|
1901
|
+
};
|
|
1902
|
+
const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
|
|
1903
|
+
let t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
|
|
1904
|
+
const secondsLeft = () => (t1 === null ? null : Math.max(0, t1 - Math.floor(clockMs() / 1000)));
|
|
1905
|
+
// THE CLAIM WINDOW BELONGS TO THE CONTRACT, NOT TO THE RELAY. The relay can forward any half it is given, so
|
|
1906
|
+
// the client must refuse to hand it over before `readyBy` without the ready mark, after `t1`, and inside the
|
|
1907
|
+
// settlement margin when neither a sender nor the seller's own claim can still land. The check reads the
|
|
1908
|
+
// escrow's ready mark and both deadlines for EVERY sender, not once for the whole list: a slot can cross a
|
|
1909
|
+
// boundary while the previous sender is being polled.
|
|
1910
|
+
const CLAIM_MARGIN_SEC = 120;
|
|
1911
|
+
const SELLER_CLAIM_SEC = 60;
|
|
1912
|
+
const windowOf = async () => {
|
|
1913
|
+
let deadlines;
|
|
1914
|
+
try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
|
|
1915
|
+
catch { return { ok: false, reason: "unreadable" }; }
|
|
1916
|
+
const t1Sec = Number(deadlines.t1);
|
|
1917
|
+
const readyBySec = Number(deadlines.readyBy);
|
|
1918
|
+
const nowSec = Math.floor(clockMs() / 1000);
|
|
1919
|
+
if (![t1Sec, readyBySec, nowSec].every(Number.isSafeInteger)) {
|
|
1920
|
+
return { ok: false, reason: "unreadable" };
|
|
1921
|
+
}
|
|
1922
|
+
let marked;
|
|
1923
|
+
try {
|
|
1924
|
+
const raw = await reader({ to: escrow, data: engine.evm.encodeRead("ready") });
|
|
1925
|
+
marked = BigInt(String(raw || "").replace(/^0x/, "") || "0") !== 0n;
|
|
1926
|
+
} catch { return { ok: false, reason: "unreadable" }; }
|
|
1927
|
+
if (nowSec >= t1Sec) return { ok: false, reason: "window-closed" };
|
|
1928
|
+
// A SEND LANDS IN A LATER BLOCK. The last 120 s belong to the relay's settlement margin, and the seller
|
|
1929
|
+
// still needs a slot plus time for their own claim if the relay cannot land it.
|
|
1930
|
+
if (nowSec + CLAIM_MARGIN_SEC + Math.ceil(slotMs / 1000) + SELLER_CLAIM_SEC >= t1Sec) {
|
|
1931
|
+
return { ok: false, reason: "settlement-margin" };
|
|
1932
|
+
}
|
|
1933
|
+
if (nowSec < readyBySec && !marked) return { ok: false, reason: "not-ready" };
|
|
1934
|
+
return { ok: true, t1: t1Sec, readyBy: readyBySec, nowSec };
|
|
1935
|
+
};
|
|
1936
|
+
const windowResult = (reason, tried) => ({
|
|
1937
|
+
id, state: "claim-window", reason, provider: null, claimSender: null, escrow, relayUrl,
|
|
1938
|
+
txid: null, from: null, tipWei: tip.toString(), t1, secondsLeft: secondsLeft(), tried,
|
|
1666
1939
|
});
|
|
1667
|
-
|
|
1940
|
+
const STOP_ESCROW_CODES = new Set([
|
|
1941
|
+
"claim-not-ready", "claim-window-closed", "claim-settlement-margin",
|
|
1942
|
+
"claim-not-funded", "claim-already-closed", "claim-half-invalid",
|
|
1943
|
+
]);
|
|
1944
|
+
const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
|
|
1945
|
+
id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
|
|
1946
|
+
txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
|
|
1947
|
+
tipWei: (answer && answer.tipWei) || tip.toString(), tried,
|
|
1948
|
+
});
|
|
1949
|
+
// A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
|
|
1950
|
+
// the previous attempt; read the escrow before the first POST, and read it once more before returning
|
|
1951
|
+
// `claim-yourself`, so a late claim cannot be reported as "claim yourself".
|
|
1952
|
+
const initial = await readStatus();
|
|
1953
|
+
if (initial.isClaimed) return claimedByEscrow();
|
|
1954
|
+
if (!initial.isFunded) return windowResult("not-funded", []);
|
|
1955
|
+
let refunded = Boolean(initial.isRefunded);
|
|
1956
|
+
const tried = [];
|
|
1957
|
+
// A SENDER THAT MAY HAVE RECEIVED THE HALF IS NOT TRIED AGAIN AFTER A RELOAD. The record gets the sender
|
|
1958
|
+
// before the POST, so a crash or a lost answer leaves a durable trace. A refused sender may be skipped; an
|
|
1959
|
+
// attempt left in flight or unknown stops the list with claim-unknown, because the half may already be out.
|
|
1960
|
+
const priorAttempts = Array.isArray(swap.claimAttempts) ? swap.claimAttempts : [];
|
|
1961
|
+
const attempted = new Set(priorAttempts.map((entry) => String(entry && entry.sender || "").toLowerCase()));
|
|
1962
|
+
const pendingSenders = senders.filter((sender) => !attempted.has(String(sender).toLowerCase()));
|
|
1963
|
+
const priorTried = priorAttempts.map((entry) => ({
|
|
1964
|
+
sender: entry.sender, outcome: entry.outcome || "unknown", code: entry.code || null,
|
|
1965
|
+
params: entry.params || null, txid: entry.txid || null,
|
|
1966
|
+
}));
|
|
1967
|
+
if (priorAttempts.some((entry) => entry && (entry.outcome === "sending" || entry.outcome === "unknown"))) {
|
|
1968
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "previous-sender-unknown" });
|
|
1969
|
+
}
|
|
1970
|
+
if (!pendingSenders.length) {
|
|
1971
|
+
// THE RESUME PATH MUST NAME A REFUND LIKE THE FINAL PATH DOES. All senders may already be recorded as tried
|
|
1972
|
+
// when the escrow moves to refunded; `claim-yourself` would send the seller to `sellClaim` on a closed order.
|
|
1973
|
+
if (refunded) return windowResult("escrow-refunded", priorTried);
|
|
1974
|
+
return { id, state: "claim-yourself", reason: "senders-exhausted",
|
|
1975
|
+
provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
|
|
1976
|
+
t1, secondsLeft: secondsLeft(), tried: priorTried };
|
|
1977
|
+
}
|
|
1978
|
+
const persistAttempts = (entry, outcome, extra = {}) => {
|
|
1979
|
+
if (entry) Object.assign(entry, { outcome, ...extra });
|
|
1980
|
+
try { engine.swap.saveSwap(swap, store); }
|
|
1981
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-attempt" }); }
|
|
1982
|
+
};
|
|
1983
|
+
const beginAttempt = (sender) => {
|
|
1984
|
+
const entry = { sender, at: Math.floor(clockMs() / 1000), outcome: "sending" };
|
|
1985
|
+
swap.claimAttempts = [...(Array.isArray(swap.claimAttempts) ? swap.claimAttempts : []), entry];
|
|
1986
|
+
persistAttempts(entry, "sending");
|
|
1987
|
+
return entry;
|
|
1988
|
+
};
|
|
1989
|
+
const finishAttempt = (entry, outcome, extra = {}) => {
|
|
1990
|
+
try { persistAttempts(entry, outcome, extra); } catch { /* the chain answer is already known */ }
|
|
1991
|
+
};
|
|
1992
|
+
if (!refunded) for (const sender of pendingSenders) {
|
|
1993
|
+
const gate = await windowOf();
|
|
1994
|
+
if (!gate.ok) return windowResult(gate.reason, tried);
|
|
1995
|
+
if (gate.t1 !== null) t1 = gate.t1;
|
|
1996
|
+
const attempt = beginAttempt(sender);
|
|
1997
|
+
// THE SLOT STARTS WHEN THE SENDER IS ENTERED, NOT WHEN ITS POST RETURNS. A slow POST must not stretch the
|
|
1998
|
+
// 15-30 s slot into twice the advertised time.
|
|
1999
|
+
const slotStartedAt = clockMs();
|
|
2000
|
+
let answer = null;
|
|
2001
|
+
let failure = null;
|
|
2002
|
+
try {
|
|
2003
|
+
answer = await postRelayClaim({
|
|
2004
|
+
relayUrl, provider: sender, escrow, halfClaimer, expectedTipWei: tip,
|
|
2005
|
+
fetchImpl: request.fetchImpl || fetchImpl || null, timeoutMs,
|
|
2006
|
+
});
|
|
2007
|
+
} catch (error) {
|
|
2008
|
+
failure = error;
|
|
2009
|
+
}
|
|
2010
|
+
// A REFUSAL IS THE SENDER'S ANSWER, NOT A CLAIM IN FLIGHT. Move to the next one at once; only an unknown
|
|
2011
|
+
// outcome (or a txid, which is not yet a claim on chain) deserves the slot. An escrow-state refusal is
|
|
2012
|
+
// different: it says the order itself is closed, so trying another sender would publish the half for no
|
|
2013
|
+
// reason. Read the escrow and stop.
|
|
2014
|
+
if (failure && failure.code !== "claim-unknown") {
|
|
2015
|
+
const refused = { sender, outcome: "refused", code: failure.code || "unknown",
|
|
2016
|
+
params: failure.params || null };
|
|
2017
|
+
tried.push(refused);
|
|
2018
|
+
finishAttempt(attempt, "refused", { code: refused.code, params: refused.params });
|
|
2019
|
+
if (STOP_ESCROW_CODES.has(String((failure.params && failure.params.code) || ""))) {
|
|
2020
|
+
const stopped = await readStatus();
|
|
2021
|
+
if (stopped.isClaimed) return claimedByEscrow(sender, null, tried);
|
|
2022
|
+
if (stopped.isRefunded) return windowResult("escrow-refunded", tried);
|
|
2023
|
+
return windowResult("escrow-refused", tried);
|
|
2024
|
+
}
|
|
2025
|
+
continue;
|
|
2026
|
+
}
|
|
2027
|
+
const slotEnd = slotStartedAt + slotMs;
|
|
2028
|
+
for (;;) {
|
|
2029
|
+
const status = await readStatus();
|
|
2030
|
+
if (status && status.isClaimed) {
|
|
2031
|
+
swap.claimSender = sender;
|
|
2032
|
+
finishAttempt(attempt, "claimed", { txid: answer ? answer.txid : null });
|
|
2033
|
+
try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
|
|
2034
|
+
return claimedByEscrow(sender, answer, tried);
|
|
2035
|
+
}
|
|
2036
|
+
if (status && status.isRefunded) { refunded = true; break; }
|
|
2037
|
+
const left = slotEnd - clockMs();
|
|
2038
|
+
if (left <= 0) break;
|
|
2039
|
+
await sleepFor(Math.min(pollMs, left));
|
|
2040
|
+
}
|
|
2041
|
+
const ended = { sender, outcome: failure ? "unknown" : "unconfirmed",
|
|
2042
|
+
txid: answer ? answer.txid : null, code: failure ? failure.code : null };
|
|
2043
|
+
tried.push(ended);
|
|
2044
|
+
finishAttempt(attempt, ended.outcome, { txid: ended.txid, code: ended.code });
|
|
2045
|
+
if (refunded) break;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
// THE LAST LOOK BEFORE THE FALLBACK. A claim can land after the last slot ended or while a later sender is
|
|
2049
|
+
// refusing; the seller must not be sent to `sellClaim` on an escrow that is already closed as claimed.
|
|
2050
|
+
const finalStatus = await readStatus();
|
|
2051
|
+
if (finalStatus.isClaimed) {
|
|
2052
|
+
try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
|
|
2053
|
+
return claimedByEscrow(null, null, tried);
|
|
2054
|
+
}
|
|
2055
|
+
if (finalStatus.isRefunded) refunded = true;
|
|
2056
|
+
if (!finalStatus.isFunded) return windowResult("not-funded", tried);
|
|
2057
|
+
if (refunded) return windowResult("escrow-refunded", tried);
|
|
2058
|
+
const finalGate = await windowOf();
|
|
2059
|
+
if (!finalGate.ok) return windowResult(finalGate.reason, tried);
|
|
2060
|
+
return { id, state: "claim-yourself", reason: "senders-exhausted",
|
|
2061
|
+
provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
|
|
2062
|
+
t1, secondsLeft: secondsLeft(), tried };
|
|
1668
2063
|
},
|
|
1669
2064
|
|
|
1670
2065
|
/**
|
|
@@ -1731,13 +2126,23 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1731
2126
|
ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
|
|
1732
2127
|
}
|
|
1733
2128
|
}
|
|
1734
|
-
// AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK
|
|
1735
|
-
//
|
|
1736
|
-
|
|
2129
|
+
// AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK - BUT ONLY BEFORE t1. Without a
|
|
2130
|
+
// readable t1 the SDK cannot promise a claim window, so it keeps waiting instead of opening one on a
|
|
2131
|
+
// guess. The last 60 s are closed because a claim lands in a later block.
|
|
2132
|
+
if (lastStatus && lastStatus.isFunded && deadlines) {
|
|
2133
|
+
const readyBy = Number(deadlines.readyBy);
|
|
2134
|
+
const t1 = Number(deadlines.t1);
|
|
1737
2135
|
const at = nowSec();
|
|
1738
|
-
if (at !== null && at >=
|
|
2136
|
+
if (Number.isSafeInteger(readyBy) && Number.isSafeInteger(t1) && at !== null && at >= readyBy) {
|
|
2137
|
+
const secondsLeft = Math.max(0, t1 - at);
|
|
2138
|
+
if (at + 60 >= t1) {
|
|
2139
|
+
return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
|
|
2140
|
+
ready: false, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
|
|
2141
|
+
t1, secondsLeft };
|
|
2142
|
+
}
|
|
1739
2143
|
return { escrow, state: "claim-open", funded: true, claimed: false, refunded: false,
|
|
1740
|
-
ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started
|
|
2144
|
+
ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
|
|
2145
|
+
t1, secondsLeft };
|
|
1741
2146
|
}
|
|
1742
2147
|
}
|
|
1743
2148
|
if (Date.now() - started >= timeoutMs) {
|