@ninsei-labs/sdk 0.61.0 → 0.62.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 +35 -0
- package/README.md +56 -5
- package/assets/vendors/MANIFEST.json +1 -1
- package/assets/vendors/sdk/sdk-browser.js +4 -4
- package/engine/atomic/halfenc.js +6 -6
- package/engine/core/config.js +17 -38
- package/engine/core/format.js +1 -1
- package/engine/core/sellWindow.js +1 -1
- package/engine/core/store.js +11 -3
- package/engine/core/swap.js +3 -3
- package/engine/evm/amounts.js +2 -2
- package/engine/evm/asyncRoute.js +3 -3
- package/engine/evm/dex.js +1 -1
- package/engine/evm/factory.js +1 -1
- package/engine/evm/fees.js +62 -0
- package/engine/evm/funding.js +71 -66
- package/engine/evm/gasReserve.js +10 -0
- package/engine/evm/index.js +2 -2
- package/engine/evm/prices.js +3 -0
- package/engine/evm/session.js +1 -1
- package/engine/monero/address.js +4 -2
- package/engine/monero/arrivalRead.js +15 -2
- package/engine/monero/keyImage.js +146 -0
- package/engine/monero/keys.js +1 -0
- package/engine/monero/mnemonic.js +2 -1
- package/engine/monero/node.js +1 -0
- package/engine/monero/scan.js +12 -2
- package/engine/recovery/recoveryFile.js +31 -85
- package/engine/sdk/bridge.js +21 -51
- package/index.d.ts +412 -19
- package/package.json +20 -2
- package/src/actions.mjs +72 -6
- package/src/addressGuard.mjs +16 -0
- package/src/codes.mjs +26 -9
- package/src/config.mjs +56 -3
- package/src/decline.mjs +23 -74
- package/src/firmRequest.mjs +80 -0
- package/src/index.mjs +17 -28
- package/src/legs/cow.mjs +2 -2
- package/src/legs/evm.mjs +20 -12
- package/src/legs/kyber-spec.mjs +2 -2
- package/src/legs/kyber.mjs +1 -1
- package/src/legs/shape.mjs +1 -1
- package/src/legs/uniswaprelay.mjs +16 -4
- package/src/legs/uniswapx.mjs +29 -7
- package/src/levelsWalkSpec.mjs +1 -1
- package/src/lock.mjs +18 -37
- package/src/provider/envFile.mjs +3 -3
- package/src/provider/sign.mjs +3 -3
- package/src/public/evm.d.ts +84 -0
- package/src/public/evm.mjs +20 -0
- package/src/public/order.mjs +1 -1
- package/src/public/provider.mjs +1 -1
- package/src/public/recovery.d.ts +3 -2
- package/src/public/recovery.mjs +1 -1
- package/src/public/xmr.d.ts +2 -2
- package/src/quoteEip712Spec.mjs +4 -4
- package/src/quotes.mjs +52 -11
- package/src/recovery-key.mjs +7 -3
- package/src/relayFirmClient.mjs +4 -0
- package/src/relayQuote.mjs +1 -0
- package/src/sim.mjs +1 -1
- package/src/swap-flow.mjs +22 -32
- package/src/swaps.mjs +63 -56
- package/src/sweep-inputs.mjs +61 -0
- package/src/sweep-reconcile.mjs +71 -0
- package/src/sweep-restore.mjs +38 -9
- package/src/sweep.mjs +164 -10
- package/src/version.mjs +1 -1
- package/src/wallet.mjs +1 -1
- package/src/xmr-arrival.mjs +1041 -43
package/engine/atomic/halfenc.js
CHANGED
|
@@ -111,12 +111,12 @@ export function createHalfEnc({ secp256k1, ed25519, keccak256, randomBytes }) {
|
|
|
111
111
|
// calldata at lock(). The format is fixed, because the commitment depends on it: any other layout changes the
|
|
112
112
|
// hash and the lock is rejected.
|
|
113
113
|
//
|
|
114
|
-
// 0
|
|
115
|
-
// 1..33
|
|
116
|
-
// 34..66
|
|
117
|
-
// 67..98
|
|
118
|
-
// 99
|
|
119
|
-
// 100
|
|
114
|
+
// 0: format version (1)
|
|
115
|
+
// 1..33: encryption recipient public key (33 bytes, compressed secp256k1)
|
|
116
|
+
// 34..66: sender ephemeral point (33 bytes, compressed)
|
|
117
|
+
// 67..98: masked scalar (32 bytes, big-endian)
|
|
118
|
+
// 99: context length in bytes (0..255)
|
|
119
|
+
// 100..: order context in UTF-8
|
|
120
120
|
//
|
|
121
121
|
// Total 100 + context length bytes. JSON is deliberately not used: key order and number formatting would give
|
|
122
122
|
// different bytes for the same content, and the commitment requires uniqueness.
|
package/engine/core/config.js
CHANGED
|
@@ -109,14 +109,11 @@ export const DEX_PRICE_GATE = {
|
|
|
109
109
|
|
|
110
110
|
// PRE-SIGNING GUARD THRESHOLDS - ALSO NUMBERS IN DATA, NOT IN LOGIC (www/js/core/preSignGuards.js).
|
|
111
111
|
// Only ORDER DEADLINES live here; the price and coverage thresholds are above, at the DEX leg.
|
|
112
|
-
// minReadyLeadSec - how far the readiness
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
// strictly below the contract window.
|
|
118
|
-
// minClaimWindowSec - how far the settlement deadline (t1) must stand from the readiness deadline: the window in
|
|
119
|
-
// which the claimer claims the ETH cannot be "a few seconds". 10 minutes against the usual hour.
|
|
112
|
+
// minReadyLeadSec - how far the readiness deadline must be ahead of "now" before signing. The threshold is the
|
|
113
|
+
// soft sell window (600 s): how long the provider promises to hold the on-screen price. It
|
|
114
|
+
// must stay below the contract window (1200 s).
|
|
115
|
+
// minClaimWindowSec - how far the settlement deadline (t1) must stand from the readiness deadline. 10 minutes
|
|
116
|
+
// against the usual hour.
|
|
120
117
|
export const SIGNING_GUARDS = {
|
|
121
118
|
minReadyLeadSec: 600,
|
|
122
119
|
minClaimWindowSec: 600,
|
|
@@ -379,16 +376,10 @@ export const CHAINS = [
|
|
|
379
376
|
// (2026-09-23). IMPORTANT ABOUT THIS NETWORK: pools exist but liquidity is unusable. The 0.01% tier serves NO
|
|
380
377
|
// size ("pool cannot serve this size"), 0.05% gives ZERO output at any size, and 0.3% answers at a price that
|
|
381
378
|
// diverges from the Chainlink reference.
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
//
|
|
385
|
-
//
|
|
386
|
-
// than the reference. The method is THE SAME CODE AS IN THE INTERFACE (www/js/evm/dex.js: priceGateVerdict,
|
|
387
|
-
// reference from www/js/evm/prices.js) and is rerunnable in one command.
|
|
388
|
-
// (rerun the DEX quote check against arbitrum-sepolia)
|
|
389
|
-
// THE NUMBER DEPENDS ON SIZE (same block, same scale): 1 USDC = 77.5%, 10 USDC = 76.6%, 100 USDC = 67.6%,
|
|
390
|
-
// 1000 USDC = -16.0%. So ONE number stands here WITH A NAMED SIZE. The tool also prints a "how many times
|
|
391
|
-
// cheaper" observation (+208.6% for 100 USDC, i.e. the same 3.09x) - a RECOUNT of the same figure, not a second measurement.
|
|
379
|
+
// One measured number, with a named size and block. Measurement 2026-09-24, block 312238363, 100 USDC: the
|
|
380
|
+
// quote gave 0.116508 WETH, an implied native price of $858.31 against $2650.42 from Chainlink. That is a 67.6%
|
|
381
|
+
// divergence against a 2% threshold. The result depends on size: 1 USDC = 77.5%, 10 USDC = 76.6%, 100 USDC =
|
|
382
|
+
// 67.6%, 1000 USDC = -16.0%. Keep the size with the number.
|
|
392
383
|
uniswap: {
|
|
393
384
|
factory: "0x248ab79bbb9bc29bb72f7cd42f17e054fc40188e",
|
|
394
385
|
quoter: "0x2779a0CC1c3e0E44D2542EC3e79e3864Ae93Ef0B",
|
|
@@ -450,26 +441,14 @@ export const CHAINS = [
|
|
|
450
441
|
explorerName: "",
|
|
451
442
|
gasUsd: 0.0001,
|
|
452
443
|
routeType: "atomic",
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
// on
|
|
456
|
-
//
|
|
457
|
-
//
|
|
458
|
-
//
|
|
459
|
-
//
|
|
460
|
-
//
|
|
461
|
-
// the cashier with. The registry is the third CREATE (DEPLOY_REGISTRY=true), 4557 bytes. PREVIOUS record:
|
|
462
|
-
// factory 0x5fbdb2315678afecb367f032d93f642f64180aa3 and cashier 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512,
|
|
463
|
-
// whose code did not match the canonical cashier - the escrow would have rejected such an order.
|
|
464
|
-
// THE ESCROW IMPLEMENTATION CODE HASH: what executes each order's clone, which the interface must check itself
|
|
465
|
-
// rather than trust the factory. The value is keccak256 of NinseiEscrow's runtime code from OUR OWN build (forge
|
|
466
|
-
// inspect NinseiEscrow deployedBytecode --root mvp/contracts and keccak - matched keccak256(type(NinseiEscrow)
|
|
467
|
-
// .runtimeCode) that the factory writes, and the out/ artifact). The implementation has NO immutables, so this is
|
|
468
|
-
// a PROTOCOL CONSTANT - the same hash on any network with that build. It sits per network, not as one global
|
|
469
|
-
// number, because the policy may be absent: a network with an OLD factory (no implementation()) must stay
|
|
470
|
-
// WITHOUT a policy, else reading the pair fails and live quotes there stall. That is the case on
|
|
471
|
-
// arbitrum-sepolia: its factory does not know the build (both getters revert), so it has NO field; it is enabled
|
|
472
|
-
// in the same pass as the new deploy.
|
|
444
|
+
// The factory deployed into the local chain. CREATE derives its address from the sender and its transaction
|
|
445
|
+
// number, so a fresh chain gives the same address while a long-running chain differs. These values were measured
|
|
446
|
+
// on chain after a redeploy for the quote format with xmrAmount: anvil account 0, nonce 60, block 74, 13188
|
|
447
|
+
// bytes of code (keccak 0x9bffb62d50eef21bcfd4b59e1c3d6fb7cbb3e303257edb2f5ba9dc65b3e8719c, matched to the
|
|
448
|
+
// tree build). The cashier is the second CREATE (573 bytes, keccak
|
|
449
|
+
// 0xcca1d8bc53d1d1c98901570800e093d0933f84637c6cdc727153b3ef8d8c3c36, the hash the escrow checks).
|
|
450
|
+
// The escrow implementation code hash is keccak256 of NinseiEscrow runtime code from this build. It is a
|
|
451
|
+
// protocol constant for this build, kept per network because a network with an old factory has no policy.
|
|
473
452
|
escrow: { address: "0xcbEAF3BDe82155F56486Fb5a1072cb8baAf547cc", mode: "live", cashier: "0x1429859428C0aBc9C2C47C8Ee9FBaf82cFA0F20f", implementationCodeHash: "0xfd1ef12c1d96d3ee7060bd5901e06108723783403fad00c9630dcdeb6193674b" },
|
|
474
453
|
// There are no tokens in the sandbox: payment is native. An empty list is a fact about the sandbox, not an oversight.
|
|
475
454
|
tokens: [],
|
package/engine/core/format.js
CHANGED
|
@@ -152,7 +152,7 @@ export function shortId() {
|
|
|
152
152
|
// unnoticed. It used to be named isValidMoneroAddress - and that name was a trap: a function called
|
|
153
153
|
// "address check" that lets a typo through ends up on the money path sooner or later.
|
|
154
154
|
//
|
|
155
|
-
// THE REAL CHECK IS checkAddress() from
|
|
155
|
+
// THE REAL CHECK IS checkAddress() from../monero/address.js: format + base58 decode + keccak256 checksum
|
|
156
156
|
// + network match. The form calls that one. This one only screens out obvious garbage before the heavy decode.
|
|
157
157
|
export function looksLikeMoneroAddress(addr) {
|
|
158
158
|
const a = String(addr || "").trim();
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// WHY A FUNCTION, NOT TWO NUMBERS IN TWO PLACES. This rule is decided by the NODE (rfq/reverseArrival.mjs -
|
|
16
16
|
// the mark, the alarm, the early refund) and shown by the PAGE (www/js/core/swap.js - the on-screen countdown).
|
|
17
17
|
// A second edition would diverge from the first silently: the person would see one window while the node lived by
|
|
18
|
-
// another. The rfq -> www import direction is already accepted (precedent: rfq/reverseGas.mjs imports
|
|
18
|
+
// another. The rfq -> www import direction is already accepted (precedent: rfq/reverseGas.mjs imports../www/js/evm/claimGas.js).
|
|
19
19
|
export const SELL_WINDOW = {
|
|
20
20
|
softSec: 600, // "ten minutes": the provider's on-screen promise
|
|
21
21
|
hardSec: 1200, // contract window: 10 Monero confirmations, the maximum that goes into termsHash
|
package/engine/core/store.js
CHANGED
|
@@ -60,6 +60,14 @@ const storageFailure = (step, cause) => {
|
|
|
60
60
|
return error;
|
|
61
61
|
};
|
|
62
62
|
|
|
63
|
+
// THE DECLARED STORE IS SYNCHRONOUS. A Promise returned from one of its three methods is not a value the store
|
|
64
|
+
// can read or write; waiting for it would make the caller's save happen after the swap state was decided. Refuse it
|
|
65
|
+
// at the seam instead of letting JSON.parse turn it into a misleading parse error.
|
|
66
|
+
const ensureSync = (value, step) => {
|
|
67
|
+
if (value && typeof value.then === "function") throw storageFailure(step);
|
|
68
|
+
return value;
|
|
69
|
+
};
|
|
70
|
+
|
|
63
71
|
/** Swap the storage for setup and tests. It also releases the exclusive binding, so a later client may bind. */
|
|
64
72
|
export function setStorage(next) {
|
|
65
73
|
checkAdapter(next);
|
|
@@ -86,7 +94,7 @@ export const storage = () => adapter;
|
|
|
86
94
|
function loadStateFrom(source) {
|
|
87
95
|
let raw;
|
|
88
96
|
try {
|
|
89
|
-
raw = source.get(APP.storageKey);
|
|
97
|
+
raw = ensureSync(source.get(APP.storageKey), "read");
|
|
90
98
|
} catch (error) {
|
|
91
99
|
throw storageFailure("read", error);
|
|
92
100
|
}
|
|
@@ -120,7 +128,7 @@ function saveStateTo(source, state) {
|
|
|
120
128
|
throw storageFailure("serialize", error);
|
|
121
129
|
}
|
|
122
130
|
try {
|
|
123
|
-
source.set(APP.storageKey, text);
|
|
131
|
+
ensureSync(source.set(APP.storageKey, text), "write");
|
|
124
132
|
} catch (error) {
|
|
125
133
|
throw storageFailure("write", error);
|
|
126
134
|
}
|
|
@@ -153,7 +161,7 @@ export function update(mutator) {
|
|
|
153
161
|
|
|
154
162
|
export function reset() {
|
|
155
163
|
try {
|
|
156
|
-
adapter.remove(APP.storageKey);
|
|
164
|
+
ensureSync(adapter.remove(APP.storageKey), "remove");
|
|
157
165
|
} catch (error) {
|
|
158
166
|
throw storageFailure("remove", error);
|
|
159
167
|
}
|
package/engine/core/swap.js
CHANGED
|
@@ -121,7 +121,7 @@ export function createSwap(input, store = null) {
|
|
|
121
121
|
return swap;
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
-
// REVERSE-FLOW DEAL RECORD
|
|
124
|
+
// REVERSE-FLOW DEAL RECORD. The sell screen used to stop at the request, and there was
|
|
125
125
|
// nowhere to show a refund: a reverse deal had no record. It is created here - from exactly what the screen
|
|
126
126
|
// already has (the node ticket plus the computed halves) - and lands in the same store as the buy flow, so the
|
|
127
127
|
// deal card, the recovery file and the XMR sweep all work off it.
|
|
@@ -496,7 +496,7 @@ export function derive(swap, now = nowReal()) {
|
|
|
496
496
|
if (swap.settlement) {
|
|
497
497
|
phase = swap.settlement.phase;
|
|
498
498
|
phaseLabel = Object.values(TERMINAL).find((x) => x.phase === swap.settlement.phase)?.label || "Settled";
|
|
499
|
-
// SWEEPING OUR OWN XMR AFTER A REFUND
|
|
499
|
+
// SWEEPING OUR OWN XMR AFTER A REFUND. On the reverse flow a refund leaves the
|
|
500
500
|
// user's coins on the swap's one-time address: the claimer's ETH came back, and nobody moved the XMR. They can
|
|
501
501
|
// only be taken by assembling the spend key from OUR half and the OTHER half that the chain revealed on
|
|
502
502
|
// settlement. While the revealed half is missing we do NOT grant the right - can.sweep stays false precisely
|
|
@@ -737,7 +737,7 @@ export function derive(swap, now = nowReal()) {
|
|
|
737
737
|
},
|
|
738
738
|
// What is real now and what is a simulation. The UI must show this, not guess.
|
|
739
739
|
// The EVM leg is simulated if and only if the deal's network is not switched to live. It used to stand as a
|
|
740
|
-
// hard true, and on a LIVE deal with a real escrow the screen wrote "EVM leg
|
|
740
|
+
// hard true, and on a LIVE deal with a real escrow the screen wrote "EVM leg... is still simulated" - i.e.
|
|
741
741
|
// lied, although the order existed in the contract. The mark comes from the network settings, not from a
|
|
742
742
|
// field in the deal: the field is set at creation, and deals created earlier still have "mock" there.
|
|
743
743
|
simulated: { evm: !isLiveNetwork(swap), xmr: !xmr.live },
|
package/engine/evm/amounts.js
CHANGED
|
@@ -25,7 +25,7 @@ export function trimTrailingZeros(text) {
|
|
|
25
25
|
// Amount for display and for the MAX button: truncation (not rounding) and at most 6 decimals.
|
|
26
26
|
//
|
|
27
27
|
// Why truncation: MAX must not insert an amount larger than the real balance - else the form
|
|
28
|
-
// rightly answers "Not enough
|
|
28
|
+
// rightly answers "Not enough..." and the MAX button leads into a dead end. Rounding up did
|
|
29
29
|
// exactly that: 0.0399187 -> 0.039919 > balance.
|
|
30
30
|
// Why 6 decimals: human precision, and exactly what the balance hint shows.
|
|
31
31
|
// Returns a NUMBER (for comparisons); the string for the input field is given by amountInputValue below.
|
|
@@ -46,7 +46,7 @@ export function floorAmount(value, decimals = 6) {
|
|
|
46
46
|
// and a dot - "1e-7" would turn into "17" (caught by a check, not by a user).
|
|
47
47
|
export function amountInputValue(value, decimals = 6) {
|
|
48
48
|
// Truncate first, then format: toFixed ROUNDS itself, and without truncation you got
|
|
49
|
-
// 0.039919 - that is, more than the balance, and MAX hit "Not enough
|
|
49
|
+
// 0.039919 - that is, more than the balance, and MAX hit "Not enough...".
|
|
50
50
|
const cut = floorAmount(value, decimals);
|
|
51
51
|
if (!Number.isFinite(cut) || cut <= 0) return "0";
|
|
52
52
|
// For dust we print all digits: else toFixed would round to the first non-zero digit.
|
package/engine/evm/asyncRoute.js
CHANGED
|
@@ -127,11 +127,11 @@ const knownChainsFor = (providerId) => asyncRouteChains(providerId || asyncRoute
|
|
|
127
127
|
/**
|
|
128
128
|
* WHICH WAY AN ASYNCHRONOUS NEED GOES FOR A NETWORK - as a VALUE, with a NAMED refusal.
|
|
129
129
|
*
|
|
130
|
-
* { ok: true, kind: "single"
|
|
131
|
-
* { ok: true, kind: "composition", legs: [liquidity, native]
|
|
130
|
+
* { ok: true, kind: "single",...route, need } - one provider carries the need all the way;
|
|
131
|
+
* { ok: true, kind: "composition", legs: [liquidity, native],... } - no single provider carries a NATIVE need,
|
|
132
132
|
* but a liquidity (wrapped) leg and a
|
|
133
133
|
* native-capable leg both serve the network;
|
|
134
|
-
* { ok: false, reason: "no-async-provider" | "no-native-async-provider"
|
|
134
|
+
* { ok: false, reason: "no-async-provider" | "no-native-async-provider",... } - a named refusal.
|
|
135
135
|
*
|
|
136
136
|
* The rule that matters: a provider that does not settle what the person needs is NEVER chosen as the sole provider
|
|
137
137
|
* for that need (a route that ends in WETH must not pass as native). It may only be a leg of a composition, and a
|
package/engine/evm/dex.js
CHANGED
|
@@ -610,7 +610,7 @@ export function dexLegVerdict(leg, requiredOutWei = null) {
|
|
|
610
610
|
//
|
|
611
611
|
// THERE ARE NO HUBS HERE ANY MORE: a detour via USDC/USDT is also a declared route, not a runtime search.
|
|
612
612
|
//
|
|
613
|
-
// Returns EITHER { ok: true
|
|
613
|
+
// Returns EITHER { ok: true,... } with numbers from the chain, OR { ok: false, why } in words. Numbers and "why
|
|
614
614
|
// not" are not returned together: showing a person both means asking him to guess which of the two answers to
|
|
615
615
|
// believe.
|
|
616
616
|
// ---------------------------------------------------------------------------
|
package/engine/evm/factory.js
CHANGED
|
@@ -18,7 +18,7 @@ export const FACTORY_METHODS = {
|
|
|
18
18
|
};
|
|
19
19
|
|
|
20
20
|
// The OrderCreated event topic. It grew the registry address, the provider and the signing key, and now carries
|
|
21
|
-
// `xmrAmount` in bulk
|
|
21
|
+
// `xmrAmount` in bulk:
|
|
22
22
|
// cast keccak "OrderCreated(address,address,address,bytes32,bytes32,bytes32,bytes32,bytes32,uint256,uint256,uint64,uint64,bytes32,address,address,address)"
|
|
23
23
|
// The topic lives in TWO places and both must match; a check pins them.
|
|
24
24
|
export const ORDER_CREATED_TOPIC =
|
package/engine/evm/fees.js
CHANGED
|
@@ -30,6 +30,68 @@ export function feeWeiFor(amountWei, feeBps) {
|
|
|
30
30
|
return (amount * bps) / 10000n; // DOWN, as in Solidity: amount * feeBps / 10000
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
// THE INVERSE OF A BUY'S TOTAL. A buy pays `p + floor(p*bps/10000)` and the person names the total; this returns the
|
|
34
|
+
// largest principal that still fits. The inequality is solved exactly, so a total that does not divide evenly keeps
|
|
35
|
+
// the rounding down of the fee formula instead of gaining a wei.
|
|
36
|
+
export function principalForTotal(totalWei, feeBps) {
|
|
37
|
+
const total = BigInt(totalWei);
|
|
38
|
+
const bps = BigInt(Number(feeBps));
|
|
39
|
+
if (total < 0n || !Number.isFinite(Number(feeBps)) || bps < 0n || bps > BigInt(MAX_FEE_BPS)) {
|
|
40
|
+
throw new Error("principal: invalid total or fee rate");
|
|
41
|
+
}
|
|
42
|
+
return ((total + 1n) * 10000n - 1n) / (10000n + bps);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const payoutBig = (value, { allowZero = true } = {}) => {
|
|
46
|
+
if (value === null || value === undefined || value === "") return null;
|
|
47
|
+
try {
|
|
48
|
+
const n = BigInt(value);
|
|
49
|
+
return n < 0n || (!allowZero && n === 0n) ? null : n;
|
|
50
|
+
} catch { return null; }
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* THE SALE'S TWO FIGURES BEFORE THE CLAIM. The escrow holds `amount`; `fee` and `claimTip` are separate fields. The
|
|
55
|
+
* guaranteed minimum is `amount - fee - claimTip` (a third party sends the claim and takes the tip); the payout when
|
|
56
|
+
* the seller sends it is `amount - fee`.
|
|
57
|
+
*/
|
|
58
|
+
export function salePayoutBeforeClaim({ amountWei, feeWei, claimTipWei = 0 } = {}) {
|
|
59
|
+
const amount = payoutBig(amountWei, { allowZero: false });
|
|
60
|
+
const fee = payoutBig(feeWei);
|
|
61
|
+
const tip = payoutBig(claimTipWei);
|
|
62
|
+
if (amount === null || fee === null || tip === null || fee > amount || fee + tip > amount) return null;
|
|
63
|
+
return {
|
|
64
|
+
amountWei: amount,
|
|
65
|
+
feeWei: fee,
|
|
66
|
+
claimTipWei: tip,
|
|
67
|
+
guaranteedMinimumWei: amount - fee - tip,
|
|
68
|
+
sellerClaimWei: amount - fee,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* THE SELLER'S ACTUAL PAYOUT AFTER A CONFIRMED CLAIM. `sender` is the contract's `msg.sender`, not `tx.from`: a claim
|
|
74
|
+
* routed through another contract has a different caller. A tip of zero pays `amount - fee` even when the caller is
|
|
75
|
+
* unknown; a positive tip pays `amount - fee` only when the claimer sent it, otherwise `amount - fee - claimTip`, and
|
|
76
|
+
* is unknown when the actual caller is not known. A promised tip is never reported as the seller's payout.
|
|
77
|
+
*/
|
|
78
|
+
export function salePayoutAfterClaim({ amountWei, feeWei, claimTipWei = 0, claimed = false, claimSucceeded = false,
|
|
79
|
+
sender = null, claimer = null } = {}) {
|
|
80
|
+
const amount = payoutBig(amountWei, { allowZero: false });
|
|
81
|
+
const fee = payoutBig(feeWei);
|
|
82
|
+
const tip = payoutBig(claimTipWei);
|
|
83
|
+
if (amount === null || fee === null || tip === null) return { outcome: "unknown", payoutWei: null };
|
|
84
|
+
if (!claimed || !claimSucceeded || fee > amount || fee + tip > amount) {
|
|
85
|
+
return { outcome: "unknown", payoutWei: null };
|
|
86
|
+
}
|
|
87
|
+
if (tip === 0n) return { outcome: "claimed", payoutWei: amount - fee };
|
|
88
|
+
const from = typeof sender === "string" ? sender.trim().toLowerCase() : "";
|
|
89
|
+
const to = typeof claimer === "string" ? claimer.trim().toLowerCase() : "";
|
|
90
|
+
if (!from || !to) return { outcome: "unknown", payoutWei: null };
|
|
91
|
+
if (from === to) return { outcome: "claimed", payoutWei: amount - fee };
|
|
92
|
+
return { outcome: "claimed", payoutWei: amount - fee - tip };
|
|
93
|
+
}
|
|
94
|
+
|
|
33
95
|
const sameAddr = (a, b) => String(a || "").toLowerCase() === String(b || "").toLowerCase();
|
|
34
96
|
const zeroAddr = (a) => !a || /^0x0{40}$/i.test(String(a));
|
|
35
97
|
|
package/engine/evm/funding.js
CHANGED
|
@@ -40,13 +40,14 @@ export function newSecret() {
|
|
|
40
40
|
// TWO DEADLINES THAT DO NOT COINCIDE: until readyBy the depositor marks readiness ("I see the XMR"), from t1 a
|
|
41
41
|
// claim is closed and anyone may refund. Coincidence would restore a window where both paths are valid and gas
|
|
42
42
|
// would decide the dispute.
|
|
43
|
-
export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, amountWei, salt, claimWindowSeconds = 3600, readyWindowSeconds = 14400, readyBy, t1 }) {
|
|
43
|
+
export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, amountWei, salt, claimWindowSeconds = 3600, readyWindowSeconds = 14400, readyBy, t1, nowSec = null }) {
|
|
44
44
|
// THE VIEW POINT IS ON THE REQUIRED LIST: without it the Monero address cannot be assembled from the order
|
|
45
45
|
// fields, and the one who learns about it would be the claimer, after funding.
|
|
46
46
|
for (const [k, v] of Object.entries({ commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker })) {
|
|
47
47
|
if (!v) throw new Error("order term not set: " + k);
|
|
48
48
|
}
|
|
49
|
-
const now =
|
|
49
|
+
const now = Number.isSafeInteger(Number(nowSec)) && Number(nowSec) > 0
|
|
50
|
+
? Number(nowSec) : Math.floor(Date.now() / 1000);
|
|
50
51
|
// DEADLINES MAY BE PASSED IN READY-MADE, AND THAT IS NECESSITY, NOT CONVENIENCE. They enter the canonical order
|
|
51
52
|
// context the proof is bound to, and the proof is computed BEFORE funding. Computing the deadlines here and now
|
|
52
53
|
// would put them AFTER the proof, so the proof would bind one set of deadlines while the contract gets another.
|
|
@@ -88,11 +89,23 @@ export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfCl
|
|
|
88
89
|
};
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
// Amount in wei from a human value
|
|
92
|
+
// Amount in wei from a human decimal value and the token decimals.
|
|
93
|
+
//
|
|
94
|
+
// The value must carry its exact digits. A significant digit beyond `decimals` is a refusal; it is never sliced
|
|
95
|
+
// away, because that would fund a different amount from the signed one. Trailing zeroes beyond the decimals are
|
|
96
|
+
// not significant and are accepted.
|
|
92
97
|
export function toWei(human, decimals = 18) {
|
|
93
|
-
const
|
|
94
|
-
const
|
|
95
|
-
|
|
98
|
+
const text = String(human);
|
|
99
|
+
const match = /^(?:0|[1-9]\d*)(?:\.(\d+))?$/.exec(text);
|
|
100
|
+
if (!match) throw new Error("the amount is not a decimal number");
|
|
101
|
+
const dec = Number(decimals);
|
|
102
|
+
if (!Number.isInteger(dec) || dec < 0) throw new Error("the decimals are not a whole number");
|
|
103
|
+
const fraction = match[1] || "";
|
|
104
|
+
if (fraction.length > dec && /[1-9]/.test(fraction.slice(dec))) {
|
|
105
|
+
throw new Error("the amount has more decimal digits than the token");
|
|
106
|
+
}
|
|
107
|
+
const kept = fraction.slice(0, dec).padEnd(dec, "0");
|
|
108
|
+
return BigInt(text.split(".")[0]) * 10n ** BigInt(dec) + BigInt(kept || "0");
|
|
96
109
|
}
|
|
97
110
|
|
|
98
111
|
// THE ONE NATIVE AMOUNT OF A TOKEN-FUNDED ORDER.
|
|
@@ -111,13 +124,16 @@ export function escrowNativeWei({ quote = null, nativeDecimals = 18 } = {}) {
|
|
|
111
124
|
if (!Number.isFinite(n) || n <= 0) {
|
|
112
125
|
return { ok: false, code: "native-amount-unread", reason: "the quote's native amount is not a positive number" };
|
|
113
126
|
}
|
|
127
|
+
// A number at or above the safe-integer range has already lost digits before this function sees it.
|
|
128
|
+
if (typeof raw === "number" && Math.abs(raw) > Number.MAX_SAFE_INTEGER) {
|
|
129
|
+
return { ok: false, code: "native-amount-unread", reason: "the quote's native amount is not a safe number" };
|
|
130
|
+
}
|
|
114
131
|
const dec = Number(nativeDecimals);
|
|
115
132
|
if (!Number.isInteger(dec) || dec < 0) {
|
|
116
133
|
return { ok: false, code: "native-amount-unread", reason: "the native decimals are not a whole number" };
|
|
117
134
|
}
|
|
118
|
-
// THE QUOTE'S OWN DIGITS
|
|
119
|
-
|
|
120
|
-
const text = /e/i.test(String(raw)) ? n.toFixed(18) : String(raw);
|
|
135
|
+
// THE QUOTE'S OWN DIGITS. A canonical decimal string keeps them; exponent form is not a canonical amount.
|
|
136
|
+
const text = String(raw);
|
|
121
137
|
// DECIMAL DIGITS ONLY. BigInt accepts "0x10", and a native amount read as a hex literal would silently become
|
|
122
138
|
// sixteen times the token amount; a quote carries decimal text.
|
|
123
139
|
if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(text)) {
|
|
@@ -144,17 +160,12 @@ export function escrowNativeWei({ quote = null, nativeDecimals = 18 } = {}) {
|
|
|
144
160
|
// its gas is part of what the wallet has to be able to afford. One constant, one source (the check ties the
|
|
145
161
|
// reserve's copy to this declaration).
|
|
146
162
|
export const GAS_CREATE_ORDER_AND_FUND = 700_000n;
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
// only knows createOrderAndFund. The old lock(bytes) call and its gas constant are gone: the deposit rides in the
|
|
150
|
-
// same transaction.
|
|
163
|
+
// There is no separate "create without a deposit" constant. Each order escrow is an EIP-1167 clone, the terms live in
|
|
164
|
+
// the clone code, and the factory only has createOrderAndFund. The deposit rides in the same transaction.
|
|
151
165
|
|
|
152
|
-
// The OrderCreated event: topic0
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
// second copy here, which caused a real defect: after the OrderCreated field set changed, the stale copy failed to
|
|
156
|
-
// find the event and the escrow address silently fell back to the prediction - so the "address from the receipt"
|
|
157
|
-
// check stopped working without a word.
|
|
166
|
+
// The OrderCreated event: topic0 comes from the actual signature. Topics are [topic0, escrow, locker, claimer].
|
|
167
|
+
// Data carries both commitments, both points, the amount, readyBy, t1 and the salt.
|
|
168
|
+
// The event topic comes from the factory module, not a second copy here.
|
|
158
169
|
|
|
159
170
|
// The ACTUAL escrow address from the receipt. Returns null when the event is absent (the transaction is not in a
|
|
160
171
|
// block, or the factory is another) - then the caller must say so aloud rather than substitute a guess.
|
|
@@ -209,46 +220,50 @@ async function waitReceipt(receiptReader, hash, { tries = 12, delayMs = 1500 } =
|
|
|
209
220
|
|
|
210
221
|
// The full funding path. Steps are returned outward so the interface can show each one: predict is a free call,
|
|
211
222
|
// createOrder and lock are transactions in the user's wallet.
|
|
212
|
-
export async function fundOrder({ factory, locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, salt: providedSalt, amountWei, amountLabel, claimWindowSeconds, readyWindowSeconds, readyBy, t1, quote, call, send, receipt, onStep, onPredicted }) {
|
|
223
|
+
export async function fundOrder({ factory, locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, salt: providedSalt, amountWei, amountLabel, claimWindowSeconds, readyWindowSeconds, readyBy, t1, quote, call, send, receipt, onStep, onPredicted, nowSec = null }) {
|
|
213
224
|
if (!factory) throw new Error("no escrow factory address set for this network");
|
|
214
225
|
if (!locker) throw new Error("no EVM wallet connected: there is nobody to deposit");
|
|
215
226
|
if (!claimer) throw new Error("the order recipient (claimer) is not set");
|
|
216
227
|
if (locker.toLowerCase() === claimer.toLowerCase()) {
|
|
217
228
|
throw new Error("locker and claimer must not coincide: the contract rejects such an order");
|
|
218
229
|
}
|
|
219
|
-
// A
|
|
220
|
-
//
|
|
221
|
-
// quote is a NAMED refusal, not a silent funding of the wrong amount.
|
|
230
|
+
// A signed quote is mandatory. It carries the fee, the registry address and the provider. Without it, the order
|
|
231
|
+
// cannot be created, and funding would use the wrong amount.
|
|
222
232
|
if (!quote || typeof quote !== "object") throw new Error("a signed quote is required: the factory takes a quote, not bare order terms");
|
|
233
|
+
// THE QUOTE'S EXPIRY IS JUDGED AT THE FUNDING BOUNDARY. A device clock behind the chain lets an expired quote
|
|
234
|
+
// reach createOrderAndFund, which reverts after the fee is paid. The caller passes the chain time; when it is
|
|
235
|
+
// absent this is a test seam and the device clock remains the only clock available.
|
|
236
|
+
const fundingNowSec = Number.isSafeInteger(Number(nowSec)) && Number(nowSec) > 0
|
|
237
|
+
? Number(nowSec) : Math.floor(Date.now() / 1000);
|
|
238
|
+
const validUntil = Number(quote.validUntil);
|
|
239
|
+
if (Number.isSafeInteger(validUntil) && validUntil > 0 && validUntil <= fundingNowSec) {
|
|
240
|
+
const error = new Error("the signed quote has expired at the funding boundary");
|
|
241
|
+
error.code = "quote-expired";
|
|
242
|
+
error.params = { validUntil, now: fundingNowSec, step: "lock" };
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
223
245
|
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
// The salt determines the escrow address and must exist
|
|
246
|
+
// Commitments and points are mandatory. Without them the order can be created but cannot be claimed, and its link
|
|
247
|
+
// to the Monero address cannot be proven.
|
|
248
|
+
// The salt determines the escrow address and must exist before the terms are assembled. The terms also go to predict.
|
|
227
249
|
const salt = providedSalt || newSecret(); // CREATE2 salt: determines the escrow address
|
|
228
250
|
const terms = testOrderTerms({
|
|
229
251
|
locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker,
|
|
230
|
-
amountWei, salt, claimWindowSeconds, readyWindowSeconds, readyBy, t1,
|
|
252
|
+
amountWei, salt, claimWindowSeconds, readyWindowSeconds, readyBy, t1, nowSec,
|
|
231
253
|
});
|
|
232
|
-
//
|
|
233
|
-
//
|
|
234
|
-
//
|
|
235
|
-
//
|
|
236
|
-
// escrow. The parameters are destructured, so there is no `order` variable here; the local is named `salt` and
|
|
237
|
-
// the input `providedSalt` to avoid a temporal-dead-zone self-reference.
|
|
238
|
-
// 1) the escrow address is visible BEFORE creation - that is the point of the factory
|
|
254
|
+
// Reuse the salt from the deal when it already has one. The salt determines the escrow address, so a new salt
|
|
255
|
+
// creates a new escrow while the record keeps the old address. Reuse also makes a retry hit the same address.
|
|
256
|
+
// The parameters are destructured, so the local is `salt` and the input is `providedSalt`.
|
|
257
|
+
// 1) the escrow address is visible before creation. That is the point of the factory.
|
|
239
258
|
onStep?.("computing the escrow address");
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
// THE DEPOSITOR'S FIELDS GO AS SEPARATE FACTORY ARGUMENTS, BUT THEY ARE IN THE SIGNED SET. Since quote protocol v10
|
|
245
|
-
// the factory signs them; the overwrite below must reproduce the signed values, or the digest check rejects the
|
|
246
|
-
// creation.
|
|
259
|
+
// The prediction fields must match the creation fields byte for byte. Both paths use the same terms, so they can
|
|
260
|
+
// diverge only when one place is edited alone. Keep one source of fields.
|
|
261
|
+
// The depositor's fields go as separate factory arguments, but they are in the signed set. The overwrite below must
|
|
262
|
+
// reproduce the signed values, or the digest check rejects the order.
|
|
247
263
|
const quoteEnc = { ...quote, commitHalfLocker: terms.commitHalfLocker, edPointLocker: terms.edPointLocker, edViewPointLocker: terms.edViewPointLocker };
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
//
|
|
251
|
-
// point can be funded beside a proof for another, and the claim reveals a half that does not open the address.
|
|
264
|
+
// Quote and terms must agree. A divergence moves the escrow address and signs the wrong order.
|
|
265
|
+
// The counterparty's spend half is part of that check. The proof is checked against the counterparty side, while
|
|
266
|
+
// the factory encodes the signed quote.
|
|
252
267
|
const sameValue = (a, b) => String(a === undefined || a === null ? "" : a).replace(/^0x/i, "").toLowerCase()
|
|
253
268
|
=== String(b === undefined || b === null ? "" : b).replace(/^0x/i, "").toLowerCase();
|
|
254
269
|
for (const name of ["locker", "claimer", "amount", "readyBy", "t1", "salt", "commitHalfClaimer", "edPointClaimer",
|
|
@@ -283,21 +298,14 @@ export async function fundOrder({ factory, locker, claimer, commitHalfLocker, co
|
|
|
283
298
|
}
|
|
284
299
|
const escrowState = escrowStateVerdict({ status: stateRead.status, error: stateRead.error, address: escrow });
|
|
285
300
|
if (escrowState.blocks) throw new Error("signature not started: " + escrowState.reason);
|
|
286
|
-
// 2)
|
|
301
|
+
// 2) One transaction creates the order and funds it.
|
|
287
302
|
//
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
//
|
|
291
|
-
//
|
|
292
|
-
//
|
|
293
|
-
//
|
|
294
|
-
// one place in the project, and a second formatter here would diverge from it. The label is short on purpose: it
|
|
295
|
-
// is printed ON A BUTTON and must fit one line.
|
|
296
|
-
// THE FEE IS PART OF VALUE, AND THAT IS THE MAIN CONSEQUENCE OF ITS INTRODUCTION. The contract requires
|
|
297
|
-
// depositing EXACTLY `amount + fee`, so funding for the order amount alone is rejected - and rejected after
|
|
298
|
-
// signing, because the check lives in the contract. The order amount (`amount` in the terms) does NOT change: it
|
|
299
|
-
// is exactly what the claimer receives and what enters the terms hash. The fee is added on top, taken at claim,
|
|
300
|
-
// returned on refund.
|
|
303
|
+
// A failure rolls back creation, and one signature is enough. The sender becomes the locker, so the refund address
|
|
304
|
+
// always belongs to the payer.
|
|
305
|
+
// The amount is shown in ETH, not wei, and arrives as a ready string. Formatting lives in one place.
|
|
306
|
+
// The fee is part of the value. The contract requires exactly `amount + fee`, so funding the order amount alone is
|
|
307
|
+
// rejected after signing. The order amount is what the claimer receives and what enters the terms hash. The fee is
|
|
308
|
+
// added on top, taken at claim and returned on refund.
|
|
301
309
|
onStep?.("reading the escrow fee from the signed quote");
|
|
302
310
|
// THE FEE COMES FROM THE QUOTE AND IS MIRROR-CHECKED. Direction is already accounted for: a buy is amount + fee
|
|
303
311
|
// (on top), a sell is amount (the fee is deducted from the claimer's payout).
|
|
@@ -322,14 +330,11 @@ export async function fundOrder({ factory, locker, claimer, commitHalfLocker, co
|
|
|
322
330
|
gas: GAS_CREATE_ORDER_AND_FUND,
|
|
323
331
|
});
|
|
324
332
|
|
|
325
|
-
// 2b)
|
|
326
|
-
// and the factory code match
|
|
327
|
-
// the old one - and the deal looks broken (deadlines unreadable, no refund button). That is exactly what
|
|
328
|
-
// happened. A divergence from the prediction is named aloud: it is a sign of a real error.
|
|
333
|
+
// 2b) The escrow address comes from the receipt, not from the prediction. The prediction is right only when the
|
|
334
|
+
// salt and the factory code match. A divergence is a sign of a real error and must be named.
|
|
329
335
|
let actualEscrow = null;
|
|
330
|
-
//
|
|
331
|
-
// independent of the Monero node.
|
|
332
|
-
// not visible outside, and it must always be returned.
|
|
336
|
+
// The escrow birth block is the height where the deal exists on chain. It is the only source of that height
|
|
337
|
+
// independent of the Monero node. Declare it outside the branch so every path can return it.
|
|
333
338
|
let birthBlock = null;
|
|
334
339
|
let verdict = { status: "pending", reason: "no-receipt-reader" };
|
|
335
340
|
if (typeof receipt === "function") {
|
package/engine/evm/gasReserve.js
CHANGED
|
@@ -63,6 +63,16 @@ export function orderGasReserveWei({ gasPriceWei, readyGasLimit = ORDER_READY_GA
|
|
|
63
63
|
return gp * (ready + refund + deposit) + extra;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
// THE FUNDING RESERVE FOR MAX. The deposit is a separate transaction (`createOrderAndFund`) with its own gas limit;
|
|
67
|
+
// the balance must keep that limit times the maximum fee per gas. `orderGasReserveWei` remains the mark/refund
|
|
68
|
+
// reserve and does NOT include this deposit by default.
|
|
69
|
+
export function fundingGasReserveWei({ gasLimit = GAS_CREATE_ORDER_AND_FUND, maxFeePerGasWei } = {}) {
|
|
70
|
+
const limit = toBig(gasLimit);
|
|
71
|
+
const maxFee = toBig(maxFeePerGasWei);
|
|
72
|
+
if (limit === null || limit <= 0n || maxFee === null || maxFee <= 0n) return null;
|
|
73
|
+
return limit * maxFee;
|
|
74
|
+
}
|
|
75
|
+
|
|
66
76
|
// DISPLAY IN BOTH UNITS. A person coming from USDC has no sense of ETH scale, so the reserve is shown both
|
|
67
77
|
// in ETH and in dollars. The dollar is an estimate at the live native rate; no rate - no estimate (null), not a made-up one.
|
|
68
78
|
export function gasReserveDisplay({ reserveWei, nativeUsd, decimals = 18 } = {}) {
|
package/engine/evm/index.js
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
restoreInjected,
|
|
24
24
|
} from "./session.js";
|
|
25
25
|
import { discoverWallets } from "./injected.js";
|
|
26
|
-
// fundOrder needs a LOCAL name: `export * from
|
|
26
|
+
// fundOrder needs a LOCAL name: `export * from./funding.js` only re-exports and does not create a local
|
|
27
27
|
// variable, so fundOrderLive called a missing name and crashed.
|
|
28
28
|
import { fundOrder } from "./funding.js";
|
|
29
29
|
export * from "./factory.js";
|
|
@@ -42,7 +42,7 @@ export * from "./asyncRoute.js";
|
|
|
42
42
|
// key as the page. Screens do not need it; they read status()/isConnected().
|
|
43
43
|
export { address, balanceOf, chainIdOf, connect, disconnect, isConnected, refreshBalances, restore, status, subscribe, switchChain, currentProvider };
|
|
44
44
|
export { connectInjected, restoreInjected };
|
|
45
|
-
// IMPORTANT: this is an import, not a re-export. `export { X } from
|
|
45
|
+
// IMPORTANT: this is an import, not a re-export. `export { X } from...` only re-exports and does NOT create
|
|
46
46
|
// a local name, while fundOrderLive uses sendTransaction/readContract directly - this already broke twice.
|
|
47
47
|
import { sendTransaction, readContract, readReceipt, readCode } from "./session.js";
|
|
48
48
|
export { sendTransaction, readContract, readReceipt, readCode };
|
package/engine/evm/prices.js
CHANGED
|
@@ -38,6 +38,7 @@ async function rpc(chain, method, params = []) {
|
|
|
38
38
|
return j.result;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
// ABI words are positional 32-byte values.
|
|
41
42
|
const word = (data, i) => BigInt("0x" + String(data).slice(2).slice(i * 64, (i + 1) * 64));
|
|
42
43
|
|
|
43
44
|
// ABI string decode: [offset][length][bytes]. Needed to tell the ETH/USD feed from another one. TextDecoder,
|
|
@@ -68,12 +69,14 @@ export async function nativeUsd(chain, { force = false } = {}) {
|
|
|
68
69
|
]);
|
|
69
70
|
const desc = decodeString(descHex);
|
|
70
71
|
const answer = word(roundHex, 1);
|
|
72
|
+
// Chainlink timestamps are seconds. Date.now() below is milliseconds.
|
|
71
73
|
const updatedAt = Number(word(roundHex, 3)) * 1000;
|
|
72
74
|
const decimals = Number(feed.decimals || 8);
|
|
73
75
|
const value = Number(answer) / 10 ** decimals;
|
|
74
76
|
const fresh = updatedAt > 0 && Date.now() - updatedAt < MAX_AGE_MS;
|
|
75
77
|
const sane = value >= (feed.min || 0.01) && value <= (feed.max || 1e7);
|
|
76
78
|
if (desc !== feed.pair || !fresh || !sane) {
|
|
79
|
+
// A failed or stale read is cached as null for CACHE_MS. That avoids a retry storm on a healthy feed.
|
|
77
80
|
return put(key, null); // null, not "roughly this": silence is more honest than a guess
|
|
78
81
|
}
|
|
79
82
|
return put(key, { usd: value, updatedAt, source: "chainlink", pair: desc });
|