@ninsei-labs/sdk 0.39.3 → 0.40.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 (69) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/engine/atomic/dleq2.js +86 -111
  3. package/engine/atomic/halfenc.js +58 -72
  4. package/engine/atomic/halves.js +31 -53
  5. package/engine/atomic/order-client.js +15 -16
  6. package/engine/atomic/order.js +44 -62
  7. package/engine/atomic/orderContext.js +26 -50
  8. package/engine/atomic/orderHalfCommit.js +17 -18
  9. package/engine/core/chainSource.js +54 -69
  10. package/engine/core/clock.js +11 -12
  11. package/engine/core/config.js +561 -451
  12. package/engine/core/finality.js +34 -53
  13. package/engine/core/format.js +35 -36
  14. package/engine/core/preSignGuards.js +109 -117
  15. package/engine/core/rfqSource.js +57 -75
  16. package/engine/core/sellWindow.js +23 -24
  17. package/engine/core/store.js +20 -21
  18. package/engine/core/swap.js +242 -243
  19. package/engine/evm/amounts.js +50 -51
  20. package/engine/evm/asyncExec.js +577 -0
  21. package/engine/evm/asyncLegs.js +308 -0
  22. package/engine/evm/asyncRoute.js +179 -0
  23. package/engine/evm/auth.js +41 -48
  24. package/engine/evm/claimGas.js +28 -47
  25. package/engine/evm/depositor.js +39 -43
  26. package/engine/evm/dex.js +266 -267
  27. package/engine/evm/escrow.js +113 -129
  28. package/engine/evm/factory.js +71 -77
  29. package/engine/evm/fees.js +41 -42
  30. package/engine/evm/funding.js +160 -162
  31. package/engine/evm/gasReserve.js +67 -36
  32. package/engine/evm/index.js +46 -53
  33. package/engine/evm/injected.js +34 -42
  34. package/engine/evm/permit.js +129 -56
  35. package/engine/evm/prices.js +30 -45
  36. package/engine/evm/session.js +188 -189
  37. package/engine/mock/chain.js +17 -18
  38. package/engine/monero/address.js +33 -48
  39. package/engine/monero/halvesSweep.js +25 -43
  40. package/engine/monero/node.js +14 -15
  41. package/engine/monero/scan.js +82 -95
  42. package/engine/monero/swapKeys.js +30 -33
  43. package/engine/monero/unlock.js +17 -20
  44. package/engine/monero/wallet.js +32 -42
  45. package/engine/recovery/recoveryFile.js +154 -161
  46. package/engine/recovery/restore.js +50 -61
  47. package/engine/sdk/bridge.js +244 -234
  48. package/engine/ui/dom.js +4 -5
  49. package/engine/ui/walletModal.js +20 -31
  50. package/index.d.ts +8 -0
  51. package/package.json +1 -1
  52. package/src/adapters/evm-wallet.mjs +16 -0
  53. package/src/adapters/monero-wallet.mjs +1 -1
  54. package/src/adapters/monero.mjs +1 -1
  55. package/src/adapters/node-test-evm-wallet.mjs +20 -8
  56. package/src/config.mjs +1 -1
  57. package/src/engine.mjs +4 -0
  58. package/src/legs/cow-spec.mjs +254 -0
  59. package/src/legs/cow.mjs +315 -0
  60. package/src/legs/evm.mjs +86 -2
  61. package/src/legs/kyber-spec.mjs +265 -0
  62. package/src/legs/kyber.mjs +425 -0
  63. package/src/legs/shape.mjs +35 -0
  64. package/src/legs/uniswaprelay-spec.mjs +541 -0
  65. package/src/legs/uniswaprelay.mjs +422 -0
  66. package/src/legs/uniswapx-spec.mjs +329 -0
  67. package/src/legs/uniswapx.mjs +362 -0
  68. package/src/quotes.mjs +1 -1
  69. package/src/swaps.mjs +1 -1
@@ -1,19 +1,17 @@
1
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, then run: node tools/build-sdk-engine.mjs
3
- // tools/check-sdk-engine.mjs reddens on any drift, so a stale copy cannot ship silently.
2
+ // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
4
3
  // Everything below this header is identical to the source.
5
4
 
6
- // Одноразовый Monero-кошелёк свапа.
5
+ // The one-shot Monero wallet of a swap.
7
6
  //
