@skate-org/amm-evm-v2 0.4.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 (46) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +33 -0
  3. package/dist/chain-clients.d.ts +42 -0
  4. package/dist/chain-clients.d.ts.map +1 -0
  5. package/dist/devConfig.d.ts +23 -0
  6. package/dist/devConfig.d.ts.map +1 -0
  7. package/dist/errors.d.ts +53 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/events/index.d.ts +4 -0
  10. package/dist/events/index.d.ts.map +1 -0
  11. package/dist/events/kernel.d.ts +25 -0
  12. package/dist/events/kernel.d.ts.map +1 -0
  13. package/dist/events/periphery.d.ts +21 -0
  14. package/dist/events/periphery.d.ts.map +1 -0
  15. package/dist/events/watch.d.ts +23 -0
  16. package/dist/events/watch.d.ts.map +1 -0
  17. package/dist/index.cjs +997 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +8 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +952 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/kernel/index.d.ts +3 -0
  25. package/dist/kernel/index.d.ts.map +1 -0
  26. package/dist/kernel/reader.d.ts +77 -0
  27. package/dist/kernel/reader.d.ts.map +1 -0
  28. package/dist/kernel/tickBitmap.d.ts +30 -0
  29. package/dist/kernel/tickBitmap.d.ts.map +1 -0
  30. package/dist/math/fullMath.d.ts +28 -0
  31. package/dist/math/fullMath.d.ts.map +1 -0
  32. package/dist/math/index.d.ts +5 -0
  33. package/dist/math/index.d.ts.map +1 -0
  34. package/dist/math/liquidityMath.d.ts +18 -0
  35. package/dist/math/liquidityMath.d.ts.map +1 -0
  36. package/dist/math/sqrtPriceMath.d.ts +62 -0
  37. package/dist/math/sqrtPriceMath.d.ts.map +1 -0
  38. package/dist/math/tickMath.d.ts +36 -0
  39. package/dist/math/tickMath.d.ts.map +1 -0
  40. package/dist/periphery/index.d.ts +3 -0
  41. package/dist/periphery/index.d.ts.map +1 -0
  42. package/dist/periphery/reader.d.ts +75 -0
  43. package/dist/periphery/reader.d.ts.map +1 -0
  44. package/dist/periphery/submit.d.ts +63 -0
  45. package/dist/periphery/submit.d.ts.map +1 -0
  46. package/package.json +41 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,997 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULT_DEV_API_ENDPOINT: () => DEFAULT_DEV_API_ENDPOINT,
