@ninsei-labs/sdk 0.59.0 → 0.61.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 +32 -0
- package/README.md +40 -8
- package/assets/vendors/MANIFEST.json +1 -1
- package/assets/vendors/sdk/sdk-browser.js +4 -4
- package/engine/atomic/dleq2.js +0 -4
- package/engine/atomic/halfenc.js +0 -4
- package/engine/atomic/halves.js +0 -4
- package/engine/atomic/order.js +0 -4
- package/engine/atomic/orderContext.js +0 -4
- package/engine/atomic/orderHalfCommit.js +0 -4
- package/engine/core/chainSource.js +0 -4
- package/engine/core/clock.js +0 -4
- package/engine/core/config.js +0 -4
- package/engine/core/deployments.generated.js +1 -17
- package/engine/core/finality.js +0 -4
- package/engine/core/format.js +0 -4
- package/engine/core/preSignGuards.js +0 -4
- package/engine/core/rfqSource.js +0 -3
- package/engine/core/sellWindow.js +0 -4
- package/engine/core/store.js +0 -4
- package/engine/core/swap.js +0 -4
- package/engine/evm/amounts.js +0 -4
- package/engine/evm/asyncRoute.js +0 -4
- package/engine/evm/auth.js +0 -4
- package/engine/evm/claimGas.js +2 -6
- package/engine/evm/dex.js +0 -4
- package/engine/evm/escrow.js +0 -4
- package/engine/evm/factory.js +0 -4
- package/engine/evm/fees.js +0 -4
- package/engine/evm/funding.js +2 -5
- package/engine/evm/gasReserve.js +0 -4
- package/engine/evm/index.js +5 -9
- package/engine/evm/injected.js +0 -4
- package/engine/evm/permit.js +0 -4
- package/engine/evm/prices.js +0 -4
- package/engine/evm/session.js +0 -4
- package/engine/mock/chain.js +0 -4
- package/engine/monero/address.js +0 -3
- package/engine/monero/halvesSweep.js +0 -4
- package/engine/monero/node.js +0 -4
- package/engine/monero/swapKeys.js +0 -4
- package/engine/monero/unlock.js +2 -6
- package/engine/monero/wallet.js +0 -3
- package/engine/recovery/recoveryFile.js +0 -4
- package/engine/recovery/restore.js +0 -4
- package/engine/sdk/bridge.js +3 -7
- package/engine/ui/dom.js +0 -4
- package/engine/ui/walletModal.js +0 -4
- package/index.d.ts +89 -36
- package/package.json +3 -2
- package/src/engine.mjs +17 -26
- package/src/index.mjs +1 -1
- package/src/predictEscrow.mjs +25 -0
- package/src/public/recovery.d.ts +1 -1
- package/src/quotes.mjs +2 -5
- package/src/relayClaim.mjs +17 -3
- package/src/relayFirmClient.mjs +18 -0
- package/src/swap-flow.mjs +7 -10
- package/src/swaps.mjs +349 -76
- package/src/sweep.mjs +9 -2
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +61 -41
package/src/swaps.mjs
CHANGED
|
@@ -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";
|
|
@@ -449,10 +450,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
449
450
|
};
|
|
450
451
|
if (!lockerHalf.commitHalfLocker || !lockerHalf.edPointLocker || !lockerHalf.edViewPointLocker) return null;
|
|
451
452
|
try {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
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" });
|
|
456
460
|
}
|
|
457
461
|
};
|
|
458
462
|
// THE INSTANCE TRANSPORT IS THE DEFAULT, NOT BACKGROUND MAGIC. A per-call `fetch` still wins; otherwise every
|
|
@@ -467,6 +471,24 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
467
471
|
};
|
|
468
472
|
const sleepFor = typeof sleep === "function" ? sleep
|
|
469
473
|
: (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
474
|
+
// THE CLAIM WINDOW USES THE CHAIN CLOCK, NOT THE DEVICE CLOCK. `evmBlock` is the same block-read seam the
|
|
475
|
+
// sell-side gate uses; an explicitly injected `now` remains a test seam only when no chain seam is configured.
|
|
476
|
+
// Without either, a half-revealing send must refuse rather than silently use Date.now().
|
|
477
|
+
let observedNowSec = null;
|
|
478
|
+
const chainNowSec = async () => {
|
|
479
|
+
const snapshot = await chainSnapshot();
|
|
480
|
+
if (snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0) {
|
|
481
|
+
return Number(snapshot.timestamp);
|
|
482
|
+
}
|
|
483
|
+
// A CONFIGURED CHAIN SEAM THAT IS UNREADABLE IS A REFUSAL, NOT A DEVICE CLOCK. The explicit `now` seam is only
|
|
484
|
+
// for hosts that did not configure `evmBlock` at all (simulation and tests).
|
|
485
|
+
if (typeof evmBlock === "function") return null;
|
|
486
|
+
if (typeof now === "function") {
|
|
487
|
+
const value = Math.floor(clockMs() / 1000);
|
|
488
|
+
return Number.isSafeInteger(value) && value > 0 ? value : null;
|
|
489
|
+
}
|
|
490
|
+
return null;
|
|
491
|
+
};
|
|
470
492
|
// ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
|
|
471
493
|
// wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
|
|
472
494
|
// timestamp is the chain's clock, not the device's.
|
|
@@ -924,8 +946,24 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
924
946
|
|
|
925
947
|
// RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
|
|
926
948
|
// reusing its hash is the only way to learn the escrow without a second payment.
|
|
927
|
-
const
|
|
949
|
+
const explicitSalt = request.recoverySalt;
|
|
950
|
+
const rawSaltForResume = request.recoverySalt || (request.order && request.order.salt) ||
|
|
928
951
|
(request.orderQuote && request.orderQuote.salt) || null;
|
|
952
|
+
// THE SALT THAT MATCHES THE PENDING ROW IS THE CANONICAL ONE. A caller may pass a number or a bigint
|
|
953
|
+
// (`StartRequest.recoverySalt` allows all three); the record holds hex, so the raw value would miss the row
|
|
954
|
+
// after a reload and start a second deposit. Canonicalise once, before the identity lookup.
|
|
955
|
+
let saltForResume = null;
|
|
956
|
+
try {
|
|
957
|
+
saltForResume = rawSaltForResume === null || rawSaltForResume === undefined || rawSaltForResume === ""
|
|
958
|
+
? null : recoverySaltOf(rawSaltForResume);
|
|
959
|
+
} catch {
|
|
960
|
+
// AN INVALID SALT THE CALLER NAMED IS A REFUSAL, NOT "NO SALT". Falling through to the salt-less path
|
|
961
|
+
// would hide a malformed input behind a different diagnosis; an absent salt is the only case that may.
|
|
962
|
+
if (explicitSalt !== undefined && explicitSalt !== null && String(explicitSalt).trim() !== "") {
|
|
963
|
+
throw new SdkError("bad-input", { field: "recoverySalt", why: "unreadable" });
|
|
964
|
+
}
|
|
965
|
+
saltForResume = null;
|
|
966
|
+
}
|
|
929
967
|
const resumeIdentity = {
|
|
930
968
|
salt: saltForResume,
|
|
931
969
|
// THE QUOTE ID IS ONLY A SELECTOR. It lets a salt-less retry name the pending row and be refused loudly, but
|
|
@@ -1334,17 +1372,28 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1334
1372
|
const wantExpect = request.expect !== undefined && request.expect !== null;
|
|
1335
1373
|
const wantWallet = request.wallet !== undefined && request.wallet !== null;
|
|
1336
1374
|
if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
|
|
1337
|
-
|
|
1338
|
-
|
|
1375
|
+
// THE RECORD IS READ ONCE. It supplies the escrow for the auto ready-mark and the joint Monero address for
|
|
1376
|
+
// the result; `request.address` was never part of the public watch request.
|
|
1377
|
+
const record = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
|
|
1378
|
+
const storedSwap = record;
|
|
1379
|
+
const sameAddress = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase()
|
|
1380
|
+
=== String(b || "").replace(/^0x/, "").toLowerCase();
|
|
1381
|
+
const recordEscrow = record && record.escrow && record.escrow.address;
|
|
1382
|
+
if (request.escrow !== undefined && request.escrow !== null && String(request.escrow).trim()
|
|
1383
|
+
&& recordEscrow && !sameAddress(request.escrow, recordEscrow)) {
|
|
1384
|
+
throw new SdkError("bad-input", { field: "escrow", why: "record-mismatch" });
|
|
1385
|
+
}
|
|
1386
|
+
const escrowAddress = request.escrow || recordEscrow || null;
|
|
1387
|
+
if (wantExpect && !escrowAddress) throw new SdkError("bad-input", { field: "escrow" });
|
|
1339
1388
|
const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
|
|
1340
1389
|
const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
|
|
1341
1390
|
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
|
|
1342
1391
|
// THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
|
|
1343
1392
|
const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
|
|
1344
1393
|
? Math.trunc(Number(request.minConfirmations)) : limitOf("xmrConfirmations", 10);
|
|
1345
|
-
// THE CLIENT-SIDE CHECK IS
|
|
1346
|
-
//
|
|
1347
|
-
//
|
|
1394
|
+
// THE CLIENT-SIDE CHECK IS THE WATCH: it needs the joint address, the joint view secret and the joint spend
|
|
1395
|
+
// public key - all of which the client has and the backend no longer needs. Without them the wait is refused
|
|
1396
|
+
// by name (`bad-input`/`verify`); the retired service answer is not a fallback.
|
|
1348
1397
|
const verifyRequest = request.verify && typeof request.verify === "object"
|
|
1349
1398
|
? { ...request.verify,
|
|
1350
1399
|
nodes: Array.isArray(request.verify.nodes) ? request.verify.nodes
|
|
@@ -1367,6 +1416,17 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1367
1416
|
// the spend public key. Without them there is nothing to wait on: a named refusal, not a request to the
|
|
1368
1417
|
// page's own origin and not a fallback to a retired backend.
|
|
1369
1418
|
if (!verifyRequest) throw new SdkError("bad-input", { field: "verify", why: "required" });
|
|
1419
|
+
// THE JOINT MONERO ADDRESS IS THE ONE THE CLIENT CHECKS, NOT THE ESCROW. `verify.address` is the joint address;
|
|
1420
|
+
// the record's `moneroAddress` is the same value after a reload. The EVM escrow never leaves this method as
|
|
1421
|
+
// the XMR address, and it is the only address the auto ready-mark may receive.
|
|
1422
|
+
const moneroAddress = typeof verifyRequest.address === "string" && verifyRequest.address
|
|
1423
|
+
? verifyRequest.address
|
|
1424
|
+
: (record && record.escrow && record.escrow.moneroAddress) || null;
|
|
1425
|
+
if (verifyRequest.address && record && record.escrow && record.escrow.moneroAddress
|
|
1426
|
+
&& String(verifyRequest.address) !== String(record.escrow.moneroAddress)) {
|
|
1427
|
+
throw new SdkError("bad-input", { field: "verify.address", why: "record-mismatch" });
|
|
1428
|
+
}
|
|
1429
|
+
if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
|
|
1370
1430
|
const started = Date.now();
|
|
1371
1431
|
// --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
|
|
1372
1432
|
// A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
|
|
@@ -1381,9 +1441,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1381
1441
|
// A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
|
|
1382
1442
|
// durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
|
|
1383
1443
|
// must not start failing where it did not before.
|
|
1384
|
-
let record = null;
|
|
1385
|
-
try { record = engine.swap.getSwap(id, store); } catch { record = null; }
|
|
1386
|
-
const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
|
|
1387
1444
|
// FROM THE ESCROW'S BIRTH HEIGHT when the record knows it: the event cannot be older than the funding, and
|
|
1388
1445
|
// walking the whole chain every tick is a cost with no answer behind it.
|
|
1389
1446
|
const fromBlock = blockBoundaryOf(record && record.escrow
|
|
@@ -1432,7 +1489,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1432
1489
|
let last = null;
|
|
1433
1490
|
for (;;) {
|
|
1434
1491
|
await readDeclineLogs();
|
|
1435
|
-
last = { address:
|
|
1492
|
+
last = { address: moneroAddress, expectedXmr: request.expectedXmr ?? null, status: null };
|
|
1436
1493
|
// THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
|
|
1437
1494
|
// to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
|
|
1438
1495
|
const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
|
|
@@ -1462,7 +1519,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1462
1519
|
source: "client" };
|
|
1463
1520
|
if (wantExpect && wantWallet) {
|
|
1464
1521
|
verified.marked = await actions.markReady(
|
|
1465
|
-
{ escrow:
|
|
1522
|
+
{ escrow: escrowAddress, expect: request.expect, onStep: request.onStep }, request.wallet);
|
|
1466
1523
|
} else {
|
|
1467
1524
|
verified.next = "mark-ready";
|
|
1468
1525
|
}
|
|
@@ -1474,8 +1531,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1474
1531
|
/**
|
|
1475
1532
|
* START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
|
|
1476
1533
|
* the record keeps the one-time address, the escrow, our half, the order expectations and the relay origin, so a
|
|
1477
|
-
* reload can continue with `get` + `sellWatch` + `sellClaim`. The
|
|
1478
|
-
*
|
|
1534
|
+
* reload can continue with `get` + `sellWatch` + `sellClaim`. The ordered `claimSenders` list is the only
|
|
1535
|
+
* sender source; it is stored for the later claim. This method sends nothing.
|
|
1479
1536
|
*/
|
|
1480
1537
|
async startSell(request) {
|
|
1481
1538
|
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
|
|
@@ -1504,19 +1561,41 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1504
1561
|
|| !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
|
|
1505
1562
|
throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
|
|
1506
1563
|
}
|
|
1507
|
-
// THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps
|
|
1508
|
-
// the same node; a sender naming the maker or the quote key owner would reveal the half to the party
|
|
1509
|
-
// must never receive it.
|
|
1564
|
+
// THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps the list so a reload claims
|
|
1565
|
+
// through the same node; a sender naming the maker or the quote key owner would reveal the half to the party
|
|
1566
|
+
// that must never receive it. The old scalar is retired: it is not a second source and is refused by name.
|
|
1510
1567
|
const dealMaker = addressTextOf(quote.provider, "provider");
|
|
1511
1568
|
const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
|
|
1512
1569
|
|| String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1570
|
+
if (request.claimSender !== undefined && request.claimSender !== null
|
|
1571
|
+
&& String(request.claimSender).trim() !== "") {
|
|
1572
|
+
throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
|
|
1573
|
+
}
|
|
1574
|
+
const requestedList = request.claimSenders === undefined || request.claimSenders === null
|
|
1575
|
+
? null : request.claimSenders;
|
|
1576
|
+
if (requestedList !== null && !Array.isArray(requestedList)) {
|
|
1577
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
|
|
1517
1578
|
}
|
|
1518
|
-
if (
|
|
1519
|
-
throw new SdkError("bad-input", { field: "
|
|
1579
|
+
if (requestedList && requestedList.length === 0) {
|
|
1580
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1581
|
+
}
|
|
1582
|
+
const offerSender = offer.claimSender === undefined || offer.claimSender === null
|
|
1583
|
+
|| String(offer.claimSender).trim() === "" ? null : addressTextOf(offer.claimSender, "offer.claimSender");
|
|
1584
|
+
// THE STORED LIST IS BUILT HERE, ONCE. An explicit list wins; otherwise the relay's published claimSender is
|
|
1585
|
+
// the only fallback, as a one-element list. There is no legacy request scalar.
|
|
1586
|
+
const explicitSenders = requestedList;
|
|
1587
|
+
const rawSenders = explicitSenders || (offerSender ? [offerSender] : []);
|
|
1588
|
+
const claimSenders = [];
|
|
1589
|
+
for (const raw of rawSenders) {
|
|
1590
|
+
if (raw === undefined || raw === null || String(raw).trim() === "") {
|
|
1591
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1592
|
+
}
|
|
1593
|
+
const sender = addressTextOf(raw, "claimSenders");
|
|
1594
|
+
if (sender === dealMaker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
|
|
1595
|
+
if (quoteKeyOwner && sender === quoteKeyOwner) {
|
|
1596
|
+
throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
|
|
1597
|
+
}
|
|
1598
|
+
if (!claimSenders.includes(sender)) claimSenders.push(sender);
|
|
1520
1599
|
}
|
|
1521
1600
|
// THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
|
|
1522
1601
|
// one-time address and escrow; a second record would be a second promise about one deal.
|
|
@@ -1534,14 +1613,19 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1534
1613
|
|| !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
|
|
1535
1614
|
throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
|
|
1536
1615
|
}
|
|
1537
|
-
const
|
|
1616
|
+
const storedList = Array.isArray(existing.claimSenders) ? existing.claimSenders : null;
|
|
1538
1617
|
// THE OLD SCALAR IS NOT A PIN. A reload may name another sender or bring the ordered list at claim time; the
|
|
1539
|
-
// record keeps the latest
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1618
|
+
// record keeps the latest list and its first sender for callers that still use the scalar. An offer-only
|
|
1619
|
+
// sender fills a record that has no list; it never replaces a list the client already chose.
|
|
1620
|
+
if (explicitSenders && claimSenders.length && (!storedList || storedList.length !== claimSenders.length
|
|
1621
|
+
|| storedList.some((value, index) => String(value).toLowerCase() !== claimSenders[index]))) {
|
|
1622
|
+
existing.claimSenders = claimSenders;
|
|
1623
|
+
try { engine.swap.saveSwap(existing, store); }
|
|
1624
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1625
|
+
} else if (!explicitSenders && !storedList && claimSenders.length) {
|
|
1626
|
+
existing.claimSenders = claimSenders;
|
|
1543
1627
|
try { engine.swap.saveSwap(existing, store); }
|
|
1544
|
-
catch { throw new SdkError("storage-unavailable", { step: "save-claim-
|
|
1628
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1545
1629
|
}
|
|
1546
1630
|
// THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
|
|
1547
1631
|
// a resumed offer naming another origin is a different offer; one that now names the same origin fills a
|
|
@@ -1572,7 +1656,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1572
1656
|
address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
|
|
1573
1657
|
xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
|
|
1574
1658
|
claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
|
|
1575
|
-
|
|
1659
|
+
claimSenders: Array.isArray(existing.claimSenders) ? existing.claimSenders : [],
|
|
1576
1660
|
readyWindow: existing.readyWindow || existing.sellWindow || null,
|
|
1577
1661
|
resumed: true, next: "send-xmr" };
|
|
1578
1662
|
}
|
|
@@ -1642,9 +1726,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1642
1726
|
swap.orderQuote = offer.orderQuote || null;
|
|
1643
1727
|
swap.quote = quote;
|
|
1644
1728
|
swap.claimTip = quote.claimTip || null;
|
|
1645
|
-
// THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping
|
|
1729
|
+
// THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping the list means a reload cannot silently
|
|
1646
1730
|
// send the half to a different node than the one the client selected.
|
|
1647
|
-
if (
|
|
1731
|
+
if (claimSenders.length) swap.claimSenders = claimSenders;
|
|
1648
1732
|
swap.expect = {
|
|
1649
1733
|
chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
|
|
1650
1734
|
readyBy: order.readyBy, t1: order.t1, salt: order.salt,
|
|
@@ -1680,7 +1764,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1680
1764
|
try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
|
|
1681
1765
|
return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
|
|
1682
1766
|
xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
|
|
1683
|
-
|
|
1767
|
+
claimSenders: Array.isArray(swap.claimSenders) ? swap.claimSenders : [],
|
|
1684
1768
|
readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
|
|
1685
1769
|
},
|
|
1686
1770
|
|
|
@@ -1751,13 +1835,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1751
1835
|
}
|
|
1752
1836
|
const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
|
|
1753
1837
|
|| String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
// THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; the
|
|
1759
|
-
//
|
|
1760
|
-
// tried when this one refuses or its slot ends.
|
|
1838
|
+
if (request.claimSender !== undefined && request.claimSender !== null
|
|
1839
|
+
&& String(request.claimSender).trim() !== "") {
|
|
1840
|
+
throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
|
|
1841
|
+
}
|
|
1842
|
+
// THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; otherwise the stored list is the
|
|
1843
|
+
// fallback for an id-only reload. There is no legacy scalar and no second source.
|
|
1761
1844
|
if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
|
|
1762
1845
|
throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
|
|
1763
1846
|
}
|
|
@@ -1765,12 +1848,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1765
1848
|
if (explicitList && explicitList.length === 0) {
|
|
1766
1849
|
throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
|
|
1767
1850
|
}
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|| (Array.isArray(swap.claimSenders) ? swap.claimSenders : null)
|
|
1773
|
-
|| (storedSenderRaw ? [storedSenderRaw] : []);
|
|
1851
|
+
const legacyStored = swap.claimSender === undefined || swap.claimSender === null
|
|
1852
|
+
|| String(swap.claimSender).trim() === "" ? null : swap.claimSender;
|
|
1853
|
+
const rawSenders = explicitList || (Array.isArray(swap.claimSenders) && swap.claimSenders.length
|
|
1854
|
+
? swap.claimSenders : (legacyStored ? [legacyStored] : []));
|
|
1774
1855
|
if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
|
|
1775
1856
|
const senders = [];
|
|
1776
1857
|
for (const raw of rawSenders) {
|
|
@@ -1802,42 +1883,199 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1802
1883
|
}
|
|
1803
1884
|
}
|
|
1804
1885
|
// A LIST IS NOT A PIN. It is saved only as the fallback for a reload whose caller no longer has the relay's
|
|
1805
|
-
// answer; a later request that brings its own order ignores it.
|
|
1886
|
+
// answer; a later request that brings its own order ignores it. The retired scalar is removed even when the
|
|
1887
|
+
// list already matches, so a migrated record cannot keep two sources.
|
|
1888
|
+
let sendersChanged = false;
|
|
1806
1889
|
if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
|
|
1807
1890
|
|| swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
|
|
1808
1891
|
swap.claimSenders = senders;
|
|
1809
|
-
|
|
1892
|
+
sendersChanged = true;
|
|
1893
|
+
}
|
|
1894
|
+
if (Object.prototype.hasOwnProperty.call(swap, "claimSender")) {
|
|
1895
|
+
delete swap.claimSender;
|
|
1896
|
+
sendersChanged = true;
|
|
1897
|
+
}
|
|
1898
|
+
if (sendersChanged) {
|
|
1810
1899
|
try { engine.swap.saveSwap(swap, store); }
|
|
1811
1900
|
catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
|
|
1812
1901
|
}
|
|
1813
1902
|
|
|
1814
1903
|
const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
|
|
1815
|
-
? Number(request.timeoutMs) : 20_000;
|
|
1904
|
+
? Math.min(120_000, Number(request.timeoutMs)) : 20_000;
|
|
1816
1905
|
// ONE SENDER AT A TIME, EACH WITH ITS OWN SLOT. Refusal moves on immediately; an accepted/unknown answer is
|
|
1817
1906
|
// followed by reading the escrow until it says claimed or the slot ends. A txid alone is never success.
|
|
1818
1907
|
const slotMs = Number.isFinite(Number(request.slotMs)) && Number(request.slotMs) > 0
|
|
1819
1908
|
? Math.min(30_000, Math.max(15_000, Number(request.slotMs))) : 20_000;
|
|
1909
|
+
// A POLL UNDER 250 ms only burns chain reads, and a timeout above two minutes would hide a stuck sender
|
|
1910
|
+
// behind a wait the caller does not expect.
|
|
1820
1911
|
const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
|
|
1821
|
-
? Math.min(slotMs, Number(request.pollMs)) : 2_000;
|
|
1912
|
+
? Math.min(slotMs, Math.max(250, Number(request.pollMs))) : 2_000;
|
|
1822
1913
|
const readStatus = async () => {
|
|
1823
|
-
try { return await flow.orderStatus(escrow, { call: reader }); }
|
|
1914
|
+
try { return await flow.orderStatus(escrow, { call: reader }); }
|
|
1915
|
+
catch (error) {
|
|
1916
|
+
// AN UNREAD ESCROW IS NOT AN OPEN ONE. The caller must not be told to claim a sale whose state we could
|
|
1917
|
+
// not read; the half may already have landed. This is the same unknown state as a lost relay answer.
|
|
1918
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "escrow-unread",
|
|
1919
|
+
detail: String((error && error.message) || error).slice(0, 160) });
|
|
1920
|
+
}
|
|
1824
1921
|
};
|
|
1825
1922
|
const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
|
|
1826
|
-
|
|
1827
|
-
|
|
1923
|
+
let t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
|
|
1924
|
+
// THE TIME LEFT IS THE CHAIN'S TIME. It is null until the same clock used by windowOf has been read.
|
|
1925
|
+
const secondsLeft = () => (t1 === null || observedNowSec === null ? null : Math.max(0, t1 - observedNowSec));
|
|
1926
|
+
// THE CLAIM WINDOW BELONGS TO THE CONTRACT, NOT TO THE RELAY. The relay can forward any half it is given, so
|
|
1927
|
+
// the client must refuse to hand it over before `readyBy` without the ready mark, after `t1`, and inside the
|
|
1928
|
+
// settlement margin when neither a sender nor the seller's own claim can still land. The check reads the
|
|
1929
|
+
// escrow's ready mark and both deadlines for EVERY sender, not once for the whole list: a slot can cross a
|
|
1930
|
+
// boundary while the previous sender is being polled.
|
|
1931
|
+
const CLAIM_MARGIN_SEC = 120;
|
|
1932
|
+
const SELLER_CLAIM_SEC = 60;
|
|
1933
|
+
const windowOf = async () => {
|
|
1934
|
+
let nowSec;
|
|
1935
|
+
try { nowSec = await chainNowSec(); }
|
|
1936
|
+
catch { nowSec = null; }
|
|
1937
|
+
if (!Number.isSafeInteger(nowSec) || nowSec <= 0) {
|
|
1938
|
+
observedNowSec = null;
|
|
1939
|
+
return { ok: false, reason: "unreadable" };
|
|
1940
|
+
}
|
|
1941
|
+
observedNowSec = nowSec;
|
|
1942
|
+
let deadlines;
|
|
1943
|
+
try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
|
|
1944
|
+
catch { return { ok: false, reason: "unreadable" }; }
|
|
1945
|
+
const t1Sec = Number(deadlines.t1);
|
|
1946
|
+
const readyBySec = Number(deadlines.readyBy);
|
|
1947
|
+
if (![t1Sec, readyBySec].every(Number.isSafeInteger)) {
|
|
1948
|
+
return { ok: false, reason: "unreadable" };
|
|
1949
|
+
}
|
|
1950
|
+
if (Number.isSafeInteger(t1Sec)) t1 = t1Sec;
|
|
1951
|
+
let marked;
|
|
1952
|
+
try {
|
|
1953
|
+
const raw = await reader({ to: escrow, data: engine.evm.encodeRead("ready") });
|
|
1954
|
+
marked = BigInt(String(raw || "").replace(/^0x/, "") || "0") !== 0n;
|
|
1955
|
+
} catch { return { ok: false, reason: "unreadable" }; }
|
|
1956
|
+
if (nowSec >= t1Sec) return { ok: false, reason: "window-closed" };
|
|
1957
|
+
// A SEND LANDS IN A LATER BLOCK. The last 120 s belong to the relay's settlement margin, and the seller
|
|
1958
|
+
// still needs a slot plus time for their own claim if the relay cannot land it.
|
|
1959
|
+
if (nowSec + CLAIM_MARGIN_SEC + Math.ceil(slotMs / 1000) + SELLER_CLAIM_SEC >= t1Sec) {
|
|
1960
|
+
return { ok: false, reason: "settlement-margin" };
|
|
1961
|
+
}
|
|
1962
|
+
if (nowSec < readyBySec && !marked) return { ok: false, reason: "not-ready" };
|
|
1963
|
+
return { ok: true, t1: t1Sec, readyBy: readyBySec, nowSec };
|
|
1964
|
+
};
|
|
1965
|
+
const windowResult = (reason, tried) => ({
|
|
1966
|
+
id, state: "claim-window", reason, provider: null, escrow, relayUrl,
|
|
1967
|
+
txid: null, from: null, tipWei: tip.toString(), t1, secondsLeft: secondsLeft(), tried,
|
|
1968
|
+
});
|
|
1969
|
+
const STOP_ESCROW_CODES = new Set([
|
|
1970
|
+
"claim-not-ready", "claim-window-closed", "claim-settlement-margin",
|
|
1971
|
+
"claim-not-funded", "claim-already-closed", "claim-half-invalid",
|
|
1972
|
+
]);
|
|
1828
1973
|
const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
|
|
1829
|
-
id, state: "claimed", provider: sender,
|
|
1974
|
+
id, state: "claimed", provider: sender, escrow, relayUrl,
|
|
1830
1975
|
txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
|
|
1831
1976
|
tipWei: (answer && answer.tipWei) || tip.toString(), tried,
|
|
1832
1977
|
});
|
|
1978
|
+
// A WINDOW STOP AFTER SENDS IS NOT A BLIND STOP. The last sender's claim can land just after its slot; before
|
|
1979
|
+
// reporting a closing window, read the escrow once more and let a claimed/refunded/defunded state win.
|
|
1980
|
+
const windowStop = async (reason, currentTried) => {
|
|
1981
|
+
let status;
|
|
1982
|
+
try {
|
|
1983
|
+
status = await readStatus();
|
|
1984
|
+
} catch {
|
|
1985
|
+
// THE WINDOW STOP MUST STAY A RESULT. If the escrow cannot be read, the caller still needs the named
|
|
1986
|
+
// window state; throwing here would change a pre-existing `claim-window` answer into an exception.
|
|
1987
|
+
return windowResult(reason, currentTried);
|
|
1988
|
+
}
|
|
1989
|
+
if (status.isClaimed) {
|
|
1990
|
+
try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
|
|
1991
|
+
return claimedByEscrow(null, null, currentTried);
|
|
1992
|
+
}
|
|
1993
|
+
if (status.isRefunded) return windowResult("escrow-refunded", currentTried);
|
|
1994
|
+
if (!status.isFunded) return windowResult("not-funded", currentTried);
|
|
1995
|
+
return windowResult(reason, currentTried);
|
|
1996
|
+
};
|
|
1833
1997
|
// A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
|
|
1834
1998
|
// the previous attempt; read the escrow before the first POST, and read it once more before returning
|
|
1835
1999
|
// `claim-yourself`, so a late claim cannot be reported as "claim yourself".
|
|
1836
|
-
const
|
|
1837
|
-
|
|
1838
|
-
|
|
2000
|
+
const priorAttempts = Array.isArray(swap.claimAttempts) ? swap.claimAttempts : [];
|
|
2001
|
+
let initial;
|
|
2002
|
+
try {
|
|
2003
|
+
initial = await readStatus();
|
|
2004
|
+
} catch (error) {
|
|
2005
|
+
// NOTHING HAS BEEN SENT IN THIS CALL. Without an earlier attempt this is a pre-send refusal, not "the claim
|
|
2006
|
+
// may already have been sent"; the window result says the clock/escrow could not be read.
|
|
2007
|
+
if (!priorAttempts.length && error && error.code === "claim-unknown"
|
|
2008
|
+
&& error.params && error.params.why === "escrow-unread") {
|
|
2009
|
+
return windowResult("unreadable", []);
|
|
2010
|
+
}
|
|
2011
|
+
throw error;
|
|
2012
|
+
}
|
|
2013
|
+
if (initial.isClaimed) return claimedByEscrow();
|
|
2014
|
+
if (!initial.isFunded) return windowResult("not-funded", []);
|
|
2015
|
+
let refunded = Boolean(initial.isRefunded);
|
|
1839
2016
|
const tried = [];
|
|
2017
|
+
// A SENDER THAT MAY HAVE RECEIVED THE HALF IS NOT A DONE MARK. The record gets the sender before the POST, so
|
|
2018
|
+
// a crash or a lost answer leaves a durable trace; a later call reads the escrow and may try the same sender
|
|
2019
|
+
// again. Only a sender whose slot is still running is held back, and even then the slot is polled rather than
|
|
2020
|
+
// allowed to block the list forever.
|
|
2021
|
+
const priorTried = priorAttempts.map((entry) => ({
|
|
2022
|
+
sender: entry.sender, outcome: entry.outcome || "unknown", code: entry.code || null,
|
|
2023
|
+
params: entry.params || null, txid: entry.txid || null,
|
|
2024
|
+
}));
|
|
2025
|
+
const latest = priorAttempts[priorAttempts.length - 1];
|
|
2026
|
+
if (latest && (latest.outcome === "sending" || latest.outcome === "unknown")
|
|
2027
|
+
&& Number.isFinite(Number(latest.at))) {
|
|
2028
|
+
const gate = await windowOf();
|
|
2029
|
+
if (!gate.ok) {
|
|
2030
|
+
// A PRIOR ATTEMPT MAY HAVE SENT THE HALF. The same late-read rule as the sender loop applies here: do not
|
|
2031
|
+
// report a closing window without one last escrow read.
|
|
2032
|
+
return priorTried.length ? windowStop(gate.reason, priorTried)
|
|
2033
|
+
: windowResult(gate.reason, priorTried);
|
|
2034
|
+
}
|
|
2035
|
+
// AN OLD RECORD MAY CARRY A DEVICE-CLOCK `at` AHEAD OF CHAIN TIME. A slot is 15-30 s by construction, so cap
|
|
2036
|
+
// the wait at one slot from the chain clock instead of trusting a future timestamp indefinitely.
|
|
2037
|
+
const slotEnd = Math.min(Number(latest.at) + Math.ceil(slotMs / 1000),
|
|
2038
|
+
observedNowSec + Math.ceil(slotMs / 1000));
|
|
2039
|
+
while (observedNowSec !== null && observedNowSec < slotEnd) {
|
|
2040
|
+
const status = await readStatus();
|
|
2041
|
+
if (status && status.isClaimed) return claimedByEscrow(latest.sender, null, priorTried);
|
|
2042
|
+
if (status && status.isRefunded) return windowResult("escrow-refunded", priorTried);
|
|
2043
|
+
const waitMs = Math.max(1, Math.min(pollMs, (slotEnd - observedNowSec) * 1000));
|
|
2044
|
+
await sleepFor(waitMs);
|
|
2045
|
+
const next = await chainNowSec();
|
|
2046
|
+
if (!Number.isSafeInteger(next) || next <= 0) {
|
|
2047
|
+
throw new SdkError("claim-unknown", { step: "relay-claim", why: "clock-unreadable" });
|
|
2048
|
+
}
|
|
2049
|
+
observedNowSec = next;
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
if (refunded) return windowResult("escrow-refunded", priorTried);
|
|
2053
|
+
const persistAttempts = (entry, outcome, extra = {}) => {
|
|
2054
|
+
if (entry) Object.assign(entry, { outcome, ...extra });
|
|
2055
|
+
try { engine.swap.saveSwap(swap, store); }
|
|
2056
|
+
catch { throw new SdkError("storage-unavailable", { step: "save-claim-attempt" }); }
|
|
2057
|
+
};
|
|
2058
|
+
const beginAttempt = (sender) => {
|
|
2059
|
+
const at = Number.isSafeInteger(observedNowSec) ? observedNowSec : Math.floor(clockMs() / 1000);
|
|
2060
|
+
const entry = { sender, at, outcome: "sending" };
|
|
2061
|
+
swap.claimAttempts = [...(Array.isArray(swap.claimAttempts) ? swap.claimAttempts : []), entry];
|
|
2062
|
+
persistAttempts(entry, "sending");
|
|
2063
|
+
return entry;
|
|
2064
|
+
};
|
|
2065
|
+
const finishAttempt = (entry, outcome, extra = {}) => {
|
|
2066
|
+
try { persistAttempts(entry, outcome, extra); } catch { /* the chain answer is already known */ }
|
|
2067
|
+
};
|
|
1840
2068
|
if (!refunded) for (const sender of senders) {
|
|
2069
|
+
const gate = await windowOf();
|
|
2070
|
+
if (!gate.ok) {
|
|
2071
|
+
if (tried.length || priorTried.length) return windowStop(gate.reason, tried);
|
|
2072
|
+
return windowResult(gate.reason, tried);
|
|
2073
|
+
}
|
|
2074
|
+
if (gate.t1 !== null) t1 = gate.t1;
|
|
2075
|
+
const attempt = beginAttempt(sender);
|
|
2076
|
+
// THE SLOT STARTS WHEN THE SENDER IS ENTERED, NOT WHEN ITS POST RETURNS. A slow POST must not stretch the
|
|
2077
|
+
// 15-30 s slot into twice the advertised time.
|
|
2078
|
+
const slotStartedAt = clockMs();
|
|
1841
2079
|
let answer = null;
|
|
1842
2080
|
let failure = null;
|
|
1843
2081
|
try {
|
|
@@ -1849,17 +2087,27 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1849
2087
|
failure = error;
|
|
1850
2088
|
}
|
|
1851
2089
|
// A REFUSAL IS THE SENDER'S ANSWER, NOT A CLAIM IN FLIGHT. Move to the next one at once; only an unknown
|
|
1852
|
-
// outcome (or a txid, which is not yet a claim on chain) deserves the slot.
|
|
2090
|
+
// outcome (or a txid, which is not yet a claim on chain) deserves the slot. An escrow-state refusal is
|
|
2091
|
+
// different: it says the order itself is closed, so trying another sender would publish the half for no
|
|
2092
|
+
// reason. Read the escrow and stop.
|
|
1853
2093
|
if (failure && failure.code !== "claim-unknown") {
|
|
1854
|
-
|
|
1855
|
-
params: failure.params || null }
|
|
2094
|
+
const refused = { sender, outcome: "refused", code: failure.code || "unknown",
|
|
2095
|
+
params: failure.params || null };
|
|
2096
|
+
tried.push(refused);
|
|
2097
|
+
finishAttempt(attempt, "refused", { code: refused.code, params: refused.params });
|
|
2098
|
+
if (STOP_ESCROW_CODES.has(String((failure.params && failure.params.code) || ""))) {
|
|
2099
|
+
const stopped = await readStatus();
|
|
2100
|
+
if (stopped.isClaimed) return claimedByEscrow(sender, null, tried);
|
|
2101
|
+
if (stopped.isRefunded) return windowResult("escrow-refunded", tried);
|
|
2102
|
+
return windowResult("escrow-refused", tried);
|
|
2103
|
+
}
|
|
1856
2104
|
continue;
|
|
1857
2105
|
}
|
|
1858
|
-
const slotEnd =
|
|
2106
|
+
const slotEnd = slotStartedAt + slotMs;
|
|
1859
2107
|
for (;;) {
|
|
1860
2108
|
const status = await readStatus();
|
|
1861
2109
|
if (status && status.isClaimed) {
|
|
1862
|
-
|
|
2110
|
+
finishAttempt(attempt, "claimed", { txid: answer ? answer.txid : null });
|
|
1863
2111
|
try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
|
|
1864
2112
|
return claimedByEscrow(sender, answer, tried);
|
|
1865
2113
|
}
|
|
@@ -1868,21 +2116,27 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1868
2116
|
if (left <= 0) break;
|
|
1869
2117
|
await sleepFor(Math.min(pollMs, left));
|
|
1870
2118
|
}
|
|
1871
|
-
|
|
1872
|
-
txid: answer ? answer.txid : null, code: failure ? failure.code : null }
|
|
2119
|
+
const ended = { sender, outcome: failure ? "unknown" : "unconfirmed",
|
|
2120
|
+
txid: answer ? answer.txid : null, code: failure ? failure.code : null };
|
|
2121
|
+
tried.push(ended);
|
|
2122
|
+
finishAttempt(attempt, ended.outcome, { txid: ended.txid, code: ended.code });
|
|
1873
2123
|
if (refunded) break;
|
|
1874
2124
|
}
|
|
1875
2125
|
|
|
1876
2126
|
// THE LAST LOOK BEFORE THE FALLBACK. A claim can land after the last slot ended or while a later sender is
|
|
1877
2127
|
// refusing; the seller must not be sent to `sellClaim` on an escrow that is already closed as claimed.
|
|
1878
2128
|
const finalStatus = await readStatus();
|
|
1879
|
-
if (finalStatus
|
|
2129
|
+
if (finalStatus.isClaimed) {
|
|
1880
2130
|
try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
|
|
1881
2131
|
return claimedByEscrow(null, null, tried);
|
|
1882
2132
|
}
|
|
1883
|
-
if (finalStatus
|
|
1884
|
-
|
|
1885
|
-
|
|
2133
|
+
if (finalStatus.isRefunded) refunded = true;
|
|
2134
|
+
if (!finalStatus.isFunded) return windowResult("not-funded", tried);
|
|
2135
|
+
if (refunded) return windowResult("escrow-refunded", tried);
|
|
2136
|
+
const finalGate = await windowOf();
|
|
2137
|
+
if (!finalGate.ok) return windowResult(finalGate.reason, tried);
|
|
2138
|
+
return { id, state: "claim-yourself", reason: "senders-exhausted",
|
|
2139
|
+
provider: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
|
|
1886
2140
|
t1, secondsLeft: secondsLeft(), tried };
|
|
1887
2141
|
},
|
|
1888
2142
|
|
|
@@ -1946,17 +2200,36 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
|
|
|
1946
2200
|
ready = hex.length > 0 && BigInt("0x" + hex) !== 0n;
|
|
1947
2201
|
} catch (error) { lastError = (error && error.code) || "ready-unread"; }
|
|
1948
2202
|
if (ready === true) {
|
|
2203
|
+
// A ready mark after t1 is not a usable sell window: the contract's claim is already closed. Name it
|
|
2204
|
+
// as a claim-window state instead of returning `ready` and letting the host promise a claim.
|
|
2205
|
+
const t1 = deadlines ? Number(deadlines.t1) : null;
|
|
2206
|
+
const at = nowSec();
|
|
2207
|
+
if (Number.isSafeInteger(t1) && at !== null && at >= t1) {
|
|
2208
|
+
return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
|
|
2209
|
+
ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
|
|
2210
|
+
t1, secondsLeft: 0 };
|
|
2211
|
+
}
|
|
1949
2212
|
return { escrow, state: "ready", funded: true, claimed: false, refunded: false,
|
|
1950
2213
|
ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
|
|
1951
2214
|
}
|
|
1952
2215
|
}
|
|
1953
|
-
// AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK
|
|
1954
|
-
//
|
|
1955
|
-
|
|
2216
|
+
// AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK - BUT ONLY BEFORE t1. Without a
|
|
2217
|
+
// readable t1 the SDK cannot promise a claim window, so it keeps waiting instead of opening one on a
|
|
2218
|
+
// guess. The last 60 s are closed because a claim lands in a later block.
|
|
2219
|
+
if (lastStatus && lastStatus.isFunded && deadlines) {
|
|
2220
|
+
const readyBy = Number(deadlines.readyBy);
|
|
2221
|
+
const t1 = Number(deadlines.t1);
|
|
1956
2222
|
const at = nowSec();
|
|
1957
|
-
if (at !== null && at >=
|
|
2223
|
+
if (Number.isSafeInteger(readyBy) && Number.isSafeInteger(t1) && at !== null && at >= readyBy) {
|
|
2224
|
+
const secondsLeft = Math.max(0, t1 - at);
|
|
2225
|
+
if (at + 60 >= t1) {
|
|
2226
|
+
return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
|
|
2227
|
+
ready: false, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
|
|
2228
|
+
t1, secondsLeft };
|
|
2229
|
+
}
|
|
1958
2230
|
return { escrow, state: "claim-open", funded: true, claimed: false, refunded: false,
|
|
1959
|
-
ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started
|
|
2231
|
+
ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
|
|
2232
|
+
t1, secondsLeft };
|
|
1960
2233
|
}
|
|
1961
2234
|
}
|
|
1962
2235
|
if (Date.now() - started >= timeoutMs) {
|