8
- // Ключи считает monero-js (ebellocchia/monero-js, MIT, вендорен в www/assets/vendors/monero-js):
9
- // мнемоника и ключи чистым JS - реальные и мгновенные. Библиотека умеет только mainnet-префиксы
10
- // адресов, поэтому строку адреса собирает наш энкодер (monero/address.js) для сети из конфига -
11
- // так работает и stagenet (24/36).
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.
12
11
  //
13
- // Ключи НЕ покидают браузер: наружу (на бэкенд, для watch-only кошелька) уходит только view key,
14
- // и делает это отдельная явная функция - recovery/restore.js::watchOnlyShareFromWallet. Так это
15
- // и описано в litepaper §5.4: кошелёк одноразовый, на одну сделку, seed основного кошелька
16
- // пользователя никогда не импортируется.
12
+ // Keys NEVER leave the browser: only the view key goes out (to the backend, for a watch-only wallet), and a
13
+ // separate explicit function does it - recovery/restore.js::watchOnlyShareFromWallet. The wallet is one-shot,
14
+ // for one deal, and the user's main-wallet seed is never imported.
17
15
 
18
16
  import { MONERO } from "../core/config.js";
19
17
  import { randomHex, toHex } from "../core/format.js";
@@ -32,11 +30,11 @@ function base58(bytes) {
32
30
  return out;
33
31
  }
34
32
 
35
- // Псевдо-адрес для мок-режима: правильная длина (95) и префикс сети, но БЕЗ checksum.
36
- // В UI он всегда помечен как mock - чтобы никто не отправил туда XMR.
33
+ // A pseudo-address for mock mode: the right length (95) and network prefix, but WITHOUT a checksum.
34
+ // The UI always marks it as mock, so nobody sends XMR there.
37
35
 
38
36
  // ---------------------------------------------------------------------------
39
- // monero-js (мнемоника + ключи + адреса, чистый JS)
37
+ // monero-js (mnemonic + keys + addresses, pure JS)
40
38
  // ---------------------------------------------------------------------------
41
39
 
42
40
  let moneroJsModule = null;
@@ -50,9 +48,9 @@ export async function loadMoneroJs() {
50
48
  moneroJsModule = mod.default || mod;
51
49
  return moneroJsModule;
52
50
  } catch (e) {
53
- // Причину не подменяем: «бандл не собран», «не залит» и «заблокирован CSP» - разные проблемы
51
+ // The reason is not replaced: "bundle not built", "not uploaded" and "blocked by CSP" are different problems
54
52
  moneroJsError = "monero-js unavailable: " + e.message +
55
- " (соберите npm run build:vendor; про CSP см. .hermes/docs/06-deploy.md)";
53
+ " (run npm run build:vendor; for CSP see the deploy notes)";
56
54
  throw new Error(moneroJsError);
57
55
  }
58
56
  }