24
+ EvmReadError: () => EvmReadError,
25
+ EvmWriteError: () => EvmWriteError,
26
+ KERNEL_EVENT_NAMES: () => KERNEL_EVENT_NAMES,
27
+ MAX_SQRT_RATIO: () => MAX_SQRT_RATIO,
28
+ MAX_TICK: () => MAX_TICK,
29
+ MIN_SQRT_RATIO: () => MIN_SQRT_RATIO,
30
+ MIN_TICK: () => MIN_TICK,
31
+ PERIPHERY_EVENT_NAMES: () => PERIPHERY_EVENT_NAMES,
32
+ addDelta: () => addDelta,
33
+ computePositionAmounts: () => computePositionAmounts,
34
+ createDevConfig: () => createDevConfig,
35
+ decodeTickBitmapWord: () => decodeTickBitmapWord,
36
+ getAmount0Delta: () => getAmount0Delta,
37
+ getAmount0DeltaSigned: () => getAmount0DeltaSigned,
38
+ getAmount1Delta: () => getAmount1Delta,
39
+ getAmount1DeltaSigned: () => getAmount1DeltaSigned,
40
+ getKernelPublicClient: () => getKernelPublicClient,
41
+ getNextSqrtPriceFromAmount0RoundingUp: () => getNextSqrtPriceFromAmount0RoundingUp,
42
+ getNextSqrtPriceFromAmount1RoundingDown: () => getNextSqrtPriceFromAmount1RoundingDown,
43
+ getNextSqrtPriceFromInput: () => getNextSqrtPriceFromInput,
44
+ getNextSqrtPriceFromOutput: () => getNextSqrtPriceFromOutput,
45
+ getSourcePublicClient: () => getSourcePublicClient,
46
+ getSqrtRatioAtTick: () => getSqrtRatioAtTick,
47
+ getTickAtSqrtRatio: () => getTickAtSqrtRatio,
48
+ megaethChain: () => megaethChain,
49
+ mulDiv: () => mulDiv,
50
+ mulDivRoundingUp: () => mulDivRoundingUp,
51
+ parseKernelEventLog: () => parseKernelEventLog,
52
+ parsePeripheryEventLog: () => parsePeripheryEventLog,
53
+ readPeripheryPool: () => readPeripheryPool,
54
+ readPool: () => readPool,
55
+ readPosition: () => readPosition,
56
+ readTick: () => readTick,
57
+ readTickBitmap: () => readTickBitmap,
58
+ readUserPoolBalances: () => readUserPoolBalances,
59
+ submitAction: () => submitAction,
60
+ submitApproval: () => submitApproval,
61
+ submitSwap: () => submitSwap,
62
+ watchKernelEvents: () => watchKernelEvents,
63
+ watchPeripheryEvents: () => watchPeripheryEvents
64
+ });
65
+ module.exports = __toCommonJS(index_exports);
66
+
67
+ // src/chain-clients.ts
68
+ var import_viem = require("viem");
69
+ var import_chains = require("viem/chains");
70
+ var import_amm_core_v2 = require("@skate-org/amm-core-v2");
71
+ var megaethChain = (0, import_viem.defineChain)({
72
+ id: 4326,
73
+ name: "MegaETH",
74
+ network: "megaeth",
75
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
76
+ rpcUrls: {
77
+ default: { http: ["https://mainnet.megaeth.com/rpc"] },
78
+ public: { http: ["https://mainnet.megaeth.com/rpc"] }
79
+ },
80
+ blockExplorers: {
81
+ default: { name: "Blockscout", url: import_amm_core_v2.BLOCK_EXPLORER.MEGAETH }
82
+ }
83
+ });
84
+ var DEFAULT_RPC = {
85
+ [import_amm_core_v2.CHAIN.MEGAETH]: "https://mainnet.megaeth.com/rpc",
86
+ [import_amm_core_v2.CHAIN.ARBITRUM]: "https://arb1.arbitrum.io/rpc"
87
+ };
88
+ function chainDefFor(chain) {
89
+ switch (chain) {
90
+ case import_amm_core_v2.CHAIN.MEGAETH:
91
+ return megaethChain;
92
+ case import_amm_core_v2.CHAIN.ARBITRUM:
93
+ return import_chains.arbitrum;
94
+ default:
95
+ return void 0;
96
+ }
97
+ }
98
+ function resolveRpcUrl(chain, mode) {
99
+ const { config } = (0, import_amm_core_v2.normalizeMode)(mode);
100
+ return config?.rpcEndpoints?.[chain] ?? DEFAULT_RPC[chain];
101
+ }
102
+ function getKernelPublicClient(mode, transport) {
103
+ return (0, import_viem.createPublicClient)({
104
+ chain: megaethChain,
105
+ transport: transport ?? (0, import_viem.http)(resolveRpcUrl(import_amm_core_v2.CHAIN.MEGAETH, mode))
106
+ });
107
+ }
108
+ function getSourcePublicClient(chain, mode, transport) {
109
+ if ((0, import_amm_core_v2.vmTypeFromChain)(chain) !== import_amm_core_v2.VM.EVM) {
110
+ throw new Error(
111
+ `getSourcePublicClient: chain ${chain} is not an EVM chain`
112
+ );
113
+ }
114
+ const chainDef = chainDefFor(chain);
115
+ if (!chainDef) {
116
+ throw new Error(
117
+ `getSourcePublicClient: no chain definition registered for chain ${chain}`
118
+ );
119
+ }
120
+ const rpc = resolveRpcUrl(chain, mode);
121
+ if (!rpc && !transport) {
122
+ throw new Error(
123
+ `getSourcePublicClient: no default or override RPC configured for chain ${chain}; pass a transport override or set DevModeConfig.rpcEndpoints[${chain}]`
124
+ );
125
+ }
126
+ return (0, import_viem.createPublicClient)({
127
+ chain: chainDef,
128
+ transport: transport ?? (0, import_viem.http)(rpc)
129
+ });
130
+ }
131
+
132
+ // src/devConfig.ts
133
+ var DEFAULT_DEV_API_ENDPOINT = "https://dev.api.skatechain.org/amm-action-v2";
134
+ function createDevConfig(overrides = {}) {
135
+ return {
136
+ mode: "DEV",
137
+ config: {
138
+ apiEndpoint: overrides.apiEndpoint ?? DEFAULT_DEV_API_ENDPOINT,
139
+ ...overrides.rpcEndpoints ? { rpcEndpoints: overrides.rpcEndpoints } : {}
140
+ }
141
+ };
142
+ }
143
+
144
+ // src/errors.ts
145
+ var import_amm_core_v22 = require("@skate-org/amm-core-v2");
146
+ var EvmReadError = class extends import_amm_core_v22.SdkError {
147
+ name = "EvmReadError";
148
+ functionName;
149
+ constructor(functionName, message, options) {
150
+ super(`${functionName}: ${message}`, options);
151
+ this.functionName = functionName;
152
+ }
153
+ };
154
+ var EvmWriteError = class extends import_amm_core_v22.SdkError {
155
+ name = "EvmWriteError";
156
+ functionName;
157
+ constructor(functionName, message, options) {
158
+ super(`${functionName}: ${message}`, options);
159
+ this.functionName = functionName;
160
+ }
161
+ };
162
+ function wrapReadError(err, functionName) {
163
+ const outerName = err?.name;
164
+ const causeName = err?.cause?.name;
165
+ const message = err?.shortMessage ?? err?.message ?? String(err);
166
+ const isViemContractError = outerName === "ContractFunctionExecutionError" || outerName === "ContractFunctionRevertedError" || outerName === "ContractFunctionZeroDataError" || causeName === "ContractFunctionRevertedError" || causeName === "ContractFunctionZeroDataError";
167
+ if (isViemContractError) {
168
+ return new EvmReadError(functionName, `reverted: ${message}`, {
169
+ cause: err
170
+ });
171
+ }
172
+ return new EvmReadError(functionName, message, { cause: err });
173
+ }
174
+ function wrapWriteError(err, functionName) {
175
+ const message = err?.shortMessage ?? err?.message ?? String(err);
176
+ return new EvmWriteError(functionName, message, { cause: err });
177
+ }
178
+
179
+ // src/math/tickMath.ts
180
+ var MAX_UINT256 = (1n << 256n) - 1n;
181
+ var Q160_MASK = (1n << 160n) - 1n;
182
+ var Q256_MOD = 1n << 256n;
183
+ var MIN_TICK = -887272;
184
+ var MAX_TICK = 887272;
185
+ var MIN_SQRT_RATIO = 4295128739n;
186
+ var MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342n;
187
+ function getSqrtRatioAtTick(tick) {
188
+ if (!Number.isInteger(tick)) {
189
+ throw new Error("TickMath: tick must be an integer");
190
+ }
191
+ const absTick = BigInt(tick < 0 ? -tick : tick);
192
+ if (absTick > BigInt(MAX_TICK)) {
193
+ throw new Error("T");
194
+ }
195
+ let ratio = (absTick & 0x1n) !== 0n ? 0xfffcb933bd6fad37aa2d162d1a594001n : 0x100000000000000000000000000000000n;
196
+ if ((absTick & 0x2n) !== 0n)
197
+ ratio = (ratio * 0xfff97272373d413259a46990580e213an & MAX_UINT256) >> 128n;
198
+ if ((absTick & 0x4n) !== 0n)
199
+ ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn & MAX_UINT256) >> 128n;
200
+ if ((absTick & 0x8n) !== 0n)
201
+ ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n & MAX_UINT256) >> 128n;
202
+ if ((absTick & 0x10n) !== 0n)
203
+ ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644n & MAX_UINT256) >> 128n;
204
+ if ((absTick & 0x20n) !== 0n)
205
+ ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0n & MAX_UINT256) >> 128n;
206
+ if ((absTick & 0x40n) !== 0n)
207
+ ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861n & MAX_UINT256) >> 128n;
208
+ if ((absTick & 0x80n) !== 0n)
209
+ ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053n & MAX_UINT256) >> 128n;
210
+ if ((absTick & 0x100n) !== 0n)
211
+ ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n & MAX_UINT256) >> 128n;
212
+ if ((absTick & 0x200n) !== 0n)
213
+ ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54n & MAX_UINT256) >> 128n;
214
+ if ((absTick & 0x400n) !== 0n)
215
+ ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3n & MAX_UINT256) >> 128n;
216
+ if ((absTick & 0x800n) !== 0n)
217
+ ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n & MAX_UINT256) >> 128n;
218
+ if ((absTick & 0x1000n) !== 0n)
219
+ ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n & MAX_UINT256) >> 128n;
220
+ if ((absTick & 0x2000n) !== 0n)
221
+ ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n & MAX_UINT256) >> 128n;
222
+ if ((absTick & 0x4000n) !== 0n)
223
+ ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7n & MAX_UINT256) >> 128n;
224
+ if ((absTick & 0x8000n) !== 0n)
225
+ ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6n & MAX_UINT256) >> 128n;
226
+ if ((absTick & 0x10000n) !== 0n)
227
+ ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n & MAX_UINT256) >> 128n;
228
+ if ((absTick & 0x20000n) !== 0n)
229
+ ratio = (ratio * 0x5d6af8dedb81196699c329225ee604n & MAX_UINT256) >> 128n;
230
+ if ((absTick & 0x40000n) !== 0n)
231
+ ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98n & MAX_UINT256) >> 128n;
232
+ if ((absTick & 0x80000n) !== 0n)
233
+ ratio = (ratio * 0x48a170391f7dc42444e8fa2n & MAX_UINT256) >> 128n;
234
+ if (tick > 0) ratio = MAX_UINT256 / ratio;
235
+ const shifted = ratio >> 32n;
236
+ const remainder = ratio & (1n << 32n) - 1n;
237
+ const sqrtPriceX96 = remainder === 0n ? shifted : shifted + 1n;
238
+ return sqrtPriceX96 & Q160_MASK;
239
+ }
240
+ function getTickAtSqrtRatio(sqrtPriceX96) {
241
+ if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) {
242
+ throw new Error("R");
243
+ }
244
+ const ratio = sqrtPriceX96 << 32n;
245
+ let r = ratio;
246
+ let msb = 0n;
247
+ {
248
+ const f = r > 0xffffffffffffffffffffffffffffffffn ? 128n : 0n;
249
+ msb |= f;
250
+ r >>= f;
251
+ }
252
+ {
253
+ const f = r > 0xffffffffffffffffn ? 64n : 0n;
254
+ msb |= f;
255
+ r >>= f;
256
+ }
257
+ {
258
+ const f = r > 0xffffffffn ? 32n : 0n;
259
+ msb |= f;
260
+ r >>= f;
261
+ }
262
+ {
263
+ const f = r > 0xffffn ? 16n : 0n;
264
+ msb |= f;
265
+ r >>= f;
266
+ }
267
+ {
268
+ const f = r > 0xffn ? 8n : 0n;
269
+ msb |= f;
270
+ r >>= f;
271
+ }
272
+ {
273
+ const f = r > 0xfn ? 4n : 0n;
274
+ msb |= f;
275
+ r >>= f;
276
+ }
277
+ {
278
+ const f = r > 0x3n ? 2n : 0n;
279
+ msb |= f;
280
+ r >>= f;
281
+ }
282
+ {
283
+ const f = r > 0x1n ? 1n : 0n;
284
+ msb |= f;
285
+ }
286
+ if (msb >= 128n) r = ratio >> msb - 127n;
287
+ else r = ratio << 127n - msb & MAX_UINT256;
288
+ const offset = msb - 128n;
289
+ let log_2 = offset << 64n & MAX_UINT256;
290
+ for (let i = 0; i < 14; i++) {
291
+ r = r * r >> 127n;
292
+ const f = r >> 128n;
293
+ log_2 |= f << BigInt(63 - i);
294
+ r >>= f;
295
+ }
296
+ const log_2_signed = toInt256(log_2);
297
+ const log_sqrt10001 = log_2_signed * 255738958999603826347141n;
298
+ const tickLowBig = log_sqrt10001 - 3402992956809132418596140100660247210n >> 128n;
299
+ const tickHiBig = log_sqrt10001 + 291339464771989622907027621153398088495n >> 128n;
300
+ const tickLow = toInt24(tickLowBig);
301
+ const tickHi = toInt24(tickHiBig);
302
+ if (tickLow === tickHi) return tickLow;
303
+ return getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
304
+ }
305
+ function toInt256(x) {
306
+ const masked = x & MAX_UINT256;
307
+ return masked >= 1n << 255n ? masked - Q256_MOD : masked;
308
+ }
309
+ function toInt24(x) {
310
+ const mask = (1n << 24n) - 1n;
311
+ const truncated = x & mask;
312
+ const signed = truncated >= 1n << 23n ? truncated - (1n << 24n) : truncated;
313
+ return Number(signed);
314
+ }
315
+
316
+ // src/math/fullMath.ts
317
+ var MAX_UINT2562 = (1n << 256n) - 1n;
318
+ function mulDiv(a, b, denom) {
319
+ if (denom === 0n) {
320
+ throw new Error("FullMath: division by zero");
321
+ }
322
+ if (a < 0n || b < 0n || denom < 0n) {
323
+ throw new Error("FullMath: negative input");
324
+ }
325
+ const product = a * b;
326
+ const result = product / denom;
327
+ if (result > MAX_UINT2562) {
328
+ throw new Error("FullMath: result overflows uint256");
329
+ }
330
+ return result;
331
+ }
332
+ function mulDivRoundingUp(a, b, denom) {
333
+ if (denom === 0n) {
334
+ throw new Error("FullMath: division by zero");
335
+ }
336
+ if (a < 0n || b < 0n || denom < 0n) {
337
+ throw new Error("FullMath: negative input");
338
+ }
339
+ const product = a * b;
340
+ const quotient = product / denom;
341
+ if (quotient > MAX_UINT2562) {
342
+ throw new Error("FullMath: result overflows uint256");
343
+ }
344
+ if (product % denom !== 0n) {
345
+ if (quotient === MAX_UINT2562) {
346
+ throw new Error("FullMath: rounding up overflows uint256");
347
+ }
348
+ return quotient + 1n;
349
+ }
350
+ return quotient;
351
+ }
352
+
353
+ // src/math/sqrtPriceMath.ts
354
+ var MAX_UINT128 = (1n << 128n) - 1n;
355
+ var MAX_UINT160 = (1n << 160n) - 1n;
356
+ var MAX_UINT2563 = (1n << 256n) - 1n;
357
+ var Q96_RESOLUTION = 96n;
358
+ var Q96 = 1n << 96n;
359
+ function assertUint160(x, name) {
360
+ if (x < 0n || x > MAX_UINT160) {
361
+ throw new Error(`SqrtPriceMath: ${name} out of uint160 range`);
362
+ }
363
+ }
364
+ function assertUint128(x, name) {
365
+ if (x < 0n || x > MAX_UINT128) {
366
+ throw new Error(`SqrtPriceMath: ${name} out of uint128 range`);
367
+ }
368
+ }
369
+ function assertUint256(x, name) {
370
+ if (x < 0n || x > MAX_UINT2563) {
371
+ throw new Error(`SqrtPriceMath: ${name} out of uint256 range`);
372
+ }
373
+ }
374
+ function divRoundingUp(x, y) {
375
+ if (y === 0n) throw new Error("SqrtPriceMath: div by zero");
376
+ return x / y + (x % y === 0n ? 0n : 1n);
377
+ }
378
+ function toUint160(x) {
379
+ if (x > MAX_UINT160) throw new Error("SqrtPriceMath: toUint160 overflow");
380
+ return x;
381
+ }
382
+ function getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
383
+ assertUint160(sqrtPX96, "sqrtPX96");
384
+ assertUint128(liquidity, "liquidity");
385
+ assertUint256(amount, "amount");
386
+ if (amount === 0n) return sqrtPX96;
387
+ const numerator1 = liquidity << Q96_RESOLUTION;
388
+ if (add) {
389
+ const product = amount * sqrtPX96 & MAX_UINT2563;
390
+ const noOverflow = amount === 0n || product / amount === sqrtPX96;
391
+ if (noOverflow) {
392
+ const denominator = numerator1 + product;
393
+ if (denominator >= numerator1) {
394
+ return toUint160(mulDivRoundingUp(numerator1, sqrtPX96, denominator));
395
+ }
396
+ }
397
+ if (sqrtPX96 === 0n) throw new Error("SqrtPriceMath: sqrtPX96 == 0");
398
+ const denom = numerator1 / sqrtPX96 + amount;
399
+ return toUint160(divRoundingUp(numerator1, denom));
400
+ } else {
401
+ const product = amount * sqrtPX96 & MAX_UINT2563;
402
+ const noOverflow = amount === 0n || product / amount === sqrtPX96;
403
+ if (!noOverflow || numerator1 <= product) {
404
+ throw new Error("SqrtPriceMath: getNextSqrtPriceFromAmount0 denom <= 0");
405
+ }
406
+ const denominator = numerator1 - product;
407
+ return toUint160(mulDivRoundingUp(numerator1, sqrtPX96, denominator));
408
+ }
409
+ }
410
+ function getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
411
+ assertUint160(sqrtPX96, "sqrtPX96");
412
+ assertUint128(liquidity, "liquidity");
413
+ assertUint256(amount, "amount");
414
+ if (add) {
415
+ const quotient = amount <= MAX_UINT160 ? (amount << Q96_RESOLUTION) / liquidity : mulDiv(amount, Q96, liquidity);
416
+ return toUint160(sqrtPX96 + quotient);
417
+ } else {
418
+ const quotient = amount <= MAX_UINT160 ? divRoundingUp(amount << Q96_RESOLUTION, liquidity) : mulDivRoundingUp(amount, Q96, liquidity);
419
+ if (sqrtPX96 <= quotient) {
420
+ throw new Error("SqrtPriceMath: sqrtPX96 <= quotient");
421
+ }
422
+ return sqrtPX96 - quotient;
423
+ }
424
+ }
425
+ function getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
426
+ if (sqrtPX96 <= 0n) throw new Error("SqrtPriceMath: sqrtPX96 must be > 0");
427
+ if (liquidity <= 0n)
428
+ throw new Error("SqrtPriceMath: liquidity must be > 0");
429
+ return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(
430
+ sqrtPX96,
431
+ liquidity,
432
+ amountIn,
433
+ true
434
+ );
435
+ }
436
+ function getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
437
+ if (sqrtPX96 <= 0n) throw new Error("SqrtPriceMath: sqrtPX96 must be > 0");
438
+ if (liquidity <= 0n)
439
+ throw new Error("SqrtPriceMath: liquidity must be > 0");
440
+ return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(
441
+ sqrtPX96,
442
+ liquidity,
443
+ amountOut,
444
+ false
445
+ ) : getNextSqrtPriceFromAmount0RoundingUp(
446
+ sqrtPX96,
447
+ liquidity,
448
+ amountOut,
449
+ false
450
+ );
451
+ }
452
+ function getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
453
+ assertUint160(sqrtRatioAX96, "sqrtRatioAX96");
454
+ assertUint160(sqrtRatioBX96, "sqrtRatioBX96");
455
+ assertUint128(liquidity, "liquidity");
456
+ let a = sqrtRatioAX96;
457
+ let b = sqrtRatioBX96;
458
+ if (a > b) {
459
+ [a, b] = [b, a];
460
+ }
461
+ if (a === 0n) throw new Error("SqrtPriceMath: sqrtRatio must be > 0");
462
+ const numerator1 = liquidity << Q96_RESOLUTION;
463
+ const numerator2 = b - a;
464
+ if (roundUp) {
465
+ return divRoundingUp(mulDivRoundingUp(numerator1, numerator2, b), a);
466
+ }
467
+ return mulDiv(numerator1, numerator2, b) / a;
468
+ }
469
+ function getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
470
+ assertUint160(sqrtRatioAX96, "sqrtRatioAX96");
471
+ assertUint160(sqrtRatioBX96, "sqrtRatioBX96");
472
+ assertUint128(liquidity, "liquidity");
473
+ let a = sqrtRatioAX96;
474
+ let b = sqrtRatioBX96;
475
+ if (a > b) {
476
+ [a, b] = [b, a];
477
+ }
478
+ return roundUp ? mulDivRoundingUp(liquidity, b - a, Q96) : mulDiv(liquidity, b - a, Q96);
479
+ }
480
+ function getAmount0DeltaSigned(sqrtRatioAX96, sqrtRatioBX96, liquidity) {
481
+ const INT128_MIN2 = -(1n << 127n);
482
+ const INT128_MAX2 = (1n << 127n) - 1n;
483
+ if (liquidity < INT128_MIN2 || liquidity > INT128_MAX2) {
484
+ throw new Error("SqrtPriceMath: liquidity out of int128 range");
485
+ }
486
+ if (liquidity < 0n) {
487
+ return -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, -liquidity, false);
488
+ }
489
+ return getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, true);
490
+ }
491
+ function getAmount1DeltaSigned(sqrtRatioAX96, sqrtRatioBX96, liquidity) {
492
+ const INT128_MIN2 = -(1n << 127n);
493
+ const INT128_MAX2 = (1n << 127n) - 1n;
494
+ if (liquidity < INT128_MIN2 || liquidity > INT128_MAX2) {
495
+ throw new Error("SqrtPriceMath: liquidity out of int128 range");
496
+ }
497
+ if (liquidity < 0n) {
498
+ return -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, -liquidity, false);
499
+ }
500
+ return getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, true);
501
+ }
502
+
503
+ // src/math/liquidityMath.ts
504
+ var MAX_UINT1282 = (1n << 128n) - 1n;
505
+ var INT128_MAX = (1n << 127n) - 1n;
506
+ var INT128_MIN = -(1n << 127n);
507
+ function addDelta(x, y) {
508
+ if (x < 0n || x > MAX_UINT1282) {
509
+ throw new Error("LiquidityMath: x out of uint128 range");
510
+ }
511
+ if (y < INT128_MIN || y > INT128_MAX) {
512
+ throw new Error("LiquidityMath: y out of int128 range");
513
+ }
514
+ const z = x + y;
515
+ if (y < 0n) {
516
+ if (z < 0n) throw new Error("LS");
517
+ } else {
518
+ if (z > MAX_UINT1282) throw new Error("LA");
519
+ }
520
+ return z;
521
+ }
522
+
523
+ // src/kernel/reader.ts
524
+ var import_amm_bindings = require("@skate-org/amm-bindings");
525
+ var import_amm_core_v23 = require("@skate-org/amm-core-v2");
526
+ function resolveClient(mode, client) {
527
+ return client ?? getKernelPublicClient(mode);
528
+ }
529
+ async function readPool(kernelPool, mode, client) {
530
+ const c = resolveClient(mode, client);
531
+ try {
532
+ const [slot0, liquidity] = await Promise.all([
533
+ c.readContract({
534
+ address: kernelPool,
535
+ abi: import_amm_bindings.KernelPoolABI,
536
+ functionName: "slot0"
537
+ }),
538
+ c.readContract({
539
+ address: kernelPool,
540
+ abi: import_amm_bindings.KernelPoolABI,
541
+ functionName: "liquidity"
542
+ })
543
+ ]);
544
+ const s0 = slot0;
545
+ return {
546
+ slot0: {
547
+ sqrtPriceX96: s0[0],
548
+ tick: s0[1],
549
+ observationIndex: s0[2],
550
+ observationCardinality: s0[3],
551
+ observationCardinalityNext: s0[4],
552
+ feeProtocol: s0[5],
553
+ unlocked: s0[6]
554
+ },
555
+ liquidity
556
+ };
557
+ } catch (err) {
558
+ throw wrapReadError(err, "readPool");
559
+ }
560
+ }
561
+ async function readPosition(tokenId, mode, client) {
562
+ const { mode: baseMode } = (0, import_amm_core_v23.normalizeMode)(mode);
563
+ const manager = (0, import_amm_core_v23.KernelManagerAddress)(baseMode);
564
+ const c = resolveClient(mode, client);
565
+ try {
566
+ const raw = await c.readContract({
567
+ address: manager,
568
+ abi: import_amm_bindings.KernelManagerABI,
569
+ functionName: "nftPositions",
570
+ args: [tokenId]
571
+ });
572
+ const asTuple = Array.isArray(raw) ? raw : null;
573
+ if (asTuple) {
574
+ return {
575
+ pool: asTuple[0],
576
+ tickLower: asTuple[1],
577
+ tickUpper: asTuple[2],
578
+ liquidity: asTuple[3],
579
+ feeGrowthInside0LastX128: asTuple[4],
580
+ feeGrowthInside1LastX128: asTuple[5],
581
+ tokensOwed0: asTuple[6],
582
+ tokensOwed1: asTuple[7]
583
+ };
584
+ }
585
+ return raw;
586
+ } catch (err) {
587
+ throw wrapReadError(err, "readPosition");
588
+ }
589
+ }
590
+ async function readTickBitmap(kernelPool, wordPos, mode, client) {
591
+ const c = resolveClient(mode, client);
592
+ try {
593
+ const word = await c.readContract({
594
+ address: kernelPool,
595
+ abi: import_amm_bindings.KernelPoolABI,
596
+ functionName: "tickBitmap",
597
+ args: [wordPos]
598
+ });
599
+ return word;
600
+ } catch (err) {
601
+ throw wrapReadError(err, "readTickBitmap");
602
+ }
603
+ }
604
+ async function readTick(kernelPool, tick, mode, client) {
605
+ const c = resolveClient(mode, client);
606
+ try {
607
+ const raw = await c.readContract({
608
+ address: kernelPool,
609
+ abi: import_amm_bindings.KernelPoolABI,
610
+ functionName: "ticks",
611
+ args: [tick]
612
+ });
613
+ return {
614
+ liquidityGross: raw[0],
615
+ liquidityNet: raw[1],
616
+ feeGrowthOutside0X128: raw[2],
617
+ feeGrowthOutside1X128: raw[3],
618
+ tickCumulativeOutside: raw[4],
619
+ secondsPerLiquidityOutsideX128: raw[5],
620
+ secondsOutside: raw[6],
621
+ initialized: raw[7]
622
+ };
623
+ } catch (err) {
624
+ throw wrapReadError(err, "readTick");
625
+ }
626
+ }
627
+ async function computePositionAmounts(tokenId, mode, client) {
628
+ const c = resolveClient(mode, client);
629
+ const position = await readPosition(tokenId, mode, c);
630
+ const { slot0 } = await readPool(position.pool, mode, c);
631
+ const sqrtLower = getSqrtRatioAtTick(position.tickLower);
632
+ const sqrtUpper = getSqrtRatioAtTick(position.tickUpper);
633
+ if (slot0.tick < position.tickLower) {
634
+ return {
635
+ amount0: getAmount0Delta(sqrtLower, sqrtUpper, position.liquidity, false),
636
+ amount1: 0n
637
+ };
638
+ }
639
+ if (slot0.tick >= position.tickUpper) {
640
+ return {
641
+ amount0: 0n,
642
+ amount1: getAmount1Delta(sqrtLower, sqrtUpper, position.liquidity, false)
643
+ };
644
+ }
645
+ return {
646
+ amount0: getAmount0Delta(
647
+ slot0.sqrtPriceX96,
648
+ sqrtUpper,
649
+ position.liquidity,
650
+ false
651
+ ),
652
+ amount1: getAmount1Delta(
653
+ sqrtLower,
654
+ slot0.sqrtPriceX96,
655
+ position.liquidity,
656
+ false
657
+ )
658
+ };
659
+ }
660
+
661
+ // src/kernel/tickBitmap.ts
662
+ function decodeTickBitmapWord(word, wordPos, tickSpacing) {
663
+ if (!Number.isSafeInteger(wordPos)) {
664
+ throw new RangeError(
665
+ `decodeTickBitmapWord: wordPos must be a safe integer, got ${wordPos}`
666
+ );
667
+ }
668
+ if (!Number.isSafeInteger(tickSpacing) || tickSpacing <= 0) {
669
+ throw new RangeError(
670
+ `decodeTickBitmapWord: tickSpacing must be a positive integer, got ${tickSpacing}`
671
+ );
672
+ }
673
+ const result = [];
674
+ const base = wordPos * 256;
675
+ for (let k = 0; k < 256; k++) {
676
+ if ((word >> BigInt(k) & 1n) === 1n) {
677
+ result.push((base + k) * tickSpacing);
678
+ }
679
+ }
680
+ return result;
681
+ }
682
+
683
+ // src/periphery/reader.ts
684
+ var import_amm_bindings2 = require("@skate-org/amm-bindings");
685
+ var import_amm_core_v24 = require("@skate-org/amm-core-v2");
686
+ function resolveClient2(chain, mode, client) {
687
+ return client ?? getSourcePublicClient(chain, mode);
688
+ }
689
+ async function readPeripheryPool(chain, kernelPool, mode, client) {
690
+ const { mode: baseMode } = (0, import_amm_core_v24.normalizeMode)(mode);
691
+ const details = (0, import_amm_core_v24.getPeripheryDetailsByKernelPoolAndChainId)(
692
+ kernelPool,
693
+ chain,
694
+ baseMode
695
+ );
696
+ if (!details) {
697
+ throw new EvmReadError(
698
+ "readPeripheryPool",
699
+ `no periphery entry for kernelPool=${kernelPool} chain=${chain} mode=${baseMode}`
700
+ );
701
+ }
702
+ const address = details.address;
703
+ const c = resolveClient2(chain, mode, client);
704
+ try {
705
+ const [
706
+ balancesAvailableRaw,
707
+ dust0,
708
+ dust1,
709
+ token0,
710
+ token1,
711
+ fee,
712
+ kPool
713
+ ] = await Promise.all([
714
+ c.readContract({
715
+ address,
716
+ abi: import_amm_bindings2.PeripheryPoolABI,
717
+ functionName: "balancesAvailable"
718
+ }),
719
+ c.readContract({
720
+ address,
721
+ abi: import_amm_bindings2.PeripheryPoolABI,
722
+ functionName: "dustAmount0"
723
+ }),
724
+ c.readContract({
725
+ address,
726
+ abi: import_amm_bindings2.PeripheryPoolABI,
727
+ functionName: "dustAmount1"
728
+ }),
729
+ c.readContract({
730
+ address,
731
+ abi: import_amm_bindings2.PeripheryPoolABI,
732
+ functionName: "token0"
733
+ }),
734
+ c.readContract({
735
+ address,
736
+ abi: import_amm_bindings2.PeripheryPoolABI,
737
+ functionName: "token1"
738
+ }),
739
+ c.readContract({
740
+ address,
741
+ abi: import_amm_bindings2.PeripheryPoolABI,
742
+ functionName: "fee"
743
+ }),
744
+ c.readContract({
745
+ address,
746
+ abi: import_amm_bindings2.PeripheryPoolABI,
747
+ functionName: "kernelPool"
748
+ })
749
+ ]);
750
+ const bAvail = balancesAvailableRaw;
751
+ return {
752
+ address,
753
+ token0,
754
+ token1,
755
+ fee,
756
+ kernelPool: kPool,
757
+ balancesAvailable: {
758
+ amount0Available: bAvail[0],
759
+ amount1Available: bAvail[1]
760
+ },
761
+ dustAmount0: dust0,
762
+ dustAmount1: dust1
763
+ };
764
+ } catch (err) {
765
+ throw wrapReadError(err, "readPeripheryPool");
766
+ }
767
+ }
768
+ async function readUserPoolBalances(chain, kernelPool, user, mode, client) {
769
+ const { mode: baseMode } = (0, import_amm_core_v24.normalizeMode)(mode);
770
+ const details = (0, import_amm_core_v24.getPeripheryDetailsByKernelPoolAndChainId)(
771
+ kernelPool,
772
+ chain,
773
+ baseMode
774
+ );
775
+ if (!details) {
776
+ throw new EvmReadError(
777
+ "readUserPoolBalances",
778
+ `no periphery entry for kernelPool=${kernelPool} chain=${chain} mode=${baseMode}`
779
+ );
780
+ }
781
+ const c = resolveClient2(chain, mode, client);
782
+ try {
783
+ const raw = await c.readContract({
784
+ address: details.address,
785
+ abi: import_amm_bindings2.PeripheryPoolABI,
786
+ functionName: "usersData",
787
+ args: [user]
788
+ });
789
+ if (Array.isArray(raw)) {
790
+ const tuple = raw;
791
+ return { amount0: tuple[0], amount1: tuple[1] };
792
+ }
793
+ const asObject = raw;
794
+ return { amount0: asObject.amount0, amount1: asObject.amount1 };
795
+ } catch (err) {
796
+ throw wrapReadError(err, "readUserPoolBalances");
797
+ }
798
+ }
799
+
800
+ // src/periphery/submit.ts
801
+ async function submitAction(wallet, params, _mode) {
802
+ if (wallet.chain?.id !== params.chain) {
803
+ throw new EvmWriteError(
804
+ "submitAction",
805
+ `wallet chain ${wallet.chain?.id ?? "undefined"} != params.chain ${params.chain}`
806
+ );
807
+ }
808
+ try {
809
+ const account = wallet.account;
810
+ if (!account) {
811
+ throw new EvmWriteError(
812
+ "submitAction",
813
+ "wallet has no account; callers must provide a wallet with wallet.account set"
814
+ );
815
+ }
816
+ return await wallet.sendTransaction({
817
+ to: params.to,
818
+ data: params.data,
819
+ value: params.value ?? 0n,
820
+ chain: wallet.chain,
821
+ account
822
+ });
823
+ } catch (err) {
824
+ if (err instanceof EvmWriteError) throw err;
825
+ throw wrapWriteError(err, "submitAction");
826
+ }
827
+ }
828
+ async function submitSwap(wallet, params, mode) {
829
+ try {
830
+ return await submitAction(wallet, params, mode);
831
+ } catch (err) {
832
+ if (err instanceof EvmWriteError) throw err;
833
+ throw wrapWriteError(err, "submitSwap");
834
+ }
835
+ }
836
+ async function submitApproval(wallet, params, mode) {
837
+ try {
838
+ return await submitAction(wallet, params, mode);
839
+ } catch (err) {
840
+ if (err instanceof EvmWriteError) throw err;
841
+ throw wrapWriteError(err, "submitApproval");
842
+ }
843
+ }
844
+
845
+ // src/events/kernel.ts
846
+ var import_viem2 = require("viem");
847
+ var import_amm_bindings3 = require("@skate-org/amm-bindings");
848
+ var KERNEL_EVENT_NAMES = [
849
+ "Burn",
850
+ "Collect",
851
+ "CollectProtocol",
852
+ "IncreaseObservationCardinalityNext",
853
+ "Initialize",
854
+ "Mint",
855
+ "PeripheryPoolAdded",
856
+ "PeripheryPoolChanged",
857
+ "PoolCreated",
858
+ "PoolDescriptionUpdated",
859
+ "SetFeeProtocol",
860
+ "Swap"
861
+ ];
862
+ function parseKernelEventLog(log) {
863
+ try {
864
+ const decoded = (0, import_viem2.decodeEventLog)({
865
+ abi: import_amm_bindings3.KernelEventEmitterABI,
866
+ data: log.data,
867
+ topics: log.topics
868
+ });
869
+ return {
870
+ eventName: decoded.eventName,
871
+ args: decoded.args ?? {},
872
+ log
873
+ };
874
+ } catch (err) {
875
+ const message = err.shortMessage ?? err.message ?? String(err);
876
+ throw new EvmReadError(
877
+ "parseKernelEventLog",
878
+ `failed to decode log: ${message}`,
879
+ { cause: err }
880
+ );
881
+ }
882
+ }
883
+
884
+ // src/events/periphery.ts
885
+ var import_viem3 = require("viem");
886
+ var import_amm_bindings4 = require("@skate-org/amm-bindings");
887
+ var PERIPHERY_EVENT_NAMES = [
888
+ "AmountSettled",
889
+ "Burned",
890
+ "LiquidityDecreased",
891
+ "LiquidityIncreased",
892
+ "MintSettled",
893
+ "Minted",
894
+ "PoolCreated",
895
+ "PoolDeployed",
896
+ "Swapped",
897
+ "TransferredTo"
898
+ ];
899
+ function parsePeripheryEventLog(log) {
900
+ try {
901
+ const decoded = (0, import_viem3.decodeEventLog)({
902
+ abi: import_amm_bindings4.PeripheryEventEmitterABI,
903
+ data: log.data,
904
+ topics: log.topics
905
+ });
906
+ return {
907
+ eventName: decoded.eventName,
908
+ args: decoded.args ?? {},
909
+ log
910
+ };
911
+ } catch (err) {
912
+ const message = err.shortMessage ?? err.message ?? String(err);
913
+ throw new EvmReadError(
914
+ "parsePeripheryEventLog",
915
+ `failed to decode log: ${message}`,
916
+ { cause: err }
917
+ );
918
+ }
919
+ }
920
+
921
+ // src/events/watch.ts
922
+ var import_amm_bindings5 = require("@skate-org/amm-bindings");
923
+ function watchKernelEvents(client, address, opts) {
924
+ return client.watchContractEvent({
925
+ abi: import_amm_bindings5.KernelEventEmitterABI,
926
+ address,
927
+ onLogs: (logs) => {
928
+ for (const log of logs) {
929
+ try {
930
+ opts.onEvent(parseKernelEventLog(log));
931
+ } catch (err) {
932
+ opts.onError?.(err);
933
+ }
934
+ }
935
+ }
936
+ });
937
+ }
938
+ function watchPeripheryEvents(client, address, opts) {
939
+ return client.watchContractEvent({
940
+ abi: import_amm_bindings5.PeripheryEventEmitterABI,
941
+ address,
942
+ onLogs: (logs) => {
943
+ for (const log of logs) {
944
+ try {
945
+ opts.onEvent(parsePeripheryEventLog(log));
946
+ } catch (err) {
947
+ opts.onError?.(err);
948
+ }
949
+ }
950
+ }
951
+ });
952
+ }
953
+ // Annotate the CommonJS export names for ESM import in node:
954
+ 0 && (module.exports = {
955
+ DEFAULT_DEV_API_ENDPOINT,
956
+ EvmReadError,
957
+ EvmWriteError,
958
+ KERNEL_EVENT_NAMES,
959
+ MAX_SQRT_RATIO,
960
+ MAX_TICK,
961
+ MIN_SQRT_RATIO,
962
+ MIN_TICK,
963
+ PERIPHERY_EVENT_NAMES,
964
+ addDelta,
965
+ computePositionAmounts,
966
+ createDevConfig,
967
+ decodeTickBitmapWord,
968
+ getAmount0Delta,
969
+ getAmount0DeltaSigned,
970
+ getAmount1Delta,
971
+ getAmount1DeltaSigned,
972
+ getKernelPublicClient,
973
+ getNextSqrtPriceFromAmount0RoundingUp,
974
+ getNextSqrtPriceFromAmount1RoundingDown,
975
+ getNextSqrtPriceFromInput,
976
+ getNextSqrtPriceFromOutput,
977
+ getSourcePublicClient,
978
+ getSqrtRatioAtTick,
979
+ getTickAtSqrtRatio,
980
+ megaethChain,
981
+ mulDiv,
982
+ mulDivRoundingUp,
983
+ parseKernelEventLog,
984
+ parsePeripheryEventLog,
985
+ readPeripheryPool,
986
+ readPool,
987
+ readPosition,
988
+ readTick,
989
+ readTickBitmap,
990
+ readUserPoolBalances,
991
+ submitAction,
992
+ submitApproval,
993
+ submitSwap,
994
+ watchKernelEvents,
995
+ watchPeripheryEvents
996
+ });
997
+ //# sourceMappingURL=index.cjs.map