@ninsei-labs/sdk 0.39.2 → 0.40.0-develop.1

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 (72) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +4 -1
  3. package/engine/atomic/dleq2.js +86 -111
  4. package/engine/atomic/halfenc.js +58 -72
  5. package/engine/atomic/halves.js +31 -53
  6. package/engine/atomic/order-client.js +15 -16
  7. package/engine/atomic/order.js +44 -62
  8. package/engine/atomic/orderContext.js +26 -50
  9. package/engine/atomic/orderHalfCommit.js +17 -18
  10. package/engine/core/chainSource.js +54 -69
  11. package/engine/core/clock.js +11 -12
  12. package/engine/core/config.js +554 -449
  13. package/engine/core/finality.js +34 -53
  14. package/engine/core/format.js +35 -36
  15. package/engine/core/preSignGuards.js +109 -117
  16. package/engine/core/rfqSource.js +57 -75
  17. package/engine/core/sellWindow.js +23 -24
  18. package/engine/core/store.js +20 -21
  19. package/engine/core/swap.js +242 -243
  20. package/engine/evm/amounts.js +50 -51
  21. package/engine/evm/asyncExec.js +577 -0
  22. package/engine/evm/asyncLegs.js +308 -0
  23. package/engine/evm/asyncRoute.js +179 -0
  24. package/engine/evm/auth.js +41 -48
  25. package/engine/evm/claimGas.js +28 -47
  26. package/engine/evm/depositor.js +39 -43
  27. package/engine/evm/dex.js +266 -267
  28. package/engine/evm/escrow.js +113 -129
  29. package/engine/evm/factory.js +71 -77
  30. package/engine/evm/fees.js +41 -42
  31. package/engine/evm/funding.js +160 -162
  32. package/engine/evm/gasReserve.js +67 -36
  33. package/engine/evm/index.js +46 -53
  34. package/engine/evm/injected.js +34 -42
  35. package/engine/evm/permit.js +129 -56
  36. package/engine/evm/prices.js +30 -45
  37. package/engine/evm/session.js +188 -189
  38. package/engine/mock/chain.js +17 -18
  39. package/engine/monero/address.js +33 -48
  40. package/engine/monero/halvesSweep.js +25 -43
  41. package/engine/monero/node.js +14 -15
  42. package/engine/monero/scan.js +82 -95
  43. package/engine/monero/swapKeys.js +30 -33
  44. package/engine/monero/unlock.js +17 -20
  45. package/engine/monero/wallet.js +32 -42
  46. package/engine/recovery/recoveryFile.js +154 -161
  47. package/engine/recovery/restore.js +50 -61
  48. package/engine/sdk/bridge.js +244 -234
  49. package/engine/ui/dom.js +4 -5
  50. package/engine/ui/walletModal.js +20 -31
  51. package/index.d.ts +26 -0
  52. package/package.json +1 -1
  53. package/src/adapters/evm-wallet.mjs +16 -0
  54. package/src/adapters/monero-wallet.mjs +1 -1
  55. package/src/adapters/monero.mjs +1 -1
  56. package/src/adapters/node-test-evm-wallet.mjs +5 -5
  57. package/src/codes.mjs +5 -0
  58. package/src/config.mjs +1 -1
  59. package/src/engine.mjs +4 -0
  60. package/src/index.mjs +16 -2
  61. package/src/legs/cow-spec.mjs +254 -0
  62. package/src/legs/cow.mjs +315 -0
  63. package/src/legs/evm.mjs +86 -2
  64. package/src/legs/kyber-spec.mjs +265 -0
  65. package/src/legs/kyber.mjs +425 -0
  66. package/src/legs/shape.mjs +35 -0
  67. package/src/legs/uniswaprelay-spec.mjs +541 -0
  68. package/src/legs/uniswaprelay.mjs +422 -0
  69. package/src/legs/uniswapx-spec.mjs +329 -0
  70. package/src/legs/uniswapx.mjs +362 -0
  71. package/src/quotes.mjs +23 -5
  72. package/src/swaps.mjs +18 -1
@@ -1,88 +1,87 @@
1
1
  // GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/amounts.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
