@ninsei-labs/sdk 0.56.1 → 0.58.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +78 -28
  4. package/THIRD_PARTY_NOTICES.md +176 -2
  5. package/assets/vendors/MANIFEST.json +1 -13
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +20 -46
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/rfqSource.js +6 -133
  12. package/engine/core/swap.js +8 -8
  13. package/engine/evm/asyncRoute.js +1 -1
  14. package/engine/evm/claimGas.js +2 -1
  15. package/engine/evm/escrow.js +13 -8
  16. package/engine/evm/factory.js +11 -6
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +5 -6
  19. package/engine/evm/session.js +48 -279
  20. package/engine/monero/address.js +15 -33
  21. package/engine/monero/keys.js +124 -0
  22. package/engine/monero/mnemonic.js +104 -0
  23. package/engine/monero/scan.js +121 -28
  24. package/engine/monero/wallet.js +31 -68
  25. package/engine/monero/wordlist.en.js +210 -0
  26. package/engine/recovery/restore.js +9 -9
  27. package/engine/sdk/bridge.js +9 -187
  28. package/engine/ui/walletModal.js +7 -27
  29. package/index.d.ts +234 -262
  30. package/package.json +7 -6
  31. package/src/actions.mjs +8 -5
  32. package/src/codes.mjs +17 -0
  33. package/src/config.mjs +17 -54
  34. package/src/engine.mjs +9 -6
  35. package/src/feeEstimate.mjs +11 -4
  36. package/src/http.mjs +4 -1
  37. package/src/index.mjs +24 -45
  38. package/src/legs/kyber.mjs +23 -0
  39. package/src/lock.mjs +1 -0
  40. package/src/order.mjs +110 -22
  41. package/src/primitives.mjs +4 -5
  42. package/src/probes.mjs +9 -3
  43. package/src/public/networks.d.ts +45 -0
  44. package/src/public/networks.mjs +10 -1
  45. package/src/public/recovery.d.ts +17 -1
  46. package/src/public/recovery.mjs +1 -0
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quotePolicy.mjs +25 -0
  49. package/src/quotes.mjs +109 -765
  50. package/src/readyWindow.mjs +76 -0
  51. package/src/recovery-key.mjs +71 -16
  52. package/src/recovery.mjs +11 -28
  53. package/src/relayClaim.mjs +132 -0
  54. package/src/relayFeatures.mjs +25 -13
  55. package/src/relayFirmClient.mjs +36 -7
  56. package/src/relayQuote.mjs +92 -11
  57. package/src/relayView.mjs +3 -3
  58. package/src/swap-flow.mjs +146 -60
  59. package/src/swaps.mjs +521 -357
  60. package/src/sweep-action.mjs +73 -0
  61. package/src/sweep-restore.mjs +8 -4
  62. package/src/sweep.mjs +12 -2
  63. package/src/version.mjs +1 -1
  64. package/src/xmr-arrival.mjs +328 -29
  65. package/src/xmrAmountPolicy.mjs +35 -0
  66. package/assets/vendors/atomic/atomic-browser.js +0 -24
  67. package/assets/vendors/monero/monero-js-browser.js +0 -58
  68. package/assets/vendors/monero-js/LICENSE +0 -9
  69. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
  70. package/engine/atomic/order-client.js +0 -56
  71. package/engine/atomic/order-worker.js +0 -156
  72. package/engine/evm/asyncExec.js +0 -577
  73. package/engine/evm/asyncLegs.js +0 -308
