@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.
- package/CHANGELOG.md +29 -0
- package/LICENSE-POLICY.md +9 -2
- package/README.md +78 -28
- package/THIRD_PARTY_NOTICES.md +176 -2
- package/assets/vendors/MANIFEST.json +1 -13
- package/assets/vendors/sdk/sdk-browser.js +5 -4
- package/engine/atomic/dleq2.js +116 -15
- package/engine/atomic/order.js +21 -3
- package/engine/core/config.js +20 -46
- package/engine/core/deployments.generated.js +103 -0
- package/engine/core/rfqSource.js +6 -133
- package/engine/core/swap.js +8 -8
- package/engine/evm/asyncRoute.js +1 -1
- package/engine/evm/claimGas.js +2 -1
- package/engine/evm/escrow.js +13 -8
- package/engine/evm/factory.js +11 -6
- package/engine/evm/funding.js +8 -3
- package/engine/evm/index.js +5 -6
- package/engine/evm/session.js +48 -279
- package/engine/monero/address.js +15 -33
- package/engine/monero/keys.js +124 -0
- package/engine/monero/mnemonic.js +104 -0
- package/engine/monero/scan.js +121 -28
- package/engine/monero/wallet.js +31 -68
- package/engine/monero/wordlist.en.js +210 -0
- package/engine/recovery/restore.js +9 -9
- package/engine/sdk/bridge.js +9 -187
- package/engine/ui/walletModal.js +7 -27
- package/index.d.ts +234 -262
- package/package.json +7 -6
- package/src/actions.mjs +8 -5
- package/src/codes.mjs +17 -0
- package/src/config.mjs +17 -54
- package/src/engine.mjs +9 -6
- package/src/feeEstimate.mjs +11 -4
- package/src/http.mjs +4 -1
- package/src/index.mjs +24 -45
- package/src/legs/kyber.mjs +23 -0
- package/src/lock.mjs +1 -0
- package/src/order.mjs +110 -22
- package/src/primitives.mjs +4 -5
- package/src/probes.mjs +9 -3
- package/src/public/networks.d.ts +45 -0
- package/src/public/networks.mjs +10 -1
- package/src/public/recovery.d.ts +17 -1
- package/src/public/recovery.mjs +1 -0
- package/src/public/xmr.mjs +1 -1
- package/src/quotePolicy.mjs +25 -0
- package/src/quotes.mjs +109 -765
- package/src/readyWindow.mjs +76 -0
- package/src/recovery-key.mjs +71 -16
- package/src/recovery.mjs +11 -28
- package/src/relayClaim.mjs +132 -0
- package/src/relayFeatures.mjs +25 -13
- package/src/relayFirmClient.mjs +36 -7
- package/src/relayQuote.mjs +92 -11
- package/src/relayView.mjs +3 -3
- package/src/swap-flow.mjs +146 -60
- package/src/swaps.mjs +521 -357
- package/src/sweep-action.mjs +73 -0
- package/src/sweep-restore.mjs +8 -4
- package/src/sweep.mjs +12 -2
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +328 -29
- package/src/xmrAmountPolicy.mjs +35 -0
- package/assets/vendors/atomic/atomic-browser.js +0 -24
- package/assets/vendors/monero/monero-js-browser.js +0 -58
- package/assets/vendors/monero-js/LICENSE +0 -9
- package/assets/vendors/walletconnect/wc-browser.js +0 -6202
- package/engine/atomic/order-client.js +0 -56
- package/engine/atomic/order-worker.js +0 -156
- package/engine/evm/asyncExec.js +0 -577
- package/engine/evm/asyncLegs.js +0 -308
package/engine/evm/session.js
CHANGED
|
@@ -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
|
|
5
|
+
// The EVM wallet: state, balances, network switching and the injected connector.
|
|
6
6
|
|
|
7
|
-
//
|
|
8
|
-
// the
|
|
9
|
-
//
|
|
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 (
|
|
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):
|
|
22
|
-
//
|
|
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 {
|
|
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, //
|
|
45
|
-
label: null, // wallet name for the UI: "
|
|
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=13fe06e5");
|
|
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
|
|
116
|
+
// --- the injected connector -----------------------------------------------------------------
|
|
136
117
|
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
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
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
402
|
-
//
|
|
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
|
|
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}
|
|
427
|
-
hint: "Browser wallets are detected in this browser
|
|
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
|
|
455
|
-
: "No browser wallet found in this browser
|
|
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
|
|
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
|
-
|
|
520
|
-
await refreshBalances();
|
|
521
|
-
return { address: state.address, chainId: state.chainId };
|
|
293
|
+
return res;
|
|
522
294
|
} catch (e) {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
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
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
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
|
|
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
|
|
@@ -654,11 +423,11 @@ export async function switchChain(chainSlugOrId) {
|
|
|
654
423
|
//
|
|
655
424
|
// Needed to learn the escrow address BEFORE it is created (factory.predict) and to read state
|
|
656
425
|
// (escrow.status) while polling. Requires no keys, asks the wallet nothing - only the provider.
|
|
657
|
-
export async function readContract({ to, data } = {}) {
|
|
426
|
+
export async function readContract({ to, data, block = "latest" } = {}) {
|
|
658
427
|
if (!provider) throw new Error("wallet not connected: nothing to read the contract with");
|
|
659
428
|
if (!to) throw new Error("no contract address given");
|
|
660
429
|
if (!data) throw new Error("no call data given");
|
|
661
|
-
const result = await provider.request({ method: "eth_call", params: [{ to, data }, "latest"] });
|
|
430
|
+
const result = await provider.request({ method: "eth_call", params: [{ to, data }, block || "latest"] });
|
|
662
431
|
if (typeof result !== "string" || !result.startsWith("0x")) {
|
|
663
432
|
throw new Error("unexpected answer to a contract call: " + String(result).slice(0, 60));
|
|
664
433
|
}
|
package/engine/monero/address.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
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
|
|
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 }
|
|
191
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
229
|
+
// Build an address of the right network from wallet keys.
|
|
246
230
|
export async function addressForNetwork({ network, kind = "primary", spendPub, viewPub }) {
|
|
247
|
-
|
|
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
|
}
|