- // Пересчёт балансов из «сырых» единиц контракта в человекочитаемые.
5
+ // Recalculating balances from the contract raw units into human-readable ones.
7
6
  //
8
- // Отдельным модулем, потому что это денежная математика и её надо проверять без браузера:
9
- // правильность decimals - самая частая ошибка EVM-кошельков (у USDT/USDC на BSC их 18, а не 6),
10
- // а цена ошибки - баланс, отличающийся на 10^12. Проверка живёт в tools/validate.mjs (npm test),
11
- // поэтому она гоняется и в CI, и локально.
7
+ // A separate module, because this is money maths and it must be checked without a browser:
8
+ // getting decimals right is the most common EVM-wallet bug (USDT/USDC on BSC have 18, not 6),
9
+ // and the price of the error is a balance off by 10^12. The check runs in the test battery,
10
+ // so it runs both in CI and locally.
12
11
 
13
- // BigInt (сырые единицы) -> число с точкой.
12
+ // BigInt (raw units) -> a decimal number.
14
13
  //
15
- // Делим как Number, а не целочисленно: вариант "raw * 1e6 / 10^dec" съедал мелкие значения -
16
- // 55000 wei при 18 decimals превращались ровно в 0, и демка показывала пустой баланс там, где
17
- // деньги есть (поймано проверкой на конкретных числах). Точности double достаточно: 15-16
18
- // значащих цифр против 6 знаков после точки, которые показывает интерфейс.
14
+ // We divide as Number, not integer: the variant "raw * 1e6 / 10^dec" swallowed small values -
15
+ // 55000 wei at 18 decimals turned into exactly 0, and the demo showed an empty balance where
16
+ // there is money (caught by a check on specific numbers). Double precision is enough: 15-16
17
+ // significant digits against the 6 decimals the interface shows.
19
18
  export function toHuman(raw, decimals) {
20
19
  return Number(raw) / 10 ** decimals;
21
20
  }
22
21
 
23
- // Убирает хвостовые нули у строки с точкой: "12.180000" -> "12.18".
24
- // Точка обязательна: у "1000" хвостовые нули трогать нельзя.
22
+ // Trims trailing zeros from a decimal string: "12.180000" -> "12.18".
23
+ // A dot is mandatory: for "1000" the trailing zeros must not be touched.
25
24
  export function trimTrailingZeros(text) {
26
25
  const s = String(text);
27
26
  return s.includes(".") ? s.replace(/0+$/, "").replace(/\.$/, "") : s;
28
27
  }
29
28
 
30
- // Сумма для показа и для кнопки MAX: усечение (не округление) и не больше 6 знаков после точки.
29
+ // Amount for display and for the MAX button: truncation (not rounding) and at most 6 decimals.
31
30
  //
32
- // Почему усечение: MAX не имеет права подставить сумму больше реального баланса - иначе форма
33
- // справедливо ответит "Not enough ...", и кнопка MAX приведёт в тупик. Округление вверх как раз
34
- // это и делало: 0.0399187 -> 0.039919 > баланса.
35
- // Почему 6 знаков: человеческая точность, и ровно столько же показывает подсказка с балансом.
36
- // Возвращает ЧИСЛО (для сравнений); строку для поля ввода даёт amountInputValue ниже.
31
+ // Why truncation: MAX must not insert an amount larger than the real balance - else the form
32
+ // rightly answers "Not enough ..." and the MAX button leads into a dead end. Rounding up did
33
+ // exactly that: 0.0399187 -> 0.039919 > balance.
34
+ // Why 6 decimals: human precision, and exactly what the balance hint shows.
35
+ // Returns a NUMBER (for comparisons); the string for the input field is given by amountInputValue below.
37
36
  export function floorAmount(value, decimals = 6) {
38
37
  const n = Number(value);
39
38
  if (!Number.isFinite(n) || n <= 0) return 0;
40
39
  const scaled = Math.floor(n * 10 ** decimals);
41
40
  if (scaled > 0) return scaled / 10 ** decimals;
42
- // Меньше 10^-decimals: это пыль. Отдаём значение целиком (точность до 18 знаков), чтобы
43
- // MAX не подставил 0.0000001 вместо 0.000000123 - то есть не отбросил баланс почти целиком.
41
+ // Below 10^-decimals: this is dust. We return the value whole (18-digit precision) so that
42
+ // MAX does not insert 0.0000001 instead of 0.000000123 - that is, does not drop the balance almost entirely.
44
43
  return Math.floor(n * 1e18) / 1e18;
45
44
  }