@@ -61,20 +59,19 @@ async function withMoneroJs({ mnemonic: phrase, network = MONERO.networkType } =
61
59
  const lib = await loadMoneroJs();
62
60
  await lib.wallet.initEcc();
63
61
 
64
- // Если фразу передали - она обязана быть валидной. Раньше невалидная фраза молча заменялась
65
- // свежесгенерированной, и восстановление из испорченного recovery-файла давало ДРУГОЙ кошелёк:
66
- // ошибка выглядела бы как успех, а средства остались бы недоступны. Генерация - только когда
67
- // фразы нет вовсе.
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.
68
65
  let words;
69
66
  if (phrase) {
70
67
  if (!lib.mnemonic.isValid(phrase)) {
71
- throw new Error("мнемоника не прошла проверку контрольной суммы (файл или форма повреждены?)");
68
+ throw new Error("the mnemonic failed its checksum check (file or form corrupted?)");
72
69
  }
73
70
  words = String(phrase).trim();
74
71
  } else {
75
72
  words = lib.mnemonic.generateWithChecksum();
76
73
  }
77
- const seed = lib.mnemonic.toSeed(words); // 32 байта: для Monero сид == декодированная мнемоника
74
+ const seed = lib.mnemonic.toSeed(words); // 32 bytes: for Monero the seed == the decoded mnemonic
78
75
  const w = lib.wallet.fromSeed(seed);
79
76
 
80
77
  const net = network || "mainnet";
@@ -82,8 +79,8 @@ async function withMoneroJs({ mnemonic: phrase, network = MONERO.networkType } =
82
79
  const spendPub = toHex(w.publicSpendKey);
83
80
  const viewPub = toHex(w.publicViewKey);
84
81
  const sub = w.subaddress(1, 0);
85
- // адрес своей сети собираем сами (библиотека умеет только mainnet);
86
- // addressMainnet оставляем для сверки: на mainnet они обязаны совпадать
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
87
84
  const address = addressFromKeys({ network: net, kind: "primary", spendPub, viewPub }, deps);
88
85
  const subaddress = addressFromKeys(
89
86
  { network: net, kind: "subaddress", spendPub: toHex(sub.publicSpendKey), viewPub: toHex(sub.publicViewKey) },
@@ -109,19 +106,13 @@ async function withMoneroJs({ mnemonic: phrase, network = MONERO.networkType } =
109
106
  }
110
107
 
111
108
  // ---------------------------------------------------------------------------
112
- // monero-ts убран
109
+ // monero-ts removed
113
110
  // ---------------------------------------------------------------------------
114
- // Здесь был второй режим кошелька - WebAssembly wallet2 (woodser/monero-ts), который собирался
115
- // в www/assets/vendors/monero/monero-ts-browser.js. Он удалён из демки по двум причинам:
116
- // 1) WASM-кошельку нужен SharedArrayBuffer, то есть COOP/COEP, а на домене демки COEP заблокировал
117
- // бы сторонние ресурсы (шрифты, Verify WalletConnect);
118
- // 2) сам бандл переехал в sweep/ - у него свой домен с COOP/COEP (см. .hermes/docs/09-sweep-origin.md).
119
- // Раньше здесь называлась третья причина - «политика демки не пускает webpack-сборку monero-ts, она
120
- // использует eval». Причина была настоящей, но перестала ею быть: с monero-ts 0.11.16 бандл под
121
- // строгой политикой (script-src 'self' 'wasm-unsafe-eval', без 'unsafe-eval') работает, и это
122
- // доказано прогоном tools/check-csp-eval.mjs - прежний 0.11.15 под ней же падает на импорте.
123
- // Пока ветка кода оставалась, она тянула import по несуществующему пути - то есть была мёртвой
124
- // и при этом выглядела рабочей. Ключи в демке считает monero-js, и это единственный путь.
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.
125
116
 
126
117
  // ---------------------------------------------------------------------------
127
118
 
@@ -129,7 +120,7 @@ export async function createSwapWallet({ network = MONERO.networkType, seed } =
129
120
  return withMoneroJs({ mnemonic: seed, network });
130
121
  }
131
122
 
132
- // Доступна ли библиотека ключей (панель Demo controls показывает это одной строкой).
123
+ // Whether the key library is available (the Demo controls panel shows this as one line).
133
124
  export async function probeMode() {
134
125
  try {
135
126
  const lib = await loadMoneroJs();
@@ -140,10 +131,9 @@ export async function probeMode() {
140
131
  }
141
132
  }
142
133
 
143
- // Совместный адрес свапа. В реальном протоколе это адрес из СУММЫ публичных ключей
144
- // двух сторон (S_a + S_b, V_a + V_b): потратить выход можно только собрав обе половины
145
- // spend-ключа, а DLEQ-доказательство связывает половины с секретом.
146
- // В демке сумма считается по хешу от ключей: интерфейс и поток те же, криптография подменена явно.
134
+ // The joint swap address. In the real protocol it is the SUM of both sides' public keys (S_a + S_b, V_a + V_b):
135
+ // the output can be spent only with both halves of the spend key, and the DLEQ proof binds the halves to the
136
+ // secret. In the demo the sum is a hash of the keys: same interface and flow, cryptography openly replaced.
147
137
  export function combineAddress({ swapId, userPublicSpendKey, userPublicViewKey, makerKeySeed }) {
148
138
  const mk = (salt) => {
149
139
  const payload = `${salt}|${swapId}|${userPublicSpendKey}|${userPublicViewKey}`;
@@ -159,7 +149,7 @@ export function combineAddress({ swapId, userPublicSpendKey, userPublicViewKey,
159
149
  address: "8" + mk(makerKeySeed).slice(0, 94),
160
150
  spendShare: "0x" + mk("spend-share").slice(0, 64),
161
151
  viewShare: "0x" + mk("view-share").slice(0, 64),
162
- note: "mock: в реальном протоколе это сумма публичных ключей обеих сторон с DLEQ-доказательством",
152
+ note: "mock: in the real protocol this is the sum of both sides' public keys with a DLEQ proof",
163
153
  };
164
154
  }
165
155