@@ -0,0 +1,124 @@
1
+ // MONERO KEYS FROM A SEED, WITHOUT THE VENDORED MONERO-JS BUNDLE.
2
+ //
3
+ // Monero is edwards25519, but its key derivation is not the BIP39/BIP32 one:
4
+ // spend secret = sc_reduce32(seed)
5
+ // view secret = sc_reduce32(keccak256(spend secret))
6
+ // public keys = secret * G (compressed)
7
+ // The subaddress formula is the Monero one: m = Hs("SubAddr\0" || view secret || account || index), then
8
+ // (spend public + m*G, view secret * that public point).
9
+ //
10
+ // The primitives are the package's own: @noble/curves for ed25519 and @noble/hashes for keccak. No new dependency
11
+ // and no second implementation of the curve are introduced by this module.
12
+ import { ed25519, keccak256 } from "../../src/primitives.mjs";
13
+
14
+ const ORDER = ed25519.Point.Fn.ORDER;
15
+ const SCALAR_BYTES = 32;
16
+
17
+ function toBigIntLE(bytes) {
18
+ let value = 0n;
19
+ for (let i = bytes.length - 1; i >= 0; i -= 1) value = (value << 8n) | BigInt(bytes[i]);
20
+ return value;
21
+ }
22
+
23
+ function toBytesLE(value, width = SCALAR_BYTES) {
24
+ const out = new Uint8Array(width);
25
+ let n = value;
26
+ for (let i = 0; i < width; i += 1) {
27
+ out[i] = Number(n & 0xffn);
28
+ n >>= 8n;
29
+ }
30
+ return out;
31
+ }
32
+
33
+ function reduce(bytes) {
34
+ if (bytes.length > 64) throw new Error("scalar is longer than 64 bytes");
35
+ const padded = new Uint8Array(64);
36
+ padded.set(bytes);
37
+ return toBytesLE(toBigIntLE(padded) % ORDER);
38
+ }
39
+
40
+ function bytesOf(value) {
41
+ if (value instanceof Uint8Array) return value;
42
+ if (value && value.buffer instanceof ArrayBuffer) return new Uint8Array(value);
43
+ return Uint8Array.from(value || []);
44
+ }
45
+
46
+ function hexOf(bytes) {
47
+ let out = "";
48
+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
49
+ return out;
50
+ }
51
+
52
+ function pointOf(bytes) {
53
+ return ed25519.Point.fromHex(hexOf(bytes));
54
+ }
55
+
56
+ function publicOf(secret) {
57
+ return ed25519.Point.BASE.multiply(toBigIntLE(secret)).toBytes();
58
+ }
59
+
60
+ function uint32LE(value) {
61
+ if (!Number.isSafeInteger(value) || value < 0 || value >= 2 ** 32) throw new Error("invalid subaddress index");
62
+ const out = new Uint8Array(4);
63
+ out[0] = value & 0xff;
64
+ out[1] = (value >>> 8) & 0xff;
65
+ out[2] = (value >>> 16) & 0xff;
66
+ out[3] = (value >>> 24) & 0xff;
67
+ return out;
68
+ }
69
+
70
+ const SUBADDR_PREFIX = new TextEncoder().encode("SubAddr\0");
71
+
72
+ function subaddressKeys({ privateView, publicSpend }, index, account) {
73
+ if (index === 0 && account === 0) return { publicSpendKey: publicSpend, publicViewKey: publicOf(privateView) };
74
+ const buffer = new Uint8Array(SUBADDR_PREFIX.length + SCALAR_BYTES + 8);
75
+ buffer.set(SUBADDR_PREFIX, 0);
76
+ buffer.set(privateView, SUBADDR_PREFIX.length);
77
+ buffer.set(uint32LE(account), SUBADDR_PREFIX.length + SCALAR_BYTES);
78
+ buffer.set(uint32LE(index), SUBADDR_PREFIX.length + SCALAR_BYTES + 4);
79
+ const scalar = reduce(keccak256(buffer));
80
+ const publicSpendKey = pointOf(publicSpend).add(ed25519.Point.BASE.multiply(toBigIntLE(scalar))).toBytes();
81
+ const publicViewKey = pointOf(publicSpendKey).multiply(toBigIntLE(privateView)).toBytes();
82
+ return { publicSpendKey, publicViewKey };
83
+ }
84
+
85
+ export class Wallet {
86
+ #privateSpend;
87
+ #privateView;
88
+ #publicSpend;
89
+ #publicView;
90
+
91
+ constructor(privateSpend) {
92
+ if (!(privateSpend instanceof Uint8Array) || privateSpend.length !== SCALAR_BYTES) {
93
+ throw new Error("invalid private spend key");
94
+ }
95
+ if (toBigIntLE(privateSpend) >= ORDER) throw new Error("invalid private spend key");
96
+ this.#privateSpend = privateSpend;
97
+ this.#privateView = reduce(keccak256(privateSpend));
98
+ this.#publicSpend = publicOf(privateSpend);
99
+ this.#publicView = publicOf(this.#privateView);
100
+ }
101
+
102
+ get privateSpendKey() { return this.#privateSpend; }
103
+ get privateViewKey() { return this.#privateView; }
104
+ get publicSpendKey() { return this.#publicSpend; }
105
+ get publicViewKey() { return this.#publicView; }
106
+
107
+ subaddress(index = 0, account = 0) {
108
+ return subaddressKeys({ privateView: this.#privateView, publicSpend: this.#publicSpend }, index, account);
109
+ }
110
+ }
111
+
112
+ export function fromSeed(seed) {
113
+ const bytes = bytesOf(seed);
114
+ return new Wallet(reduce(bytes.length === SCALAR_BYTES ? bytes : keccak256(bytes)));
115
+ }
116
+
117
+ export function fromPrivateSpendKey(key) {
118
+ return new Wallet(bytesOf(key));
119
+ }
120
+
121
+ export async function initEcc() {
122
+ // The noble primitives are ready on import; the old async libsodium initialiser is gone.
123
+ return undefined;
124
+ }
@@ -0,0 +1,104 @@
1
+ // MONERO MNEMONIC, WITHOUT A VENDORED LIBRARY.
2
+ //
3
+ // Monero uses its own 1626-word list and a checksum over the first three letters of the 24 payload words. The
4
+ // algorithm is fixed and small; `@noble` primitives are not involved. Keeping it here removes the old monero-js
5
+ // bundle from the package and leaves one wordlist, one encoder and one decoder.
6
+ import { randomBytes } from "../../src/primitives.mjs";
7
+ import { WORDLIST } from "./wordlist.en.js";
8
+
9
+ const WORD_COUNT = 24;
10
+ const CHECKSUM_WORD_COUNT = 25;
11
+ const ENTROPY_BYTES = 32;
12
+ const PREFIX = 3;
13
+ const WORD_INDEX = new Map(WORDLIST.map((word, index) => [word, index]));
14
+
15
+ const CRC_TABLE = (() => {
16
+ const table = new Uint32Array(256);
17
+ for (let n = 0; n < 256; n += 1) {
18
+ let c = n;
19
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
20
+ table[n] = c >>> 0;
21
+ }
22
+ return table;
23
+ })();
24
+
25
+ function crc32(bytes) {
26
+ let c = 0xffffffff;
27
+ for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
28
+ return (c ^ 0xffffffff) >>> 0;
29
+ }
30
+
31
+ function wordsToChunk(one, two, three) {
32
+ const n = WORDLIST.length;
33
+ const a = WORD_INDEX.get(one);
34
+ const b = WORD_INDEX.get(two);
35
+ const c = WORD_INDEX.get(three);
36
+ if (a === undefined || b === undefined || c === undefined) throw new Error("invalid mnemonic word");
37
+ // The word order encodes a value in a mixed radix; the inverse is in chunkToWords.
38
+ return a + n * (((b - a) % n + n) % n) + n * n * (((c - b) % n + n) % n);
39
+ }
40
+
41
+ function chunkToWords(value) {
42
+ const n = WORDLIST.length;
43
+ const one = value % n;
44
+ const two = (Math.floor(value / n) + one) % n;
45
+ const three = (Math.floor(Math.floor(value / n) / n) + two) % n;
46
+ return [WORDLIST[one], WORDLIST[two], WORDLIST[three]];
47
+ }
48
+
49
+ function checksumWord(words) {
50
+ const prefix = words.map((word) => word.slice(0, PREFIX)).join("");
51
+ return words[crc32(new TextEncoder().encode(prefix)) % words.length];
52
+ }
53
+
54
+ function validateWords(words) {
55
+ return (words.length === WORD_COUNT || words.length === CHECKSUM_WORD_COUNT)
56
+ && words.every((word) => WORD_INDEX.has(word));
57
+ }
58
+
59
+ export function encode(entropy) {
60
+ const bytes = entropy instanceof Uint8Array ? entropy : Uint8Array.from(entropy);
61
+ if (bytes.length !== ENTROPY_BYTES) throw new Error("invalid entropy length");
62
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
63
+ const words = [];
64
+ for (let i = 0; i < bytes.length; i += 4) words.push(...chunkToWords(view.getUint32(i, true)));
65
+ return words.join(" ");
66
+ }
67
+
68
+ export function encodeWithChecksum(entropy) {
69
+ const words = encode(entropy).split(" ");
70
+ words.push(checksumWord(words));
71
+ return words.join(" ");
72
+ }
73
+
74
+ export function generate() {
75
+ return encode(randomBytes(ENTROPY_BYTES));
76
+ }
77
+
78
+ export function generateWithChecksum() {
79
+ return encodeWithChecksum(randomBytes(ENTROPY_BYTES));
80
+ }
81
+
82
+ export function decode(mnemonic) {
83
+ const words = String(mnemonic || "").trim().split(/\s+/).filter(Boolean);
84
+ if (!validateWords(words)) throw new Error("invalid mnemonic phrase (length or words)");
85
+ if (words.length === CHECKSUM_WORD_COUNT) {
86
+ const payload = words.slice(0, WORD_COUNT);
87
+ if (words[WORD_COUNT] !== checksumWord(payload)) throw new Error("invalid mnemonic checksum");
88
+ }
89
+ const entropy = new Uint8Array(ENTROPY_BYTES);
90
+ const view = new DataView(entropy.buffer);
91
+ const count = Math.min(words.length, WORD_COUNT);
92
+ for (let i = 0; i < count / 3; i += 1) {
93
+ view.setUint32(i * 4, wordsToChunk(words[i * 3], words[i * 3 + 1], words[i * 3 + 2]), true);
94
+ }
95
+ return entropy;
96
+ }
97
+
98
+ export function isValid(mnemonic) {
99
+ try { decode(mnemonic); return true; } catch { return false; }
100
+ }
101
+
102
+ export function toSeed(mnemonic) {
103
+ return decode(mnemonic);
104
+ }
@@ -144,17 +144,72 @@ export function derivedOutputKey(derivation, outputIndex, spendPubHex) {
144
144
 
145
145
  // Helper: the tx public key sits in the transaction extra, tag 0x01, 32 bytes. We read extra as is - the same
146
146
  // parse the wallet does. extra arrives from the node as a BYTE ARRAY (not hex), so both forms are accepted.
147
- export function txPublicKeyFromExtra(extra) {
147
+ //
148
+ // MONERO'S EXTRA IS A TAGGED SEQUENCE, NOT A FIXED LAYOUT. The tags we must know here:
149
+ // 0x00 padding - a run of zero bytes (the tag itself is one of them), no length field;
150
+ // 0x01 public key - 32 bytes;
151
+ // 0x02 nonce - varint length, then that many bytes;
152
+ // 0x03 merge mining - a length-prefixed string holding varint depth + 32-byte hash;
153
+ // 0x04 additional - varint count, then count * 32-byte public keys, ONE PER OUTPUT INDEX.
154
+ // The old parser treated 0x00 as an additional key and skipped it with `1 + b[i+1]`, and it stopped at 0x04.
155
+ // A subaddress payment in a mixed transaction then looked absent: the main key does not derive that output.
156
+ function readExtraVarint(bytes, at) {
157
+ let value = 0n;
158
+ let shift = 0n;
159
+ let i = at;
160
+ for (let count = 0; count < 10 && i < bytes.length; count++) {
161
+ const byte = bytes[i++];
162
+ value |= BigInt(byte & 0x7f) << shift;
163
+ if ((byte & 0x80) === 0) return { value, next: i };
164
+ shift += 7n;
165
+ }
166
+ return null;
167
+ }
168
+
169
+ /** The transaction keys in `extra`: the main key(s) and the per-output additional keys (tag 0x04). */
170
+ export function txKeysFromExtra(extra) {
148
171
  const b = Array.isArray(extra) ? Uint8Array.from(extra) : hexToBytes(extra);
172
+ const txPublicKeys = [];
173
+ const additionalPublicKeys = [];
149
174
  let i = 0;
150
175
  while (i < b.length) {
151
- const tag = b[i];
152
- if (tag === 0x01) return bytesToHex(b.subarray(i + 1, i + 33));
153
- if (tag === 0x02) { i += 1 + b[i + 1]; continue; } // nonce
154
- if (tag === 0x00) { i += 1 + b[i + 1]; continue; } // additional public key
155
- return null; // unknown tag: we do not guess
176
+ const tag = b[i++];
177
+ if (tag === 0x00) {
178
+ // Padding is a run of zeros; the next non-zero byte is the next tag (or the end).
179
+ while (i < b.length && b[i] === 0x00) i++;
180
+ continue;
181
+ }
182
+ if (tag === 0x01) {
183
+ if (i + 32 > b.length) break;
184
+ txPublicKeys.push(bytesToHex(b.subarray(i, i + 32)));
185
+ i += 32;
186
+ continue;
187
+ }
188
+ if (tag === 0x02 || tag === 0x03) {
189
+ const size = readExtraVarint(b, i);
190
+ if (!size || size.value > BigInt(b.length - size.next)) break;
191
+ i = size.next + Number(size.value);
192
+ continue;
193
+ }
194
+ if (tag === 0x04) {
195
+ const count = readExtraVarint(b, i);
196
+ if (!count || count.value > BigInt(Math.floor((b.length - count.next) / 32))) break;
197
+ i = count.next;
198
+ for (let n = 0; n < Number(count.value); n++) {
199
+ additionalPublicKeys.push(bytesToHex(b.subarray(i, i + 32)));
200
+ i += 32;
201
+ }
202
+ continue;
203
+ }
204
+ // An unknown tag is not a guess: stop before it and use only what was parsed unambiguously.
205
+ break;
156
206
  }
157
- return null;
207
+ return { txPublicKeys, additionalPublicKeys };
208
+ }
209
+
210
+ /** The first tx public key in `extra`, or null. Kept for callers that only need the primary key. */
211
+ export function txPublicKeyFromExtra(extra) {
212
+ return txKeysFromExtra(extra).txPublicKeys[0] || null;
158
213
  }
159
214
 
160
215
  // Amount and mask decryption. THE ENCODING IS CHOSEN BY THE RingCT TYPE, not by a boolean:
@@ -201,20 +256,42 @@ export function decodeMask(ecdhMaskHex, scalarLE, rctType) {
201
256
  }
202
257
 
203
258
  // MAIN: parse a transaction and return OUR outputs (their indices, keys and amounts).
204
- // txView - { txPublicKey, vout: [{key, index}], ecdhAmounts: [...], ecdhMasks: [...], outPk: [...], rctVersion }
205
- export function findOurOutputs({ txPublicKey, viewSecretHex, spendPubHex, outputs, ecdhAmounts = [], ecdhMasks = [], outPk = [], rctVersion = 2 }) {
206
- if (!txPublicKey) throw new Error("the transaction has no public key (extra tag 0x01) - nothing to parse");
259
+ // txView - { txPublicKey(s), additionalPublicKeys, vout: [{key, index}], ecdhAmounts: [...], ecdhMasks: [...], outPk: [...], rctVersion }
260
+ //
261
+ // ADDITIONAL KEYS ARE PER OUTPUT, NOT PER TRANSACTION. A transaction paying several subaddresses carries tag 0x04:
262
+ // key i belongs to output i. Trying only the main key misses those outputs; trying every additional key against
263
+ // every output would be wrong in the other direction and can match another recipient's output. The main key is
264
+ // tried first, then this output's own additional key, exactly as the wallet does.
265
+ export function findOurOutputs({ txPublicKey = null, txPublicKeys = null, additionalPublicKeys = [], viewSecretHex, spendPubHex, outputs, ecdhAmounts = [], ecdhMasks = [], outPk = [], rctVersion = 2 }) {
266
+ const primaryKeys = Array.isArray(txPublicKeys) ? txPublicKeys.filter(Boolean)
267
+ : (txPublicKey ? [txPublicKey] : []);
268
+ const additional = Array.isArray(additionalPublicKeys) ? additionalPublicKeys : [];
269
+ if (!primaryKeys.length && !additional.length) throw new Error("the transaction has no public key (extra tag 0x01/0x04) - nothing to parse");
207
270
  // The key form is tried EXPLICITLY; the winner's name goes up so the log shows what was used. If none matched,
208
271
  // the first meaningful form is returned, not nothing.
209
272
  const usable = viewSecretCandidates(viewSecretHex).filter(([, v]) => v !== null);
210
273
  const first = usable[0] || ["unparsed", null];
211
274
  for (const [form, secret] of usable) {
212
- const derivation = keyDerivation(txPublicKey, secret);
275
+ // A MALFORMED EXTRA KEY IS NOT A REASON TO STOP LOOKING AT THE OTHER KEYS. Monero's wallet skips a key that is
276
+ // not a curve point and keeps scanning; a transaction with one bad tag-0x01 key otherwise blinds every arrival
277
+ // whose range includes its block.
278
+ const primaryDerivations = [];
279
+ for (const key of primaryKeys) {
280
+ try { primaryDerivations.push(keyDerivation(key, secret)); }
281
+ catch { /* skip this candidate; the other keys may still be ours */ }
282
+ }
213
283
  const found = [];
214
284
  for (const o of outputs) {
215
- const scalar = hashToScalar(derivation, varint(o.index));
216
- const derived = derivedOutputKey(derivation, o.index, spendPubHex);
217
- if (derived.toLowerCase() === String(o.key).toLowerCase()) {
285
+ // The main keys first, then only THIS output's additional key.
286
+ const candidates = primaryDerivations.slice();
287
+ if (additional[o.index]) {
288
+ try { candidates.push(keyDerivation(additional[o.index], secret)); }
289
+ catch { /* a malformed per-output key is skipped, like the primary list */ }
290
+ }
291
+ for (const derivation of candidates) {
292
+ const scalar = hashToScalar(derivation, varint(o.index));
293
+ const derived = derivedOutputKey(derivation, o.index, spendPubHex);
294
+ if (derived.toLowerCase() !== String(o.key).toLowerCase()) continue;
218
295
  // The amount decryption uses THIS output's SCALAR, least-significant first.
219
296
  const amount = ecdhAmounts[o.index] ? decodeAmount(ecdhAmounts[o.index], scalarToBytesLE(scalar), rctVersion) : null;
220
297
  // THE COMMITMENT CHECK: outPk[i] = mask*G + amount*H. A node can flip a bit of the encrypted amount
@@ -230,17 +307,22 @@ export function findOurOutputs({ txPublicKey, viewSecretHex, spendPubHex, output
230
307
  amountVerified = amountMaskCommitment(amount, mask).toLowerCase() === String(outPk[o.index]).replace(/^0x/, "").toLowerCase();
231
308
  } catch { amountVerified = false; }
232
309
  }
233
- found.push({ index: o.index, key: o.key, amountAtomic: amount, maskAtomic: mask, amountVerified });
310
+ found.push({ index: o.index, key: o.key, amountAtomic: amount, maskAtomic: mask, amountVerified, derivation: bytesToHex(derivation) });
311
+ break; // one derivation per output; a later key cannot make it ours twice
234
312
  }
235
313
  }
236
- if (found.length) return { derivation: bytesToHex(derivation), outputs: found, viewKeyForm: form };
237
- }
238
- return {
239
- derivation: first[1] === null ? null : bytesToHex(keyDerivation(txPublicKey, first[1])),
240
- outputs: [],
241
- viewKeyForm: first[0],
242
- };
243
- }
314
+ if (found.length) return { derivation: found[0].derivation, outputs: found, viewKeyForm: form };
315
+ }
316
+ let fallback = null;
317
+ if (first[1] !== null && primaryKeys.length) {
318
+ try { fallback = bytesToHex(keyDerivation(primaryKeys[0], first[1])); } catch { fallback = null; }
319
+ }
320
+ return {
321
+ derivation: fallback,
322
+ outputs: [],
323
+ viewKeyForm: first[0],
324
+ };
325
+ }
244
326
 
245
327
  // ============================================================================================
246
328
  // SCANNING A HEIGHT RANGE. This is the indexing itself: read blocks in order, take their transaction hashes
@@ -260,10 +342,15 @@ const baseUrl = (value) => {
260
342
  return out;
261
343
  };
262
344
 
263
- export async function fetchBlock(daemonUrl, height, fetchImpl = globalThis.fetch) {
345
+ export async function fetchBlock(daemonUrl, height, fetchImpl = globalThis.fetch, timeoutMs = 8000) {
346
+ // THE DEADLINE COVERS THE BODY, NOT ONLY THE HEADERS. Without a signal a daemon that sends `{` and stops holds
347
+ // the whole scan forever.
348
+ const signal = typeof AbortSignal !== "undefined" && AbortSignal.timeout
349
+ ? AbortSignal.timeout(Math.max(1, Number(timeoutMs) || 8000)) : undefined;
264
350
  const res = await fetchImpl(`${baseUrl(daemonUrl)}/json_rpc`, {
265
351
  method: "POST", headers: { "Content-Type": "application/json" },
266
352
  body: JSON.stringify({ jsonrpc: "2.0", id: "block", method: "get_block", params: { height } }),
353
+ signal,
267
354
  });
268
355
  const j = await res.json();
269
356
  // A BUSY ANSWER IS NOT AN EMPTY BLOCK. The daemon answers BUSY while it is still indexing; a reader that treats
@@ -281,11 +368,14 @@ export async function fetchBlock(daemonUrl, height, fetchImpl = globalThis.fetch
281
368
 
282
369
  // Transactions by hash list. We hit the PATH /get_transactions, not /json_rpc: over JSON-RPC this method
283
370
  // silently returns empty, which looks like "no transactions".
284
- export async function fetchTransactions(daemonUrl, hashes, fetchImpl = globalThis.fetch) {
371
+ export async function fetchTransactions(daemonUrl, hashes, fetchImpl = globalThis.fetch, timeoutMs = 8000) {
285
372
  if (!hashes.length) return [];
373
+ const signal = typeof AbortSignal !== "undefined" && AbortSignal.timeout
374
+ ? AbortSignal.timeout(Math.max(1, Number(timeoutMs) || 8000)) : undefined;
286
375
  const res = await fetchImpl(`${baseUrl(daemonUrl)}/get_transactions`, {
287
376
  method: "POST", headers: { "Content-Type": "application/json" },
288
377
  body: JSON.stringify({ txs_hashes: hashes, decode_as_json: true }),
378
+ signal,
289
379
  });
290
380
  const j = await res.json();
291
381
  // A BUSY ANSWER IS NOT AN EMPTY BLOCK. The daemon says BUSY while it is still indexing; returning [] would turn
@@ -327,8 +417,10 @@ export async function fetchTransactions(daemonUrl, hashes, fetchImpl = globalThi
327
417
  // is taken as a number, LE-hex or BE-hex. The result carries viewKeyForm: the form name that matched.
328
418
  export function matchTransaction(tx, watched, { height = null, tipHeight = null, nowSec = null } = {}) {
329
419
  const out = [];
330
- const txPublicKey = txPublicKeyFromExtra(tx.extra);
331
- if (!txPublicKey) return out; // no key in extra - nothing to look at
420
+ // BOTH KEY LISTS ARE PART OF THE TRANSACTION. A subaddress output carries its own key under tag 0x04; using only
421
+ // `txPublicKeyFromExtra` drops exactly those outputs.
422
+ const keys = txKeysFromExtra(tx.extra);
423
+ if (!keys.txPublicKeys.length && !keys.additionalPublicKeys.length) return out;
332
424
  // WHETHER THE OUTPUT IS LOCKED IS DECIDED HERE, ONCE PER TRANSACTION: all its outputs carry one unlock_time.
333
425
  // A normal transaction (unlock_time = 0) goes as before; the height comes from the block holding the transfer.
334
426
  const blockHeight = height === null || height === undefined ? (tx.block_height ?? null) : height;
@@ -346,7 +438,8 @@ export function matchTransaction(tx, watched, { height = null, tipHeight = null,
346
438
  const rctVersion = (tx.rct_signatures || {}).type || 2;
347
439
  for (const w of watched) {
348
440
  const r = findOurOutputs({
349
- txPublicKey, viewSecretHex: w.viewSecret, spendPubHex: w.spendPub,
441
+ txPublicKeys: keys.txPublicKeys, additionalPublicKeys: keys.additionalPublicKeys,
442
+ viewSecretHex: w.viewSecret, spendPubHex: w.spendPub,
350
443
  outputs, ecdhAmounts, ecdhMasks, outPk, rctVersion: Number(rctVersion) || 1,
351
444
  });
352
445
  if (r.outputs.length) out.push({ address: w.address, index: w.index ?? null, outputs: r.outputs, derivation: r.derivation, viewKeyForm: r.viewKeyForm, unlockTime: Number(tx.unlock_time) || 0, unlock });
@@ -1,13 +1,11 @@
1
- // GENERATED FILE - a byte-for-byte copy of the engine module www/js/monero/wallet.js for the SDK package.
2
- // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
3
- // Everything below this header is identical to the source.
1
+ // SDK ENGINE MODULE - the demo's sdk/ mirror copies this file byte for byte (tools/build-sdk-engine.mjs).
2
+ // The page's own www/js module is a separate copy; edit this package source and regenerate the mirror.
4
3
 
5
4
  // The one-shot Monero wallet of a swap.
6
5
  //
7
- // Keys are computed by monero-js (ebellocchia/monero-js, MIT, vendored under www/assets/vendors/monero-js):
8
- // a mnemonic and keys in pure JS, real and instant. The library only knows mainnet address prefixes, so the
9
- // address string is built by our encoder (monero/address.js) for the network from the config - which is how
10
- // stagenet (24/36) also works.
6
+ // Keys are derived by the package's own Monero module (engine/monero/keys.js) from @noble/curves; the 25-word
7
+ // mnemonic is encoded/decoded by engine/monero/mnemonic.js. The old vendored monero-js bundle is gone. The address
8
+ // string is built by our encoder (monero/address.js), which knows mainnet, stagenet and testnet prefixes.
11
9
  //
12
10
  // Keys NEVER leave the browser: only the view key goes out (to the backend, for a watch-only wallet), and a
13
11
  // separate explicit function does it - recovery/restore.js::watchOnlyShareFromWallet. The wallet is one-shot,
@@ -15,81 +13,51 @@
15
13
 
16
14
  import { MONERO } from "../core/config.js";
17
15
  import { randomHex, toHex } from "../core/format.js";
16
+ import { keccak256 } from "../../src/primitives.mjs";
18
17
  import { addressFromKeys } from "./address.js";
19
-
20
- const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
21
-
22
- function base58(bytes) {
23
- let num = 0n;
24
- for (const b of bytes) num = num * 256n + BigInt(b);
25
- let out = "";
26
- while (num > 0n) {
27
- out = B58[Number(num % 58n)] + out;
28
- num /= 58n;
29
- }
30
- return out;
31
- }
18
+ import * as moneroMnemonic from "./mnemonic.js";
19
+ import * as moneroKeys from "./keys.js";
32
20
 
33
21
  // A pseudo-address for mock mode: the right length (95) and network prefix, but WITHOUT a checksum.
34
22
  // The UI always marks it as mock, so nobody sends XMR there.
35
23
 
36
24
  // ---------------------------------------------------------------------------
37
- // monero-js (mnemonic + keys + addresses, pure JS)
25
+ // Monero mnemonic + keys + addresses (the package's own implementation)
38
26
  // ---------------------------------------------------------------------------
39
27
 
40
- let moneroJsModule = null;
41
- let moneroJsError = null;
42
-
43
- export async function loadMoneroJs() {
44
- if (moneroJsModule) return moneroJsModule;
45
- if (moneroJsError) throw new Error(moneroJsError);
46
- try {
47
- const mod = await import("../../assets/vendors/monero/monero-js-browser.js?v=05c682ea");
48
- moneroJsModule = mod.default || mod;
49
- return moneroJsModule;
50
- } catch (e) {
51
- // The reason is not replaced: "bundle not built", "not uploaded" and "blocked by CSP" are different problems
52
- moneroJsError = "monero-js unavailable: " + e.message +
53
- " (run npm run build:vendor; for CSP see the deploy notes)";
54
- throw new Error(moneroJsError);
55
- }
56
- }
57
-
58
- async function withMoneroJs({ mnemonic: phrase, network = MONERO.networkType } = {}) {
59
- const lib = await loadMoneroJs();
60
- await lib.wallet.initEcc();
61
-
62
- // A supplied phrase must be valid. An invalid phrase used to be silently replaced by a fresh one, so
63
- // recovering from a corrupt file gave a DIFFERENT wallet: the error looked like success and the funds stayed
64
- // out of reach. Generation happens only when there is no phrase at all.
28
+ // A supplied phrase must be valid. An invalid phrase used to be silently replaced by a fresh one, so recovering
29
+ // from a corrupt file gave a DIFFERENT wallet: the error looked like success and the funds stayed out of reach.
30
+ // Generation happens only when there is no phrase at all.
31
+ async function withMoneroKeys({ mnemonic: phrase, network = MONERO.networkType } = {}) {
32
+ await moneroKeys.initEcc();
65
33
  let words;
66
34
  if (phrase) {
67
- if (!lib.mnemonic.isValid(phrase)) {
35
+ if (!moneroMnemonic.isValid(phrase)) {
68
36
  throw new Error("the mnemonic failed its checksum check (file or form corrupted?)");
69
37
  }
70
38
  words = String(phrase).trim();
71
39
  } else {
72
- words = lib.mnemonic.generateWithChecksum();
40
+ words = moneroMnemonic.generateWithChecksum();
73
41
  }
74
- const seed = lib.mnemonic.toSeed(words); // 32 bytes: for Monero the seed == the decoded mnemonic
75
- const w = lib.wallet.fromSeed(seed);
42
+ const seed = moneroMnemonic.toSeed(words); // 32 bytes: for Monero the seed == the decoded mnemonic
43
+ const w = moneroKeys.fromSeed(seed);
76
44
 
77
45
  const net = network || "mainnet";
78
- const deps = { keccak256: lib.keccak256, Buffer: lib.Buffer };
46
+ const deps = { keccak256 };
79
47
  const spendPub = toHex(w.publicSpendKey);
80
48
  const viewPub = toHex(w.publicViewKey);
81
49
  const sub = w.subaddress(1, 0);
82
- // the address of our own network is built here (the library only knows mainnet);
83
- // addressMainnet is kept for cross-checking: on mainnet the two must match
50
+ // The address of our own network is built here; mainnet is kept for cross-checking.
84
51
  const address = addressFromKeys({ network: net, kind: "primary", spendPub, viewPub }, deps);
85
52
  const subaddress = addressFromKeys(
86
53
  { network: net, kind: "subaddress", spendPub: toHex(sub.publicSpendKey), viewPub: toHex(sub.publicViewKey) },
87
54
  deps
88
55
  );
56
+ const addressMainnet = addressFromKeys({ network: "mainnet", kind: "primary", spendPub, viewPub }, deps);
89
57
 
90
58
  return {
91
- source: "monero-js",
92
- library: "ebellocchia/monero-js (MIT)",
59
+ source: "ninsei-monero-keys",
60
+ library: "Ninsei Monero keys (@noble/curves + @noble/hashes)",
93
61
  network: net,
94
62
  mnemonic: words,
95
63
  mnemonicWords: words.split(" ").length,
@@ -100,31 +68,26 @@ async function withMoneroJs({ mnemonic: phrase, network = MONERO.networkType } =
100
68
  publicViewKey: viewPub,
101
69
  address,
102
70
  subaddress,
103
- addressMainnet: w.primaryAddress().encode(),
71
+ addressMainnet,
104
72
  createdAt: Date.now(),
105
73
  };
106
74
  }
107
75
 
108
76
  // ---------------------------------------------------------------------------
109
- // monero-ts removed
110
- // ---------------------------------------------------------------------------
111
- // A second wallet mode lived here - a WebAssembly wallet2 (woodser/monero-ts) built into the vendors. It was
112
- // removed for two reasons: the WASM wallet needs SharedArrayBuffer, i.e. COOP/COEP, which on the demo domain
113
- // would block third-party resources; and the bundle moved to the sweep app, which has its own COOP/COEP domain.
114
- // While the branch of code stayed, it pulled an import along a path that no longer existed - dead, yet looking
115
- // alive. Keys in the demo are computed by monero-js, and that is the only path.
116
-
77
+ // The old monero-js / monero-ts browser paths are gone.
117
78
  // ---------------------------------------------------------------------------
79
+ // Keys are derived by engine/monero/keys.js from @noble/curves. The monero-ts WASM wallet was removed earlier:
80
+ // it needs SharedArrayBuffer, i.e. COOP/COEP, which on the demo domain would block third-party resources; the
81
+ // sweep app has its own domain and wallet adapter.
118
82
 
119
83
  export async function createSwapWallet({ network = MONERO.networkType, seed } = {}) {
120
- return withMoneroJs({ mnemonic: seed, network });
84
+ return withMoneroKeys({ mnemonic: seed, network });
121
85
  }
122
86
 
123
- // Whether the key library is available (the Demo controls panel shows this as one line).
87
+ // Whether the key module is available (the Demo controls panel shows this as one line).
124
88
  export async function probeMode() {
125
89
  try {
126
- const lib = await loadMoneroJs();
127
- await lib.wallet.initEcc();
90
+ await moneroKeys.initEcc();
128
91
  return { available: true, info: "mnemonic + keys + addresses (" + MONERO.networkType + ")" };
129
92
  } catch (e) {
130
93
  return { available: false, reason: e.message };