46
45
 
47
- // Строка для поля ввода и для подсказки с балансом: одна и та же функция, поэтому MAX
48
- // подставляет ровно то число, которое видит пользователь.
46
+ // String for the input field and for the balance hint: the same function, so MAX
47
+ // inserts exactly the number the user sees.
49
48
  //
50
- // toFixed, а не String(): String(1.23e-7) даёт "1e-7", а поле ввода принимает только цифры
51
- // и точку - "1e-7" превратилось бы в "17" (это поймано проверкой, а не пользователем).
49
+ // toFixed, not String(): String(1.23e-7) gives "1e-7", and the input field accepts only digits
50
+ // and a dot - "1e-7" would turn into "17" (caught by a check, not by a user).
52
51
  export function amountInputValue(value, decimals = 6) {
53
- // Сначала усекаем, потом форматируем: toFixed САМ округляет, и без усечения получалось
54
- // 0.039919 - то есть больше баланса, и MAX упирался в "Not enough ...".
52
+ // Truncate first, then format: toFixed ROUNDS itself, and without truncation you got
53
+ // 0.039919 - that is, more than the balance, and MAX hit "Not enough ...".
55
54
  const cut = floorAmount(value, decimals);
56
55
  if (!Number.isFinite(cut) || cut <= 0) return "0";
57
- // Для пыли печатаем все знаки: иначе toFixed округлил бы до первого ненулевого разряда.
56
+ // For dust we print all digits: else toFixed would round to the first non-zero digit.
58
57
  const d = cut >= 10 ** -decimals ? decimals : 18;
59
58
  return trimTrailingZeros(cut.toFixed(d));
60
59
  }
61
60
 
62
- // Набор случаев для проверки: [сырое значение, decimals, ожидаемое].
63
- // 6 decimals - USDT/USDC на Ethereum, Arbitrum, Base; 18 - на BNB Chain и у нативных токенов.
64
- // Ожидания сверены арифметикой вручную: 1 единица при 18 decimals это 1e-18, поэтому
65
- // 55000 wei - это 5.5e-14, а не 0.000055 (последнее - это 5.5e13 wei).
61
+ // Case set for the check: [raw value, decimals, expected].
62
+ // 6 decimals - USDT/USDC on Ethereum, Arbitrum, Base; 18 - on BNB Chain and for native tokens.
63
+ // The expectations were verified by hand arithmetic: 1 unit at 18 decimals is 1e-18, so
64
+ // 55000 wei is 5.5e-14, not 0.000055 (the latter is 5.5e13 wei).
66
65
  export const AMOUNT_CASES = [
67
66
  [12345678900n, 6, 12345.6789], // USDC, 6 decimals
68
- [108275582n, 6, 108.275582], // реальный баланс, снятый с Arbitrum
67
+ [108275582n, 6, 108.275582], // real balance, taken from Arbitrum
69
68
  [10n ** 18n, 18, 1], // 1 ETH
70
69
  [1500000000000000000n, 18, 1.5], // 1.5 ETH
71
- [55000000000000n, 18, 0.000055], // 0.000055 ETH - на экране видно, но старое округление врало
72
- [55000n, 18, 5.5e-14], // пыль: старая формула давала ровно 0 (тихая потеря)
70
+ [55000000000000n, 18, 0.000055], // 0.000055 ETH - visible on screen, but the old rounding lied
71
+ [55000n, 18, 5.5e-14], // dust: the old formula gave exactly 0 (a silent loss)
73
72
  [3120000000000000000000n, 18, 3120], // 3120 BNB
74
- [0n, 18, 0], // пустой кошелёк
73
+ [0n, 18, 0], // empty wallet
75
74
  ];
76
75
 
