@ninsei-labs/sdk 0.57.2 → 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 (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +64 -27
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/assets/vendors/MANIFEST.json +1 -9
  5. package/assets/vendors/sdk/sdk-browser.js +4 -4
  6. package/engine/core/config.js +3 -22
  7. package/engine/core/rfqSource.js +6 -133
  8. package/engine/core/swap.js +1 -1
  9. package/engine/evm/index.js +3 -2
  10. package/engine/evm/session.js +46 -277
  11. package/engine/monero/address.js +15 -33
  12. package/engine/monero/keys.js +124 -0
  13. package/engine/monero/mnemonic.js +104 -0
  14. package/engine/monero/scan.js +23 -9
  15. package/engine/monero/wallet.js +31 -68
  16. package/engine/monero/wordlist.en.js +210 -0
  17. package/engine/recovery/restore.js +1 -1
  18. package/engine/sdk/bridge.js +7 -182
  19. package/engine/ui/walletModal.js +7 -27
  20. package/index.d.ts +187 -252
  21. package/package.json +4 -5
  22. package/src/codes.mjs +12 -0
  23. package/src/config.mjs +16 -54
  24. package/src/engine.mjs +3 -0
  25. package/src/index.mjs +24 -45
  26. package/src/order.mjs +2 -2
  27. package/src/public/recovery.d.ts +17 -1
  28. package/src/public/recovery.mjs +1 -0
  29. package/src/quotePolicy.mjs +25 -0
  30. package/src/quotes.mjs +21 -751
  31. package/src/readyWindow.mjs +76 -0
  32. package/src/recovery-key.mjs +39 -2
  33. package/src/recovery.mjs +11 -28
  34. package/src/relayClaim.mjs +132 -0
  35. package/src/relayFirmClient.mjs +3 -0
  36. package/src/relayQuote.mjs +5 -1
  37. package/src/swap-flow.mjs +49 -5
  38. package/src/swaps.mjs +301 -307
  39. package/src/sweep-action.mjs +73 -0
  40. package/src/sweep.mjs +7 -1
  41. package/src/version.mjs +1 -1
  42. package/src/xmr-arrival.mjs +275 -7
  43. package/src/xmrAmountPolicy.mjs +35 -0
  44. package/assets/vendors/monero/monero-js-browser.js +0 -58
  45. package/assets/vendors/monero-js/LICENSE +0 -9
  46. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
@@ -2,29 +2,26 @@
2
2
  // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
3
3
  // Everything below this header is identical to the source.
4
4
 
5
- // The EVM wallet: state, balances, network switching and two ways to connect.
5
+ // The EVM wallet: state, balances, network switching and the injected connector.
6
6
 
7
- // WHY TWO CONNECTORS. WalletConnect (Reown) is for a user coming from a phone or a wallet without an extension:
8
- // the session lives over a QR. A browser wallet (MetaMask, Rabby, Coinbase...), if installed, connects directly
9
- // over EIP-1193 - faster and with no extra hop.
10
- // Both expose the same EIP-1193 interface, so state, balances and network switching are shared:
11
- // only the handshake differs (see www/js/evm/injected.js).
7
+ // A browser wallet (MetaMask, Rabby, Coinbase...) found by EIP-6963 connects directly over EIP-1193. The SDK
8
+ // accepts the provider through `evmWallet(provider)`; WalletConnect and any other mobile connector are loaded by
9
+ // the host page, which passes the resulting EIP-1193 provider the same way. No vendor bundle is shipped here.
12
10
 
13
11
  // What is real here and what is not matters:
14
- // REAL: connecting (QR or browser extension), address, chainId, native-token and ERC-20 balances (values come
12
+ // REAL: connecting (browser extension), address, chainId, native-token and ERC-20 balances (values come
15
13
  // from the user's wallet through its provider, decimals from the config);
16
14
  //
17
15
  // NOT REAL: transfers. The escrow contract is not deployed yet and the escrow address in the demo is a mock,
18
16
  // so sending a transaction stays a simulation (see evm/index.js). The demo does not move real money
19
17
  // and must not.
20
18
 
21
- // The modal is drawn by us (ui/walletModal.js): Reown's own uses inline styles, which the demo CSP forbids.
22
- // The WalletConnect provider is initialised with showQrModal: false; the session link comes from the
23
- // display_uri event and is encoded into a QR in a data: URL.
19
+ // The modal is drawn by us (ui/walletModal.js): the browser-wallet list comes from EIP-6963, and the CSP bans
20
+ // inline styles, so everything goes through dom.h(). The host owns any QR or WalletConnect UI.
24
21
 
25
22
  // Balances are cached in the state: the UI asks balanceOf() synchronously, and refreshBalances() updates
26
23
  // them (on connect, network change, wallet event).
27
- import { CHAINS, EVM, chainById, chainByChainId, tokensOf } from "../core/config.js";
24
+ import { chainById, chainByChainId, tokensOf } from "../core/config.js";
28
25
  import {
29
26
  discoverWallets,
30
27
  explainInjectedError,
@@ -41,8 +38,8 @@ const listeners = new Set();
41
38
 
42
39
  const state = {
43
40
  status: "idle", // idle | pairing | connected | error
44
- kind: null, // walletconnect | injected - which connector is in use
45
- label: null, // wallet name for the UI: "WalletConnect", "MetaMask", "Rabby"...
41
+ kind: null, // injected - the only connector this engine owns
42
+ label: null, // wallet name for the UI: "MetaMask", "Rabby"...
46
43
  address: null,
47
44
  chainId: null, // numeric chainId of the network the wallet is on
48
45
  balances: {}, // "42161:USDC" -> a human-readable number
@@ -52,7 +49,6 @@ const state = {
52
49
 
53
50
  let provider = null;
54
51
  let modal = null;
55
- let lib = null;
56
52
 
57
53
  function emit() {
58
54
  for (const fn of listeners) {
@@ -105,21 +101,6 @@ export function balanceOf(chainSlugOrId, symbol) {
105
101
 
106
102
  const hexChainId = (id) => "0x" + Number(id).toString(16);
107
103
 
108
- async function loadLib() {
109
- if (!lib) {
110
- // A dynamic import of our own file: CSP script-src 'self' allows it,
111
- // and the 2 MB bundle loads only when the user actually presses Connect.
112
- lib = await import("../../assets/vendors/walletconnect/wc-browser.js?v=fb64f27c");
113
- }
114
- return lib;
115
- }
116
-
117
- function rpcMap() {
118
- const map = {};
119
- for (const c of CHAINS) map[c.chainId] = c.rpcUrl;
120
- return map;
121
- }
122
-
123
104
  function reset(status = "idle", error = null) {
124
105
  state.status = status;
125
106
  state.error = error;
@@ -132,11 +113,10 @@ function reset(status = "idle", error = null) {
132
113
  emit();
133
114
  }
134
115
 
135
- // --- the part shared by both connectors ------------------------------------------------------
116
+ // --- the injected connector -----------------------------------------------------------------
136
117
  //
137
- // WalletConnect and a browser wallet expose the same EIP-1193 interface, so events, state and balance reading
138
- // are shared. Only the handshake differs, so here are the handlers and in connect()/
139
- // connectInjected() - how exactly the provider was obtained.
118
+ // The browser wallet exposes EIP-1193. The host may supply WalletConnect or another connector as the same
119
+ // interface; that connector is not created or loaded here.
140
120
 
141
121
  function wireProvider(p) {
142
122
  p.on("chainChanged", (id) => {
@@ -158,172 +138,27 @@ function wireProvider(p) {
158
138
  emit();
159
139
  refreshBalances();
160
140
  });
161
- // disconnect comes from both WalletConnect and a browser wallet (e.g. on reset);
162
- // session_delete - only WalletConnect. Both mean one thing: the session is gone.
141
+ // disconnect comes from a browser wallet, for example after it resets the site.
163
142
  p.on("disconnect", () => {
164
143
  if (modal) modal.close();
165
144
  reset("idle", null);
166
145
  });
167
- p.on("session_delete", () => {
168
- if (modal) modal.close();
169
- reset("idle", null);
170
- });
171
- }
172
-
173
- // RETURNING TO THE PAGE FROM BFCACHE. Chrome (since 149) tears down the WebSocket when the page goes into the
174
- // back-forward cache, deliberately: in the console it looks like "failed: Page entered Back-Forward Cache",
175
- // although the network is not to blame. Consequence: the WalletConnect provider is cached in a variable, its
176
- // socket is closed and the relay retries froze with the page - so after returning the session LOOKS alive while
177
- // requests to the wallet do not get through. Neither the one-shot restore() nor provider events notice it. We
178
- // fix it with the same mechanism restore() relies on: init() raises the session from localStorage.
179
- // disconnect() is NOT called here - it deletes the session from storage, i.e. would break what we restore.
180
- let resumeInFlight = false;
181
-
182
- export async function resumeConnection() {
183
- if (resumeInFlight || state.status !== "connected" || state.kind !== "walletconnect" || !provider) return;
184
- resumeInFlight = true;
185
- const p = provider;
186
- try {
187
- await Promise.race([
188
- p.request({ method: "eth_accounts" }),
189
- new Promise((_, rej) => setTimeout(() => rej(new Error("the relay did not answer in 4 s")), 4000)),
190
- ]);
191
- console.log("[wc] the connection is alive after returning to the page");
192
- return;
193
- } catch (e) {
194
- console.log("[wc] the relay does not answer after returning (" + e.message + ") - raising the session again");
195
- } finally {
196
- resumeInFlight = false;
197
- }
198
- provider = null; // the browser closed the old socket, so caching it is pointless
199
- try {
200
- const want = state.chainId || (CHAINS.find((c) => c.escrow) || {}).chainId;
201
- const fresh = await ensureProvider(want);
202
- const accounts = await fresh.request({ method: "eth_accounts" });
203
- if (!Array.isArray(accounts) || !accounts.length) {
204
- console.log("[wc] no session left in storage - a new QR is needed");
205
- reset("idle", null);
206
- return;
207
- }
208
- state.address = accounts[0];
209
- emit();
210
- await refreshBalances();
211
- console.log("[wc] session raised again: " + state.address);
212
- } catch (e) {
213
- console.log("[wc] could not raise the session: " + e.message);
214
- reset("idle", null);
215
- }
216
- }
217
-
218
- // Returning to the page: pageshow (including from bfcache) and tab visibility. Debounced so switching
219
- // tabs does not poke the relay on every twitch.
220
- let resumeTimer = null;
221
- const scheduleResume = () => {
222
- clearTimeout(resumeTimer);
223
- resumeTimer = setTimeout(() => { resumeConnection(); }, 400);
224
- };
225
- // WINDOW-EVENT SUBSCRIPTION ONLY WHERE THERE IS A WINDOW. It used to run with no environment check, and the
226
- // module failed on load in Node (repo checks) and in the SDK, which promises "no DOM": the failure came not at
227
- // subscription time but on importing the file - i.e. it broke everything that pulls it in.
228
- if (typeof window !== "undefined" && typeof document !== "undefined") {
229
- window.addEventListener("pageshow", () => scheduleResume());
230
- document.addEventListener("visibilitychange", () => { if (!document.hidden) scheduleResume(); });
231
- }
232
-
233
- async function ensureProvider(wantChainId) {
234
- if (provider) return provider;
235
- const { EthereumProvider } = await loadLib();
236
- provider = await EthereumProvider.init({
237
- projectId: EVM.projectId,
238
- chains: [wantChainId],
239
- // Only networks the demo can settle on: there is no point offering the wallet a network without an escrow
240
- // (and the WalletConnect project may not know it, which would break the connection).
241
- optionalChains: CHAINS.filter((c) => c.escrow).map((c) => c.chainId),
242
- showQrModal: false,
243
- rpcMap: rpcMap(),
244
- // The url in the WalletConnect metadata is compared against the page's actual origin (the app-origin
245
- // check). Substituting the production domain breaks the session locally and on a test domain - hence
246
- // the origin is taken, not a constant.
247
- metadata: { ...EVM.metadata, url: location.origin },
248
- });
249
-
250
- provider.on("display_uri", (uri) => showUri(uri));
251
- wireProvider(provider);
252
- // kind/label are NOT set here: the provider is created, but there is no connection yet. Otherwise, after
253
- // a reload without a session the state would be idle while the UI counted the wallet as connected
254
- // (a browser check catches this: status=idle, kind=walletconnect).
255
- return provider;
256
- }
257
-
258
- async function showUri(uri) {
259
- if (!modal || modal.closed.value) return;
260
- try {
261
- const { QRCode } = await loadLib();
262
- const qrDataUrl = await QRCode.toDataURL(uri, {
263
- margin: 1,
264
- width: 440,
265
- errorCorrectionLevel: "M",
266
- color: { dark: "#0a0d13", light: "#ffffff" },
267
- });
268
- modal.update({ qrDataUrl, uri, status: "Waiting for the wallet to approve..." });
269
- } catch (e) {
270
- // The QR did not render - the link is shown anyway, it can be copied.
271
- modal.update({ uri, status: "Scan failed to render, copy the link instead", error: true });
272
- console.warn("qr render failed", e);
273
- }
274
146
  }
275
147
 
276
- // Restoring the session after a page reload.
277
- //
278
- // WalletConnect keeps the session in localStorage, and EthereumProvider.init() raises it back.
279
- // But our provider was created LAZILY - only on "Connect wallet" - so after F5 the session lay in storage while
280
- // the page knew nothing: it showed "Connect wallet" and offered a new QR. Restoration is an explicit step at
281
- // load: raise the provider and, if a session exists, declare it connected (address, network, balances).
282
- //
283
- //
284
- // State is read AFTER init, not by event: during restoration the event may arrive before
285
- // the page has subscribed to the provider.
286
- let restoreTried = false;
287
-
288
- // THE "OPTED OUT MANUALLY" MARK. WalletConnect keeps the session in localStorage, so one disconnect() is not
289
- // enough: on the next load restore() would raise it back and the logout would prove false. The mark is cleared
290
- // ONLY on a deliberate connect.
148
+ // THE "OPTED OUT MANUALLY" MARK. A browser wallet may remember the site even after
149
+ // wallet_revokePermissions is unavailable, so a deliberate disconnect must survive the next load.
291
150
  const OPTOUT_KEY = "ninsei.wallet.optOut";
292
151
  const isOptedOut = () => { try { return localStorage.getItem(OPTOUT_KEY) === "1"; } catch { return false; } };
293
152
  const setOptOut = (on) => { try { on ? localStorage.setItem(OPTOUT_KEY, "1") : localStorage.removeItem(OPTOUT_KEY); } catch {} };
294
153
 
154
+ let restoreTried = false;
155
+
156
+ // Restore the injected wallet without a prompt. The host may pass its own wallet list; otherwise EIP-6963 is used.
295
157
  export async function restore() {
296
- // Opted out manually - do not pick it up: otherwise the "log out" button means nothing.
297
- if (isOptedOut()) { restoreTried = true; console.log("[wc] restore skipped: wallet disconnected manually"); return publicState(); }
158
+ if (isOptedOut()) { restoreTried = true; console.log("[wallet] restore skipped: wallet disconnected manually"); return publicState(); }
298
159
  if (restoreTried || state.status === "connected") return publicState();
299
160
  restoreTried = true;
300
- // Order: first the WalletConnect session (in localStorage), then a browser wallet.
301
- // The second step is silent: eth_accounts shows no window, so page load does not turn into
302
- // "connect your wallet" for those who already connected before.
303
- if (EVM.projectId) {
304
- try {
305
- const want = chainById(state.chainId || undefined);
306
- const p = await ensureProvider(want.chainId);
307
- const accounts = (p && p.accounts) || [];
308
- // Empty - there is no session in storage (or it was disconnected). This is normal: below we
309
- // try a browser wallet and, if there is none either, the page will offer to connect.
310
- if (accounts.length) {
311
- state.kind = "walletconnect";
312
- state.label = "WalletConnect";
313
- state.address = accounts[0];
314
- state.chainId = Number(p.chainId) || want.chainId;
315
- state.status = "connected";
316
- state.error = null;
317
- emit();
318
- await refreshBalances();
319
- console.info("WalletConnect: session restored after reload", state.address);
320
- }
321
- } catch (e) {
322
- console.warn("WalletConnect: could not restore the session", e && e.message ? e.message : e);
323
- }
324
- }
325
- if (!isConnected()) return restoreInjected();
326
- return publicState();
161
+ return restoreInjected();
327
162
  }
328
163
 
329
164
  // A silent check for browser wallets: one already allowed for the site returns an address without a window.
@@ -398,9 +233,8 @@ export async function connectInjected({ wallet, chainSlug } = {}) {
398
233
 
399
234
  // Connect. chainSlug - the network selected in the form; it also becomes the primary in the session.
400
235
  //
401
- // WalletConnect does NOT start immediately here: first a choice is shown - browser wallets found via EIP-6963
402
- // and WalletConnect as a separate row. So a user with an extension is not given a WalletConnect session he did
403
- // not ask for, and a phone user does not have to hunt for an extension.
236
+ // Only browser wallets found through EIP-6963 are offered. WalletConnect and any other connector are loaded by
237
+ // the host page, which passes the resulting EIP-1193 provider to `evmWallet`.
404
238
  export async function connect({ chainSlug } = {}) {
405
239
  if (isConnected()) return { address: state.address, chainId: state.chainId };
406
240
  const want = chainById(chainSlug || state.chainId || undefined);
@@ -419,12 +253,12 @@ export async function connect({ chainSlug } = {}) {
419
253
  wallets.map((w) => w.name + " [" + w.source + (w.rdns ? " " + w.rdns : "") + "]").join(", ")
420
254
  );
421
255
  } else {
422
- console.info("[wallet] no browser wallets found (WalletConnect remains)");
256
+ console.info("[wallet] no browser wallets found");
423
257
  }
424
258
  modal = openWalletModal({
425
259
  title: "Connect a wallet",
426
- subtitle: `Requested network: ${want.name}. The QR below is a public WalletConnect link - nothing secret. This demo never moves real funds: there is no escrow contract on-chain yet.`,
427
- hint: "Browser wallets are detected in this browser (EIP-6963). WalletConnect works with mobile wallets by QR.",
260
+ subtitle: `Requested network: ${want.name}.`,
261
+ hint: "Browser wallets are detected in this browser through EIP-6963.",
428
262
  });
429
263
 
430
264
  const choice = await new Promise((resolve) => {
@@ -439,20 +273,11 @@ export async function connect({ chainSlug } = {}) {
439
273
  hint: w.source === "eip6963" ? null : "detected via window.ethereum",
440
274
  onClick: () => resolve({ type: "injected", wallet: w }),
441
275
  }));
442
- if (EVM.projectId) {
443
- options.push({
444
- key: "walletconnect",
445
- name: "WalletConnect",
446
- icon: null,
447
- hint: "QR code for a mobile wallet",
448
- onClick: () => resolve({ type: "walletconnect" }),
449
- });
450
- }
451
276
  modal.setChoices(options);
452
277
  modal.update({
453
278
  status: wallets.length
454
- ? "Choose a browser wallet above, or scan the QR code below."
455
- : "No browser wallet found in this browser - use the QR code below.",
279
+ ? "Choose a browser wallet above."
280
+ : "No browser wallet found in this browser. Install a browser wallet or use the host's own connector.",
456
281
  });
457
282
  });
458
283
 
@@ -462,72 +287,21 @@ export async function connect({ chainSlug } = {}) {
462
287
  }
463
288
 
464
289
  // --- browser wallet: the wallet itself shows the permission window ---
465
- if (choice.type === "injected") {
466
- try {
467
- const res = await connectInjected({ wallet: choice.wallet, chainSlug: want.id });
468
- if (modal) modal.close();
469
- return res;
470
- } catch (e) {
471
- // The modal is NOT closed: the refusal cause must stay on screen. Otherwise it is
472
- // "pressed - nothing happened", and there is nowhere to learn what happened (a check catches this).
473
- const message = String((e && e.message) || e);
474
- if (modal) {
475
- modal.update({
476
- error: message,
477
- status: "Try again, or use WalletConnect below.",
478
- });
479
- }
480
- throw e;
481
- }
482
- }
483
-
484
- // --- WalletConnect: the previous path, including instant cancel ---
485
- if (!EVM.projectId) {
486
- if (modal) modal.close();
487
- reset("error", "no-project-id");
488
- throw new Error("WalletConnect projectId is not configured");
489
- }
490
- modal.update({ status: "Preparing the session..." });
491
- // Cancel must finish the connect IMMEDIATELY. Without this, await provider.connect() hangs until the
492
- // session timeout, the "Connect wallet" button stays disabled, and the demo looks broken (the bug was
493
- // caught by a browser check: after cancel the button did not revive).
494
- let cancelReject = null;
495
- const cancelled = new Promise((_, reject) => {
496
- cancelReject = () => reject(new Error("Connection cancelled"));
497
- });
498
-
499
- modal.setOnCancel(() => {
500
- // The user closed the modal: the session must be extinguished, else it hangs.
501
- const p = provider;
502
- provider = null;
503
- if (p) Promise.resolve(p.disconnect()).catch(() => {});
504
- reset("idle", null);
505
- if (cancelReject) cancelReject();
506
- });
507
-
508
290
  try {
509
- const p = await ensureProvider(want.chainId);
510
- await Promise.race([p.connect({ chains: [want.chainId] }), cancelled]);
511
- state.kind = "walletconnect";
512
- state.label = "WalletConnect";
513
- state.address = (p.accounts && p.accounts[0]) || null;
514
- state.chainId = Number(p.chainId);
515
- state.status = "connected";
516
- state.error = null;
517
- // Exactly close(), not cancel(): the connection happened, the session must not be extinguished.
291
+ const res = await connectInjected({ wallet: choice.wallet, chainSlug: want.id });
518
292
  if (modal) modal.close();
519
- emit();
520
- await refreshBalances();
521
- return { address: state.address, chainId: state.chainId };
293
+ return res;
522
294
  } catch (e) {
523
- const message = e && e.message ? String(e.message) : String(e);
524
- console.warn("WalletConnect connect failed:", message);
525
- // The user's refusal is not an app error.
526
- const rejected = isUserRejection(e) || /cancell?ed/i.test(message);
527
- if (modal) modal.close();
528
- reset(rejected ? "idle" : "error", rejected ? null : message);
529
- if (!rejected) throw e;
530
- return null;
295
+ // The modal is NOT closed: the refusal cause must stay on screen. Otherwise it is
296
+ // "pressed - nothing happened", and there is nowhere to learn what happened (a check catches this).
297
+ const message = String((e && e.message) || e);
298
+ if (modal) {
299
+ modal.update({
300
+ error: message,
301
+ status: "Try again.",
302
+ });
303
+ }
304
+ throw e;
531
305
  }
532
306
  }
533
307
 
@@ -574,21 +348,16 @@ export async function signTypedData(typedData) {
574
348
  export async function disconnect() {
575
349
  setOptOut(true); // remember the decision: after a reload the wallet is not picked up
576
350
  const p = provider;
577
- const kind = state.kind;
578
351
  if (!p) {
579
352
  reset("idle", null);
580
353
  return;
581
354
  }
582
355
  try {
583
- if (kind === "injected") {
584
- // A browser wallet has no "session" on our side: we can only ask it to revoke the permission
585
- // (wallet_revokePermissions) and forget the address locally. Honestly: the next eth_accounts may
586
- // return the address again if the wallet remembers the site.
587
- if (typeof p.revokePermissions === "function") {
588
- await p.request({ method: "wallet_revokePermissions", params: [{ eth_accounts: {} }] });
589
- }
590
- } else {
591
- await p.disconnect();
356
+ // A browser wallet has no "session" on our side: we can only ask it to revoke the permission
357
+ // (wallet_revokePermissions) and forget the address locally. Honestly: the next eth_accounts may
358
+ // return the address again if the wallet remembers the site.
359
+ if (typeof p.revokePermissions === "function") {
360
+ await p.request({ method: "wallet_revokePermissions", params: [{ eth_accounts: {} }] });
592
361
  }
593
362
  } catch (e) {
594
363
  console.warn("disconnect failed", e);
@@ -642,7 +411,7 @@ export async function switchChain(chainSlugOrId) {
642
411
  // through eth_call (selector 0x70a08231); decimals come from the config (where the BSC trap was).
643
412
  // Send a transaction from the USER's wallet and return its hash.
644
413
  //
645
- // An EIP-1193 method, one for WalletConnect and browser wallets: both expose
414
+ // An EIP-1193 method, one for every injected browser wallet: each exposes
646
415
  // a provider with request(). The signature happens in the wallet, our code never touches keys.
647
416
  //
648
417
  // The call does not return at once: the user confirms the transaction in their wallet, and until
@@ -1,6 +1,5 @@
1
- // GENERATED FILE - a byte-for-byte copy of the engine module www/js/monero/address.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
  // Monero address checks and assembly: format + real checksum + network prefixes.
6
5
  // A detail easy to get wrong: Monero has its OWN base58 - block-based (8 bytes -> 11 chars, the remainder last).
@@ -8,7 +7,10 @@
8
7
  // '1' can be just a digit. So bs58 does not fit and base58 is implemented numerically below.
9
8
  // Without the checksum a typo in the payout address looks valid, and in an atomic swap that means lost money.
10
9
  // Network prefixes (official): mainnet 18 plain, 19 with payment id, 42 subaddress.
11
- // The vendored monero-js knows ONLY mainnet, so we have our own encoder: the library gives public keys, we build the string.
10
+ // The package owns the block-wise Monero base58 and checksum encoder; keys come from engine/monero/keys.js, not
11
+ // from a vendored browser bundle.
12
+
13
+ import { keccak256 } from "../../src/primitives.mjs";
12
14
 
13
15
  const BLOCK_CHARS = 11;
14
16
 
@@ -66,22 +68,6 @@ export function isStagenetShaped(addr) {
66
68
  return networkFromShape(addr) === "stagenet";
67
69
  }
68
70
 
69
- let lib = null;
70
- let libFailed = false;
71
-
72
- async function loadLib() {
73
- if (lib) return lib;
74
- if (libFailed) return null;
75
- try {
76
- const mod = await import("../../assets/vendors/monero/monero-js-browser.js?v=05c682ea");
77
- lib = mod.default || mod;
78
- return lib;
79
- } catch {
80
- libFailed = true;
81
- return null;
82
- }
83
- }
84
-
85
71
  // The Monero-base58 alphabet (same as Bitcoin, different encoding rules).
86
72
  const B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
87
73
  const B58_VALUES = (() => {
@@ -187,12 +173,15 @@ function hexToBytes(hex, expectedBytes, label) {
187
173
  return out;
188
174
  }
189
175
 
190
- // Assembly of the address from public keys: deps = { keccak256 } (in the browser, from the monero-js bundle).
191
- // bs58 is not needed: Monero base58 is block-based and numeric, see the comment at base58ToBlock.
176
+ // Assembly of the address from public keys: deps = { keccak256 }. bs58 is not needed: Monero base58 is block-based
177
+ // and numeric, see the comment at base58ToBlock.
192
178
  export function addressFromKeys({ network, kind = "primary", spendPub, viewPub, paymentId }, deps) {
193
179
  if (!deps?.keccak256) throw new Error("addressFromKeys needs { keccak256 }");
194
180
  const payload = addressPayload({ network, kind, spendPub, viewPub, paymentId });
195
- const digest = Uint8Array.from(deps.keccak256(deps.Buffer ? deps.Buffer.from(payload) : payload));
181
+ // The injected hash may be the `keccak256` npm package (it only accepts a Buffer); the package's own primitive
182
+ // takes a Uint8Array. The optional Buffer keeps both call styles working.
183
+ const input = deps.Buffer ? deps.Buffer.from(payload) : payload;
184
+ const digest = Uint8Array.from(deps.keccak256(input));
196
185
  const full = new Uint8Array(payload.length + 4);
197
186
  full.set(payload, 0);
198
187
  full.set(digest.slice(0, 4), payload.length);
@@ -211,18 +200,13 @@ export async function checkAddress(addr, opts = {}) {
211
200
  if (opts.expectNetwork && shape && shape !== opts.expectNetwork) {
212
201
  return { ok: false, reason: `This is a ${shape} address, but the swap runs on ${opts.expectNetwork}` };
213
202
  }
214
- const l = await loadLib();
215
- if (!l) {
216
- return { ok: true, verified: false, network: shape, reason: "Format looks valid (checksum check unavailable: monero-js bundle is not built)" };
217
- }
218
203
  try {
219
204
  const bytes = decodeMoneroBase58(a);
220
205
  const payloadLen = bytes.length - 4;
221
206
  if (payloadLen < 65) throw new Error("Address is too short");
222
207
  const payload = bytes.slice(0, payloadLen);
223
208
  const checksum = bytes.slice(payloadLen);
224
- // keccak256 from the bundle needs Buffer: it does not take Uint8Array
225
- const digest = Uint8Array.from(l.keccak256(l.Buffer.from(payload)));
209
+ const digest = Uint8Array.from(keccak256(payload));
226
210
  const match = checksum.length === 4 && checksum.every((b, i) => b === digest[i]);
227
211
  if (!match) {
228
212
  // The demo mock addresses (wallet.js, mock mode) intentionally have no checksum: the UI marks them as fake,
@@ -242,9 +226,7 @@ export async function checkAddress(addr, opts = {}) {
242
226
  }
243
227
  }
244
228
 
245
- // Helper for code that has already loaded the bundle: build an address of the right network from wallet keys.
229
+ // Build an address of the right network from wallet keys.
246
230
  export async function addressForNetwork({ network, kind = "primary", spendPub, viewPub }) {
247
- const l = await loadLib();
248
- if (!l) throw new Error("monero-js bundle is not available");
249
- return addressFromKeys({ network, kind, spendPub, viewPub }, { keccak256: l.keccak256, Buffer: l.Buffer });
231
+ return addressFromKeys({ network, kind, spendPub, viewPub }, { keccak256 });
250
232
  }
@@ -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
+ }