77
- // Случаи для показа баланса и MAX: [баланс, ожидаемая строка].
78
- // Первый - ровно то, на что жаловался пользователь: 0.03991877164758065 попадало в поле целиком.
76
+ // Cases for balance display and MAX: [balance, expected string].
77
+ // The first is exactly what the user complained about: 0.03991877164758065 landed in the field whole.
79
78
  export const MAX_CASES = [
80
- [0.03991877164758065, "0.039918"], // тот самый ETH: 6 знаков, как в подсказке
81
- [0.0399187, "0.039918"], // усечение вниз, а не округление вверх до 0.039919
82
- [12431.18, "12431.18"], // стейбл: хвостовых нулей нет
79
+ [0.03991877164758065, "0.039918"], // that very ETH: 6 digits, as in the hint
80
+ [0.0399187, "0.039918"], // truncation down, not rounding up to 0.039919
81
+ [12431.18, "12431.18"], // stable: no trailing zeros
83
82
  [3.4125, "3.4125"],
84
83
  [1, "1"],
85
- [0.000000123, "0.000000123"], // пыль: ни нуля, ни экспоненты "1e-7"
84
+ [0.000000123, "0.000000123"], // dust: neither zero nor the exponent "1e-7"
86
85
  [0, "0"],
87
86
  ];
88
87
 
@@ -94,8 +93,8 @@ export const TRIM_CASES = [
94
93
  ["0.000000", "0"],
95
94
  ];
96
95
 
97
- // Поле ввода принимает только цифры и точку (см. oninput в swapForm.js). Если строка этому
98
- // не удовлетворяет, поле молча превратит её в другое число - поэтому проверяем и это.
96
+ // The input field accepts only digits and a dot (see oninput in swapForm.js). If a string does not
97
+ // satisfy this, the field silently turns it into another number - so we check that too.
99
98
  const INPUT_PATTERN = /^[0-9]+(\.[0-9]+)?$/;
100
99
 
101
100
  export function checkAmounts({ tolerance = 1e-9 } = {}) {
@@ -104,27 +103,27 @@ export function checkAmounts({ tolerance = 1e-9 } = {}) {
104
103
  for (const [raw, decimals, expected] of AMOUNT_CASES) {
105
104
  const got = toHuman(raw, decimals);
106
105
  if (!Number.isFinite(got) || Math.abs(got - expected) > tolerance) {
107
- failures.push(`${raw} при ${decimals} decimals -> ${got}, ожидалось ${expected}`);
106
+ failures.push(`${raw} at ${decimals} decimals -> ${got}, expected ${expected}`);
108
107
  }
109
108
  }
110
109
 
111
110
  for (const [balance, expected] of MAX_CASES) {
112
111
  const got = amountInputValue(balance);
113
112
  if (got !== expected) {
114
- failures.push(`MAX при балансе ${balance} -> "${got}", ожидалось "${expected}"`);
113
+ failures.push(`MAX at balance ${balance} -> "${got}", expected "${expected}"`);
115
114
  }
116
115
  if (!INPUT_PATTERN.test(got)) {
117
- failures.push(`MAX при балансе ${balance} дал "${got}" - поле ввода такое значение исказит`);
116
+ failures.push(`MAX at balance ${balance} gave "${got}" - the input field will distort that value`);
118
117
  }
119
- // Главное свойство MAX: подставленная сумма НЕ больше баланса.
118
+ // The key property of MAX: the inserted amount is NOT larger than the balance.
120
119
  if (floorAmount(balance) > balance) {
121
- failures.push(`MAX при балансе ${balance} подставил больше баланса: ${floorAmount(balance)}`);
120
+ failures.push(`MAX at balance ${balance} inserted more than the balance: ${floorAmount(balance)}`);
122
121
  }
123
122
  }
124
123
 
125
124
  for (const [input, expected] of TRIM_CASES) {
126
125
  const got = trimTrailingZeros(input);
127
- if (got !== expected) failures.push(`показ баланса "${input}" -> "${got}", ожидалось "${expected}"`);
126
+ if (got !== expected) failures.push(`balance display "${input}" -> "${got}", expected "${expected}"`);
128
127
  }
129
128
 
130
129
  return failures;