@skate-org/amm-evm-v2 2.0.0-beta.22 → 2.0.0-beta.24
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/dist/chain-clients.d.ts +8 -0
- package/dist/chain-clients.d.ts.map +1 -1
- package/dist/index.cjs +19 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +18 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/chain-clients.d.ts
CHANGED
|
@@ -15,6 +15,14 @@ import { CHAIN, type EnvModeWithConfig } from "@skate-org/amm-core-v2";
|
|
|
15
15
|
* contract addresses.
|
|
16
16
|
*/
|
|
17
17
|
export declare const megaethChain: Chain;
|
|
18
|
+
/**
|
|
19
|
+
* Robinhood Chain definition (id 4663) — Arbitrum-Orbit L2, native ETH.
|
|
20
|
+
*
|
|
21
|
+
* A source periphery chain for the WETH/USDG pool. Defined locally so the SDK
|
|
22
|
+
* controls the RPC URL + block-explorer metadata (viem ships no built-in for
|
|
23
|
+
* 4663).
|
|
24
|
+
*/
|
|
25
|
+
export declare const robinhoodChain: Chain;
|
|
18
26
|
/**
|
|
19
27
|
* Return a fresh `PublicClient` bound to the kernel chain for `mode`.
|
|
20
28
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain-clients.d.ts","sourceRoot":"","sources":["../src/chain-clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,MAAM,CAAC;AAEd,OAAO,EAEL,KAAK,EAKL,KAAK,iBAAiB,EACvB,MAAM,wBAAwB,CAAC;AAEhC;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY,EAAE,KAYzB,CAAC;
|
|
1
|
+
{"version":3,"file":"chain-clients.d.ts","sourceRoot":"","sources":["../src/chain-clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,MAAM,CAAC;AAEd,OAAO,EAEL,KAAK,EAKL,KAAK,iBAAiB,EACvB,MAAM,wBAAwB,CAAC;AAEhC;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY,EAAE,KAYzB,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,EAAE,KAY3B,CAAC;AAkDH;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,iBAAiB,EACvB,SAAS,CAAC,EAAE,SAAS,GACpB,YAAY,CAcd;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,iBAAiB,EACvB,SAAS,CAAC,EAAE,SAAS,GACpB,YAAY,CAsBd"}
|
package/dist/index.cjs
CHANGED
|
@@ -46,6 +46,7 @@ __export(index_exports, {
|
|
|
46
46
|
readTick: () => readTick,
|
|
47
47
|
readTickBitmap: () => readTickBitmap,
|
|
48
48
|
readUserPoolBalances: () => readUserPoolBalances,
|
|
49
|
+
robinhoodChain: () => robinhoodChain,
|
|
49
50
|
simulateBurn: () => simulateBurn,
|
|
50
51
|
simulateDecreaseLiquidity: () => simulateDecreaseLiquidity,
|
|
51
52
|
simulateMint: () => simulateMint,
|
|
@@ -75,10 +76,24 @@ var megaethChain = (0, import_viem.defineChain)({
|
|
|
75
76
|
default: { name: "Blockscout", url: import_amm_core_v2.BLOCK_EXPLORER.MEGAETH }
|
|
76
77
|
}
|
|
77
78
|
});
|
|
79
|
+
var robinhoodChain = (0, import_viem.defineChain)({
|
|
80
|
+
id: 4663,
|
|
81
|
+
name: "Robinhood Chain",
|
|
82
|
+
network: "robinhood",
|
|
83
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
84
|
+
rpcUrls: {
|
|
85
|
+
default: { http: ["https://rpc.mainnet.chain.robinhood.com"] },
|
|
86
|
+
public: { http: ["https://rpc.mainnet.chain.robinhood.com"] }
|
|
87
|
+
},
|
|
88
|
+
blockExplorers: {
|
|
89
|
+
default: { name: "Blockscout", url: import_amm_core_v2.BLOCK_EXPLORER.ROBINHOOD }
|
|
90
|
+
}
|
|
91
|
+
});
|
|
78
92
|
var DEFAULT_RPC = {
|
|
79
93
|
[import_amm_core_v2.CHAIN.MEGAETH]: "https://mainnet.megaeth.com/rpc",
|
|
80
94
|
[import_amm_core_v2.CHAIN.ARBITRUM]: "https://arb1.arbitrum.io/rpc",
|
|
81
|
-
[import_amm_core_v2.CHAIN.ETHEREUM]: "https://ethereum-rpc.publicnode.com"
|
|
95
|
+
[import_amm_core_v2.CHAIN.ETHEREUM]: "https://ethereum-rpc.publicnode.com",
|
|
96
|
+
[import_amm_core_v2.CHAIN.ROBINHOOD]: "https://rpc.mainnet.chain.robinhood.com"
|
|
82
97
|
};
|
|
83
98
|
function chainDefFor(chain) {
|
|
84
99
|
switch (chain) {
|
|
@@ -88,6 +103,8 @@ function chainDefFor(chain) {
|
|
|
88
103
|
return import_chains.arbitrum;
|
|
89
104
|
case import_amm_core_v2.CHAIN.ETHEREUM:
|
|
90
105
|
return import_chains.mainnet;
|
|
106
|
+
case import_amm_core_v2.CHAIN.ROBINHOOD:
|
|
107
|
+
return robinhoodChain;
|
|
91
108
|
default:
|
|
92
109
|
return void 0;
|
|
93
110
|
}
|
|
@@ -1109,6 +1126,7 @@ function watchPeripheryEvents(client, address, opts) {
|
|
|
1109
1126
|
readTick,
|
|
1110
1127
|
readTickBitmap,
|
|
1111
1128
|
readUserPoolBalances,
|
|
1129
|
+
robinhoodChain,
|
|
1112
1130
|
simulateBurn,
|
|
1113
1131
|
simulateDecreaseLiquidity,
|
|
1114
1132
|
simulateMint,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/chain-clients.ts","../src/kernel/reader.ts","../src/errors.ts","../src/kernel/_client.ts","../src/kernel/lens.ts","../src/periphery/reader.ts","../src/periphery/submit.ts","../src/periphery/calldata.ts","../src/client.ts","../src/skate-amm.ts","../src/devConfig.ts","../src/kernel/tickBitmap.ts","../src/events/kernel.ts","../src/events/periphery.ts","../src/events/watch.ts"],"sourcesContent":["export * from \"./chain-clients\";\nexport { AmmEvm } from \"./client\";\nexport { SkateAmm } from \"./skate-amm\";\n// `DEFAULT_DEV_API_ENDPOINT` is intentionally not re-exported — it's\n// `createDevConfig`'s private default value, duplicates the canonical\n// URL in `api`, and shouldn't be part of the evm public surface.\nexport { createDevConfig } from \"./devConfig\";\n// Public error classes only; wrap* helpers are internal implementation\n// detail shared between readers/submitters and are not re-exported.\nexport { EvmReadError, EvmWriteError } from \"./errors\";\nexport * from \"./kernel\";\nexport * from \"./periphery\";\nexport * from \"./events\";\n","import {\n createPublicClient,\n defineChain,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n} from \"viem\";\nimport { arbitrum, mainnet } from \"viem/chains\";\nimport {\n BLOCK_EXPLORER,\n CHAIN,\n KernelChain,\n VM,\n vmTypeFromChain,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * MegaETH chain definition — `@public`.\n *\n * Exported for callers who need to build their own viem `WalletClient` or\n * `PublicClient` against the same chain the SDK uses internally (e.g. wallet\n * integrations that construct a `WalletClient` ahead of calling\n * `submitAction`). Prefer {@link getKernelPublicClient} when you just need a\n * read client.\n *\n * viem ships a `megaeth` chain at id 4326, but with a different default RPC\n * than the one Skate uses for kernel reads. Define locally so we control the\n * RPC URL + block-explorer metadata and don't inherit unrelated op-stack\n * contract addresses.\n */\nexport const megaethChain: Chain = defineChain({\n id: 4326,\n name: \"MegaETH\",\n network: \"megaeth\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n public: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.MEGAETH },\n },\n});\n\n/**\n * Default public RPC URLs by chain id.\n *\n * Callers can override per-chain via `DevModeConfig.rpcEndpoints` or by\n * passing an explicit `transport` to the factory functions below.\n */\nconst DEFAULT_RPC: Partial<Record<CHAIN, string>> = {\n [CHAIN.MEGAETH]: \"https://mainnet.megaeth.com/rpc\",\n [CHAIN.ARBITRUM]: \"https://arb1.arbitrum.io/rpc\",\n [CHAIN.ETHEREUM]: \"https://ethereum-rpc.publicnode.com\",\n};\n\n/**\n * Map a supported EVM `CHAIN` to a viem `Chain` definition.\n *\n * Only chains we actively support in Phase 2 are listed; unknown chains\n * return `undefined` and the caller throws.\n */\nfunction chainDefFor(chain: CHAIN): Chain | undefined {\n switch (chain) {\n case CHAIN.MEGAETH:\n return megaethChain;\n case CHAIN.ARBITRUM:\n return arbitrum;\n case CHAIN.ETHEREUM:\n return mainnet;\n default:\n return undefined;\n }\n}\n\n/**\n * Resolve the RPC URL for a given chain under the precedence:\n * transport override (caller arg) > mode.config.rpcEndpoints[chain] > DEFAULT_RPC[chain]\n * Returns `undefined` if none is set — callers must have already decided whether\n * to use a caller-supplied transport.\n */\nfunction resolveRpcUrl(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): string | undefined {\n const { config } = normalizeMode(mode);\n return config?.rpcEndpoints?.[chain] ?? DEFAULT_RPC[chain];\n}\n\n/**\n * Return a fresh `PublicClient` bound to the kernel chain for `mode`.\n *\n * Today every env (`DEV` / `STAGING` / `PRODUCTION`) resolves to MegaETH —\n * see `KERNEL_CHAIN_BY_MODE` in `@skate-org/amm-core-v2`. Pointing a future\n * env at a different kernel chain is a one-line edit there; this factory\n * reads from that mapping so client + address tables stay in sync.\n *\n * Pure — no singletons, no caching. Pass a custom `transport` to override\n * the default RPC (useful for tests and custom RPC providers).\n */\nexport function getKernelPublicClient(\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n const { mode: baseMode } = normalizeMode(mode);\n const kernelChainId = KernelChain(baseMode);\n const chainDef = chainDefFor(kernelChainId);\n if (!chainDef) {\n throw new Error(\n `getKernelPublicClient: no chain definition registered for kernel chain ${kernelChainId} ` +\n `(mode=${baseMode}); update chainDefFor() in chain-clients.ts to support it.`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(resolveRpcUrl(kernelChainId, mode)),\n });\n}\n\n/**\n * Return a fresh `PublicClient` for a source EVM chain (e.g. Arbitrum).\n *\n * Throws a descriptive `Error` when:\n * - `chain` is not an EVM chain (per `vmTypeFromChain`); or\n * - no viem chain definition is registered for `chain`; or\n * - no default RPC URL is configured for `chain` and no `transport` override\n * was provided.\n *\n * Pure — no singletons, no caching.\n */\nexport function getSourcePublicClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n if (vmTypeFromChain(chain) !== VM.EVM) {\n throw new Error(\n `getSourcePublicClient: chain ${chain} is not an EVM chain`,\n );\n }\n const chainDef = chainDefFor(chain);\n if (!chainDef) {\n throw new Error(\n `getSourcePublicClient: no chain definition registered for chain ${chain}`,\n );\n }\n const rpc = resolveRpcUrl(chain, mode);\n if (!rpc && !transport) {\n throw new Error(\n `getSourcePublicClient: no default or override RPC configured for chain ${chain}; pass a transport override or set DevModeConfig.rpcEndpoints[${chain}]`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(rpc),\n });\n}\n","import type { PublicClient } from \"viem\";\nimport {\n KernelManagerABI,\n KernelPoolABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n getAmount0Delta,\n getAmount1Delta,\n getSqrtRatioAtTick,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/** Decoded kernel-pool `slot0` state (named fields, per the ABI tuple). */\nexport interface KernelSlot0 {\n sqrtPriceX96: bigint;\n tick: number;\n observationIndex: number;\n observationCardinality: number;\n observationCardinalityNext: number;\n feeProtocol: number;\n unlocked: boolean;\n}\n\n/** Decoded pool state returned by `readPool`. */\nexport interface KernelPoolState {\n slot0: KernelSlot0;\n liquidity: bigint;\n}\n\n/** Decoded NFT position returned by `readPosition`. */\nexport interface KernelNftPosition {\n pool: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n liquidity: bigint;\n feeGrowthInside0LastX128: bigint;\n feeGrowthInside1LastX128: bigint;\n tokensOwed0: bigint;\n tokensOwed1: bigint;\n}\n\n/** Decoded kernel-pool `ticks(tick)` struct. */\nexport interface KernelTick {\n liquidityGross: bigint;\n liquidityNet: bigint;\n feeGrowthOutside0X128: bigint;\n feeGrowthOutside1X128: bigint;\n tickCumulativeOutside: bigint;\n secondsPerLiquidityOutsideX128: bigint;\n secondsOutside: number;\n initialized: boolean;\n}\n\n/**\n * Read `slot0` and `liquidity` from a kernel pool. Returns both in a single\n * object; the reads are fired in parallel.\n *\n * The `client` optional parameter is the standard test-injection point.\n */\nexport async function readPool(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelPoolState> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [slot0, liquidity] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"slot0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"liquidity\",\n }),\n ]);\n // Viem returns named outputs as a positional tuple (array) when every\n // output has a name — normalize to a named-field object here so callers\n // don't depend on viem's tuple/object split.\n const s0 = slot0 as readonly [\n bigint,\n number,\n number,\n number,\n number,\n number,\n boolean,\n ];\n return {\n slot0: {\n sqrtPriceX96: s0[0],\n tick: s0[1],\n observationIndex: s0[2],\n observationCardinality: s0[3],\n observationCardinalityNext: s0[4],\n feeProtocol: s0[5],\n unlocked: s0[6],\n },\n liquidity: liquidity as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPool\");\n }\n}\n\n/** Decoded kernel-pool token balances returned by `readKernelBalances`. */\nexport interface KernelBalances {\n balance0: bigint;\n balance1: bigint;\n}\n\n/**\n * Read `balance0` and `balance1` from a kernel pool (raw token reserves on\n * the kernel side, before periphery scaling). Reads are fired in parallel.\n */\nexport async function readKernelBalances(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelBalances> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [balance0, balance1] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance1\",\n }),\n ]);\n return { balance0: balance0 as bigint, balance1: balance1 as bigint };\n } catch (err) {\n throw wrapReadError(err, \"readKernelBalances\");\n }\n}\n\n/**\n * Read an NFT position by token id from the kernel manager.\n *\n * Calls `KernelManager.nftPositions(tokenId)` — per the ABI this returns a\n * `DataTypes.NFTPosition` tuple including `pool`, `tickLower`, `tickUpper`,\n * `liquidity`, fee growth, and tokens owed.\n */\nexport async function readPosition(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelNftPosition> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const manager = KernelManagerAddress(baseMode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: manager,\n abi: KernelManagerABI,\n functionName: \"nftPositions\",\n args: [p.tokenId],\n })) as unknown;\n // Accept either a positional tuple or an already-named object from\n // viem — normalize to a named-field object, mirroring readPool's\n // defensive remap.\n const asTuple = Array.isArray(raw)\n ? (raw as unknown as readonly [\n `0x${string}`,\n number,\n number,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n ])\n : null;\n if (asTuple) {\n return {\n pool: asTuple[0],\n tickLower: asTuple[1],\n tickUpper: asTuple[2],\n liquidity: asTuple[3],\n feeGrowthInside0LastX128: asTuple[4],\n feeGrowthInside1LastX128: asTuple[5],\n tokensOwed0: asTuple[6],\n tokensOwed1: asTuple[7],\n };\n }\n return raw as KernelNftPosition;\n } catch (err) {\n throw wrapReadError(err, \"readPosition\");\n }\n}\n\n/**\n * Read a kernel-pool tick-bitmap word (`tickBitmap(int16 wordPos)`).\n *\n * Returns the raw `uint256` word as a bigint.\n */\nexport async function readTickBitmap(p: {\n kernelPool: `0x${string}`;\n wordPos: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<bigint> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const word = await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"tickBitmap\",\n args: [p.wordPos],\n });\n return word as bigint;\n } catch (err) {\n throw wrapReadError(err, \"readTickBitmap\");\n }\n}\n\n/** Read the `ticks(tick)` struct from a kernel pool. */\nexport async function readTick(p: {\n kernelPool: `0x${string}`;\n tick: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelTick> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"ticks\",\n args: [p.tick],\n })) as readonly [\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n number,\n boolean,\n ];\n return {\n liquidityGross: raw[0],\n liquidityNet: raw[1],\n feeGrowthOutside0X128: raw[2],\n feeGrowthOutside1X128: raw[3],\n tickCumulativeOutside: raw[4],\n secondsPerLiquidityOutsideX128: raw[5],\n secondsOutside: raw[6],\n initialized: raw[7],\n };\n } catch (err) {\n throw wrapReadError(err, \"readTick\");\n }\n}\n\n/**\n * Compute `{amount0, amount1}` for an NFT position using the Group 3 math.\n *\n * Reads the position (to learn `pool`, `tickLower`, `tickUpper`,\n * `liquidity`) and the pool's `slot0`, then splits based on whether the\n * current tick is below, inside, or above the position range — mirroring\n * `PositionValue.principal` from Uniswap v3 periphery.\n */\nexport async function computePositionAmounts(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<{ amount0: bigint; amount1: bigint }> {\n const c = resolveKernelClient(p.mode, p.client);\n const position = await readPosition({ tokenId: p.tokenId, mode: p.mode, client: c });\n const { slot0 } = await readPool({ kernelPool: position.pool, mode: p.mode, client: c });\n\n const sqrtLower = getSqrtRatioAtTick(position.tickLower);\n const sqrtUpper = getSqrtRatioAtTick(position.tickUpper);\n\n if (slot0.tick < position.tickLower) {\n return {\n amount0: getAmount0Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n amount1: 0n,\n };\n }\n if (slot0.tick >= position.tickUpper) {\n return {\n amount0: 0n,\n amount1: getAmount1Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n };\n }\n return {\n amount0: getAmount0Delta(\n slot0.sqrtPriceX96,\n sqrtUpper,\n position.liquidity,\n false,\n ),\n amount1: getAmount1Delta(\n sqrtLower,\n slot0.sqrtPriceX96,\n position.liquidity,\n false,\n ),\n };\n}\n","/**\n * Shared error types for the `@skate-org/amm-evm-v2` package.\n *\n * `EvmReadError` / `EvmWriteError` extend `SdkError` (from core) so callers\n * can `instanceof SdkError` to catch any SDK-origin error without needing\n * to know the specific subclass.\n */\n\nimport { SdkError } from \"@skate-org/amm-core-v2\";\n\n/** SDK-level error thrown when an EVM read reverts or decodes badly. */\nexport class EvmReadError extends SdkError {\n override readonly name: string = \"EvmReadError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * SDK-level error thrown when an EVM write (broadcast) fails.\n *\n * Symmetric with {@link EvmReadError}, but covers the write path: viem's\n * `TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`, as well as submitter\n * pre-flight guards (e.g. wrong-chain, missing account).\n */\nexport class EvmWriteError extends SdkError {\n override readonly name: string = \"EvmWriteError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * Wrap any error from an EVM read into `EvmReadError`. Viem always wraps\n * revert-path errors in `ContractFunctionExecutionError` (see\n * `viem/utils/errors/getContractError`), so we check both the outer name and\n * the `.cause` chain for `ContractFunctionRevertedError` /\n * `ContractFunctionZeroDataError`.\n *\n * Shared by `kernel/reader.ts` and `periphery/reader.ts` — depends only on\n * `EvmReadError` and generic Error inspection (no reader-module imports), so\n * it is safe from circular-import concerns.\n */\nexport function wrapReadError(\n err: unknown,\n functionName: string,\n): EvmReadError {\n const outerName = (err as { name?: string } | null)?.name;\n const causeName = (err as { cause?: { name?: string } } | null)?.cause?.name;\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n const isViemContractError =\n outerName === \"ContractFunctionExecutionError\" ||\n outerName === \"ContractFunctionRevertedError\" ||\n outerName === \"ContractFunctionZeroDataError\" ||\n causeName === \"ContractFunctionRevertedError\" ||\n causeName === \"ContractFunctionZeroDataError\";\n if (isViemContractError) {\n return new EvmReadError(functionName, `reverted: ${message}`, {\n cause: err as Error,\n });\n }\n return new EvmReadError(functionName, message, { cause: err as Error });\n}\n\n/**\n * Wrap any error from an EVM write-path call (typically\n * `WalletClient.sendTransaction`) into `EvmWriteError`.\n *\n * Any thrown error reaching a submitter is treated as a write failure. If\n * we later want to differentiate known viem write errors\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`) from unknown errors —\n * e.g. to prefix the message or re-throw unknowns raw — that dispatch goes\n * here. Keeping the single-return shape until a concrete caller need\n * surfaces.\n */\nexport function wrapWriteError(\n err: unknown,\n functionName: string,\n): EvmWriteError {\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n return new EvmWriteError(functionName, message, { cause: err as Error });\n}\n","import type { PublicClient } from \"viem\";\nimport type { EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { getKernelPublicClient } from \"../chain-clients\";\n\n/**\n * Return the caller-provided client if present, otherwise build a fresh\n * MegaETH kernel client for the given mode. Shared by readers + lens\n * helpers; intentionally unexported from the package barrel.\n */\nexport function resolveKernelClient(\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getKernelPublicClient(mode);\n}\n","import type { PublicClient } from \"viem\";\nimport { KernelManagerABI } from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/**\n * Kernel lens (simulate) helpers — wrap KernelManager's `lens*` functions as\n * static-call simulations. Lens functions are marked nonpayable in the ABI,\n * but viem's `simulateContract` evaluates them with `eth_call`, so they\n * reuse the same client + RPC plumbing as the readers and never produce a\n * transaction.\n *\n * Errors funnel through `wrapReadError`: lens calls share the read-path\n * error model (revert reasons + RPC failures), and tagging them as \"writes\"\n * would be misleading since no state changes.\n */\n\nexport interface SimulateSwapParams {\n /** Kernel-pool address (EVM) */\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 (use `toBytes32Address` for cross-VM) */\n recipient: `0x${string}`;\n zeroForOne: boolean;\n /** Positive = exactInput, negative = exactOutput, per Uniswap v3 convention */\n amountSpecified: bigint;\n sqrtPriceLimitX96: bigint;\n}\n\nexport interface SimulateSwapResult {\n amount0: bigint;\n amount1: bigint;\n sqrtPriceX96After: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateSwap(p: {\n params: SimulateSwapParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateSwapResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensSwap\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.zeroForOne,\n p.params.amountSpecified,\n p.params.sqrtPriceLimitX96,\n ],\n });\n const [amount0, amount1, sqrtPriceX96After, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, sqrtPriceX96After, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateSwap\");\n }\n}\n\nexport interface SimulateMintParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n /** Caller-supplied callback data (passed to `IKernelMintCallback`) */\n data: `0x${string}`;\n}\n\nexport interface SimulateMintResult {\n amount0Used: bigint;\n amount1Used: bigint;\n liquidityAmount: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateMint(p: {\n params: SimulateMintParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateMintResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensMint\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount0,\n p.params.amount1,\n p.params.data,\n ],\n });\n const [amount0Used, amount1Used, liquidityAmount, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0Used, amount1Used, liquidityAmount, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateMint\");\n }\n}\n\nexport interface SimulateBurnParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n /** Liquidity amount to burn (uint128). */\n amount: bigint;\n}\n\nexport interface SimulateBurnResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateBurn(p: {\n params: SimulateBurnParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateBurnResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensBurn\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount,\n ],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateBurn\");\n }\n}\n\nexport interface SimulateDecreaseLiquidityParams {\n /** NFT position id (v2 positions). */\n tokenId: bigint;\n /** Liquidity amount to remove (uint128). */\n liquidity: bigint;\n}\n\nexport interface SimulateDecreaseLiquidityResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateDecreaseLiquidity(p: {\n params: SimulateDecreaseLiquidityParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateDecreaseLiquidityResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensDecreaseLiquidity\",\n args: [p.params.tokenId, p.params.liquidity],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateDecreaseLiquidity\");\n }\n}\n","import type { PublicClient } from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n CHAIN,\n getPeripheryDetailsByKernelPoolAndChainId,\n normalizeMode,\n type EnvModeWithConfig,\n type EvmChain,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\nimport { getSourcePublicClient } from \"../chain-clients\";\nimport { EvmReadError, wrapReadError } from \"../errors\";\n\n/**\n * Decoded periphery-pool state assembled by {@link readPeripheryPool}.\n *\n * The periphery pool does **not** expose a `slot0`-style view — pricing\n * state lives on the kernel pool on MegaETH (see `readPool`). What the\n * periphery pool does expose is: the configured pair\n * (`token0`, `token1`, `fee`, `kernelPool` reference), the escrowed\n * in-pool settlement balances (`balancesAvailable`), and the two\n * `dustAmount{0,1}` accumulators. Together these are enough for a\n * source-chain caller to reason about pending settlement and dust.\n */\nexport interface PeripheryPoolState {\n /** Periphery pool contract address on the source chain. */\n address: `0x${string}`;\n /** Source-chain ERC-20 address for token0. */\n token0: `0x${string}`;\n /** Source-chain ERC-20 address for token1. */\n token1: `0x${string}`;\n /** Fee tier (uint24) the periphery pool was deployed with. */\n fee: number;\n /** Address of the paired kernel pool on MegaETH. */\n kernelPool: `0x${string}`;\n /** Aggregate in-pool balances available for settlement. */\n balancesAvailable: { amount0Available: bigint; amount1Available: bigint };\n /** token0 dust accumulator. */\n dustAmount0: bigint;\n /** token1 dust accumulator. */\n dustAmount1: bigint;\n}\n\n/**\n * Decoded user per-pool in-flight token balances.\n *\n * Returned by `PeripheryPool.usersData(user)` as `(uint256 amount0, uint256 amount1)`.\n */\nexport interface UserPoolBalances {\n amount0: bigint;\n amount1: bigint;\n}\n\n/**\n * Return the caller-provided client, or build a fresh source-chain\n * client for `chain` under the given `mode`. Mirrors the kernel reader\n * injection pattern.\n */\nfunction resolveClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getSourcePublicClient(chain, mode);\n}\n\n/**\n * Read the assembled periphery-pool state on a source chain.\n *\n * Resolves the periphery pool address via\n * `getPeripheryDetailsByKernelPoolAndChainId` (from\n * `@skate-org/amm-core-v2`) — **no addresses are hardcoded here**. If the\n * `(kernelPool, chain, mode)` triple has no entry in the aggregated pool\n * catalog, throws with the triple in the message for debuggability.\n *\n * All sub-reads are fired in parallel and normalized to named fields.\n */\nexport async function readPeripheryPool(p: {\n chain: CHAIN;\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<PeripheryPoolState> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const details = getPeripheryDetailsByKernelPoolAndChainId(\n p.kernelPool,\n p.chain as EvmChain,\n baseMode,\n );\n if (!details) {\n throw new EvmReadError(\n \"readPeripheryPool\",\n `no periphery entry for kernelPool=${p.kernelPool} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const address = details.address;\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const [\n balancesAvailableRaw,\n dust0,\n dust1,\n token0,\n token1,\n fee,\n kPool,\n ] = await Promise.all([\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"balancesAvailable\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"fee\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"kernelPool\",\n }),\n ]);\n // Viem decodes multi-output tuples with all-named outputs as a\n // positional tuple — normalize to a named-field object.\n const bAvail = balancesAvailableRaw as readonly [bigint, bigint];\n return {\n address,\n token0: token0 as `0x${string}`,\n token1: token1 as `0x${string}`,\n fee: fee as number,\n kernelPool: kPool as `0x${string}`,\n balancesAvailable: {\n amount0Available: bAvail[0],\n amount1Available: bAvail[1],\n },\n dustAmount0: dust0 as bigint,\n dustAmount1: dust1 as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPeripheryPool\");\n }\n}\n\n/**\n * Read a user's per-pool in-flight balances on a source chain.\n *\n * Resolves the periphery pool address via AmmCore.getPoolInfoByKey +\n * peripheryInfo[chain].address (no hardcoded addresses) and calls\n * `PeripheryPool.usersData(user)` which returns\n * `(uint256 amount0, uint256 amount1)`.\n */\nexport async function readUserPoolBalances(p: {\n user: `0x${string}`;\n poolKey: string;\n chain: CHAIN;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<UserPoolBalances> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const core = new AmmCore(p.mode);\n const info = core.getPoolInfoByKey(p.poolKey);\n const periphery = info?.peripheryInfo[p.chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new EvmReadError(\n \"readUserPoolBalances\",\n `no periphery entry for poolKey=${p.poolKey} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: periphery.address,\n abi: PeripheryPoolABI,\n functionName: \"usersData\",\n args: [p.user],\n })) as unknown;\n // `usersData` returns `(uint256 amount0, uint256 amount1)`.\n // Viem decodes tuples with all-named outputs as a positional tuple;\n // handle both the positional and (older) object shapes defensively.\n if (Array.isArray(raw)) {\n const tuple = raw as unknown as readonly [bigint, bigint];\n return { amount0: tuple[0], amount1: tuple[1] };\n }\n const asObject = raw as { amount0: bigint; amount1: bigint };\n return { amount0: asObject.amount0, amount1: asObject.amount1 };\n } catch (err) {\n throw wrapReadError(err, \"readUserPoolBalances\");\n }\n}\n","import type { Address, Hex, WalletClient } from \"viem\";\nimport type { CHAIN, EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { EvmWriteError, wrapWriteError } from \"../errors\";\n\n/**\n * Pre-built source-chain transaction payload accepted by\n * {@link submitAction}.\n *\n * The SDK does **not** fabricate calldata in Group 6 — callers build the\n * payload (e.g. from a quote's `serializedCall`) and this submitter only\n * broadcasts it. This keeps the SDK decoupled from any off-chain\n * routing/quote surface.\n */\nexport type SubmitActionParams = {\n /** Source-chain id the wallet must be connected to. */\n chain: CHAIN;\n /** Destination address of the broadcast tx. */\n to: Address;\n /** Pre-encoded calldata. */\n data: Hex;\n /** Native-value payable amount; defaults to `0n`. */\n value?: bigint;\n};\n\n/**\n * Broadcast a pre-built periphery action tx from the caller's\n * `WalletClient`.\n *\n * Guarantees:\n * - Throws {@link EvmWriteError} immediately if\n * `wallet.chain?.id !== params.chain` — no RPC call is made.\n * - Throws {@link EvmWriteError} if `wallet.account` is not set.\n * - Forwards the payload to `wallet.sendTransaction` and returns the\n * resulting tx hash.\n * - Wraps any thrown viem write-path error\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, …) into an {@link EvmWriteError} via\n * {@link wrapWriteError}.\n *\n * The `mode` parameter is currently unused at runtime; it is accepted for\n * API symmetry with the readers and as a forward-compat hook for a future\n * mode-specific submission policy (e.g. DEV-only simulation, staging\n * retries). The `_` prefix marks it unused for the TypeScript checker.\n *\n * Non-goals (per plan guardrails):\n * - Does NOT sign — the caller brings a `WalletClient` wired to their\n * signer.\n * - Does NOT switch chains — callers are responsible for\n * `wallet.switchChain(...)`.\n * - Does NOT retry or manage nonces — delegated to the caller's wallet.\n */\nexport async function submitAction(\n wallet: WalletClient,\n params: SubmitActionParams,\n _mode: EnvModeWithConfig,\n): Promise<Hex> {\n if (wallet.chain?.id !== params.chain) {\n throw new EvmWriteError(\n \"submitAction\",\n `wallet chain ${wallet.chain?.id ?? \"undefined\"} != params.chain ${params.chain}`,\n );\n }\n\n try {\n const account = wallet.account;\n if (!account) {\n throw new EvmWriteError(\n \"submitAction\",\n \"wallet has no account; callers must provide a wallet with wallet.account set\",\n );\n }\n return await wallet.sendTransaction({\n to: params.to,\n data: params.data,\n value: params.value ?? 0n,\n chain: wallet.chain,\n account,\n });\n } catch (err) {\n // Preserve our own pre-flight guards verbatim — they are already\n // EvmWriteError instances and don't need re-wrapping.\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitAction\");\n }\n}\n\n/**\n * Broadcast a periphery *swap* action — thin wrapper around\n * {@link submitAction} that re-labels any unknown error as `submitSwap` to\n * aid log-line triage. Behaviourally identical to `submitAction`; shares\n * its pre-flight guards.\n */\nexport async function submitSwap(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitSwap\");\n }\n}\n\n/**\n * Broadcast a periphery *approval* action (ERC-20 approve to the source\n * chain's periphery contract) — thin wrapper around {@link submitAction}.\n * See {@link submitSwap} for labeling rationale.\n */\nexport async function submitApproval(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitApproval\");\n }\n}\n","/**\n * Pure ABI encoders for periphery-pool `swap` / `mint` / `burn` /\n * `increaseLiquidity` / `decreaseLiquidity` calldata.\n *\n * No client, no signing, no submission — quote routes use these to mirror\n * the on-chain calldata shape without paying for an RPC round-trip. For the\n * full submit-and-confirm flow, use the submitters in `./submit.ts`.\n *\n * Each `build*` function resolves the EVM periphery contract address for the\n * given `poolKey` + `chain` via `AmmCore`, encodes the calldata, and returns\n * a `CalldataCall` ready for submission.\n *\n * Encoding does NOT change — only call signatures and return types are new.\n */\n\nimport {\n encodeAbiParameters,\n encodeFunctionData,\n maxUint256,\n parseAbiParameters,\n} from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n type CHAIN,\n type EnvModeWithConfig,\n type CalldataCall,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * Resolve the EVM periphery pool contract address for a `(poolKey, chain, mode)` triple.\n * Throws with a descriptive message if the poolKey is unknown or has no periphery on `chain`.\n *\n * Resolves by poolKey via the aggregated catalog — deliberately not reusing\n * `getPeripheryDetailsByKernelPoolAndChainId`, which is keyed by kernelPool.\n */\nfunction resolvePeripheryTarget(\n poolKey: string,\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): `0x${string}` {\n const core = new AmmCore(mode);\n const info = core.getPoolInfoByKey(poolKey);\n if (!info) throw new Error(`unknown poolKey: ${poolKey}`);\n const periphery = info.peripheryInfo[chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new Error(`pool ${poolKey} has no periphery on chain ${chain}`);\n }\n return periphery.address;\n}\n\n// ── Param types ───────────────────────────────────────────────────────────────\n\n/** Common fields injected into every Build*Params type. */\ninterface BuildBaseParams {\n /** Pool key, e.g. \"USDC_USDT\" — resolves the source periphery pool target. */\n poolKey: string;\n /** Source chain the action is submitted on. */\n chain: CHAIN;\n /** Env mode. Omitted when called via AmmEvm (injected). */\n mode: EnvModeWithConfig;\n}\n\nexport interface BuildSwapParams extends BuildBaseParams {\n /** Swap recipient address in bytes32 format. */\n recipient: `0x${string}`;\n destChainId: number;\n destVmType: number;\n zeroForOne: boolean;\n /** Raw amount, subject to token native decimals. */\n amount: bigint;\n sqrtPriceLimitX96: bigint;\n /** Raw amount, subject to token native decimals. Default 0n. */\n minAmountOut?: bigint;\n /** Enforced at kernel timestamp. Default `maxUint256`. */\n deadline?: bigint;\n}\n\nexport interface BuildMintParams extends BuildBaseParams {\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildBurnParams extends BuildBaseParams {\n tokenId: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildIncreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildDecreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n /** Kernel-side liquidity amount — `sqrt(normalizedAmount0 * normalizedAmount1)` in 18-decimal space. */\n liquidityAmount: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\n// ── Internal encoders (pure, NOT exported) ────────────────────────────────────\n\nfunction encodeSwap(params: Omit<BuildSwapParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n zeroForOne,\n amount,\n sqrtPriceLimitX96,\n destVmType,\n destChainId,\n minAmountOut,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256,uint256\"),\n [\n minAmountOut ?? 0n,\n BigInt(destChainId),\n BigInt(destVmType),\n deadline ?? maxUint256,\n ],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"swap\",\n args: [recipient, zeroForOne, amount, sqrtPriceLimitX96, extraData],\n });\n}\n\nfunction encodeMint(params: Omit<BuildMintParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n tickLower,\n tickUpper,\n amount0,\n amount1,\n amount0Min,\n amount1Min,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"mint\",\n args: [recipient, tickLower, tickUpper, amount0, amount1, extraData],\n });\n}\n\nfunction encodeBurn(params: Omit<BuildBurnParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"burn\",\n args: [tokenId, extraData] as const,\n });\n}\n\nfunction encodeIncreaseLiquidity(params: Omit<BuildIncreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0, amount1, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"increaseLiquidity\",\n args: [tokenId, amount0, amount1, extraData],\n });\n}\n\nfunction encodeDecreaseLiquidity(params: Omit<BuildDecreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, liquidityAmount, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"decreaseLiquidity\",\n args: [tokenId, liquidityAmount, extraData],\n });\n}\n\n// ── Public async builders ─────────────────────────────────────────────────────\n\n/** Build calldata for a `swap` on the resolved EVM periphery pool. */\nexport async function buildSwap(params: BuildSwapParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeSwap(encodeParams),\n };\n}\n\n/** Build calldata for a `mint` on the resolved EVM periphery pool. */\nexport async function buildMint(params: BuildMintParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeMint(encodeParams),\n };\n}\n\n/** Build calldata for a `burn` on the resolved EVM periphery pool. */\nexport async function buildBurn(params: BuildBurnParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeBurn(encodeParams),\n };\n}\n\n/** Build calldata for `increaseLiquidity` on the resolved EVM periphery pool. */\nexport async function buildIncreaseLiquidity(params: BuildIncreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeIncreaseLiquidity(encodeParams),\n };\n}\n\n/**\n * Build calldata for `decreaseLiquidity` on the resolved EVM periphery pool.\n *\n * WARN: `liquidityAmount` is kernel-side, computed as\n * `sqrt(normalizedAmount0 * normalizedAmount1)` (18-decimal space).\n */\nexport async function buildDecreaseLiquidity(params: BuildDecreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeDecreaseLiquidity(encodeParams),\n };\n}\n","import type { PublicClient, Transport, WalletClient } from \"viem\";\nimport type { EnvModeWithConfig, CHAIN, CalldataCall, AmmVmClient } from \"@skate-org/amm-core-v2\";\nimport {\n readPool,\n readKernelBalances,\n readPosition,\n readTickBitmap,\n readTick,\n computePositionAmounts,\n} from \"./kernel/reader\";\nimport {\n simulateSwap,\n simulateMint,\n simulateBurn,\n simulateDecreaseLiquidity,\n type SimulateSwapParams,\n type SimulateMintParams,\n type SimulateBurnParams,\n type SimulateDecreaseLiquidityParams,\n} from \"./kernel/lens\";\nimport {\n readPeripheryPool,\n readUserPoolBalances,\n type PeripheryPoolState,\n type UserPoolBalances,\n} from \"./periphery/reader\";\nimport {\n submitAction,\n submitSwap,\n submitApproval,\n type SubmitActionParams,\n} from \"./periphery/submit\";\nimport {\n buildSwap,\n buildMint,\n buildBurn,\n buildIncreaseLiquidity,\n buildDecreaseLiquidity,\n type BuildSwapParams,\n type BuildMintParams,\n type BuildBurnParams,\n type BuildIncreaseLiquidityParams,\n type BuildDecreaseLiquidityParams,\n} from \"./periphery/calldata\";\nimport {\n getKernelPublicClient,\n getSourcePublicClient,\n} from \"./chain-clients\";\n\n/**\n * Env-bound client that wraps all EVM mode-taking functions with a fixed\n * `EnvModeWithConfig`. Construct once with the desired env and call methods\n * without the `mode` parameter.\n *\n * The raw `EnvModeWithConfig` is stored as-is (not normalized) so that\n * `config.rpcEndpoints` overrides pass through intact to the underlying\n * readers and chain-client factories.\n *\n * Implements `AmmVmClient<CalldataCall, WalletClient, 0x${string}, PeripheryPoolState, UserPoolBalances>`.\n * EVM submits any action type through the same `submitAction` path — the four\n * extra `AmmVmClient` submit methods are thin aliases.\n *\n * @example\n * const evm = new AmmEvm('PRODUCTION');\n * const pool = await evm.readPool({ kernelPool: '0x...' });\n * const call = await evm.buildSwap({ poolKey: 'USDC_USDT', chain: CHAIN.ARBITRUM, ... });\n */\nexport class AmmEvm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n }\n\n // ── Kernel readers ────────────────────────────────────────────────────────\n\n readPool(p: Omit<Parameters<typeof readPool>[0], \"mode\">) {\n return readPool({ ...p, mode: this.env, client: p.client });\n }\n\n readKernelBalances(p: Omit<Parameters<typeof readKernelBalances>[0], \"mode\">) {\n return readKernelBalances({ ...p, mode: this.env, client: p.client });\n }\n\n readPosition(p: Omit<Parameters<typeof readPosition>[0], \"mode\">) {\n return readPosition({ ...p, mode: this.env, client: p.client });\n }\n\n readTickBitmap(p: Omit<Parameters<typeof readTickBitmap>[0], \"mode\">) {\n return readTickBitmap({ ...p, mode: this.env, client: p.client });\n }\n\n readTick(p: Omit<Parameters<typeof readTick>[0], \"mode\">) {\n return readTick({ ...p, mode: this.env, client: p.client });\n }\n\n computePositionAmounts(p: Omit<Parameters<typeof computePositionAmounts>[0], \"mode\">) {\n return computePositionAmounts({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Kernel lens (simulate) ────────────────────────────────────────────────\n\n simulateSwap(p: { params: SimulateSwapParams; client?: PublicClient }) {\n return simulateSwap({ ...p, mode: this.env, client: p.client });\n }\n\n simulateMint(p: { params: SimulateMintParams; client?: PublicClient }) {\n return simulateMint({ ...p, mode: this.env, client: p.client });\n }\n\n simulateBurn(p: { params: SimulateBurnParams; client?: PublicClient }) {\n return simulateBurn({ ...p, mode: this.env, client: p.client });\n }\n\n simulateDecreaseLiquidity(p: { params: SimulateDecreaseLiquidityParams; client?: PublicClient }) {\n return simulateDecreaseLiquidity({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Omit<Parameters<typeof readPeripheryPool>[0], \"mode\">): Promise<PeripheryPoolState> {\n return readPeripheryPool({ ...p, mode: this.env, client: p.client });\n }\n\n readUserPoolBalances(p: Omit<Parameters<typeof readUserPoolBalances>[0], \"mode\">): Promise<UserPoolBalances> {\n return readUserPoolBalances({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery calldata builders ───────────────────────────────────────────\n\n buildSwap(p: Omit<BuildSwapParams, \"mode\">): Promise<CalldataCall> {\n return buildSwap({ ...p, mode: this.env });\n }\n\n buildMint(p: Omit<BuildMintParams, \"mode\">): Promise<CalldataCall> {\n return buildMint({ ...p, mode: this.env });\n }\n\n buildBurn(p: Omit<BuildBurnParams, \"mode\">): Promise<CalldataCall> {\n return buildBurn({ ...p, mode: this.env });\n }\n\n buildIncreaseLiquidity(p: Omit<BuildIncreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildIncreaseLiquidity({ ...p, mode: this.env });\n }\n\n buildDecreaseLiquidity(p: Omit<BuildDecreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildDecreaseLiquidity({ ...p, mode: this.env });\n }\n\n // ── Periphery submitters ──────────────────────────────────────────────────\n\n submitAction(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n submitSwap(wallet: WalletClient, params: SubmitActionParams) {\n return submitSwap(wallet, params, this.env);\n }\n\n submitApproval(wallet: WalletClient, params: SubmitActionParams) {\n return submitApproval(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitMint(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitBurn(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitIncreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitDecreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n // ── Chain-client factories ────────────────────────────────────────────────\n\n getKernelPublicClient(transport?: Transport) {\n return getKernelPublicClient(this.env, transport);\n }\n\n getSourcePublicClient(chain: CHAIN, transport?: Transport) {\n return getSourcePublicClient(chain, this.env, transport);\n }\n}\n","import { AmmCore, type EnvModeWithConfig, type AmmVmClient, type CalldataCall } from \"@skate-org/amm-core-v2\";\nimport { AmmApi } from \"@skate-org/amm-api-v2\";\nimport type { WalletClient } from \"viem\";\nimport { AmmEvm } from \"./client\";\nimport type { PeripheryPoolState, UserPoolBalances } from \"./periphery/reader\";\n\n/**\n * Single entry point for EVM consumers: quotes + actions (AmmApi), pool\n * catalog (AmmCore), and EVM build/submit/read (AmmEvm) behind one env-bound\n * object.\n *\n * `import { SkateAmm } from \"@skate-org/amm-evm-v2\"`\n *\n * @remarks\n * `quote.*`, `actions.*`, and `pools.*` are bound to the composed instances at\n * construction time. Patching `amm.api` or `amm.core` methods after construction\n * does not propagate to those namespaces.\n *\n * @example\n * const amm = new SkateAmm(\"PRODUCTION\");\n * const call = await amm.buildSwap({ poolKey: \"USDC_USDT\", chain: CHAIN.ARBITRUM, ... });\n * const quote = await amm.quote.swap({ poolKey: \"USDC_USDT\", ... });\n */\nexport class SkateAmm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n readonly core: AmmCore;\n readonly api: AmmApi;\n readonly vm: AmmEvm;\n\n readonly quote: {\n swap: AmmApi[\"swapQuote\"];\n mint: AmmApi[\"mintQuote\"];\n burn: AmmApi[\"burnQuote\"];\n increaseLiquidity: AmmApi[\"increaseLiquidityQuote\"];\n decreaseLiquidity: AmmApi[\"decreaseLiquidityQuote\"];\n boostedMint: AmmApi[\"boostedMintQuote\"];\n boostedRange: AmmApi[\"boostedRangeQuote\"];\n streamSwap: AmmApi[\"streamSwapQuote\"];\n subscribeSwap: AmmApi[\"subscribeSwapQuote\"];\n };\n\n readonly actions: {\n get: AmmApi[\"getAction\"];\n byUser: AmmApi[\"getActionsByUser\"];\n byUserTimeRange: AmmApi[\"getActionsByUserTimeRange\"];\n waitForExecuted: AmmApi[\"waitForExecuted\"];\n position: AmmApi[\"getPosition\"];\n };\n\n readonly pools: {\n all: AmmCore[\"getAllPoolInfo\"];\n keys: AmmCore[\"getAllPoolKeys\"];\n byKey: AmmCore[\"getPoolInfoByKey\"];\n supportedChains: AmmCore[\"getSupportedChains\"];\n supportedPairs: AmmCore[\"getSupportedPairs\"];\n supportedTokens: AmmCore[\"getSupportedTokens\"];\n keyByKernelPool: AmmCore[\"kernelPoolToPoolKey\"];\n };\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n this.core = new AmmCore(env);\n this.api = new AmmApi(env);\n this.vm = new AmmEvm(env);\n\n const api = this.api;\n const core = this.core;\n\n this.quote = {\n swap: api.swapQuote.bind(api),\n mint: api.mintQuote.bind(api),\n burn: api.burnQuote.bind(api),\n increaseLiquidity: api.increaseLiquidityQuote.bind(api),\n decreaseLiquidity: api.decreaseLiquidityQuote.bind(api),\n boostedMint: api.boostedMintQuote.bind(api),\n boostedRange: api.boostedRangeQuote.bind(api),\n streamSwap: api.streamSwapQuote.bind(api),\n subscribeSwap: api.subscribeSwapQuote.bind(api),\n };\n\n this.actions = {\n get: api.getAction.bind(api),\n byUser: api.getActionsByUser.bind(api),\n byUserTimeRange: api.getActionsByUserTimeRange.bind(api),\n waitForExecuted: api.waitForExecuted.bind(api),\n position: api.getPosition.bind(api),\n };\n\n this.pools = {\n all: core.getAllPoolInfo.bind(core),\n keys: core.getAllPoolKeys.bind(core),\n byKey: core.getPoolInfoByKey.bind(core),\n supportedChains: core.getSupportedChains.bind(core),\n supportedPairs: core.getSupportedPairs.bind(core),\n supportedTokens: core.getSupportedTokens.bind(core),\n keyByKernelPool: core.kernelPoolToPoolKey.bind(core),\n };\n }\n\n // ── AmmVmClient: builders ────────────────────────────────────────────────────\n\n buildSwap(p: Parameters<AmmEvm[\"buildSwap\"]>[0]) { return this.vm.buildSwap(p); }\n buildMint(p: Parameters<AmmEvm[\"buildMint\"]>[0]) { return this.vm.buildMint(p); }\n buildBurn(p: Parameters<AmmEvm[\"buildBurn\"]>[0]) { return this.vm.buildBurn(p); }\n buildIncreaseLiquidity(p: Parameters<AmmEvm[\"buildIncreaseLiquidity\"]>[0]) { return this.vm.buildIncreaseLiquidity(p); }\n buildDecreaseLiquidity(p: Parameters<AmmEvm[\"buildDecreaseLiquidity\"]>[0]) { return this.vm.buildDecreaseLiquidity(p); }\n\n // ── AmmVmClient: submitters ──────────────────────────────────────────────────\n\n submitSwap(w: WalletClient, p: Parameters<AmmEvm[\"submitSwap\"]>[1]) { return this.vm.submitSwap(w, p); }\n submitMint(w: WalletClient, p: Parameters<AmmEvm[\"submitMint\"]>[1]) { return this.vm.submitMint(w, p); }\n submitBurn(w: WalletClient, p: Parameters<AmmEvm[\"submitBurn\"]>[1]) { return this.vm.submitBurn(w, p); }\n submitIncreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitIncreaseLiquidity\"]>[1]) { return this.vm.submitIncreaseLiquidity(w, p); }\n submitDecreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitDecreaseLiquidity\"]>[1]) { return this.vm.submitDecreaseLiquidity(w, p); }\n\n // ── AmmVmClient: readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Parameters<AmmEvm[\"readPeripheryPool\"]>[0]) { return this.vm.readPeripheryPool(p); }\n readUserPoolBalances(p: Parameters<AmmEvm[\"readUserPoolBalances\"]>[0]) { return this.vm.readUserPoolBalances(p); }\n\n // ── EVM extras ───────────────────────────────────────────────────────────────\n\n /** Read raw kernel pool slot. */\n readPool(p: Parameters<AmmEvm[\"readPool\"]>[0]) { return this.vm.readPool(p); }\n readKernelBalances(p: Parameters<AmmEvm[\"readKernelBalances\"]>[0]) { return this.vm.readKernelBalances(p); }\n readPosition(p: Parameters<AmmEvm[\"readPosition\"]>[0]) { return this.vm.readPosition(p); }\n readTickBitmap(p: Parameters<AmmEvm[\"readTickBitmap\"]>[0]) { return this.vm.readTickBitmap(p); }\n readTick(p: Parameters<AmmEvm[\"readTick\"]>[0]) { return this.vm.readTick(p); }\n computePositionAmounts(p: Parameters<AmmEvm[\"computePositionAmounts\"]>[0]) { return this.vm.computePositionAmounts(p); }\n\n simulateSwap(p: Parameters<AmmEvm[\"simulateSwap\"]>[0]) { return this.vm.simulateSwap(p); }\n simulateMint(p: Parameters<AmmEvm[\"simulateMint\"]>[0]) { return this.vm.simulateMint(p); }\n simulateBurn(p: Parameters<AmmEvm[\"simulateBurn\"]>[0]) { return this.vm.simulateBurn(p); }\n simulateDecreaseLiquidity(p: Parameters<AmmEvm[\"simulateDecreaseLiquidity\"]>[0]) { return this.vm.simulateDecreaseLiquidity(p); }\n\n submitAction(w: WalletClient, p: Parameters<AmmEvm[\"submitAction\"]>[1]) { return this.vm.submitAction(w, p); }\n submitApproval(w: WalletClient, p: Parameters<AmmEvm[\"submitApproval\"]>[1]) { return this.vm.submitApproval(w, p); }\n\n getKernelPublicClient(...args: Parameters<AmmEvm[\"getKernelPublicClient\"]>) { return this.vm.getKernelPublicClient(...args); }\n getSourcePublicClient(...args: Parameters<AmmEvm[\"getSourcePublicClient\"]>) { return this.vm.getSourcePublicClient(...args); }\n}\n","import type { DevModeConfig } from \"@skate-org/amm-core-v2\";\n\n/** Default DEV api endpoint — matches Phase 1's api client default. */\nconst DEFAULT_DEV_API_ENDPOINT =\n \"https://dev.api.skatechain.org/amm-action-v2\";\n\n/**\n * Convenience factory for the `{ mode: \"DEV\"; config: DevModeConfig }` tuple.\n *\n * Reduces ceremony at call sites that want to override a single field (e.g.,\n * `rpcEndpoints`) without reconstructing the full object:\n *\n * ```ts\n * const mode = createDevConfig({\n * rpcEndpoints: { [CHAIN.MEGAETH]: \"https://my-private-megaeth/rpc\" },\n * });\n * submitAction(wallet, params, mode);\n * ```\n *\n * Pass nothing to use all defaults.\n */\nexport function createDevConfig(\n overrides: Partial<DevModeConfig> = {},\n): { mode: \"DEV\"; config: DevModeConfig } {\n return {\n mode: \"DEV\",\n config: {\n apiEndpoint: overrides.apiEndpoint ?? DEFAULT_DEV_API_ENDPOINT,\n ...(overrides.rpcEndpoints\n ? { rpcEndpoints: overrides.rpcEndpoints }\n : {}),\n },\n };\n}\n","/**\n * Decode a single Uniswap-v3 tick-bitmap `uint256` word into the list of\n * real (non-compressed) ticks it marks as initialized.\n *\n * A tick bitmap word covers 256 compressed ticks. For a given `wordPos`\n * (int16) the word spans compressed ticks `wordPos * 256` through\n * `(wordPos + 1) * 256 - 1`, and bit `k` (0..255) corresponds to the\n * compressed tick `wordPos * 256 + k`. The real tick at bit `k` is\n * `(wordPos * 256 + k) * tickSpacing`.\n *\n * Intended composition with the reader:\n *\n * ```ts\n * const word = await readTickBitmap(pool, wordPos, mode);\n * const ticks = decodeTickBitmapWord(word, wordPos, tickSpacing);\n * ```\n *\n * Pure function: no network, no viem, no external deps.\n *\n * @param word The 256-bit bitmap word returned by PoolAbi.tickBitmap(int16).\n * @param wordPos The int16 word position (-128 .. 127 per Uniswap, but\n * we accept any safe-integer int16-shaped value).\n * @param tickSpacing The pool's tickSpacing (positive integer, typically 1,\n * 10, 60, 200, etc.).\n * @returns Real ticks whose bits are set in the word, ascending.\n *\n * @throws {RangeError} if `tickSpacing <= 0` or if `wordPos` is not a safe integer.\n */\nexport function decodeTickBitmapWord(\n word: bigint,\n wordPos: number,\n tickSpacing: number,\n): number[] {\n if (!Number.isSafeInteger(wordPos)) {\n throw new RangeError(\n `decodeTickBitmapWord: wordPos must be a safe integer, got ${wordPos}`,\n );\n }\n if (!Number.isSafeInteger(tickSpacing) || tickSpacing <= 0) {\n throw new RangeError(\n `decodeTickBitmapWord: tickSpacing must be a positive integer, got ${tickSpacing}`,\n );\n }\n const result: number[] = [];\n // wordPos * 256 gives the base compressed-tick of this word. Each set bit k\n // contributes compressed-tick (wordPos * 256 + k), which becomes real tick\n // (wordPos * 256 + k) * tickSpacing.\n const base = wordPos * 256;\n for (let k = 0; k < 256; k++) {\n if (((word >> BigInt(k)) & 1n) === 1n) {\n result.push((base + k) * tickSpacing);\n }\n }\n return result;\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { KernelEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by the Skate kernel's `KernelEventEmitter`, sourced\n * directly from `@skate-org/amm-bindings`.\n */\nexport type KernelEventName =\n | \"Burn\"\n | \"Collect\"\n | \"CollectProtocol\"\n | \"IncreaseObservationCardinalityNext\"\n | \"Initialize\"\n | \"Mint\"\n | \"PeripheryPoolAdded\"\n | \"PeripheryPoolChanged\"\n | \"PoolCreated\"\n | \"PoolDescriptionUpdated\"\n | \"SetFeeProtocol\"\n | \"Swap\";\n\n/** Exhaustive list of known kernel event names — same values as {@link KernelEventName}. */\nexport const KERNEL_EVENT_NAMES: readonly KernelEventName[] = [\n \"Burn\",\n \"Collect\",\n \"CollectProtocol\",\n \"IncreaseObservationCardinalityNext\",\n \"Initialize\",\n \"Mint\",\n \"PeripheryPoolAdded\",\n \"PeripheryPoolChanged\",\n \"PoolCreated\",\n \"PoolDescriptionUpdated\",\n \"SetFeeProtocol\",\n \"Swap\",\n];\n\n/**\n * A decoded kernel event — the event name, its named args, and the original\n * viem `Log` for context (tx hash, block number, etc.).\n */\nexport interface KernelParsedEvent {\n eventName: KernelEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by the Skate kernel's `KernelEventEmitter`.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known kernel event\n * or if ABI decoding fails.\n */\nexport function parseKernelEventLog(log: Log): KernelParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: KernelEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as KernelEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parseKernelEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { PeripheryEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by `PeripheryEventEmitter` on the source chain.\n */\nexport type PeripheryEventName =\n | \"AmountSettled\"\n | \"Burned\"\n | \"LiquidityDecreased\"\n | \"LiquidityIncreased\"\n | \"MintSettled\"\n | \"Minted\"\n | \"PoolCreated\"\n | \"PoolDeployed\"\n | \"Swapped\"\n | \"TransferredTo\";\n\n/** Exhaustive list of known periphery event names. */\nexport const PERIPHERY_EVENT_NAMES: readonly PeripheryEventName[] = [\n \"AmountSettled\",\n \"Burned\",\n \"LiquidityDecreased\",\n \"LiquidityIncreased\",\n \"MintSettled\",\n \"Minted\",\n \"PoolCreated\",\n \"PoolDeployed\",\n \"Swapped\",\n \"TransferredTo\",\n];\n\n/** A decoded periphery event — name, named args, and the original viem `Log`. */\nexport interface PeripheryParsedEvent {\n eventName: PeripheryEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by `PeripheryEventEmitter` on a source chain.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known periphery\n * event or if ABI decoding fails.\n */\nexport function parsePeripheryEventLog(log: Log): PeripheryParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: PeripheryEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as PeripheryEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parsePeripheryEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import type { Address, Log, PublicClient } from \"viem\";\nimport {\n KernelEventEmitterABI,\n PeripheryEventEmitterABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n parseKernelEventLog,\n type KernelParsedEvent,\n} from \"./kernel\";\nimport {\n parsePeripheryEventLog,\n type PeripheryParsedEvent,\n} from \"./periphery\";\n\nexport interface EventSubscriptionOptions<E> {\n /** Called for each decoded event. */\n onEvent: (event: E) => void;\n /** Called when a log fails to decode (subscription stays alive). */\n onError?: (err: unknown) => void;\n}\n\n/**\n * Subscribe to kernel events emitted by the `KernelEventEmitter` contract\n * at `address`. Returns an unsubscribe function.\n *\n * Decode failures are surfaced via `opts.onError` (if provided) rather than\n * throwing — the subscription continues.\n */\nexport function watchKernelEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<KernelParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: KernelEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parseKernelEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n\n/**\n * Subscribe to periphery events emitted by `PeripheryEventEmitter` at\n * `address` on the source chain the `client` is connected to.\n */\nexport function watchPeripheryEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<PeripheryParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: PeripheryEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parsePeripheryEventLog(log));\n } cat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names":["import_amm_core_v2","import_amm_core_v2","import_amm_bindings","import_amm_core_v2","import_amm_bindings","import_amm_core_v2","import_viem","import_amm_bindings","import_amm_core_v2","import_amm_core_v2","import_viem","import_amm_bindings","import_viem","import_amm_bindings","import_amm_bindings"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/chain-clients.ts","../src/kernel/reader.ts","../src/errors.ts","../src/kernel/_client.ts","../src/kernel/lens.ts","../src/periphery/reader.ts","../src/periphery/submit.ts","../src/periphery/calldata.ts","../src/client.ts","../src/skate-amm.ts","../src/devConfig.ts","../src/kernel/tickBitmap.ts","../src/events/kernel.ts","../src/events/periphery.ts","../src/events/watch.ts"],"sourcesContent":["export * from \"./chain-clients\";\nexport { AmmEvm } from \"./client\";\nexport { SkateAmm } from \"./skate-amm\";\n// `DEFAULT_DEV_API_ENDPOINT` is intentionally not re-exported — it's\n// `createDevConfig`'s private default value, duplicates the canonical\n// URL in `api`, and shouldn't be part of the evm public surface.\nexport { createDevConfig } from \"./devConfig\";\n// Public error classes only; wrap* helpers are internal implementation\n// detail shared between readers/submitters and are not re-exported.\nexport { EvmReadError, EvmWriteError } from \"./errors\";\nexport * from \"./kernel\";\nexport * from \"./periphery\";\nexport * from \"./events\";\n","import {\n createPublicClient,\n defineChain,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n} from \"viem\";\nimport { arbitrum, mainnet } from \"viem/chains\";\nimport {\n BLOCK_EXPLORER,\n CHAIN,\n KernelChain,\n VM,\n vmTypeFromChain,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * MegaETH chain definition — `@public`.\n *\n * Exported for callers who need to build their own viem `WalletClient` or\n * `PublicClient` against the same chain the SDK uses internally (e.g. wallet\n * integrations that construct a `WalletClient` ahead of calling\n * `submitAction`). Prefer {@link getKernelPublicClient} when you just need a\n * read client.\n *\n * viem ships a `megaeth` chain at id 4326, but with a different default RPC\n * than the one Skate uses for kernel reads. Define locally so we control the\n * RPC URL + block-explorer metadata and don't inherit unrelated op-stack\n * contract addresses.\n */\nexport const megaethChain: Chain = defineChain({\n id: 4326,\n name: \"MegaETH\",\n network: \"megaeth\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n public: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.MEGAETH },\n },\n});\n\n/**\n * Robinhood Chain definition (id 4663) — Arbitrum-Orbit L2, native ETH.\n *\n * A source periphery chain for the WETH/USDG pool. Defined locally so the SDK\n * controls the RPC URL + block-explorer metadata (viem ships no built-in for\n * 4663).\n */\nexport const robinhoodChain: Chain = defineChain({\n id: 4663,\n name: \"Robinhood Chain\",\n network: \"robinhood\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://rpc.mainnet.chain.robinhood.com\"] },\n public: { http: [\"https://rpc.mainnet.chain.robinhood.com\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.ROBINHOOD },\n },\n});\n\n/**\n * Default public RPC URLs by chain id.\n *\n * Callers can override per-chain via `DevModeConfig.rpcEndpoints` or by\n * passing an explicit `transport` to the factory functions below.\n */\nconst DEFAULT_RPC: Partial<Record<CHAIN, string>> = {\n [CHAIN.MEGAETH]: \"https://mainnet.megaeth.com/rpc\",\n [CHAIN.ARBITRUM]: \"https://arb1.arbitrum.io/rpc\",\n [CHAIN.ETHEREUM]: \"https://ethereum-rpc.publicnode.com\",\n [CHAIN.ROBINHOOD]: \"https://rpc.mainnet.chain.robinhood.com\",\n};\n\n/**\n * Map a supported EVM `CHAIN` to a viem `Chain` definition.\n *\n * Only chains we actively support in Phase 2 are listed; unknown chains\n * return `undefined` and the caller throws.\n */\nfunction chainDefFor(chain: CHAIN): Chain | undefined {\n switch (chain) {\n case CHAIN.MEGAETH:\n return megaethChain;\n case CHAIN.ARBITRUM:\n return arbitrum;\n case CHAIN.ETHEREUM:\n return mainnet;\n case CHAIN.ROBINHOOD:\n return robinhoodChain;\n default:\n return undefined;\n }\n}\n\n/**\n * Resolve the RPC URL for a given chain under the precedence:\n * transport override (caller arg) > mode.config.rpcEndpoints[chain] > DEFAULT_RPC[chain]\n * Returns `undefined` if none is set — callers must have already decided whether\n * to use a caller-supplied transport.\n */\nfunction resolveRpcUrl(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): string | undefined {\n const { config } = normalizeMode(mode);\n return config?.rpcEndpoints?.[chain] ?? DEFAULT_RPC[chain];\n}\n\n/**\n * Return a fresh `PublicClient` bound to the kernel chain for `mode`.\n *\n * Today every env (`DEV` / `STAGING` / `PRODUCTION`) resolves to MegaETH —\n * see `KERNEL_CHAIN_BY_MODE` in `@skate-org/amm-core-v2`. Pointing a future\n * env at a different kernel chain is a one-line edit there; this factory\n * reads from that mapping so client + address tables stay in sync.\n *\n * Pure — no singletons, no caching. Pass a custom `transport` to override\n * the default RPC (useful for tests and custom RPC providers).\n */\nexport function getKernelPublicClient(\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n const { mode: baseMode } = normalizeMode(mode);\n const kernelChainId = KernelChain(baseMode);\n const chainDef = chainDefFor(kernelChainId);\n if (!chainDef) {\n throw new Error(\n `getKernelPublicClient: no chain definition registered for kernel chain ${kernelChainId} ` +\n `(mode=${baseMode}); update chainDefFor() in chain-clients.ts to support it.`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(resolveRpcUrl(kernelChainId, mode)),\n });\n}\n\n/**\n * Return a fresh `PublicClient` for a source EVM chain (e.g. Arbitrum).\n *\n * Throws a descriptive `Error` when:\n * - `chain` is not an EVM chain (per `vmTypeFromChain`); or\n * - no viem chain definition is registered for `chain`; or\n * - no default RPC URL is configured for `chain` and no `transport` override\n * was provided.\n *\n * Pure — no singletons, no caching.\n */\nexport function getSourcePublicClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n if (vmTypeFromChain(chain) !== VM.EVM) {\n throw new Error(\n `getSourcePublicClient: chain ${chain} is not an EVM chain`,\n );\n }\n const chainDef = chainDefFor(chain);\n if (!chainDef) {\n throw new Error(\n `getSourcePublicClient: no chain definition registered for chain ${chain}`,\n );\n }\n const rpc = resolveRpcUrl(chain, mode);\n if (!rpc && !transport) {\n throw new Error(\n `getSourcePublicClient: no default or override RPC configured for chain ${chain}; pass a transport override or set DevModeConfig.rpcEndpoints[${chain}]`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(rpc),\n });\n}\n","import type { PublicClient } from \"viem\";\nimport {\n KernelManagerABI,\n KernelPoolABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n getAmount0Delta,\n getAmount1Delta,\n getSqrtRatioAtTick,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/** Decoded kernel-pool `slot0` state (named fields, per the ABI tuple). */\nexport interface KernelSlot0 {\n sqrtPriceX96: bigint;\n tick: number;\n observationIndex: number;\n observationCardinality: number;\n observationCardinalityNext: number;\n feeProtocol: number;\n unlocked: boolean;\n}\n\n/** Decoded pool state returned by `readPool`. */\nexport interface KernelPoolState {\n slot0: KernelSlot0;\n liquidity: bigint;\n}\n\n/** Decoded NFT position returned by `readPosition`. */\nexport interface KernelNftPosition {\n pool: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n liquidity: bigint;\n feeGrowthInside0LastX128: bigint;\n feeGrowthInside1LastX128: bigint;\n tokensOwed0: bigint;\n tokensOwed1: bigint;\n}\n\n/** Decoded kernel-pool `ticks(tick)` struct. */\nexport interface KernelTick {\n liquidityGross: bigint;\n liquidityNet: bigint;\n feeGrowthOutside0X128: bigint;\n feeGrowthOutside1X128: bigint;\n tickCumulativeOutside: bigint;\n secondsPerLiquidityOutsideX128: bigint;\n secondsOutside: number;\n initialized: boolean;\n}\n\n/**\n * Read `slot0` and `liquidity` from a kernel pool. Returns both in a single\n * object; the reads are fired in parallel.\n *\n * The `client` optional parameter is the standard test-injection point.\n */\nexport async function readPool(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelPoolState> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [slot0, liquidity] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"slot0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"liquidity\",\n }),\n ]);\n // Viem returns named outputs as a positional tuple (array) when every\n // output has a name — normalize to a named-field object here so callers\n // don't depend on viem's tuple/object split.\n const s0 = slot0 as readonly [\n bigint,\n number,\n number,\n number,\n number,\n number,\n boolean,\n ];\n return {\n slot0: {\n sqrtPriceX96: s0[0],\n tick: s0[1],\n observationIndex: s0[2],\n observationCardinality: s0[3],\n observationCardinalityNext: s0[4],\n feeProtocol: s0[5],\n unlocked: s0[6],\n },\n liquidity: liquidity as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPool\");\n }\n}\n\n/** Decoded kernel-pool token balances returned by `readKernelBalances`. */\nexport interface KernelBalances {\n balance0: bigint;\n balance1: bigint;\n}\n\n/**\n * Read `balance0` and `balance1` from a kernel pool (raw token reserves on\n * the kernel side, before periphery scaling). Reads are fired in parallel.\n */\nexport async function readKernelBalances(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelBalances> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [balance0, balance1] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance1\",\n }),\n ]);\n return { balance0: balance0 as bigint, balance1: balance1 as bigint };\n } catch (err) {\n throw wrapReadError(err, \"readKernelBalances\");\n }\n}\n\n/**\n * Read an NFT position by token id from the kernel manager.\n *\n * Calls `KernelManager.nftPositions(tokenId)` — per the ABI this returns a\n * `DataTypes.NFTPosition` tuple including `pool`, `tickLower`, `tickUpper`,\n * `liquidity`, fee growth, and tokens owed.\n */\nexport async function readPosition(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelNftPosition> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const manager = KernelManagerAddress(baseMode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: manager,\n abi: KernelManagerABI,\n functionName: \"nftPositions\",\n args: [p.tokenId],\n })) as unknown;\n // Accept either a positional tuple or an already-named object from\n // viem — normalize to a named-field object, mirroring readPool's\n // defensive remap.\n const asTuple = Array.isArray(raw)\n ? (raw as unknown as readonly [\n `0x${string}`,\n number,\n number,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n ])\n : null;\n if (asTuple) {\n return {\n pool: asTuple[0],\n tickLower: asTuple[1],\n tickUpper: asTuple[2],\n liquidity: asTuple[3],\n feeGrowthInside0LastX128: asTuple[4],\n feeGrowthInside1LastX128: asTuple[5],\n tokensOwed0: asTuple[6],\n tokensOwed1: asTuple[7],\n };\n }\n return raw as KernelNftPosition;\n } catch (err) {\n throw wrapReadError(err, \"readPosition\");\n }\n}\n\n/**\n * Read a kernel-pool tick-bitmap word (`tickBitmap(int16 wordPos)`).\n *\n * Returns the raw `uint256` word as a bigint.\n */\nexport async function readTickBitmap(p: {\n kernelPool: `0x${string}`;\n wordPos: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<bigint> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const word = await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"tickBitmap\",\n args: [p.wordPos],\n });\n return word as bigint;\n } catch (err) {\n throw wrapReadError(err, \"readTickBitmap\");\n }\n}\n\n/** Read the `ticks(tick)` struct from a kernel pool. */\nexport async function readTick(p: {\n kernelPool: `0x${string}`;\n tick: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelTick> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"ticks\",\n args: [p.tick],\n })) as readonly [\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n number,\n boolean,\n ];\n return {\n liquidityGross: raw[0],\n liquidityNet: raw[1],\n feeGrowthOutside0X128: raw[2],\n feeGrowthOutside1X128: raw[3],\n tickCumulativeOutside: raw[4],\n secondsPerLiquidityOutsideX128: raw[5],\n secondsOutside: raw[6],\n initialized: raw[7],\n };\n } catch (err) {\n throw wrapReadError(err, \"readTick\");\n }\n}\n\n/**\n * Compute `{amount0, amount1}` for an NFT position using the Group 3 math.\n *\n * Reads the position (to learn `pool`, `tickLower`, `tickUpper`,\n * `liquidity`) and the pool's `slot0`, then splits based on whether the\n * current tick is below, inside, or above the position range — mirroring\n * `PositionValue.principal` from Uniswap v3 periphery.\n */\nexport async function computePositionAmounts(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<{ amount0: bigint; amount1: bigint }> {\n const c = resolveKernelClient(p.mode, p.client);\n const position = await readPosition({ tokenId: p.tokenId, mode: p.mode, client: c });\n const { slot0 } = await readPool({ kernelPool: position.pool, mode: p.mode, client: c });\n\n const sqrtLower = getSqrtRatioAtTick(position.tickLower);\n const sqrtUpper = getSqrtRatioAtTick(position.tickUpper);\n\n if (slot0.tick < position.tickLower) {\n return {\n amount0: getAmount0Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n amount1: 0n,\n };\n }\n if (slot0.tick >= position.tickUpper) {\n return {\n amount0: 0n,\n amount1: getAmount1Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n };\n }\n return {\n amount0: getAmount0Delta(\n slot0.sqrtPriceX96,\n sqrtUpper,\n position.liquidity,\n false,\n ),\n amount1: getAmount1Delta(\n sqrtLower,\n slot0.sqrtPriceX96,\n position.liquidity,\n false,\n ),\n };\n}\n","/**\n * Shared error types for the `@skate-org/amm-evm-v2` package.\n *\n * `EvmReadError` / `EvmWriteError` extend `SdkError` (from core) so callers\n * can `instanceof SdkError` to catch any SDK-origin error without needing\n * to know the specific subclass.\n */\n\nimport { SdkError } from \"@skate-org/amm-core-v2\";\n\n/** SDK-level error thrown when an EVM read reverts or decodes badly. */\nexport class EvmReadError extends SdkError {\n override readonly name: string = \"EvmReadError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * SDK-level error thrown when an EVM write (broadcast) fails.\n *\n * Symmetric with {@link EvmReadError}, but covers the write path: viem's\n * `TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`, as well as submitter\n * pre-flight guards (e.g. wrong-chain, missing account).\n */\nexport class EvmWriteError extends SdkError {\n override readonly name: string = \"EvmWriteError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * Wrap any error from an EVM read into `EvmReadError`. Viem always wraps\n * revert-path errors in `ContractFunctionExecutionError` (see\n * `viem/utils/errors/getContractError`), so we check both the outer name and\n * the `.cause` chain for `ContractFunctionRevertedError` /\n * `ContractFunctionZeroDataError`.\n *\n * Shared by `kernel/reader.ts` and `periphery/reader.ts` — depends only on\n * `EvmReadError` and generic Error inspection (no reader-module imports), so\n * it is safe from circular-import concerns.\n */\nexport function wrapReadError(\n err: unknown,\n functionName: string,\n): EvmReadError {\n const outerName = (err as { name?: string } | null)?.name;\n const causeName = (err as { cause?: { name?: string } } | null)?.cause?.name;\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n const isViemContractError =\n outerName === \"ContractFunctionExecutionError\" ||\n outerName === \"ContractFunctionRevertedError\" ||\n outerName === \"ContractFunctionZeroDataError\" ||\n causeName === \"ContractFunctionRevertedError\" ||\n causeName === \"ContractFunctionZeroDataError\";\n if (isViemContractError) {\n return new EvmReadError(functionName, `reverted: ${message}`, {\n cause: err as Error,\n });\n }\n return new EvmReadError(functionName, message, { cause: err as Error });\n}\n\n/**\n * Wrap any error from an EVM write-path call (typically\n * `WalletClient.sendTransaction`) into `EvmWriteError`.\n *\n * Any thrown error reaching a submitter is treated as a write failure. If\n * we later want to differentiate known viem write errors\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`) from unknown errors —\n * e.g. to prefix the message or re-throw unknowns raw — that dispatch goes\n * here. Keeping the single-return shape until a concrete caller need\n * surfaces.\n */\nexport function wrapWriteError(\n err: unknown,\n functionName: string,\n): EvmWriteError {\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n return new EvmWriteError(functionName, message, { cause: err as Error });\n}\n","import type { PublicClient } from \"viem\";\nimport type { EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { getKernelPublicClient } from \"../chain-clients\";\n\n/**\n * Return the caller-provided client if present, otherwise build a fresh\n * MegaETH kernel client for the given mode. Shared by readers + lens\n * helpers; intentionally unexported from the package barrel.\n */\nexport function resolveKernelClient(\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getKernelPublicClient(mode);\n}\n","import type { PublicClient } from \"viem\";\nimport { KernelManagerABI } from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/**\n * Kernel lens (simulate) helpers — wrap KernelManager's `lens*` functions as\n * static-call simulations. Lens functions are marked nonpayable in the ABI,\n * but viem's `simulateContract` evaluates them with `eth_call`, so they\n * reuse the same client + RPC plumbing as the readers and never produce a\n * transaction.\n *\n * Errors funnel through `wrapReadError`: lens calls share the read-path\n * error model (revert reasons + RPC failures), and tagging them as \"writes\"\n * would be misleading since no state changes.\n */\n\nexport interface SimulateSwapParams {\n /** Kernel-pool address (EVM) */\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 (use `toBytes32Address` for cross-VM) */\n recipient: `0x${string}`;\n zeroForOne: boolean;\n /** Positive = exactInput, negative = exactOutput, per Uniswap v3 convention */\n amountSpecified: bigint;\n sqrtPriceLimitX96: bigint;\n}\n\nexport interface SimulateSwapResult {\n amount0: bigint;\n amount1: bigint;\n sqrtPriceX96After: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateSwap(p: {\n params: SimulateSwapParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateSwapResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensSwap\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.zeroForOne,\n p.params.amountSpecified,\n p.params.sqrtPriceLimitX96,\n ],\n });\n const [amount0, amount1, sqrtPriceX96After, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, sqrtPriceX96After, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateSwap\");\n }\n}\n\nexport interface SimulateMintParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n /** Caller-supplied callback data (passed to `IKernelMintCallback`) */\n data: `0x${string}`;\n}\n\nexport interface SimulateMintResult {\n amount0Used: bigint;\n amount1Used: bigint;\n liquidityAmount: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateMint(p: {\n params: SimulateMintParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateMintResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensMint\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount0,\n p.params.amount1,\n p.params.data,\n ],\n });\n const [amount0Used, amount1Used, liquidityAmount, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0Used, amount1Used, liquidityAmount, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateMint\");\n }\n}\n\nexport interface SimulateBurnParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n /** Liquidity amount to burn (uint128). */\n amount: bigint;\n}\n\nexport interface SimulateBurnResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateBurn(p: {\n params: SimulateBurnParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateBurnResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensBurn\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount,\n ],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateBurn\");\n }\n}\n\nexport interface SimulateDecreaseLiquidityParams {\n /** NFT position id (v2 positions). */\n tokenId: bigint;\n /** Liquidity amount to remove (uint128). */\n liquidity: bigint;\n}\n\nexport interface SimulateDecreaseLiquidityResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateDecreaseLiquidity(p: {\n params: SimulateDecreaseLiquidityParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateDecreaseLiquidityResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensDecreaseLiquidity\",\n args: [p.params.tokenId, p.params.liquidity],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateDecreaseLiquidity\");\n }\n}\n","import type { PublicClient } from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n CHAIN,\n getPeripheryDetailsByKernelPoolAndChainId,\n normalizeMode,\n type EnvModeWithConfig,\n type EvmChain,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\nimport { getSourcePublicClient } from \"../chain-clients\";\nimport { EvmReadError, wrapReadError } from \"../errors\";\n\n/**\n * Decoded periphery-pool state assembled by {@link readPeripheryPool}.\n *\n * The periphery pool does **not** expose a `slot0`-style view — pricing\n * state lives on the kernel pool on MegaETH (see `readPool`). What the\n * periphery pool does expose is: the configured pair\n * (`token0`, `token1`, `fee`, `kernelPool` reference), the escrowed\n * in-pool settlement balances (`balancesAvailable`), and the two\n * `dustAmount{0,1}` accumulators. Together these are enough for a\n * source-chain caller to reason about pending settlement and dust.\n */\nexport interface PeripheryPoolState {\n /** Periphery pool contract address on the source chain. */\n address: `0x${string}`;\n /** Source-chain ERC-20 address for token0. */\n token0: `0x${string}`;\n /** Source-chain ERC-20 address for token1. */\n token1: `0x${string}`;\n /** Fee tier (uint24) the periphery pool was deployed with. */\n fee: number;\n /** Address of the paired kernel pool on MegaETH. */\n kernelPool: `0x${string}`;\n /** Aggregate in-pool balances available for settlement. */\n balancesAvailable: { amount0Available: bigint; amount1Available: bigint };\n /** token0 dust accumulator. */\n dustAmount0: bigint;\n /** token1 dust accumulator. */\n dustAmount1: bigint;\n}\n\n/**\n * Decoded user per-pool in-flight token balances.\n *\n * Returned by `PeripheryPool.usersData(user)` as `(uint256 amount0, uint256 amount1)`.\n */\nexport interface UserPoolBalances {\n amount0: bigint;\n amount1: bigint;\n}\n\n/**\n * Return the caller-provided client, or build a fresh source-chain\n * client for `chain` under the given `mode`. Mirrors the kernel reader\n * injection pattern.\n */\nfunction resolveClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getSourcePublicClient(chain, mode);\n}\n\n/**\n * Read the assembled periphery-pool state on a source chain.\n *\n * Resolves the periphery pool address via\n * `getPeripheryDetailsByKernelPoolAndChainId` (from\n * `@skate-org/amm-core-v2`) — **no addresses are hardcoded here**. If the\n * `(kernelPool, chain, mode)` triple has no entry in the aggregated pool\n * catalog, throws with the triple in the message for debuggability.\n *\n * All sub-reads are fired in parallel and normalized to named fields.\n */\nexport async function readPeripheryPool(p: {\n chain: CHAIN;\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<PeripheryPoolState> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const details = getPeripheryDetailsByKernelPoolAndChainId(\n p.kernelPool,\n p.chain as EvmChain,\n baseMode,\n );\n if (!details) {\n throw new EvmReadError(\n \"readPeripheryPool\",\n `no periphery entry for kernelPool=${p.kernelPool} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const address = details.address;\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const [\n balancesAvailableRaw,\n dust0,\n dust1,\n token0,\n token1,\n fee,\n kPool,\n ] = await Promise.all([\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"balancesAvailable\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"fee\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"kernelPool\",\n }),\n ]);\n // Viem decodes multi-output tuples with all-named outputs as a\n // positional tuple — normalize to a named-field object.\n const bAvail = balancesAvailableRaw as readonly [bigint, bigint];\n return {\n address,\n token0: token0 as `0x${string}`,\n token1: token1 as `0x${string}`,\n fee: fee as number,\n kernelPool: kPool as `0x${string}`,\n balancesAvailable: {\n amount0Available: bAvail[0],\n amount1Available: bAvail[1],\n },\n dustAmount0: dust0 as bigint,\n dustAmount1: dust1 as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPeripheryPool\");\n }\n}\n\n/**\n * Read a user's per-pool in-flight balances on a source chain.\n *\n * Resolves the periphery pool address via AmmCore.getPoolInfoByKey +\n * peripheryInfo[chain].address (no hardcoded addresses) and calls\n * `PeripheryPool.usersData(user)` which returns\n * `(uint256 amount0, uint256 amount1)`.\n */\nexport async function readUserPoolBalances(p: {\n user: `0x${string}`;\n poolKey: string;\n chain: CHAIN;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<UserPoolBalances> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const core = new AmmCore(p.mode);\n const info = core.getPoolInfoByKey(p.poolKey);\n const periphery = info?.peripheryInfo[p.chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new EvmReadError(\n \"readUserPoolBalances\",\n `no periphery entry for poolKey=${p.poolKey} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: periphery.address,\n abi: PeripheryPoolABI,\n functionName: \"usersData\",\n args: [p.user],\n })) as unknown;\n // `usersData` returns `(uint256 amount0, uint256 amount1)`.\n // Viem decodes tuples with all-named outputs as a positional tuple;\n // handle both the positional and (older) object shapes defensively.\n if (Array.isArray(raw)) {\n const tuple = raw as unknown as readonly [bigint, bigint];\n return { amount0: tuple[0], amount1: tuple[1] };\n }\n const asObject = raw as { amount0: bigint; amount1: bigint };\n return { amount0: asObject.amount0, amount1: asObject.amount1 };\n } catch (err) {\n throw wrapReadError(err, \"readUserPoolBalances\");\n }\n}\n","import type { Address, Hex, WalletClient } from \"viem\";\nimport type { CHAIN, EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { EvmWriteError, wrapWriteError } from \"../errors\";\n\n/**\n * Pre-built source-chain transaction payload accepted by\n * {@link submitAction}.\n *\n * The SDK does **not** fabricate calldata in Group 6 — callers build the\n * payload (e.g. from a quote's `serializedCall`) and this submitter only\n * broadcasts it. This keeps the SDK decoupled from any off-chain\n * routing/quote surface.\n */\nexport type SubmitActionParams = {\n /** Source-chain id the wallet must be connected to. */\n chain: CHAIN;\n /** Destination address of the broadcast tx. */\n to: Address;\n /** Pre-encoded calldata. */\n data: Hex;\n /** Native-value payable amount; defaults to `0n`. */\n value?: bigint;\n};\n\n/**\n * Broadcast a pre-built periphery action tx from the caller's\n * `WalletClient`.\n *\n * Guarantees:\n * - Throws {@link EvmWriteError} immediately if\n * `wallet.chain?.id !== params.chain` — no RPC call is made.\n * - Throws {@link EvmWriteError} if `wallet.account` is not set.\n * - Forwards the payload to `wallet.sendTransaction` and returns the\n * resulting tx hash.\n * - Wraps any thrown viem write-path error\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, …) into an {@link EvmWriteError} via\n * {@link wrapWriteError}.\n *\n * The `mode` parameter is currently unused at runtime; it is accepted for\n * API symmetry with the readers and as a forward-compat hook for a future\n * mode-specific submission policy (e.g. DEV-only simulation, staging\n * retries). The `_` prefix marks it unused for the TypeScript checker.\n *\n * Non-goals (per plan guardrails):\n * - Does NOT sign — the caller brings a `WalletClient` wired to their\n * signer.\n * - Does NOT switch chains — callers are responsible for\n * `wallet.switchChain(...)`.\n * - Does NOT retry or manage nonces — delegated to the caller's wallet.\n */\nexport async function submitAction(\n wallet: WalletClient,\n params: SubmitActionParams,\n _mode: EnvModeWithConfig,\n): Promise<Hex> {\n if (wallet.chain?.id !== params.chain) {\n throw new EvmWriteError(\n \"submitAction\",\n `wallet chain ${wallet.chain?.id ?? \"undefined\"} != params.chain ${params.chain}`,\n );\n }\n\n try {\n const account = wallet.account;\n if (!account) {\n throw new EvmWriteError(\n \"submitAction\",\n \"wallet has no account; callers must provide a wallet with wallet.account set\",\n );\n }\n return await wallet.sendTransaction({\n to: params.to,\n data: params.data,\n value: params.value ?? 0n,\n chain: wallet.chain,\n account,\n });\n } catch (err) {\n // Preserve our own pre-flight guards verbatim — they are already\n // EvmWriteError instances and don't need re-wrapping.\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitAction\");\n }\n}\n\n/**\n * Broadcast a periphery *swap* action — thin wrapper around\n * {@link submitAction} that re-labels any unknown error as `submitSwap` to\n * aid log-line triage. Behaviourally identical to `submitAction`; shares\n * its pre-flight guards.\n */\nexport async function submitSwap(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitSwap\");\n }\n}\n\n/**\n * Broadcast a periphery *approval* action (ERC-20 approve to the source\n * chain's periphery contract) — thin wrapper around {@link submitAction}.\n * See {@link submitSwap} for labeling rationale.\n */\nexport async function submitApproval(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitApproval\");\n }\n}\n","/**\n * Pure ABI encoders for periphery-pool `swap` / `mint` / `burn` /\n * `increaseLiquidity` / `decreaseLiquidity` calldata.\n *\n * No client, no signing, no submission — quote routes use these to mirror\n * the on-chain calldata shape without paying for an RPC round-trip. For the\n * full submit-and-confirm flow, use the submitters in `./submit.ts`.\n *\n * Each `build*` function resolves the EVM periphery contract address for the\n * given `poolKey` + `chain` via `AmmCore`, encodes the calldata, and returns\n * a `CalldataCall` ready for submission.\n *\n * Encoding does NOT change — only call signatures and return types are new.\n */\n\nimport {\n encodeAbiParameters,\n encodeFunctionData,\n maxUint256,\n parseAbiParameters,\n} from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n type CHAIN,\n type EnvModeWithConfig,\n type CalldataCall,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * Resolve the EVM periphery pool contract address for a `(poolKey, chain, mode)` triple.\n * Throws with a descriptive message if the poolKey is unknown or has no periphery on `chain`.\n *\n * Resolves by poolKey via the aggregated catalog — deliberately not reusing\n * `getPeripheryDetailsByKernelPoolAndChainId`, which is keyed by kernelPool.\n */\nfunction resolvePeripheryTarget(\n poolKey: string,\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): `0x${string}` {\n const core = new AmmCore(mode);\n const info = core.getPoolInfoByKey(poolKey);\n if (!info) throw new Error(`unknown poolKey: ${poolKey}`);\n const periphery = info.peripheryInfo[chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new Error(`pool ${poolKey} has no periphery on chain ${chain}`);\n }\n return periphery.address;\n}\n\n// ── Param types ───────────────────────────────────────────────────────────────\n\n/** Common fields injected into every Build*Params type. */\ninterface BuildBaseParams {\n /** Pool key, e.g. \"USDC_USDT\" — resolves the source periphery pool target. */\n poolKey: string;\n /** Source chain the action is submitted on. */\n chain: CHAIN;\n /** Env mode. Omitted when called via AmmEvm (injected). */\n mode: EnvModeWithConfig;\n}\n\nexport interface BuildSwapParams extends BuildBaseParams {\n /** Swap recipient address in bytes32 format. */\n recipient: `0x${string}`;\n destChainId: number;\n destVmType: number;\n zeroForOne: boolean;\n /** Raw amount, subject to token native decimals. */\n amount: bigint;\n sqrtPriceLimitX96: bigint;\n /** Raw amount, subject to token native decimals. Default 0n. */\n minAmountOut?: bigint;\n /** Enforced at kernel timestamp. Default `maxUint256`. */\n deadline?: bigint;\n}\n\nexport interface BuildMintParams extends BuildBaseParams {\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildBurnParams extends BuildBaseParams {\n tokenId: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildIncreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildDecreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n /** Kernel-side liquidity amount — `sqrt(normalizedAmount0 * normalizedAmount1)` in 18-decimal space. */\n liquidityAmount: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\n// ── Internal encoders (pure, NOT exported) ────────────────────────────────────\n\nfunction encodeSwap(params: Omit<BuildSwapParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n zeroForOne,\n amount,\n sqrtPriceLimitX96,\n destVmType,\n destChainId,\n minAmountOut,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256,uint256\"),\n [\n minAmountOut ?? 0n,\n BigInt(destChainId),\n BigInt(destVmType),\n deadline ?? maxUint256,\n ],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"swap\",\n args: [recipient, zeroForOne, amount, sqrtPriceLimitX96, extraData],\n });\n}\n\nfunction encodeMint(params: Omit<BuildMintParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n tickLower,\n tickUpper,\n amount0,\n amount1,\n amount0Min,\n amount1Min,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"mint\",\n args: [recipient, tickLower, tickUpper, amount0, amount1, extraData],\n });\n}\n\nfunction encodeBurn(params: Omit<BuildBurnParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"burn\",\n args: [tokenId, extraData] as const,\n });\n}\n\nfunction encodeIncreaseLiquidity(params: Omit<BuildIncreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0, amount1, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"increaseLiquidity\",\n args: [tokenId, amount0, amount1, extraData],\n });\n}\n\nfunction encodeDecreaseLiquidity(params: Omit<BuildDecreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, liquidityAmount, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"decreaseLiquidity\",\n args: [tokenId, liquidityAmount, extraData],\n });\n}\n\n// ── Public async builders ─────────────────────────────────────────────────────\n\n/** Build calldata for a `swap` on the resolved EVM periphery pool. */\nexport async function buildSwap(params: BuildSwapParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeSwap(encodeParams),\n };\n}\n\n/** Build calldata for a `mint` on the resolved EVM periphery pool. */\nexport async function buildMint(params: BuildMintParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeMint(encodeParams),\n };\n}\n\n/** Build calldata for a `burn` on the resolved EVM periphery pool. */\nexport async function buildBurn(params: BuildBurnParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeBurn(encodeParams),\n };\n}\n\n/** Build calldata for `increaseLiquidity` on the resolved EVM periphery pool. */\nexport async function buildIncreaseLiquidity(params: BuildIncreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeIncreaseLiquidity(encodeParams),\n };\n}\n\n/**\n * Build calldata for `decreaseLiquidity` on the resolved EVM periphery pool.\n *\n * WARN: `liquidityAmount` is kernel-side, computed as\n * `sqrt(normalizedAmount0 * normalizedAmount1)` (18-decimal space).\n */\nexport async function buildDecreaseLiquidity(params: BuildDecreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeDecreaseLiquidity(encodeParams),\n };\n}\n","import type { PublicClient, Transport, WalletClient } from \"viem\";\nimport type { EnvModeWithConfig, CHAIN, CalldataCall, AmmVmClient } from \"@skate-org/amm-core-v2\";\nimport {\n readPool,\n readKernelBalances,\n readPosition,\n readTickBitmap,\n readTick,\n computePositionAmounts,\n} from \"./kernel/reader\";\nimport {\n simulateSwap,\n simulateMint,\n simulateBurn,\n simulateDecreaseLiquidity,\n type SimulateSwapParams,\n type SimulateMintParams,\n type SimulateBurnParams,\n type SimulateDecreaseLiquidityParams,\n} from \"./kernel/lens\";\nimport {\n readPeripheryPool,\n readUserPoolBalances,\n type PeripheryPoolState,\n type UserPoolBalances,\n} from \"./periphery/reader\";\nimport {\n submitAction,\n submitSwap,\n submitApproval,\n type SubmitActionParams,\n} from \"./periphery/submit\";\nimport {\n buildSwap,\n buildMint,\n buildBurn,\n buildIncreaseLiquidity,\n buildDecreaseLiquidity,\n type BuildSwapParams,\n type BuildMintParams,\n type BuildBurnParams,\n type BuildIncreaseLiquidityParams,\n type BuildDecreaseLiquidityParams,\n} from \"./periphery/calldata\";\nimport {\n getKernelPublicClient,\n getSourcePublicClient,\n} from \"./chain-clients\";\n\n/**\n * Env-bound client that wraps all EVM mode-taking functions with a fixed\n * `EnvModeWithConfig`. Construct once with the desired env and call methods\n * without the `mode` parameter.\n *\n * The raw `EnvModeWithConfig` is stored as-is (not normalized) so that\n * `config.rpcEndpoints` overrides pass through intact to the underlying\n * readers and chain-client factories.\n *\n * Implements `AmmVmClient<CalldataCall, WalletClient, 0x${string}, PeripheryPoolState, UserPoolBalances>`.\n * EVM submits any action type through the same `submitAction` path — the four\n * extra `AmmVmClient` submit methods are thin aliases.\n *\n * @example\n * const evm = new AmmEvm('PRODUCTION');\n * const pool = await evm.readPool({ kernelPool: '0x...' });\n * const call = await evm.buildSwap({ poolKey: 'USDC_USDT', chain: CHAIN.ARBITRUM, ... });\n */\nexport class AmmEvm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n }\n\n // ── Kernel readers ────────────────────────────────────────────────────────\n\n readPool(p: Omit<Parameters<typeof readPool>[0], \"mode\">) {\n return readPool({ ...p, mode: this.env, client: p.client });\n }\n\n readKernelBalances(p: Omit<Parameters<typeof readKernelBalances>[0], \"mode\">) {\n return readKernelBalances({ ...p, mode: this.env, client: p.client });\n }\n\n readPosition(p: Omit<Parameters<typeof readPosition>[0], \"mode\">) {\n return readPosition({ ...p, mode: this.env, client: p.client });\n }\n\n readTickBitmap(p: Omit<Parameters<typeof readTickBitmap>[0], \"mode\">) {\n return readTickBitmap({ ...p, mode: this.env, client: p.client });\n }\n\n readTick(p: Omit<Parameters<typeof readTick>[0], \"mode\">) {\n return readTick({ ...p, mode: this.env, client: p.client });\n }\n\n computePositionAmounts(p: Omit<Parameters<typeof computePositionAmounts>[0], \"mode\">) {\n return computePositionAmounts({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Kernel lens (simulate) ────────────────────────────────────────────────\n\n simulateSwap(p: { params: SimulateSwapParams; client?: PublicClient }) {\n return simulateSwap({ ...p, mode: this.env, client: p.client });\n }\n\n simulateMint(p: { params: SimulateMintParams; client?: PublicClient }) {\n return simulateMint({ ...p, mode: this.env, client: p.client });\n }\n\n simulateBurn(p: { params: SimulateBurnParams; client?: PublicClient }) {\n return simulateBurn({ ...p, mode: this.env, client: p.client });\n }\n\n simulateDecreaseLiquidity(p: { params: SimulateDecreaseLiquidityParams; client?: PublicClient }) {\n return simulateDecreaseLiquidity({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Omit<Parameters<typeof readPeripheryPool>[0], \"mode\">): Promise<PeripheryPoolState> {\n return readPeripheryPool({ ...p, mode: this.env, client: p.client });\n }\n\n readUserPoolBalances(p: Omit<Parameters<typeof readUserPoolBalances>[0], \"mode\">): Promise<UserPoolBalances> {\n return readUserPoolBalances({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery calldata builders ───────────────────────────────────────────\n\n buildSwap(p: Omit<BuildSwapParams, \"mode\">): Promise<CalldataCall> {\n return buildSwap({ ...p, mode: this.env });\n }\n\n buildMint(p: Omit<BuildMintParams, \"mode\">): Promise<CalldataCall> {\n return buildMint({ ...p, mode: this.env });\n }\n\n buildBurn(p: Omit<BuildBurnParams, \"mode\">): Promise<CalldataCall> {\n return buildBurn({ ...p, mode: this.env });\n }\n\n buildIncreaseLiquidity(p: Omit<BuildIncreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildIncreaseLiquidity({ ...p, mode: this.env });\n }\n\n buildDecreaseLiquidity(p: Omit<BuildDecreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildDecreaseLiquidity({ ...p, mode: this.env });\n }\n\n // ── Periphery submitters ──────────────────────────────────────────────────\n\n submitAction(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n submitSwap(wallet: WalletClient, params: SubmitActionParams) {\n return submitSwap(wallet, params, this.env);\n }\n\n submitApproval(wallet: WalletClient, params: SubmitActionParams) {\n return submitApproval(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitMint(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitBurn(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitIncreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitDecreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n // ── Chain-client factories ────────────────────────────────────────────────\n\n getKernelPublicClient(transport?: Transport) {\n return getKernelPublicClient(this.env, transport);\n }\n\n getSourcePublicClient(chain: CHAIN, transport?: Transport) {\n return getSourcePublicClient(chain, this.env, transport);\n }\n}\n","import { AmmCore, type EnvModeWithConfig, type AmmVmClient, type CalldataCall } from \"@skate-org/amm-core-v2\";\nimport { AmmApi } from \"@skate-org/amm-api-v2\";\nimport type { WalletClient } from \"viem\";\nimport { AmmEvm } from \"./client\";\nimport type { PeripheryPoolState, UserPoolBalances } from \"./periphery/reader\";\n\n/**\n * Single entry point for EVM consumers: quotes + actions (AmmApi), pool\n * catalog (AmmCore), and EVM build/submit/read (AmmEvm) behind one env-bound\n * object.\n *\n * `import { SkateAmm } from \"@skate-org/amm-evm-v2\"`\n *\n * @remarks\n * `quote.*`, `actions.*`, and `pools.*` are bound to the composed instances at\n * construction time. Patching `amm.api` or `amm.core` methods after construction\n * does not propagate to those namespaces.\n *\n * @example\n * const amm = new SkateAmm(\"PRODUCTION\");\n * const call = await amm.buildSwap({ poolKey: \"USDC_USDT\", chain: CHAIN.ARBITRUM, ... });\n * const quote = await amm.quote.swap({ poolKey: \"USDC_USDT\", ... });\n */\nexport class SkateAmm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n readonly core: AmmCore;\n readonly api: AmmApi;\n readonly vm: AmmEvm;\n\n readonly quote: {\n swap: AmmApi[\"swapQuote\"];\n mint: AmmApi[\"mintQuote\"];\n burn: AmmApi[\"burnQuote\"];\n increaseLiquidity: AmmApi[\"increaseLiquidityQuote\"];\n decreaseLiquidity: AmmApi[\"decreaseLiquidityQuote\"];\n boostedMint: AmmApi[\"boostedMintQuote\"];\n boostedRange: AmmApi[\"boostedRangeQuote\"];\n streamSwap: AmmApi[\"streamSwapQuote\"];\n subscribeSwap: AmmApi[\"subscribeSwapQuote\"];\n };\n\n readonly actions: {\n get: AmmApi[\"getAction\"];\n byUser: AmmApi[\"getActionsByUser\"];\n byUserTimeRange: AmmApi[\"getActionsByUserTimeRange\"];\n waitForExecuted: AmmApi[\"waitForExecuted\"];\n position: AmmApi[\"getPosition\"];\n };\n\n readonly pools: {\n all: AmmCore[\"getAllPoolInfo\"];\n keys: AmmCore[\"getAllPoolKeys\"];\n byKey: AmmCore[\"getPoolInfoByKey\"];\n supportedChains: AmmCore[\"getSupportedChains\"];\n supportedPairs: AmmCore[\"getSupportedPairs\"];\n supportedTokens: AmmCore[\"getSupportedTokens\"];\n keyByKernelPool: AmmCore[\"kernelPoolToPoolKey\"];\n };\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n this.core = new AmmCore(env);\n this.api = new AmmApi(env);\n this.vm = new AmmEvm(env);\n\n const api = this.api;\n const core = this.core;\n\n this.quote = {\n swap: api.swapQuote.bind(api),\n mint: api.mintQuote.bind(api),\n burn: api.burnQuote.bind(api),\n increaseLiquidity: api.increaseLiquidityQuote.bind(api),\n decreaseLiquidity: api.decreaseLiquidityQuote.bind(api),\n boostedMint: api.boostedMintQuote.bind(api),\n boostedRange: api.boostedRangeQuote.bind(api),\n streamSwap: api.streamSwapQuote.bind(api),\n subscribeSwap: api.subscribeSwapQuote.bind(api),\n };\n\n this.actions = {\n get: api.getAction.bind(api),\n byUser: api.getActionsByUser.bind(api),\n byUserTimeRange: api.getActionsByUserTimeRange.bind(api),\n waitForExecuted: api.waitForExecuted.bind(api),\n position: api.getPosition.bind(api),\n };\n\n this.pools = {\n all: core.getAllPoolInfo.bind(core),\n keys: core.getAllPoolKeys.bind(core),\n byKey: core.getPoolInfoByKey.bind(core),\n supportedChains: core.getSupportedChains.bind(core),\n supportedPairs: core.getSupportedPairs.bind(core),\n supportedTokens: core.getSupportedTokens.bind(core),\n keyByKernelPool: core.kernelPoolToPoolKey.bind(core),\n };\n }\n\n // ── AmmVmClient: builders ────────────────────────────────────────────────────\n\n buildSwap(p: Parameters<AmmEvm[\"buildSwap\"]>[0]) { return this.vm.buildSwap(p); }\n buildMint(p: Parameters<AmmEvm[\"buildMint\"]>[0]) { return this.vm.buildMint(p); }\n buildBurn(p: Parameters<AmmEvm[\"buildBurn\"]>[0]) { return this.vm.buildBurn(p); }\n buildIncreaseLiquidity(p: Parameters<AmmEvm[\"buildIncreaseLiquidity\"]>[0]) { return this.vm.buildIncreaseLiquidity(p); }\n buildDecreaseLiquidity(p: Parameters<AmmEvm[\"buildDecreaseLiquidity\"]>[0]) { return this.vm.buildDecreaseLiquidity(p); }\n\n // ── AmmVmClient: submitters ──────────────────────────────────────────────────\n\n submitSwap(w: WalletClient, p: Parameters<AmmEvm[\"submitSwap\"]>[1]) { return this.vm.submitSwap(w, p); }\n submitMint(w: WalletClient, p: Parameters<AmmEvm[\"submitMint\"]>[1]) { return this.vm.submitMint(w, p); }\n submitBurn(w: WalletClient, p: Parameters<AmmEvm[\"submitBurn\"]>[1]) { return this.vm.submitBurn(w, p); }\n submitIncreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitIncreaseLiquidity\"]>[1]) { return this.vm.submitIncreaseLiquidity(w, p); }\n submitDecreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitDecreaseLiquidity\"]>[1]) { return this.vm.submitDecreaseLiquidity(w, p); }\n\n // ── AmmVmClient: readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Parameters<AmmEvm[\"readPeripheryPool\"]>[0]) { return this.vm.readPeripheryPool(p); }\n readUserPoolBalances(p: Parameters<AmmEvm[\"readUserPoolBalances\"]>[0]) { return this.vm.readUserPoolBalances(p); }\n\n // ── EVM extras ───────────────────────────────────────────────────────────────\n\n /** Read raw kernel pool slot. */\n readPool(p: Parameters<AmmEvm[\"readPool\"]>[0]) { return this.vm.readPool(p); }\n readKernelBalances(p: Parameters<AmmEvm[\"readKernelBalances\"]>[0]) { return this.vm.readKernelBalances(p); }\n readPosition(p: Parameters<AmmEvm[\"readPosition\"]>[0]) { return this.vm.readPosition(p); }\n readTickBitmap(p: Parameters<AmmEvm[\"readTickBitmap\"]>[0]) { return this.vm.readTickBitmap(p); }\n readTick(p: Parameters<AmmEvm[\"readTick\"]>[0]) { return this.vm.readTick(p); }\n computePositionAmounts(p: Parameters<AmmEvm[\"computePositionAmounts\"]>[0]) { return this.vm.computePositionAmounts(p); }\n\n simulateSwap(p: Parameters<AmmEvm[\"simulateSwap\"]>[0]) { return this.vm.simulateSwap(p); }\n simulateMint(p: Parameters<AmmEvm[\"simulateMint\"]>[0]) { return this.vm.simulateMint(p); }\n simulateBurn(p: Parameters<AmmEvm[\"simulateBurn\"]>[0]) { return this.vm.simulateBurn(p); }\n simulateDecreaseLiquidity(p: Parameters<AmmEvm[\"simulateDecreaseLiquidity\"]>[0]) { return this.vm.simulateDecreaseLiquidity(p); }\n\n submitAction(w: WalletClient, p: Parameters<AmmEvm[\"submitAction\"]>[1]) { return this.vm.submitAction(w, p); }\n submitApproval(w: WalletClient, p: Parameters<AmmEvm[\"submitApproval\"]>[1]) { return this.vm.submitApproval(w, p); }\n\n getKernelPublicClient(...args: Parameters<AmmEvm[\"getKernelPublicClient\"]>) { return this.vm.getKernelPublicClient(...args); }\n getSourcePublicClient(...args: Parameters<AmmEvm[\"getSourcePublicClient\"]>) { return this.vm.getSourcePublicClient(...args); }\n}\n","import type { DevModeConfig } from \"@skate-org/amm-core-v2\";\n\n/** Default DEV api endpoint — matches Phase 1's api client default. */\nconst DEFAULT_DEV_API_ENDPOINT =\n \"https://dev.api.skatechain.org/amm-action-v2\";\n\n/**\n * Convenience factory for the `{ mode: \"DEV\"; config: DevModeConfig }` tuple.\n *\n * Reduces ceremony at call sites that want to override a single field (e.g.,\n * `rpcEndpoints`) without reconstructing the full object:\n *\n * ```ts\n * const mode = createDevConfig({\n * rpcEndpoints: { [CHAIN.MEGAETH]: \"https://my-private-megaeth/rpc\" },\n * });\n * submitAction(wallet, params, mode);\n * ```\n *\n * Pass nothing to use all defaults.\n */\nexport function createDevConfig(\n overrides: Partial<DevModeConfig> = {},\n): { mode: \"DEV\"; config: DevModeConfig } {\n return {\n mode: \"DEV\",\n config: {\n apiEndpoint: overrides.apiEndpoint ?? DEFAULT_DEV_API_ENDPOINT,\n ...(overrides.rpcEndpoints\n ? { rpcEndpoints: overrides.rpcEndpoints }\n : {}),\n },\n };\n}\n","/**\n * Decode a single Uniswap-v3 tick-bitmap `uint256` word into the list of\n * real (non-compressed) ticks it marks as initialized.\n *\n * A tick bitmap word covers 256 compressed ticks. For a given `wordPos`\n * (int16) the word spans compressed ticks `wordPos * 256` through\n * `(wordPos + 1) * 256 - 1`, and bit `k` (0..255) corresponds to the\n * compressed tick `wordPos * 256 + k`. The real tick at bit `k` is\n * `(wordPos * 256 + k) * tickSpacing`.\n *\n * Intended composition with the reader:\n *\n * ```ts\n * const word = await readTickBitmap(pool, wordPos, mode);\n * const ticks = decodeTickBitmapWord(word, wordPos, tickSpacing);\n * ```\n *\n * Pure function: no network, no viem, no external deps.\n *\n * @param word The 256-bit bitmap word returned by PoolAbi.tickBitmap(int16).\n * @param wordPos The int16 word position (-128 .. 127 per Uniswap, but\n * we accept any safe-integer int16-shaped value).\n * @param tickSpacing The pool's tickSpacing (positive integer, typically 1,\n * 10, 60, 200, etc.).\n * @returns Real ticks whose bits are set in the word, ascending.\n *\n * @throws {RangeError} if `tickSpacing <= 0` or if `wordPos` is not a safe integer.\n */\nexport function decodeTickBitmapWord(\n word: bigint,\n wordPos: number,\n tickSpacing: number,\n): number[] {\n if (!Number.isSafeInteger(wordPos)) {\n throw new RangeError(\n `decodeTickBitmapWord: wordPos must be a safe integer, got ${wordPos}`,\n );\n }\n if (!Number.isSafeInteger(tickSpacing) || tickSpacing <= 0) {\n throw new RangeError(\n `decodeTickBitmapWord: tickSpacing must be a positive integer, got ${tickSpacing}`,\n );\n }\n const result: number[] = [];\n // wordPos * 256 gives the base compressed-tick of this word. Each set bit k\n // contributes compressed-tick (wordPos * 256 + k), which becomes real tick\n // (wordPos * 256 + k) * tickSpacing.\n const base = wordPos * 256;\n for (let k = 0; k < 256; k++) {\n if (((word >> BigInt(k)) & 1n) === 1n) {\n result.push((base + k) * tickSpacing);\n }\n }\n return result;\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { KernelEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by the Skate kernel's `KernelEventEmitter`, sourced\n * directly from `@skate-org/amm-bindings`.\n */\nexport type KernelEventName =\n | \"Burn\"\n | \"Collect\"\n | \"CollectProtocol\"\n | \"IncreaseObservationCardinalityNext\"\n | \"Initialize\"\n | \"Mint\"\n | \"PeripheryPoolAdded\"\n | \"PeripheryPoolChanged\"\n | \"PoolCreated\"\n | \"PoolDescriptionUpdated\"\n | \"SetFeeProtocol\"\n | \"Swap\";\n\n/** Exhaustive list of known kernel event names — same values as {@link KernelEventName}. */\nexport const KERNEL_EVENT_NAMES: readonly KernelEventName[] = [\n \"Burn\",\n \"Collect\",\n \"CollectProtocol\",\n \"IncreaseObservationCardinalityNext\",\n \"Initialize\",\n \"Mint\",\n \"PeripheryPoolAdded\",\n \"PeripheryPoolChanged\",\n \"PoolCreated\",\n \"PoolDescriptionUpdated\",\n \"SetFeeProtocol\",\n \"Swap\",\n];\n\n/**\n * A decoded kernel event — the event name, its named args, and the original\n * viem `Log` for context (tx hash, block number, etc.).\n */\nexport interface KernelParsedEvent {\n eventName: KernelEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by the Skate kernel's `KernelEventEmitter`.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known kernel event\n * or if ABI decoding fails.\n */\nexport function parseKernelEventLog(log: Log): KernelParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: KernelEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as KernelEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parseKernelEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { PeripheryEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by `PeripheryEventEmitter` on the source chain.\n */\nexport type PeripheryEventName =\n | \"AmountSettled\"\n | \"Burned\"\n | \"LiquidityDecreased\"\n | \"LiquidityIncreased\"\n | \"MintSettled\"\n | \"Minted\"\n | \"PoolCreated\"\n | \"PoolDeployed\"\n | \"Swapped\"\n | \"TransferredTo\";\n\n/** Exhaustive list of known periphery event names. */\nexport const PERIPHERY_EVENT_NAMES: readonly PeripheryEventName[] = [\n \"AmountSettled\",\n \"Burned\",\n \"LiquidityDecreased\",\n \"LiquidityIncreased\",\n \"MintSettled\",\n \"Minted\",\n \"PoolCreated\",\n \"PoolDeployed\",\n \"Swapped\",\n \"TransferredTo\",\n];\n\n/** A decoded periphery event — name, named args, and the original viem `Log`. */\nexport interface PeripheryParsedEvent {\n eventName: PeripheryEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by `PeripheryEventEmitter` on a source chain.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known periphery\n * event or if ABI decoding fails.\n */\nexport function parsePeripheryEventLog(log: Log): PeripheryParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: PeripheryEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as PeripheryEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parsePeripheryEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import type { Address, Log, PublicClient } from \"viem\";\nimport {\n KernelEventEmitterABI,\n PeripheryEventEmitterABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n parseKernelEventLog,\n type KernelParsedEvent,\n} from \"./kernel\";\nimport {\n parsePeripheryEventLog,\n type PeripheryParsedEvent,\n} from \"./periphery\";\n\nexport interface EventSubscriptionOptions<E> {\n /** Called for each decoded event. */\n onEvent: (event: E) => void;\n /** Called when a log fails to decode (subscription stays alive). */\n onError?: (err: unknown) => void;\n}\n\n/**\n * Subscribe to kernel events emitted by the `KernelEventEmitter` contract\n * at `address`. Returns an unsubscribe function.\n *\n * Decode failures are surfaced via `opts.onError` (if provided) rather than\n * throwing — the subscription continues.\n */\nexport function watchKernelEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<KernelParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: KernelEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parseKernelEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n\n/**\n * Subscribe to periphery events emitted by `PeripheryEventEmitter` at\n * `address` on the source chain the `client` is connected to.\n */\nexport function watchPeripheryEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<PeripheryParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: PeripheryEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parsePeripheryEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAOO;AACP,oBAAkC;AAClC,yBAQO;AAgBA,IAAM,mBAAsB,yBAAY;AAAA,EAC7C,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,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C;AACH;","names":["import_amm_core_v2","import_amm_core_v2","import_amm_bindings","import_amm_core_v2","import_amm_bindings","import_amm_core_v2","import_viem","import_amm_bindings","import_amm_core_v2","import_amm_core_v2","import_viem","import_amm_bindings","import_viem","import_amm_bindings","import_amm_bindings"]}
|
package/dist/index.js
CHANGED
|
@@ -26,10 +26,24 @@ var megaethChain = defineChain({
|
|
|
26
26
|
default: { name: "Blockscout", url: BLOCK_EXPLORER.MEGAETH }
|
|
27
27
|
}
|
|
28
28
|
});
|
|
29
|
+
var robinhoodChain = defineChain({
|
|
30
|
+
id: 4663,
|
|
31
|
+
name: "Robinhood Chain",
|
|
32
|
+
network: "robinhood",
|
|
33
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
34
|
+
rpcUrls: {
|
|
35
|
+
default: { http: ["https://rpc.mainnet.chain.robinhood.com"] },
|
|
36
|
+
public: { http: ["https://rpc.mainnet.chain.robinhood.com"] }
|
|
37
|
+
},
|
|
38
|
+
blockExplorers: {
|
|
39
|
+
default: { name: "Blockscout", url: BLOCK_EXPLORER.ROBINHOOD }
|
|
40
|
+
}
|
|
41
|
+
});
|
|
29
42
|
var DEFAULT_RPC = {
|
|
30
43
|
[CHAIN.MEGAETH]: "https://mainnet.megaeth.com/rpc",
|
|
31
44
|
[CHAIN.ARBITRUM]: "https://arb1.arbitrum.io/rpc",
|
|
32
|
-
[CHAIN.ETHEREUM]: "https://ethereum-rpc.publicnode.com"
|
|
45
|
+
[CHAIN.ETHEREUM]: "https://ethereum-rpc.publicnode.com",
|
|
46
|
+
[CHAIN.ROBINHOOD]: "https://rpc.mainnet.chain.robinhood.com"
|
|
33
47
|
};
|
|
34
48
|
function chainDefFor(chain) {
|
|
35
49
|
switch (chain) {
|
|
@@ -39,6 +53,8 @@ function chainDefFor(chain) {
|
|
|
39
53
|
return arbitrum;
|
|
40
54
|
case CHAIN.ETHEREUM:
|
|
41
55
|
return mainnet;
|
|
56
|
+
case CHAIN.ROBINHOOD:
|
|
57
|
+
return robinhoodChain;
|
|
42
58
|
default:
|
|
43
59
|
return void 0;
|
|
44
60
|
}
|
|
@@ -1085,6 +1101,7 @@ export {
|
|
|
1085
1101
|
readTick,
|
|
1086
1102
|
readTickBitmap,
|
|
1087
1103
|
readUserPoolBalances,
|
|
1104
|
+
robinhoodChain,
|
|
1088
1105
|
simulateBurn,
|
|
1089
1106
|
simulateDecreaseLiquidity,
|
|
1090
1107
|
simulateMint,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chain-clients.ts","../src/kernel/reader.ts","../src/errors.ts","../src/kernel/_client.ts","../src/kernel/lens.ts","../src/periphery/reader.ts","../src/periphery/submit.ts","../src/periphery/calldata.ts","../src/client.ts","../src/skate-amm.ts","../src/devConfig.ts","../src/kernel/tickBitmap.ts","../src/events/kernel.ts","../src/events/periphery.ts","../src/events/watch.ts"],"sourcesContent":["import {\n createPublicClient,\n defineChain,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n} from \"viem\";\nimport { arbitrum, mainnet } from \"viem/chains\";\nimport {\n BLOCK_EXPLORER,\n CHAIN,\n KernelChain,\n VM,\n vmTypeFromChain,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * MegaETH chain definition — `@public`.\n *\n * Exported for callers who need to build their own viem `WalletClient` or\n * `PublicClient` against the same chain the SDK uses internally (e.g. wallet\n * integrations that construct a `WalletClient` ahead of calling\n * `submitAction`). Prefer {@link getKernelPublicClient} when you just need a\n * read client.\n *\n * viem ships a `megaeth` chain at id 4326, but with a different default RPC\n * than the one Skate uses for kernel reads. Define locally so we control the\n * RPC URL + block-explorer metadata and don't inherit unrelated op-stack\n * contract addresses.\n */\nexport const megaethChain: Chain = defineChain({\n id: 4326,\n name: \"MegaETH\",\n network: \"megaeth\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n public: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.MEGAETH },\n },\n});\n\n/**\n * Default public RPC URLs by chain id.\n *\n * Callers can override per-chain via `DevModeConfig.rpcEndpoints` or by\n * passing an explicit `transport` to the factory functions below.\n */\nconst DEFAULT_RPC: Partial<Record<CHAIN, string>> = {\n [CHAIN.MEGAETH]: \"https://mainnet.megaeth.com/rpc\",\n [CHAIN.ARBITRUM]: \"https://arb1.arbitrum.io/rpc\",\n [CHAIN.ETHEREUM]: \"https://ethereum-rpc.publicnode.com\",\n};\n\n/**\n * Map a supported EVM `CHAIN` to a viem `Chain` definition.\n *\n * Only chains we actively support in Phase 2 are listed; unknown chains\n * return `undefined` and the caller throws.\n */\nfunction chainDefFor(chain: CHAIN): Chain | undefined {\n switch (chain) {\n case CHAIN.MEGAETH:\n return megaethChain;\n case CHAIN.ARBITRUM:\n return arbitrum;\n case CHAIN.ETHEREUM:\n return mainnet;\n default:\n return undefined;\n }\n}\n\n/**\n * Resolve the RPC URL for a given chain under the precedence:\n * transport override (caller arg) > mode.config.rpcEndpoints[chain] > DEFAULT_RPC[chain]\n * Returns `undefined` if none is set — callers must have already decided whether\n * to use a caller-supplied transport.\n */\nfunction resolveRpcUrl(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): string | undefined {\n const { config } = normalizeMode(mode);\n return config?.rpcEndpoints?.[chain] ?? DEFAULT_RPC[chain];\n}\n\n/**\n * Return a fresh `PublicClient` bound to the kernel chain for `mode`.\n *\n * Today every env (`DEV` / `STAGING` / `PRODUCTION`) resolves to MegaETH —\n * see `KERNEL_CHAIN_BY_MODE` in `@skate-org/amm-core-v2`. Pointing a future\n * env at a different kernel chain is a one-line edit there; this factory\n * reads from that mapping so client + address tables stay in sync.\n *\n * Pure — no singletons, no caching. Pass a custom `transport` to override\n * the default RPC (useful for tests and custom RPC providers).\n */\nexport function getKernelPublicClient(\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n const { mode: baseMode } = normalizeMode(mode);\n const kernelChainId = KernelChain(baseMode);\n const chainDef = chainDefFor(kernelChainId);\n if (!chainDef) {\n throw new Error(\n `getKernelPublicClient: no chain definition registered for kernel chain ${kernelChainId} ` +\n `(mode=${baseMode}); update chainDefFor() in chain-clients.ts to support it.`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(resolveRpcUrl(kernelChainId, mode)),\n });\n}\n\n/**\n * Return a fresh `PublicClient` for a source EVM chain (e.g. Arbitrum).\n *\n * Throws a descriptive `Error` when:\n * - `chain` is not an EVM chain (per `vmTypeFromChain`); or\n * - no viem chain definition is registered for `chain`; or\n * - no default RPC URL is configured for `chain` and no `transport` override\n * was provided.\n *\n * Pure — no singletons, no caching.\n */\nexport function getSourcePublicClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n if (vmTypeFromChain(chain) !== VM.EVM) {\n throw new Error(\n `getSourcePublicClient: chain ${chain} is not an EVM chain`,\n );\n }\n const chainDef = chainDefFor(chain);\n if (!chainDef) {\n throw new Error(\n `getSourcePublicClient: no chain definition registered for chain ${chain}`,\n );\n }\n const rpc = resolveRpcUrl(chain, mode);\n if (!rpc && !transport) {\n throw new Error(\n `getSourcePublicClient: no default or override RPC configured for chain ${chain}; pass a transport override or set DevModeConfig.rpcEndpoints[${chain}]`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(rpc),\n });\n}\n","import type { PublicClient } from \"viem\";\nimport {\n KernelManagerABI,\n KernelPoolABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n getAmount0Delta,\n getAmount1Delta,\n getSqrtRatioAtTick,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/** Decoded kernel-pool `slot0` state (named fields, per the ABI tuple). */\nexport interface KernelSlot0 {\n sqrtPriceX96: bigint;\n tick: number;\n observationIndex: number;\n observationCardinality: number;\n observationCardinalityNext: number;\n feeProtocol: number;\n unlocked: boolean;\n}\n\n/** Decoded pool state returned by `readPool`. */\nexport interface KernelPoolState {\n slot0: KernelSlot0;\n liquidity: bigint;\n}\n\n/** Decoded NFT position returned by `readPosition`. */\nexport interface KernelNftPosition {\n pool: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n liquidity: bigint;\n feeGrowthInside0LastX128: bigint;\n feeGrowthInside1LastX128: bigint;\n tokensOwed0: bigint;\n tokensOwed1: bigint;\n}\n\n/** Decoded kernel-pool `ticks(tick)` struct. */\nexport interface KernelTick {\n liquidityGross: bigint;\n liquidityNet: bigint;\n feeGrowthOutside0X128: bigint;\n feeGrowthOutside1X128: bigint;\n tickCumulativeOutside: bigint;\n secondsPerLiquidityOutsideX128: bigint;\n secondsOutside: number;\n initialized: boolean;\n}\n\n/**\n * Read `slot0` and `liquidity` from a kernel pool. Returns both in a single\n * object; the reads are fired in parallel.\n *\n * The `client` optional parameter is the standard test-injection point.\n */\nexport async function readPool(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelPoolState> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [slot0, liquidity] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"slot0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"liquidity\",\n }),\n ]);\n // Viem returns named outputs as a positional tuple (array) when every\n // output has a name — normalize to a named-field object here so callers\n // don't depend on viem's tuple/object split.\n const s0 = slot0 as readonly [\n bigint,\n number,\n number,\n number,\n number,\n number,\n boolean,\n ];\n return {\n slot0: {\n sqrtPriceX96: s0[0],\n tick: s0[1],\n observationIndex: s0[2],\n observationCardinality: s0[3],\n observationCardinalityNext: s0[4],\n feeProtocol: s0[5],\n unlocked: s0[6],\n },\n liquidity: liquidity as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPool\");\n }\n}\n\n/** Decoded kernel-pool token balances returned by `readKernelBalances`. */\nexport interface KernelBalances {\n balance0: bigint;\n balance1: bigint;\n}\n\n/**\n * Read `balance0` and `balance1` from a kernel pool (raw token reserves on\n * the kernel side, before periphery scaling). Reads are fired in parallel.\n */\nexport async function readKernelBalances(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelBalances> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [balance0, balance1] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance1\",\n }),\n ]);\n return { balance0: balance0 as bigint, balance1: balance1 as bigint };\n } catch (err) {\n throw wrapReadError(err, \"readKernelBalances\");\n }\n}\n\n/**\n * Read an NFT position by token id from the kernel manager.\n *\n * Calls `KernelManager.nftPositions(tokenId)` — per the ABI this returns a\n * `DataTypes.NFTPosition` tuple including `pool`, `tickLower`, `tickUpper`,\n * `liquidity`, fee growth, and tokens owed.\n */\nexport async function readPosition(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelNftPosition> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const manager = KernelManagerAddress(baseMode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: manager,\n abi: KernelManagerABI,\n functionName: \"nftPositions\",\n args: [p.tokenId],\n })) as unknown;\n // Accept either a positional tuple or an already-named object from\n // viem — normalize to a named-field object, mirroring readPool's\n // defensive remap.\n const asTuple = Array.isArray(raw)\n ? (raw as unknown as readonly [\n `0x${string}`,\n number,\n number,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n ])\n : null;\n if (asTuple) {\n return {\n pool: asTuple[0],\n tickLower: asTuple[1],\n tickUpper: asTuple[2],\n liquidity: asTuple[3],\n feeGrowthInside0LastX128: asTuple[4],\n feeGrowthInside1LastX128: asTuple[5],\n tokensOwed0: asTuple[6],\n tokensOwed1: asTuple[7],\n };\n }\n return raw as KernelNftPosition;\n } catch (err) {\n throw wrapReadError(err, \"readPosition\");\n }\n}\n\n/**\n * Read a kernel-pool tick-bitmap word (`tickBitmap(int16 wordPos)`).\n *\n * Returns the raw `uint256` word as a bigint.\n */\nexport async function readTickBitmap(p: {\n kernelPool: `0x${string}`;\n wordPos: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<bigint> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const word = await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"tickBitmap\",\n args: [p.wordPos],\n });\n return word as bigint;\n } catch (err) {\n throw wrapReadError(err, \"readTickBitmap\");\n }\n}\n\n/** Read the `ticks(tick)` struct from a kernel pool. */\nexport async function readTick(p: {\n kernelPool: `0x${string}`;\n tick: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelTick> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"ticks\",\n args: [p.tick],\n })) as readonly [\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n number,\n boolean,\n ];\n return {\n liquidityGross: raw[0],\n liquidityNet: raw[1],\n feeGrowthOutside0X128: raw[2],\n feeGrowthOutside1X128: raw[3],\n tickCumulativeOutside: raw[4],\n secondsPerLiquidityOutsideX128: raw[5],\n secondsOutside: raw[6],\n initialized: raw[7],\n };\n } catch (err) {\n throw wrapReadError(err, \"readTick\");\n }\n}\n\n/**\n * Compute `{amount0, amount1}` for an NFT position using the Group 3 math.\n *\n * Reads the position (to learn `pool`, `tickLower`, `tickUpper`,\n * `liquidity`) and the pool's `slot0`, then splits based on whether the\n * current tick is below, inside, or above the position range — mirroring\n * `PositionValue.principal` from Uniswap v3 periphery.\n */\nexport async function computePositionAmounts(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<{ amount0: bigint; amount1: bigint }> {\n const c = resolveKernelClient(p.mode, p.client);\n const position = await readPosition({ tokenId: p.tokenId, mode: p.mode, client: c });\n const { slot0 } = await readPool({ kernelPool: position.pool, mode: p.mode, client: c });\n\n const sqrtLower = getSqrtRatioAtTick(position.tickLower);\n const sqrtUpper = getSqrtRatioAtTick(position.tickUpper);\n\n if (slot0.tick < position.tickLower) {\n return {\n amount0: getAmount0Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n amount1: 0n,\n };\n }\n if (slot0.tick >= position.tickUpper) {\n return {\n amount0: 0n,\n amount1: getAmount1Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n };\n }\n return {\n amount0: getAmount0Delta(\n slot0.sqrtPriceX96,\n sqrtUpper,\n position.liquidity,\n false,\n ),\n amount1: getAmount1Delta(\n sqrtLower,\n slot0.sqrtPriceX96,\n position.liquidity,\n false,\n ),\n };\n}\n","/**\n * Shared error types for the `@skate-org/amm-evm-v2` package.\n *\n * `EvmReadError` / `EvmWriteError` extend `SdkError` (from core) so callers\n * can `instanceof SdkError` to catch any SDK-origin error without needing\n * to know the specific subclass.\n */\n\nimport { SdkError } from \"@skate-org/amm-core-v2\";\n\n/** SDK-level error thrown when an EVM read reverts or decodes badly. */\nexport class EvmReadError extends SdkError {\n override readonly name: string = \"EvmReadError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * SDK-level error thrown when an EVM write (broadcast) fails.\n *\n * Symmetric with {@link EvmReadError}, but covers the write path: viem's\n * `TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`, as well as submitter\n * pre-flight guards (e.g. wrong-chain, missing account).\n */\nexport class EvmWriteError extends SdkError {\n override readonly name: string = \"EvmWriteError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * Wrap any error from an EVM read into `EvmReadError`. Viem always wraps\n * revert-path errors in `ContractFunctionExecutionError` (see\n * `viem/utils/errors/getContractError`), so we check both the outer name and\n * the `.cause` chain for `ContractFunctionRevertedError` /\n * `ContractFunctionZeroDataError`.\n *\n * Shared by `kernel/reader.ts` and `periphery/reader.ts` — depends only on\n * `EvmReadError` and generic Error inspection (no reader-module imports), so\n * it is safe from circular-import concerns.\n */\nexport function wrapReadError(\n err: unknown,\n functionName: string,\n): EvmReadError {\n const outerName = (err as { name?: string } | null)?.name;\n const causeName = (err as { cause?: { name?: string } } | null)?.cause?.name;\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n const isViemContractError =\n outerName === \"ContractFunctionExecutionError\" ||\n outerName === \"ContractFunctionRevertedError\" ||\n outerName === \"ContractFunctionZeroDataError\" ||\n causeName === \"ContractFunctionRevertedError\" ||\n causeName === \"ContractFunctionZeroDataError\";\n if (isViemContractError) {\n return new EvmReadError(functionName, `reverted: ${message}`, {\n cause: err as Error,\n });\n }\n return new EvmReadError(functionName, message, { cause: err as Error });\n}\n\n/**\n * Wrap any error from an EVM write-path call (typically\n * `WalletClient.sendTransaction`) into `EvmWriteError`.\n *\n * Any thrown error reaching a submitter is treated as a write failure. If\n * we later want to differentiate known viem write errors\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`) from unknown errors —\n * e.g. to prefix the message or re-throw unknowns raw — that dispatch goes\n * here. Keeping the single-return shape until a concrete caller need\n * surfaces.\n */\nexport function wrapWriteError(\n err: unknown,\n functionName: string,\n): EvmWriteError {\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n return new EvmWriteError(functionName, message, { cause: err as Error });\n}\n","import type { PublicClient } from \"viem\";\nimport type { EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { getKernelPublicClient } from \"../chain-clients\";\n\n/**\n * Return the caller-provided client if present, otherwise build a fresh\n * MegaETH kernel client for the given mode. Shared by readers + lens\n * helpers; intentionally unexported from the package barrel.\n */\nexport function resolveKernelClient(\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getKernelPublicClient(mode);\n}\n","import type { PublicClient } from \"viem\";\nimport { KernelManagerABI } from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/**\n * Kernel lens (simulate) helpers — wrap KernelManager's `lens*` functions as\n * static-call simulations. Lens functions are marked nonpayable in the ABI,\n * but viem's `simulateContract` evaluates them with `eth_call`, so they\n * reuse the same client + RPC plumbing as the readers and never produce a\n * transaction.\n *\n * Errors funnel through `wrapReadError`: lens calls share the read-path\n * error model (revert reasons + RPC failures), and tagging them as \"writes\"\n * would be misleading since no state changes.\n */\n\nexport interface SimulateSwapParams {\n /** Kernel-pool address (EVM) */\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 (use `toBytes32Address` for cross-VM) */\n recipient: `0x${string}`;\n zeroForOne: boolean;\n /** Positive = exactInput, negative = exactOutput, per Uniswap v3 convention */\n amountSpecified: bigint;\n sqrtPriceLimitX96: bigint;\n}\n\nexport interface SimulateSwapResult {\n amount0: bigint;\n amount1: bigint;\n sqrtPriceX96After: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateSwap(p: {\n params: SimulateSwapParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateSwapResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensSwap\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.zeroForOne,\n p.params.amountSpecified,\n p.params.sqrtPriceLimitX96,\n ],\n });\n const [amount0, amount1, sqrtPriceX96After, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, sqrtPriceX96After, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateSwap\");\n }\n}\n\nexport interface SimulateMintParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n /** Caller-supplied callback data (passed to `IKernelMintCallback`) */\n data: `0x${string}`;\n}\n\nexport interface SimulateMintResult {\n amount0Used: bigint;\n amount1Used: bigint;\n liquidityAmount: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateMint(p: {\n params: SimulateMintParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateMintResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensMint\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount0,\n p.params.amount1,\n p.params.data,\n ],\n });\n const [amount0Used, amount1Used, liquidityAmount, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0Used, amount1Used, liquidityAmount, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateMint\");\n }\n}\n\nexport interface SimulateBurnParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n /** Liquidity amount to burn (uint128). */\n amount: bigint;\n}\n\nexport interface SimulateBurnResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateBurn(p: {\n params: SimulateBurnParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateBurnResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensBurn\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount,\n ],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateBurn\");\n }\n}\n\nexport interface SimulateDecreaseLiquidityParams {\n /** NFT position id (v2 positions). */\n tokenId: bigint;\n /** Liquidity amount to remove (uint128). */\n liquidity: bigint;\n}\n\nexport interface SimulateDecreaseLiquidityResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateDecreaseLiquidity(p: {\n params: SimulateDecreaseLiquidityParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateDecreaseLiquidityResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensDecreaseLiquidity\",\n args: [p.params.tokenId, p.params.liquidity],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateDecreaseLiquidity\");\n }\n}\n","import type { PublicClient } from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n CHAIN,\n getPeripheryDetailsByKernelPoolAndChainId,\n normalizeMode,\n type EnvModeWithConfig,\n type EvmChain,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\nimport { getSourcePublicClient } from \"../chain-clients\";\nimport { EvmReadError, wrapReadError } from \"../errors\";\n\n/**\n * Decoded periphery-pool state assembled by {@link readPeripheryPool}.\n *\n * The periphery pool does **not** expose a `slot0`-style view — pricing\n * state lives on the kernel pool on MegaETH (see `readPool`). What the\n * periphery pool does expose is: the configured pair\n * (`token0`, `token1`, `fee`, `kernelPool` reference), the escrowed\n * in-pool settlement balances (`balancesAvailable`), and the two\n * `dustAmount{0,1}` accumulators. Together these are enough for a\n * source-chain caller to reason about pending settlement and dust.\n */\nexport interface PeripheryPoolState {\n /** Periphery pool contract address on the source chain. */\n address: `0x${string}`;\n /** Source-chain ERC-20 address for token0. */\n token0: `0x${string}`;\n /** Source-chain ERC-20 address for token1. */\n token1: `0x${string}`;\n /** Fee tier (uint24) the periphery pool was deployed with. */\n fee: number;\n /** Address of the paired kernel pool on MegaETH. */\n kernelPool: `0x${string}`;\n /** Aggregate in-pool balances available for settlement. */\n balancesAvailable: { amount0Available: bigint; amount1Available: bigint };\n /** token0 dust accumulator. */\n dustAmount0: bigint;\n /** token1 dust accumulator. */\n dustAmount1: bigint;\n}\n\n/**\n * Decoded user per-pool in-flight token balances.\n *\n * Returned by `PeripheryPool.usersData(user)` as `(uint256 amount0, uint256 amount1)`.\n */\nexport interface UserPoolBalances {\n amount0: bigint;\n amount1: bigint;\n}\n\n/**\n * Return the caller-provided client, or build a fresh source-chain\n * client for `chain` under the given `mode`. Mirrors the kernel reader\n * injection pattern.\n */\nfunction resolveClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getSourcePublicClient(chain, mode);\n}\n\n/**\n * Read the assembled periphery-pool state on a source chain.\n *\n * Resolves the periphery pool address via\n * `getPeripheryDetailsByKernelPoolAndChainId` (from\n * `@skate-org/amm-core-v2`) — **no addresses are hardcoded here**. If the\n * `(kernelPool, chain, mode)` triple has no entry in the aggregated pool\n * catalog, throws with the triple in the message for debuggability.\n *\n * All sub-reads are fired in parallel and normalized to named fields.\n */\nexport async function readPeripheryPool(p: {\n chain: CHAIN;\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<PeripheryPoolState> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const details = getPeripheryDetailsByKernelPoolAndChainId(\n p.kernelPool,\n p.chain as EvmChain,\n baseMode,\n );\n if (!details) {\n throw new EvmReadError(\n \"readPeripheryPool\",\n `no periphery entry for kernelPool=${p.kernelPool} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const address = details.address;\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const [\n balancesAvailableRaw,\n dust0,\n dust1,\n token0,\n token1,\n fee,\n kPool,\n ] = await Promise.all([\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"balancesAvailable\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"fee\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"kernelPool\",\n }),\n ]);\n // Viem decodes multi-output tuples with all-named outputs as a\n // positional tuple — normalize to a named-field object.\n const bAvail = balancesAvailableRaw as readonly [bigint, bigint];\n return {\n address,\n token0: token0 as `0x${string}`,\n token1: token1 as `0x${string}`,\n fee: fee as number,\n kernelPool: kPool as `0x${string}`,\n balancesAvailable: {\n amount0Available: bAvail[0],\n amount1Available: bAvail[1],\n },\n dustAmount0: dust0 as bigint,\n dustAmount1: dust1 as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPeripheryPool\");\n }\n}\n\n/**\n * Read a user's per-pool in-flight balances on a source chain.\n *\n * Resolves the periphery pool address via AmmCore.getPoolInfoByKey +\n * peripheryInfo[chain].address (no hardcoded addresses) and calls\n * `PeripheryPool.usersData(user)` which returns\n * `(uint256 amount0, uint256 amount1)`.\n */\nexport async function readUserPoolBalances(p: {\n user: `0x${string}`;\n poolKey: string;\n chain: CHAIN;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<UserPoolBalances> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const core = new AmmCore(p.mode);\n const info = core.getPoolInfoByKey(p.poolKey);\n const periphery = info?.peripheryInfo[p.chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new EvmReadError(\n \"readUserPoolBalances\",\n `no periphery entry for poolKey=${p.poolKey} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: periphery.address,\n abi: PeripheryPoolABI,\n functionName: \"usersData\",\n args: [p.user],\n })) as unknown;\n // `usersData` returns `(uint256 amount0, uint256 amount1)`.\n // Viem decodes tuples with all-named outputs as a positional tuple;\n // handle both the positional and (older) object shapes defensively.\n if (Array.isArray(raw)) {\n const tuple = raw as unknown as readonly [bigint, bigint];\n return { amount0: tuple[0], amount1: tuple[1] };\n }\n const asObject = raw as { amount0: bigint; amount1: bigint };\n return { amount0: asObject.amount0, amount1: asObject.amount1 };\n } catch (err) {\n throw wrapReadError(err, \"readUserPoolBalances\");\n }\n}\n","import type { Address, Hex, WalletClient } from \"viem\";\nimport type { CHAIN, EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { EvmWriteError, wrapWriteError } from \"../errors\";\n\n/**\n * Pre-built source-chain transaction payload accepted by\n * {@link submitAction}.\n *\n * The SDK does **not** fabricate calldata in Group 6 — callers build the\n * payload (e.g. from a quote's `serializedCall`) and this submitter only\n * broadcasts it. This keeps the SDK decoupled from any off-chain\n * routing/quote surface.\n */\nexport type SubmitActionParams = {\n /** Source-chain id the wallet must be connected to. */\n chain: CHAIN;\n /** Destination address of the broadcast tx. */\n to: Address;\n /** Pre-encoded calldata. */\n data: Hex;\n /** Native-value payable amount; defaults to `0n`. */\n value?: bigint;\n};\n\n/**\n * Broadcast a pre-built periphery action tx from the caller's\n * `WalletClient`.\n *\n * Guarantees:\n * - Throws {@link EvmWriteError} immediately if\n * `wallet.chain?.id !== params.chain` — no RPC call is made.\n * - Throws {@link EvmWriteError} if `wallet.account` is not set.\n * - Forwards the payload to `wallet.sendTransaction` and returns the\n * resulting tx hash.\n * - Wraps any thrown viem write-path error\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, …) into an {@link EvmWriteError} via\n * {@link wrapWriteError}.\n *\n * The `mode` parameter is currently unused at runtime; it is accepted for\n * API symmetry with the readers and as a forward-compat hook for a future\n * mode-specific submission policy (e.g. DEV-only simulation, staging\n * retries). The `_` prefix marks it unused for the TypeScript checker.\n *\n * Non-goals (per plan guardrails):\n * - Does NOT sign — the caller brings a `WalletClient` wired to their\n * signer.\n * - Does NOT switch chains — callers are responsible for\n * `wallet.switchChain(...)`.\n * - Does NOT retry or manage nonces — delegated to the caller's wallet.\n */\nexport async function submitAction(\n wallet: WalletClient,\n params: SubmitActionParams,\n _mode: EnvModeWithConfig,\n): Promise<Hex> {\n if (wallet.chain?.id !== params.chain) {\n throw new EvmWriteError(\n \"submitAction\",\n `wallet chain ${wallet.chain?.id ?? \"undefined\"} != params.chain ${params.chain}`,\n );\n }\n\n try {\n const account = wallet.account;\n if (!account) {\n throw new EvmWriteError(\n \"submitAction\",\n \"wallet has no account; callers must provide a wallet with wallet.account set\",\n );\n }\n return await wallet.sendTransaction({\n to: params.to,\n data: params.data,\n value: params.value ?? 0n,\n chain: wallet.chain,\n account,\n });\n } catch (err) {\n // Preserve our own pre-flight guards verbatim — they are already\n // EvmWriteError instances and don't need re-wrapping.\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitAction\");\n }\n}\n\n/**\n * Broadcast a periphery *swap* action — thin wrapper around\n * {@link submitAction} that re-labels any unknown error as `submitSwap` to\n * aid log-line triage. Behaviourally identical to `submitAction`; shares\n * its pre-flight guards.\n */\nexport async function submitSwap(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitSwap\");\n }\n}\n\n/**\n * Broadcast a periphery *approval* action (ERC-20 approve to the source\n * chain's periphery contract) — thin wrapper around {@link submitAction}.\n * See {@link submitSwap} for labeling rationale.\n */\nexport async function submitApproval(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitApproval\");\n }\n}\n","/**\n * Pure ABI encoders for periphery-pool `swap` / `mint` / `burn` /\n * `increaseLiquidity` / `decreaseLiquidity` calldata.\n *\n * No client, no signing, no submission — quote routes use these to mirror\n * the on-chain calldata shape without paying for an RPC round-trip. For the\n * full submit-and-confirm flow, use the submitters in `./submit.ts`.\n *\n * Each `build*` function resolves the EVM periphery contract address for the\n * given `poolKey` + `chain` via `AmmCore`, encodes the calldata, and returns\n * a `CalldataCall` ready for submission.\n *\n * Encoding does NOT change — only call signatures and return types are new.\n */\n\nimport {\n encodeAbiParameters,\n encodeFunctionData,\n maxUint256,\n parseAbiParameters,\n} from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n type CHAIN,\n type EnvModeWithConfig,\n type CalldataCall,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * Resolve the EVM periphery pool contract address for a `(poolKey, chain, mode)` triple.\n * Throws with a descriptive message if the poolKey is unknown or has no periphery on `chain`.\n *\n * Resolves by poolKey via the aggregated catalog — deliberately not reusing\n * `getPeripheryDetailsByKernelPoolAndChainId`, which is keyed by kernelPool.\n */\nfunction resolvePeripheryTarget(\n poolKey: string,\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): `0x${string}` {\n const core = new AmmCore(mode);\n const info = core.getPoolInfoByKey(poolKey);\n if (!info) throw new Error(`unknown poolKey: ${poolKey}`);\n const periphery = info.peripheryInfo[chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new Error(`pool ${poolKey} has no periphery on chain ${chain}`);\n }\n return periphery.address;\n}\n\n// ── Param types ───────────────────────────────────────────────────────────────\n\n/** Common fields injected into every Build*Params type. */\ninterface BuildBaseParams {\n /** Pool key, e.g. \"USDC_USDT\" — resolves the source periphery pool target. */\n poolKey: string;\n /** Source chain the action is submitted on. */\n chain: CHAIN;\n /** Env mode. Omitted when called via AmmEvm (injected). */\n mode: EnvModeWithConfig;\n}\n\nexport interface BuildSwapParams extends BuildBaseParams {\n /** Swap recipient address in bytes32 format. */\n recipient: `0x${string}`;\n destChainId: number;\n destVmType: number;\n zeroForOne: boolean;\n /** Raw amount, subject to token native decimals. */\n amount: bigint;\n sqrtPriceLimitX96: bigint;\n /** Raw amount, subject to token native decimals. Default 0n. */\n minAmountOut?: bigint;\n /** Enforced at kernel timestamp. Default `maxUint256`. */\n deadline?: bigint;\n}\n\nexport interface BuildMintParams extends BuildBaseParams {\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildBurnParams extends BuildBaseParams {\n tokenId: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildIncreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildDecreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n /** Kernel-side liquidity amount — `sqrt(normalizedAmount0 * normalizedAmount1)` in 18-decimal space. */\n liquidityAmount: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\n// ── Internal encoders (pure, NOT exported) ────────────────────────────────────\n\nfunction encodeSwap(params: Omit<BuildSwapParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n zeroForOne,\n amount,\n sqrtPriceLimitX96,\n destVmType,\n destChainId,\n minAmountOut,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256,uint256\"),\n [\n minAmountOut ?? 0n,\n BigInt(destChainId),\n BigInt(destVmType),\n deadline ?? maxUint256,\n ],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"swap\",\n args: [recipient, zeroForOne, amount, sqrtPriceLimitX96, extraData],\n });\n}\n\nfunction encodeMint(params: Omit<BuildMintParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n tickLower,\n tickUpper,\n amount0,\n amount1,\n amount0Min,\n amount1Min,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"mint\",\n args: [recipient, tickLower, tickUpper, amount0, amount1, extraData],\n });\n}\n\nfunction encodeBurn(params: Omit<BuildBurnParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"burn\",\n args: [tokenId, extraData] as const,\n });\n}\n\nfunction encodeIncreaseLiquidity(params: Omit<BuildIncreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0, amount1, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"increaseLiquidity\",\n args: [tokenId, amount0, amount1, extraData],\n });\n}\n\nfunction encodeDecreaseLiquidity(params: Omit<BuildDecreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, liquidityAmount, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"decreaseLiquidity\",\n args: [tokenId, liquidityAmount, extraData],\n });\n}\n\n// ── Public async builders ─────────────────────────────────────────────────────\n\n/** Build calldata for a `swap` on the resolved EVM periphery pool. */\nexport async function buildSwap(params: BuildSwapParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeSwap(encodeParams),\n };\n}\n\n/** Build calldata for a `mint` on the resolved EVM periphery pool. */\nexport async function buildMint(params: BuildMintParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeMint(encodeParams),\n };\n}\n\n/** Build calldata for a `burn` on the resolved EVM periphery pool. */\nexport async function buildBurn(params: BuildBurnParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeBurn(encodeParams),\n };\n}\n\n/** Build calldata for `increaseLiquidity` on the resolved EVM periphery pool. */\nexport async function buildIncreaseLiquidity(params: BuildIncreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeIncreaseLiquidity(encodeParams),\n };\n}\n\n/**\n * Build calldata for `decreaseLiquidity` on the resolved EVM periphery pool.\n *\n * WARN: `liquidityAmount` is kernel-side, computed as\n * `sqrt(normalizedAmount0 * normalizedAmount1)` (18-decimal space).\n */\nexport async function buildDecreaseLiquidity(params: BuildDecreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeDecreaseLiquidity(encodeParams),\n };\n}\n","import type { PublicClient, Transport, WalletClient } from \"viem\";\nimport type { EnvModeWithConfig, CHAIN, CalldataCall, AmmVmClient } from \"@skate-org/amm-core-v2\";\nimport {\n readPool,\n readKernelBalances,\n readPosition,\n readTickBitmap,\n readTick,\n computePositionAmounts,\n} from \"./kernel/reader\";\nimport {\n simulateSwap,\n simulateMint,\n simulateBurn,\n simulateDecreaseLiquidity,\n type SimulateSwapParams,\n type SimulateMintParams,\n type SimulateBurnParams,\n type SimulateDecreaseLiquidityParams,\n} from \"./kernel/lens\";\nimport {\n readPeripheryPool,\n readUserPoolBalances,\n type PeripheryPoolState,\n type UserPoolBalances,\n} from \"./periphery/reader\";\nimport {\n submitAction,\n submitSwap,\n submitApproval,\n type SubmitActionParams,\n} from \"./periphery/submit\";\nimport {\n buildSwap,\n buildMint,\n buildBurn,\n buildIncreaseLiquidity,\n buildDecreaseLiquidity,\n type BuildSwapParams,\n type BuildMintParams,\n type BuildBurnParams,\n type BuildIncreaseLiquidityParams,\n type BuildDecreaseLiquidityParams,\n} from \"./periphery/calldata\";\nimport {\n getKernelPublicClient,\n getSourcePublicClient,\n} from \"./chain-clients\";\n\n/**\n * Env-bound client that wraps all EVM mode-taking functions with a fixed\n * `EnvModeWithConfig`. Construct once with the desired env and call methods\n * without the `mode` parameter.\n *\n * The raw `EnvModeWithConfig` is stored as-is (not normalized) so that\n * `config.rpcEndpoints` overrides pass through intact to the underlying\n * readers and chain-client factories.\n *\n * Implements `AmmVmClient<CalldataCall, WalletClient, 0x${string}, PeripheryPoolState, UserPoolBalances>`.\n * EVM submits any action type through the same `submitAction` path — the four\n * extra `AmmVmClient` submit methods are thin aliases.\n *\n * @example\n * const evm = new AmmEvm('PRODUCTION');\n * const pool = await evm.readPool({ kernelPool: '0x...' });\n * const call = await evm.buildSwap({ poolKey: 'USDC_USDT', chain: CHAIN.ARBITRUM, ... });\n */\nexport class AmmEvm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n }\n\n // ── Kernel readers ────────────────────────────────────────────────────────\n\n readPool(p: Omit<Parameters<typeof readPool>[0], \"mode\">) {\n return readPool({ ...p, mode: this.env, client: p.client });\n }\n\n readKernelBalances(p: Omit<Parameters<typeof readKernelBalances>[0], \"mode\">) {\n return readKernelBalances({ ...p, mode: this.env, client: p.client });\n }\n\n readPosition(p: Omit<Parameters<typeof readPosition>[0], \"mode\">) {\n return readPosition({ ...p, mode: this.env, client: p.client });\n }\n\n readTickBitmap(p: Omit<Parameters<typeof readTickBitmap>[0], \"mode\">) {\n return readTickBitmap({ ...p, mode: this.env, client: p.client });\n }\n\n readTick(p: Omit<Parameters<typeof readTick>[0], \"mode\">) {\n return readTick({ ...p, mode: this.env, client: p.client });\n }\n\n computePositionAmounts(p: Omit<Parameters<typeof computePositionAmounts>[0], \"mode\">) {\n return computePositionAmounts({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Kernel lens (simulate) ────────────────────────────────────────────────\n\n simulateSwap(p: { params: SimulateSwapParams; client?: PublicClient }) {\n return simulateSwap({ ...p, mode: this.env, client: p.client });\n }\n\n simulateMint(p: { params: SimulateMintParams; client?: PublicClient }) {\n return simulateMint({ ...p, mode: this.env, client: p.client });\n }\n\n simulateBurn(p: { params: SimulateBurnParams; client?: PublicClient }) {\n return simulateBurn({ ...p, mode: this.env, client: p.client });\n }\n\n simulateDecreaseLiquidity(p: { params: SimulateDecreaseLiquidityParams; client?: PublicClient }) {\n return simulateDecreaseLiquidity({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Omit<Parameters<typeof readPeripheryPool>[0], \"mode\">): Promise<PeripheryPoolState> {\n return readPeripheryPool({ ...p, mode: this.env, client: p.client });\n }\n\n readUserPoolBalances(p: Omit<Parameters<typeof readUserPoolBalances>[0], \"mode\">): Promise<UserPoolBalances> {\n return readUserPoolBalances({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery calldata builders ───────────────────────────────────────────\n\n buildSwap(p: Omit<BuildSwapParams, \"mode\">): Promise<CalldataCall> {\n return buildSwap({ ...p, mode: this.env });\n }\n\n buildMint(p: Omit<BuildMintParams, \"mode\">): Promise<CalldataCall> {\n return buildMint({ ...p, mode: this.env });\n }\n\n buildBurn(p: Omit<BuildBurnParams, \"mode\">): Promise<CalldataCall> {\n return buildBurn({ ...p, mode: this.env });\n }\n\n buildIncreaseLiquidity(p: Omit<BuildIncreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildIncreaseLiquidity({ ...p, mode: this.env });\n }\n\n buildDecreaseLiquidity(p: Omit<BuildDecreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildDecreaseLiquidity({ ...p, mode: this.env });\n }\n\n // ── Periphery submitters ──────────────────────────────────────────────────\n\n submitAction(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n submitSwap(wallet: WalletClient, params: SubmitActionParams) {\n return submitSwap(wallet, params, this.env);\n }\n\n submitApproval(wallet: WalletClient, params: SubmitActionParams) {\n return submitApproval(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitMint(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitBurn(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitIncreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitDecreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n // ── Chain-client factories ────────────────────────────────────────────────\n\n getKernelPublicClient(transport?: Transport) {\n return getKernelPublicClient(this.env, transport);\n }\n\n getSourcePublicClient(chain: CHAIN, transport?: Transport) {\n return getSourcePublicClient(chain, this.env, transport);\n }\n}\n","import { AmmCore, type EnvModeWithConfig, type AmmVmClient, type CalldataCall } from \"@skate-org/amm-core-v2\";\nimport { AmmApi } from \"@skate-org/amm-api-v2\";\nimport type { WalletClient } from \"viem\";\nimport { AmmEvm } from \"./client\";\nimport type { PeripheryPoolState, UserPoolBalances } from \"./periphery/reader\";\n\n/**\n * Single entry point for EVM consumers: quotes + actions (AmmApi), pool\n * catalog (AmmCore), and EVM build/submit/read (AmmEvm) behind one env-bound\n * object.\n *\n * `import { SkateAmm } from \"@skate-org/amm-evm-v2\"`\n *\n * @remarks\n * `quote.*`, `actions.*`, and `pools.*` are bound to the composed instances at\n * construction time. Patching `amm.api` or `amm.core` methods after construction\n * does not propagate to those namespaces.\n *\n * @example\n * const amm = new SkateAmm(\"PRODUCTION\");\n * const call = await amm.buildSwap({ poolKey: \"USDC_USDT\", chain: CHAIN.ARBITRUM, ... });\n * const quote = await amm.quote.swap({ poolKey: \"USDC_USDT\", ... });\n */\nexport class SkateAmm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n readonly core: AmmCore;\n readonly api: AmmApi;\n readonly vm: AmmEvm;\n\n readonly quote: {\n swap: AmmApi[\"swapQuote\"];\n mint: AmmApi[\"mintQuote\"];\n burn: AmmApi[\"burnQuote\"];\n increaseLiquidity: AmmApi[\"increaseLiquidityQuote\"];\n decreaseLiquidity: AmmApi[\"decreaseLiquidityQuote\"];\n boostedMint: AmmApi[\"boostedMintQuote\"];\n boostedRange: AmmApi[\"boostedRangeQuote\"];\n streamSwap: AmmApi[\"streamSwapQuote\"];\n subscribeSwap: AmmApi[\"subscribeSwapQuote\"];\n };\n\n readonly actions: {\n get: AmmApi[\"getAction\"];\n byUser: AmmApi[\"getActionsByUser\"];\n byUserTimeRange: AmmApi[\"getActionsByUserTimeRange\"];\n waitForExecuted: AmmApi[\"waitForExecuted\"];\n position: AmmApi[\"getPosition\"];\n };\n\n readonly pools: {\n all: AmmCore[\"getAllPoolInfo\"];\n keys: AmmCore[\"getAllPoolKeys\"];\n byKey: AmmCore[\"getPoolInfoByKey\"];\n supportedChains: AmmCore[\"getSupportedChains\"];\n supportedPairs: AmmCore[\"getSupportedPairs\"];\n supportedTokens: AmmCore[\"getSupportedTokens\"];\n keyByKernelPool: AmmCore[\"kernelPoolToPoolKey\"];\n };\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n this.core = new AmmCore(env);\n this.api = new AmmApi(env);\n this.vm = new AmmEvm(env);\n\n const api = this.api;\n const core = this.core;\n\n this.quote = {\n swap: api.swapQuote.bind(api),\n mint: api.mintQuote.bind(api),\n burn: api.burnQuote.bind(api),\n increaseLiquidity: api.increaseLiquidityQuote.bind(api),\n decreaseLiquidity: api.decreaseLiquidityQuote.bind(api),\n boostedMint: api.boostedMintQuote.bind(api),\n boostedRange: api.boostedRangeQuote.bind(api),\n streamSwap: api.streamSwapQuote.bind(api),\n subscribeSwap: api.subscribeSwapQuote.bind(api),\n };\n\n this.actions = {\n get: api.getAction.bind(api),\n byUser: api.getActionsByUser.bind(api),\n byUserTimeRange: api.getActionsByUserTimeRange.bind(api),\n waitForExecuted: api.waitForExecuted.bind(api),\n position: api.getPosition.bind(api),\n };\n\n this.pools = {\n all: core.getAllPoolInfo.bind(core),\n keys: core.getAllPoolKeys.bind(core),\n byKey: core.getPoolInfoByKey.bind(core),\n supportedChains: core.getSupportedChains.bind(core),\n supportedPairs: core.getSupportedPairs.bind(core),\n supportedTokens: core.getSupportedTokens.bind(core),\n keyByKernelPool: core.kernelPoolToPoolKey.bind(core),\n };\n }\n\n // ── AmmVmClient: builders ────────────────────────────────────────────────────\n\n buildSwap(p: Parameters<AmmEvm[\"buildSwap\"]>[0]) { return this.vm.buildSwap(p); }\n buildMint(p: Parameters<AmmEvm[\"buildMint\"]>[0]) { return this.vm.buildMint(p); }\n buildBurn(p: Parameters<AmmEvm[\"buildBurn\"]>[0]) { return this.vm.buildBurn(p); }\n buildIncreaseLiquidity(p: Parameters<AmmEvm[\"buildIncreaseLiquidity\"]>[0]) { return this.vm.buildIncreaseLiquidity(p); }\n buildDecreaseLiquidity(p: Parameters<AmmEvm[\"buildDecreaseLiquidity\"]>[0]) { return this.vm.buildDecreaseLiquidity(p); }\n\n // ── AmmVmClient: submitters ──────────────────────────────────────────────────\n\n submitSwap(w: WalletClient, p: Parameters<AmmEvm[\"submitSwap\"]>[1]) { return this.vm.submitSwap(w, p); }\n submitMint(w: WalletClient, p: Parameters<AmmEvm[\"submitMint\"]>[1]) { return this.vm.submitMint(w, p); }\n submitBurn(w: WalletClient, p: Parameters<AmmEvm[\"submitBurn\"]>[1]) { return this.vm.submitBurn(w, p); }\n submitIncreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitIncreaseLiquidity\"]>[1]) { return this.vm.submitIncreaseLiquidity(w, p); }\n submitDecreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitDecreaseLiquidity\"]>[1]) { return this.vm.submitDecreaseLiquidity(w, p); }\n\n // ── AmmVmClient: readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Parameters<AmmEvm[\"readPeripheryPool\"]>[0]) { return this.vm.readPeripheryPool(p); }\n readUserPoolBalances(p: Parameters<AmmEvm[\"readUserPoolBalances\"]>[0]) { return this.vm.readUserPoolBalances(p); }\n\n // ── EVM extras ───────────────────────────────────────────────────────────────\n\n /** Read raw kernel pool slot. */\n readPool(p: Parameters<AmmEvm[\"readPool\"]>[0]) { return this.vm.readPool(p); }\n readKernelBalances(p: Parameters<AmmEvm[\"readKernelBalances\"]>[0]) { return this.vm.readKernelBalances(p); }\n readPosition(p: Parameters<AmmEvm[\"readPosition\"]>[0]) { return this.vm.readPosition(p); }\n readTickBitmap(p: Parameters<AmmEvm[\"readTickBitmap\"]>[0]) { return this.vm.readTickBitmap(p); }\n readTick(p: Parameters<AmmEvm[\"readTick\"]>[0]) { return this.vm.readTick(p); }\n computePositionAmounts(p: Parameters<AmmEvm[\"computePositionAmounts\"]>[0]) { return this.vm.computePositionAmounts(p); }\n\n simulateSwap(p: Parameters<AmmEvm[\"simulateSwap\"]>[0]) { return this.vm.simulateSwap(p); }\n simulateMint(p: Parameters<AmmEvm[\"simulateMint\"]>[0]) { return this.vm.simulateMint(p); }\n simulateBurn(p: Parameters<AmmEvm[\"simulateBurn\"]>[0]) { return this.vm.simulateBurn(p); }\n simulateDecreaseLiquidity(p: Parameters<AmmEvm[\"simulateDecreaseLiquidity\"]>[0]) { return this.vm.simulateDecreaseLiquidity(p); }\n\n submitAction(w: WalletClient, p: Parameters<AmmEvm[\"submitAction\"]>[1]) { return this.vm.submitAction(w, p); }\n submitApproval(w: WalletClient, p: Parameters<AmmEvm[\"submitApproval\"]>[1]) { return this.vm.submitApproval(w, p); }\n\n getKernelPublicClient(...args: Parameters<AmmEvm[\"getKernelPublicClient\"]>) { return this.vm.getKernelPublicClient(...args); }\n getSourcePublicClient(...args: Parameters<AmmEvm[\"getSourcePublicClient\"]>) { return this.vm.getSourcePublicClient(...args); }\n}\n","import type { DevModeConfig } from \"@skate-org/amm-core-v2\";\n\n/** Default DEV api endpoint — matches Phase 1's api client default. */\nconst DEFAULT_DEV_API_ENDPOINT =\n \"https://dev.api.skatechain.org/amm-action-v2\";\n\n/**\n * Convenience factory for the `{ mode: \"DEV\"; config: DevModeConfig }` tuple.\n *\n * Reduces ceremony at call sites that want to override a single field (e.g.,\n * `rpcEndpoints`) without reconstructing the full object:\n *\n * ```ts\n * const mode = createDevConfig({\n * rpcEndpoints: { [CHAIN.MEGAETH]: \"https://my-private-megaeth/rpc\" },\n * });\n * submitAction(wallet, params, mode);\n * ```\n *\n * Pass nothing to use all defaults.\n */\nexport function createDevConfig(\n overrides: Partial<DevModeConfig> = {},\n): { mode: \"DEV\"; config: DevModeConfig } {\n return {\n mode: \"DEV\",\n config: {\n apiEndpoint: overrides.apiEndpoint ?? DEFAULT_DEV_API_ENDPOINT,\n ...(overrides.rpcEndpoints\n ? { rpcEndpoints: overrides.rpcEndpoints }\n : {}),\n },\n };\n}\n","/**\n * Decode a single Uniswap-v3 tick-bitmap `uint256` word into the list of\n * real (non-compressed) ticks it marks as initialized.\n *\n * A tick bitmap word covers 256 compressed ticks. For a given `wordPos`\n * (int16) the word spans compressed ticks `wordPos * 256` through\n * `(wordPos + 1) * 256 - 1`, and bit `k` (0..255) corresponds to the\n * compressed tick `wordPos * 256 + k`. The real tick at bit `k` is\n * `(wordPos * 256 + k) * tickSpacing`.\n *\n * Intended composition with the reader:\n *\n * ```ts\n * const word = await readTickBitmap(pool, wordPos, mode);\n * const ticks = decodeTickBitmapWord(word, wordPos, tickSpacing);\n * ```\n *\n * Pure function: no network, no viem, no external deps.\n *\n * @param word The 256-bit bitmap word returned by PoolAbi.tickBitmap(int16).\n * @param wordPos The int16 word position (-128 .. 127 per Uniswap, but\n * we accept any safe-integer int16-shaped value).\n * @param tickSpacing The pool's tickSpacing (positive integer, typically 1,\n * 10, 60, 200, etc.).\n * @returns Real ticks whose bits are set in the word, ascending.\n *\n * @throws {RangeError} if `tickSpacing <= 0` or if `wordPos` is not a safe integer.\n */\nexport function decodeTickBitmapWord(\n word: bigint,\n wordPos: number,\n tickSpacing: number,\n): number[] {\n if (!Number.isSafeInteger(wordPos)) {\n throw new RangeError(\n `decodeTickBitmapWord: wordPos must be a safe integer, got ${wordPos}`,\n );\n }\n if (!Number.isSafeInteger(tickSpacing) || tickSpacing <= 0) {\n throw new RangeError(\n `decodeTickBitmapWord: tickSpacing must be a positive integer, got ${tickSpacing}`,\n );\n }\n const result: number[] = [];\n // wordPos * 256 gives the base compressed-tick of this word. Each set bit k\n // contributes compressed-tick (wordPos * 256 + k), which becomes real tick\n // (wordPos * 256 + k) * tickSpacing.\n const base = wordPos * 256;\n for (let k = 0; k < 256; k++) {\n if (((word >> BigInt(k)) & 1n) === 1n) {\n result.push((base + k) * tickSpacing);\n }\n }\n return result;\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { KernelEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by the Skate kernel's `KernelEventEmitter`, sourced\n * directly from `@skate-org/amm-bindings`.\n */\nexport type KernelEventName =\n | \"Burn\"\n | \"Collect\"\n | \"CollectProtocol\"\n | \"IncreaseObservationCardinalityNext\"\n | \"Initialize\"\n | \"Mint\"\n | \"PeripheryPoolAdded\"\n | \"PeripheryPoolChanged\"\n | \"PoolCreated\"\n | \"PoolDescriptionUpdated\"\n | \"SetFeeProtocol\"\n | \"Swap\";\n\n/** Exhaustive list of known kernel event names — same values as {@link KernelEventName}. */\nexport const KERNEL_EVENT_NAMES: readonly KernelEventName[] = [\n \"Burn\",\n \"Collect\",\n \"CollectProtocol\",\n \"IncreaseObservationCardinalityNext\",\n \"Initialize\",\n \"Mint\",\n \"PeripheryPoolAdded\",\n \"PeripheryPoolChanged\",\n \"PoolCreated\",\n \"PoolDescriptionUpdated\",\n \"SetFeeProtocol\",\n \"Swap\",\n];\n\n/**\n * A decoded kernel event — the event name, its named args, and the original\n * viem `Log` for context (tx hash, block number, etc.).\n */\nexport interface KernelParsedEvent {\n eventName: KernelEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by the Skate kernel's `KernelEventEmitter`.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known kernel event\n * or if ABI decoding fails.\n */\nexport function parseKernelEventLog(log: Log): KernelParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: KernelEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as KernelEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parseKernelEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { PeripheryEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by `PeripheryEventEmitter` on the source chain.\n */\nexport type PeripheryEventName =\n | \"AmountSettled\"\n | \"Burned\"\n | \"LiquidityDecreased\"\n | \"LiquidityIncreased\"\n | \"MintSettled\"\n | \"Minted\"\n | \"PoolCreated\"\n | \"PoolDeployed\"\n | \"Swapped\"\n | \"TransferredTo\";\n\n/** Exhaustive list of known periphery event names. */\nexport const PERIPHERY_EVENT_NAMES: readonly PeripheryEventName[] = [\n \"AmountSettled\",\n \"Burned\",\n \"LiquidityDecreased\",\n \"LiquidityIncreased\",\n \"MintSettled\",\n \"Minted\",\n \"PoolCreated\",\n \"PoolDeployed\",\n \"Swapped\",\n \"TransferredTo\",\n];\n\n/** A decoded periphery event — name, named args, and the original viem `Log`. */\nexport interface PeripheryParsedEvent {\n eventName: PeripheryEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by `PeripheryEventEmitter` on a source chain.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known periphery\n * event or if ABI decoding fails.\n */\nexport function parsePeripheryEventLog(log: Log): PeripheryParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: PeripheryEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as PeripheryEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parsePeripheryEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import type { Address, Log, PublicClient } from \"viem\";\nimport {\n KernelEventEmitterABI,\n PeripheryEventEmitterABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n parseKernelEventLog,\n type KernelParsedEvent,\n} from \"./kernel\";\nimport {\n parsePeripheryEventLog,\n type PeripheryParsedEvent,\n} from \"./periphery\";\n\nexport interface EventSubscriptionOptions<E> {\n /** Called for each decoded event. */\n onEvent: (event: E) => void;\n /** Called when a log fails to decode (subscription stays alive). */\n onError?: (err: unknown) => void;\n}\n\n/**\n * Subscribe to kernel events emitted by the `KernelEventEmitter` contract\n * at `address`. Returns an unsubscribe function.\n *\n * Decode failures are surfaced via `opts.onError` (if provided) rather than\n * throwing — the subscription continues.\n */\nexport function watchKernelEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<KernelParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: KernelEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parseKernelEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n\n/**\n * Subscribe to periphery events emitted by `PeripheryEventEmitter` at\n * `address` on the source chain the `client` is connected to.\n */\nexport function watchPeripheryEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<PeripheryParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: PeripheryEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parsePeripheryEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAgBA,IAAM,eAAsB,YAAY;AAAA,EAC7C,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,gBAAgB,EAAE,MAAM,SAAS,QAAQ,OAAO,UAAU,GAAG;AAAA,EAC7D,SAAS;AAAA,IACP,SAAS,EAAE,MAAM,CAAC,iCAAiC,EAAE;AAAA,IACrD,QAAQ,EAAE,MAAM,CAAC,iCAAiC,EAAE;AAAA,EACtD;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS,EAAE,MAAM,cAAc,KAAK,eAAe,QAAQ;AAAA,EAC7D;AACF,CAAC;AAQD,IAAM,cAA8C;AAAA,EAClD,CAAC,MAAM,OAAO,GAAG;AAAA,EACjB,CAAC,MAAM,QAAQ,GAAG;AAAA,EAClB,CAAC,MAAM,QAAQ,GAAG;AACpB;AAQA,SAAS,YAAY,OAAiC;AACpD,UAAQ,OAAO;AAAA,IACb,KAAK,MAAM;AACT,aAAO;AAAA,IACT,KAAK,MAAM;AACT,aAAO;AAAA,IACT,KAAK,MAAM;AACT,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAQA,SAAS,cACP,OACA,MACoB;AACpB,QAAM,EAAE,OAAO,IAAI,cAAc,IAAI;AACrC,SAAO,QAAQ,eAAe,KAAK,KAAK,YAAY,KAAK;AAC3D;AAaO,SAAS,sBACd,MACA,WACc;AACd,QAAM,EAAE,MAAM,SAAS,IAAI,cAAc,IAAI;AAC7C,QAAM,gBAAgB,YAAY,QAAQ;AAC1C,Q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AAQ,CAAC,SAAgB;AACvB,iBAAW,OAAO,MAAM;AACtB,YAAI;AACF,eAAK,QAAQ,uBAAuB,GAAG,CAAC;AAAA,QAC1C,SAAS,KAAK;AACZ,eAAK,UAAU,GAAG;AAAA,QACpB;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["normalizeMode","normalizeMode","KernelManagerABI","KernelManagerAddress","normalizeMode","normalizeMode","KernelManagerAddress","KernelManagerABI","normalizeMode","normalizeMode","PeripheryPoolABI","AmmCore","AmmCore","AmmCore","decodeEventLog","decodeEventLog","KernelEventEmitterABI","PeripheryEventEmitterABI","KernelEventEmitterABI","PeripheryEventEmitterABI"]}
|
|
1
|
+
{"version":3,"sources":["../src/chain-clients.ts","../src/kernel/reader.ts","../src/errors.ts","../src/kernel/_client.ts","../src/kernel/lens.ts","../src/periphery/reader.ts","../src/periphery/submit.ts","../src/periphery/calldata.ts","../src/client.ts","../src/skate-amm.ts","../src/devConfig.ts","../src/kernel/tickBitmap.ts","../src/events/kernel.ts","../src/events/periphery.ts","../src/events/watch.ts"],"sourcesContent":["import {\n createPublicClient,\n defineChain,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n} from \"viem\";\nimport { arbitrum, mainnet } from \"viem/chains\";\nimport {\n BLOCK_EXPLORER,\n CHAIN,\n KernelChain,\n VM,\n vmTypeFromChain,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * MegaETH chain definition — `@public`.\n *\n * Exported for callers who need to build their own viem `WalletClient` or\n * `PublicClient` against the same chain the SDK uses internally (e.g. wallet\n * integrations that construct a `WalletClient` ahead of calling\n * `submitAction`). Prefer {@link getKernelPublicClient} when you just need a\n * read client.\n *\n * viem ships a `megaeth` chain at id 4326, but with a different default RPC\n * than the one Skate uses for kernel reads. Define locally so we control the\n * RPC URL + block-explorer metadata and don't inherit unrelated op-stack\n * contract addresses.\n */\nexport const megaethChain: Chain = defineChain({\n id: 4326,\n name: \"MegaETH\",\n network: \"megaeth\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n public: { http: [\"https://mainnet.megaeth.com/rpc\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.MEGAETH },\n },\n});\n\n/**\n * Robinhood Chain definition (id 4663) — Arbitrum-Orbit L2, native ETH.\n *\n * A source periphery chain for the WETH/USDG pool. Defined locally so the SDK\n * controls the RPC URL + block-explorer metadata (viem ships no built-in for\n * 4663).\n */\nexport const robinhoodChain: Chain = defineChain({\n id: 4663,\n name: \"Robinhood Chain\",\n network: \"robinhood\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: { http: [\"https://rpc.mainnet.chain.robinhood.com\"] },\n public: { http: [\"https://rpc.mainnet.chain.robinhood.com\"] },\n },\n blockExplorers: {\n default: { name: \"Blockscout\", url: BLOCK_EXPLORER.ROBINHOOD },\n },\n});\n\n/**\n * Default public RPC URLs by chain id.\n *\n * Callers can override per-chain via `DevModeConfig.rpcEndpoints` or by\n * passing an explicit `transport` to the factory functions below.\n */\nconst DEFAULT_RPC: Partial<Record<CHAIN, string>> = {\n [CHAIN.MEGAETH]: \"https://mainnet.megaeth.com/rpc\",\n [CHAIN.ARBITRUM]: \"https://arb1.arbitrum.io/rpc\",\n [CHAIN.ETHEREUM]: \"https://ethereum-rpc.publicnode.com\",\n [CHAIN.ROBINHOOD]: \"https://rpc.mainnet.chain.robinhood.com\",\n};\n\n/**\n * Map a supported EVM `CHAIN` to a viem `Chain` definition.\n *\n * Only chains we actively support in Phase 2 are listed; unknown chains\n * return `undefined` and the caller throws.\n */\nfunction chainDefFor(chain: CHAIN): Chain | undefined {\n switch (chain) {\n case CHAIN.MEGAETH:\n return megaethChain;\n case CHAIN.ARBITRUM:\n return arbitrum;\n case CHAIN.ETHEREUM:\n return mainnet;\n case CHAIN.ROBINHOOD:\n return robinhoodChain;\n default:\n return undefined;\n }\n}\n\n/**\n * Resolve the RPC URL for a given chain under the precedence:\n * transport override (caller arg) > mode.config.rpcEndpoints[chain] > DEFAULT_RPC[chain]\n * Returns `undefined` if none is set — callers must have already decided whether\n * to use a caller-supplied transport.\n */\nfunction resolveRpcUrl(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): string | undefined {\n const { config } = normalizeMode(mode);\n return config?.rpcEndpoints?.[chain] ?? DEFAULT_RPC[chain];\n}\n\n/**\n * Return a fresh `PublicClient` bound to the kernel chain for `mode`.\n *\n * Today every env (`DEV` / `STAGING` / `PRODUCTION`) resolves to MegaETH —\n * see `KERNEL_CHAIN_BY_MODE` in `@skate-org/amm-core-v2`. Pointing a future\n * env at a different kernel chain is a one-line edit there; this factory\n * reads from that mapping so client + address tables stay in sync.\n *\n * Pure — no singletons, no caching. Pass a custom `transport` to override\n * the default RPC (useful for tests and custom RPC providers).\n */\nexport function getKernelPublicClient(\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n const { mode: baseMode } = normalizeMode(mode);\n const kernelChainId = KernelChain(baseMode);\n const chainDef = chainDefFor(kernelChainId);\n if (!chainDef) {\n throw new Error(\n `getKernelPublicClient: no chain definition registered for kernel chain ${kernelChainId} ` +\n `(mode=${baseMode}); update chainDefFor() in chain-clients.ts to support it.`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(resolveRpcUrl(kernelChainId, mode)),\n });\n}\n\n/**\n * Return a fresh `PublicClient` for a source EVM chain (e.g. Arbitrum).\n *\n * Throws a descriptive `Error` when:\n * - `chain` is not an EVM chain (per `vmTypeFromChain`); or\n * - no viem chain definition is registered for `chain`; or\n * - no default RPC URL is configured for `chain` and no `transport` override\n * was provided.\n *\n * Pure — no singletons, no caching.\n */\nexport function getSourcePublicClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n transport?: Transport,\n): PublicClient {\n if (vmTypeFromChain(chain) !== VM.EVM) {\n throw new Error(\n `getSourcePublicClient: chain ${chain} is not an EVM chain`,\n );\n }\n const chainDef = chainDefFor(chain);\n if (!chainDef) {\n throw new Error(\n `getSourcePublicClient: no chain definition registered for chain ${chain}`,\n );\n }\n const rpc = resolveRpcUrl(chain, mode);\n if (!rpc && !transport) {\n throw new Error(\n `getSourcePublicClient: no default or override RPC configured for chain ${chain}; pass a transport override or set DevModeConfig.rpcEndpoints[${chain}]`,\n );\n }\n return createPublicClient({\n chain: chainDef,\n transport: transport ?? http(rpc),\n });\n}\n","import type { PublicClient } from \"viem\";\nimport {\n KernelManagerABI,\n KernelPoolABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n getAmount0Delta,\n getAmount1Delta,\n getSqrtRatioAtTick,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/** Decoded kernel-pool `slot0` state (named fields, per the ABI tuple). */\nexport interface KernelSlot0 {\n sqrtPriceX96: bigint;\n tick: number;\n observationIndex: number;\n observationCardinality: number;\n observationCardinalityNext: number;\n feeProtocol: number;\n unlocked: boolean;\n}\n\n/** Decoded pool state returned by `readPool`. */\nexport interface KernelPoolState {\n slot0: KernelSlot0;\n liquidity: bigint;\n}\n\n/** Decoded NFT position returned by `readPosition`. */\nexport interface KernelNftPosition {\n pool: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n liquidity: bigint;\n feeGrowthInside0LastX128: bigint;\n feeGrowthInside1LastX128: bigint;\n tokensOwed0: bigint;\n tokensOwed1: bigint;\n}\n\n/** Decoded kernel-pool `ticks(tick)` struct. */\nexport interface KernelTick {\n liquidityGross: bigint;\n liquidityNet: bigint;\n feeGrowthOutside0X128: bigint;\n feeGrowthOutside1X128: bigint;\n tickCumulativeOutside: bigint;\n secondsPerLiquidityOutsideX128: bigint;\n secondsOutside: number;\n initialized: boolean;\n}\n\n/**\n * Read `slot0` and `liquidity` from a kernel pool. Returns both in a single\n * object; the reads are fired in parallel.\n *\n * The `client` optional parameter is the standard test-injection point.\n */\nexport async function readPool(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelPoolState> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [slot0, liquidity] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"slot0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"liquidity\",\n }),\n ]);\n // Viem returns named outputs as a positional tuple (array) when every\n // output has a name — normalize to a named-field object here so callers\n // don't depend on viem's tuple/object split.\n const s0 = slot0 as readonly [\n bigint,\n number,\n number,\n number,\n number,\n number,\n boolean,\n ];\n return {\n slot0: {\n sqrtPriceX96: s0[0],\n tick: s0[1],\n observationIndex: s0[2],\n observationCardinality: s0[3],\n observationCardinalityNext: s0[4],\n feeProtocol: s0[5],\n unlocked: s0[6],\n },\n liquidity: liquidity as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPool\");\n }\n}\n\n/** Decoded kernel-pool token balances returned by `readKernelBalances`. */\nexport interface KernelBalances {\n balance0: bigint;\n balance1: bigint;\n}\n\n/**\n * Read `balance0` and `balance1` from a kernel pool (raw token reserves on\n * the kernel side, before periphery scaling). Reads are fired in parallel.\n */\nexport async function readKernelBalances(p: {\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelBalances> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const [balance0, balance1] = await Promise.all([\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance0\",\n }),\n c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"balance1\",\n }),\n ]);\n return { balance0: balance0 as bigint, balance1: balance1 as bigint };\n } catch (err) {\n throw wrapReadError(err, \"readKernelBalances\");\n }\n}\n\n/**\n * Read an NFT position by token id from the kernel manager.\n *\n * Calls `KernelManager.nftPositions(tokenId)` — per the ABI this returns a\n * `DataTypes.NFTPosition` tuple including `pool`, `tickLower`, `tickUpper`,\n * `liquidity`, fee growth, and tokens owed.\n */\nexport async function readPosition(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelNftPosition> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const manager = KernelManagerAddress(baseMode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: manager,\n abi: KernelManagerABI,\n functionName: \"nftPositions\",\n args: [p.tokenId],\n })) as unknown;\n // Accept either a positional tuple or an already-named object from\n // viem — normalize to a named-field object, mirroring readPool's\n // defensive remap.\n const asTuple = Array.isArray(raw)\n ? (raw as unknown as readonly [\n `0x${string}`,\n number,\n number,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n ])\n : null;\n if (asTuple) {\n return {\n pool: asTuple[0],\n tickLower: asTuple[1],\n tickUpper: asTuple[2],\n liquidity: asTuple[3],\n feeGrowthInside0LastX128: asTuple[4],\n feeGrowthInside1LastX128: asTuple[5],\n tokensOwed0: asTuple[6],\n tokensOwed1: asTuple[7],\n };\n }\n return raw as KernelNftPosition;\n } catch (err) {\n throw wrapReadError(err, \"readPosition\");\n }\n}\n\n/**\n * Read a kernel-pool tick-bitmap word (`tickBitmap(int16 wordPos)`).\n *\n * Returns the raw `uint256` word as a bigint.\n */\nexport async function readTickBitmap(p: {\n kernelPool: `0x${string}`;\n wordPos: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<bigint> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const word = await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"tickBitmap\",\n args: [p.wordPos],\n });\n return word as bigint;\n } catch (err) {\n throw wrapReadError(err, \"readTickBitmap\");\n }\n}\n\n/** Read the `ticks(tick)` struct from a kernel pool. */\nexport async function readTick(p: {\n kernelPool: `0x${string}`;\n tick: number;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<KernelTick> {\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: p.kernelPool,\n abi: KernelPoolABI,\n functionName: \"ticks\",\n args: [p.tick],\n })) as readonly [\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n number,\n boolean,\n ];\n return {\n liquidityGross: raw[0],\n liquidityNet: raw[1],\n feeGrowthOutside0X128: raw[2],\n feeGrowthOutside1X128: raw[3],\n tickCumulativeOutside: raw[4],\n secondsPerLiquidityOutsideX128: raw[5],\n secondsOutside: raw[6],\n initialized: raw[7],\n };\n } catch (err) {\n throw wrapReadError(err, \"readTick\");\n }\n}\n\n/**\n * Compute `{amount0, amount1}` for an NFT position using the Group 3 math.\n *\n * Reads the position (to learn `pool`, `tickLower`, `tickUpper`,\n * `liquidity`) and the pool's `slot0`, then splits based on whether the\n * current tick is below, inside, or above the position range — mirroring\n * `PositionValue.principal` from Uniswap v3 periphery.\n */\nexport async function computePositionAmounts(p: {\n tokenId: bigint;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<{ amount0: bigint; amount1: bigint }> {\n const c = resolveKernelClient(p.mode, p.client);\n const position = await readPosition({ tokenId: p.tokenId, mode: p.mode, client: c });\n const { slot0 } = await readPool({ kernelPool: position.pool, mode: p.mode, client: c });\n\n const sqrtLower = getSqrtRatioAtTick(position.tickLower);\n const sqrtUpper = getSqrtRatioAtTick(position.tickUpper);\n\n if (slot0.tick < position.tickLower) {\n return {\n amount0: getAmount0Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n amount1: 0n,\n };\n }\n if (slot0.tick >= position.tickUpper) {\n return {\n amount0: 0n,\n amount1: getAmount1Delta(sqrtLower, sqrtUpper, position.liquidity, false),\n };\n }\n return {\n amount0: getAmount0Delta(\n slot0.sqrtPriceX96,\n sqrtUpper,\n position.liquidity,\n false,\n ),\n amount1: getAmount1Delta(\n sqrtLower,\n slot0.sqrtPriceX96,\n position.liquidity,\n false,\n ),\n };\n}\n","/**\n * Shared error types for the `@skate-org/amm-evm-v2` package.\n *\n * `EvmReadError` / `EvmWriteError` extend `SdkError` (from core) so callers\n * can `instanceof SdkError` to catch any SDK-origin error without needing\n * to know the specific subclass.\n */\n\nimport { SdkError } from \"@skate-org/amm-core-v2\";\n\n/** SDK-level error thrown when an EVM read reverts or decodes badly. */\nexport class EvmReadError extends SdkError {\n override readonly name: string = \"EvmReadError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * SDK-level error thrown when an EVM write (broadcast) fails.\n *\n * Symmetric with {@link EvmReadError}, but covers the write path: viem's\n * `TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`, as well as submitter\n * pre-flight guards (e.g. wrong-chain, missing account).\n */\nexport class EvmWriteError extends SdkError {\n override readonly name: string = \"EvmWriteError\";\n readonly functionName: string;\n\n constructor(functionName: string, message: string, options?: ErrorOptions) {\n super(`${functionName}: ${message}`, options);\n this.functionName = functionName;\n }\n}\n\n/**\n * Wrap any error from an EVM read into `EvmReadError`. Viem always wraps\n * revert-path errors in `ContractFunctionExecutionError` (see\n * `viem/utils/errors/getContractError`), so we check both the outer name and\n * the `.cause` chain for `ContractFunctionRevertedError` /\n * `ContractFunctionZeroDataError`.\n *\n * Shared by `kernel/reader.ts` and `periphery/reader.ts` — depends only on\n * `EvmReadError` and generic Error inspection (no reader-module imports), so\n * it is safe from circular-import concerns.\n */\nexport function wrapReadError(\n err: unknown,\n functionName: string,\n): EvmReadError {\n const outerName = (err as { name?: string } | null)?.name;\n const causeName = (err as { cause?: { name?: string } } | null)?.cause?.name;\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n const isViemContractError =\n outerName === \"ContractFunctionExecutionError\" ||\n outerName === \"ContractFunctionRevertedError\" ||\n outerName === \"ContractFunctionZeroDataError\" ||\n causeName === \"ContractFunctionRevertedError\" ||\n causeName === \"ContractFunctionZeroDataError\";\n if (isViemContractError) {\n return new EvmReadError(functionName, `reverted: ${message}`, {\n cause: err as Error,\n });\n }\n return new EvmReadError(functionName, message, { cause: err as Error });\n}\n\n/**\n * Wrap any error from an EVM write-path call (typically\n * `WalletClient.sendTransaction`) into `EvmWriteError`.\n *\n * Any thrown error reaching a submitter is treated as a write failure. If\n * we later want to differentiate known viem write errors\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, `ChainDisconnectedError`) from unknown errors —\n * e.g. to prefix the message or re-throw unknowns raw — that dispatch goes\n * here. Keeping the single-return shape until a concrete caller need\n * surfaces.\n */\nexport function wrapWriteError(\n err: unknown,\n functionName: string,\n): EvmWriteError {\n const message =\n (err as { shortMessage?: string } | null)?.shortMessage ??\n (err as { message?: string } | null)?.message ??\n String(err);\n return new EvmWriteError(functionName, message, { cause: err as Error });\n}\n","import type { PublicClient } from \"viem\";\nimport type { EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { getKernelPublicClient } from \"../chain-clients\";\n\n/**\n * Return the caller-provided client if present, otherwise build a fresh\n * MegaETH kernel client for the given mode. Shared by readers + lens\n * helpers; intentionally unexported from the package barrel.\n */\nexport function resolveKernelClient(\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getKernelPublicClient(mode);\n}\n","import type { PublicClient } from \"viem\";\nimport { KernelManagerABI } from \"@skate-org/amm-bindings\";\nimport {\n KernelManagerAddress,\n normalizeMode,\n type EnvModeWithConfig,\n} from \"@skate-org/amm-core-v2\";\nimport { wrapReadError } from \"../errors\";\nimport { resolveKernelClient } from \"./_client\";\n\n/**\n * Kernel lens (simulate) helpers — wrap KernelManager's `lens*` functions as\n * static-call simulations. Lens functions are marked nonpayable in the ABI,\n * but viem's `simulateContract` evaluates them with `eth_call`, so they\n * reuse the same client + RPC plumbing as the readers and never produce a\n * transaction.\n *\n * Errors funnel through `wrapReadError`: lens calls share the read-path\n * error model (revert reasons + RPC failures), and tagging them as \"writes\"\n * would be misleading since no state changes.\n */\n\nexport interface SimulateSwapParams {\n /** Kernel-pool address (EVM) */\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 (use `toBytes32Address` for cross-VM) */\n recipient: `0x${string}`;\n zeroForOne: boolean;\n /** Positive = exactInput, negative = exactOutput, per Uniswap v3 convention */\n amountSpecified: bigint;\n sqrtPriceLimitX96: bigint;\n}\n\nexport interface SimulateSwapResult {\n amount0: bigint;\n amount1: bigint;\n sqrtPriceX96After: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateSwap(p: {\n params: SimulateSwapParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateSwapResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensSwap\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.zeroForOne,\n p.params.amountSpecified,\n p.params.sqrtPriceLimitX96,\n ],\n });\n const [amount0, amount1, sqrtPriceX96After, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, sqrtPriceX96After, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateSwap\");\n }\n}\n\nexport interface SimulateMintParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n /** Caller-supplied callback data (passed to `IKernelMintCallback`) */\n data: `0x${string}`;\n}\n\nexport interface SimulateMintResult {\n amount0Used: bigint;\n amount1Used: bigint;\n liquidityAmount: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateMint(p: {\n params: SimulateMintParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateMintResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensMint\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount0,\n p.params.amount1,\n p.params.data,\n ],\n });\n const [amount0Used, amount1Used, liquidityAmount, returnData] = out.result as readonly [\n bigint,\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0Used, amount1Used, liquidityAmount, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateMint\");\n }\n}\n\nexport interface SimulateBurnParams {\n pool: `0x${string}`;\n /** Recipient encoded as bytes32 */\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n /** Liquidity amount to burn (uint128). */\n amount: bigint;\n}\n\nexport interface SimulateBurnResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateBurn(p: {\n params: SimulateBurnParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateBurnResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensBurn\",\n args: [\n p.params.pool,\n p.params.recipient,\n p.params.tickLower,\n p.params.tickUpper,\n p.params.amount,\n ],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateBurn\");\n }\n}\n\nexport interface SimulateDecreaseLiquidityParams {\n /** NFT position id (v2 positions). */\n tokenId: bigint;\n /** Liquidity amount to remove (uint128). */\n liquidity: bigint;\n}\n\nexport interface SimulateDecreaseLiquidityResult {\n amount0: bigint;\n amount1: bigint;\n returnData: `0x${string}`;\n}\n\nexport async function simulateDecreaseLiquidity(p: {\n params: SimulateDecreaseLiquidityParams;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<SimulateDecreaseLiquidityResult> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const c = resolveKernelClient(p.mode, p.client);\n try {\n const out = await c.simulateContract({\n address: KernelManagerAddress(baseMode),\n abi: KernelManagerABI,\n functionName: \"lensDecreaseLiquidity\",\n args: [p.params.tokenId, p.params.liquidity],\n });\n const [amount0, amount1, returnData] = out.result as readonly [\n bigint,\n bigint,\n `0x${string}`,\n ];\n return { amount0, amount1, returnData };\n } catch (err) {\n throw wrapReadError(err, \"simulateDecreaseLiquidity\");\n }\n}\n","import type { PublicClient } from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n CHAIN,\n getPeripheryDetailsByKernelPoolAndChainId,\n normalizeMode,\n type EnvModeWithConfig,\n type EvmChain,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\nimport { getSourcePublicClient } from \"../chain-clients\";\nimport { EvmReadError, wrapReadError } from \"../errors\";\n\n/**\n * Decoded periphery-pool state assembled by {@link readPeripheryPool}.\n *\n * The periphery pool does **not** expose a `slot0`-style view — pricing\n * state lives on the kernel pool on MegaETH (see `readPool`). What the\n * periphery pool does expose is: the configured pair\n * (`token0`, `token1`, `fee`, `kernelPool` reference), the escrowed\n * in-pool settlement balances (`balancesAvailable`), and the two\n * `dustAmount{0,1}` accumulators. Together these are enough for a\n * source-chain caller to reason about pending settlement and dust.\n */\nexport interface PeripheryPoolState {\n /** Periphery pool contract address on the source chain. */\n address: `0x${string}`;\n /** Source-chain ERC-20 address for token0. */\n token0: `0x${string}`;\n /** Source-chain ERC-20 address for token1. */\n token1: `0x${string}`;\n /** Fee tier (uint24) the periphery pool was deployed with. */\n fee: number;\n /** Address of the paired kernel pool on MegaETH. */\n kernelPool: `0x${string}`;\n /** Aggregate in-pool balances available for settlement. */\n balancesAvailable: { amount0Available: bigint; amount1Available: bigint };\n /** token0 dust accumulator. */\n dustAmount0: bigint;\n /** token1 dust accumulator. */\n dustAmount1: bigint;\n}\n\n/**\n * Decoded user per-pool in-flight token balances.\n *\n * Returned by `PeripheryPool.usersData(user)` as `(uint256 amount0, uint256 amount1)`.\n */\nexport interface UserPoolBalances {\n amount0: bigint;\n amount1: bigint;\n}\n\n/**\n * Return the caller-provided client, or build a fresh source-chain\n * client for `chain` under the given `mode`. Mirrors the kernel reader\n * injection pattern.\n */\nfunction resolveClient(\n chain: CHAIN,\n mode: EnvModeWithConfig,\n client?: PublicClient,\n): PublicClient {\n return client ?? getSourcePublicClient(chain, mode);\n}\n\n/**\n * Read the assembled periphery-pool state on a source chain.\n *\n * Resolves the periphery pool address via\n * `getPeripheryDetailsByKernelPoolAndChainId` (from\n * `@skate-org/amm-core-v2`) — **no addresses are hardcoded here**. If the\n * `(kernelPool, chain, mode)` triple has no entry in the aggregated pool\n * catalog, throws with the triple in the message for debuggability.\n *\n * All sub-reads are fired in parallel and normalized to named fields.\n */\nexport async function readPeripheryPool(p: {\n chain: CHAIN;\n kernelPool: `0x${string}`;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<PeripheryPoolState> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const details = getPeripheryDetailsByKernelPoolAndChainId(\n p.kernelPool,\n p.chain as EvmChain,\n baseMode,\n );\n if (!details) {\n throw new EvmReadError(\n \"readPeripheryPool\",\n `no periphery entry for kernelPool=${p.kernelPool} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const address = details.address;\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const [\n balancesAvailableRaw,\n dust0,\n dust1,\n token0,\n token1,\n fee,\n kPool,\n ] = await Promise.all([\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"balancesAvailable\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"dustAmount1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token0\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"token1\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"fee\",\n }),\n c.readContract({\n address,\n abi: PeripheryPoolABI,\n functionName: \"kernelPool\",\n }),\n ]);\n // Viem decodes multi-output tuples with all-named outputs as a\n // positional tuple — normalize to a named-field object.\n const bAvail = balancesAvailableRaw as readonly [bigint, bigint];\n return {\n address,\n token0: token0 as `0x${string}`,\n token1: token1 as `0x${string}`,\n fee: fee as number,\n kernelPool: kPool as `0x${string}`,\n balancesAvailable: {\n amount0Available: bAvail[0],\n amount1Available: bAvail[1],\n },\n dustAmount0: dust0 as bigint,\n dustAmount1: dust1 as bigint,\n };\n } catch (err) {\n throw wrapReadError(err, \"readPeripheryPool\");\n }\n}\n\n/**\n * Read a user's per-pool in-flight balances on a source chain.\n *\n * Resolves the periphery pool address via AmmCore.getPoolInfoByKey +\n * peripheryInfo[chain].address (no hardcoded addresses) and calls\n * `PeripheryPool.usersData(user)` which returns\n * `(uint256 amount0, uint256 amount1)`.\n */\nexport async function readUserPoolBalances(p: {\n user: `0x${string}`;\n poolKey: string;\n chain: CHAIN;\n mode: EnvModeWithConfig;\n client?: PublicClient;\n}): Promise<UserPoolBalances> {\n const { mode: baseMode } = normalizeMode(p.mode);\n const core = new AmmCore(p.mode);\n const info = core.getPoolInfoByKey(p.poolKey);\n const periphery = info?.peripheryInfo[p.chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new EvmReadError(\n \"readUserPoolBalances\",\n `no periphery entry for poolKey=${p.poolKey} chain=${p.chain} mode=${baseMode}`,\n );\n }\n const c = resolveClient(p.chain, p.mode, p.client);\n try {\n const raw = (await c.readContract({\n address: periphery.address,\n abi: PeripheryPoolABI,\n functionName: \"usersData\",\n args: [p.user],\n })) as unknown;\n // `usersData` returns `(uint256 amount0, uint256 amount1)`.\n // Viem decodes tuples with all-named outputs as a positional tuple;\n // handle both the positional and (older) object shapes defensively.\n if (Array.isArray(raw)) {\n const tuple = raw as unknown as readonly [bigint, bigint];\n return { amount0: tuple[0], amount1: tuple[1] };\n }\n const asObject = raw as { amount0: bigint; amount1: bigint };\n return { amount0: asObject.amount0, amount1: asObject.amount1 };\n } catch (err) {\n throw wrapReadError(err, \"readUserPoolBalances\");\n }\n}\n","import type { Address, Hex, WalletClient } from \"viem\";\nimport type { CHAIN, EnvModeWithConfig } from \"@skate-org/amm-core-v2\";\nimport { EvmWriteError, wrapWriteError } from \"../errors\";\n\n/**\n * Pre-built source-chain transaction payload accepted by\n * {@link submitAction}.\n *\n * The SDK does **not** fabricate calldata in Group 6 — callers build the\n * payload (e.g. from a quote's `serializedCall`) and this submitter only\n * broadcasts it. This keeps the SDK decoupled from any off-chain\n * routing/quote surface.\n */\nexport type SubmitActionParams = {\n /** Source-chain id the wallet must be connected to. */\n chain: CHAIN;\n /** Destination address of the broadcast tx. */\n to: Address;\n /** Pre-encoded calldata. */\n data: Hex;\n /** Native-value payable amount; defaults to `0n`. */\n value?: bigint;\n};\n\n/**\n * Broadcast a pre-built periphery action tx from the caller's\n * `WalletClient`.\n *\n * Guarantees:\n * - Throws {@link EvmWriteError} immediately if\n * `wallet.chain?.id !== params.chain` — no RPC call is made.\n * - Throws {@link EvmWriteError} if `wallet.account` is not set.\n * - Forwards the payload to `wallet.sendTransaction` and returns the\n * resulting tx hash.\n * - Wraps any thrown viem write-path error\n * (`TransactionExecutionError`, `UserRejectedRequestError`,\n * `ChainMismatchError`, …) into an {@link EvmWriteError} via\n * {@link wrapWriteError}.\n *\n * The `mode` parameter is currently unused at runtime; it is accepted for\n * API symmetry with the readers and as a forward-compat hook for a future\n * mode-specific submission policy (e.g. DEV-only simulation, staging\n * retries). The `_` prefix marks it unused for the TypeScript checker.\n *\n * Non-goals (per plan guardrails):\n * - Does NOT sign — the caller brings a `WalletClient` wired to their\n * signer.\n * - Does NOT switch chains — callers are responsible for\n * `wallet.switchChain(...)`.\n * - Does NOT retry or manage nonces — delegated to the caller's wallet.\n */\nexport async function submitAction(\n wallet: WalletClient,\n params: SubmitActionParams,\n _mode: EnvModeWithConfig,\n): Promise<Hex> {\n if (wallet.chain?.id !== params.chain) {\n throw new EvmWriteError(\n \"submitAction\",\n `wallet chain ${wallet.chain?.id ?? \"undefined\"} != params.chain ${params.chain}`,\n );\n }\n\n try {\n const account = wallet.account;\n if (!account) {\n throw new EvmWriteError(\n \"submitAction\",\n \"wallet has no account; callers must provide a wallet with wallet.account set\",\n );\n }\n return await wallet.sendTransaction({\n to: params.to,\n data: params.data,\n value: params.value ?? 0n,\n chain: wallet.chain,\n account,\n });\n } catch (err) {\n // Preserve our own pre-flight guards verbatim — they are already\n // EvmWriteError instances and don't need re-wrapping.\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitAction\");\n }\n}\n\n/**\n * Broadcast a periphery *swap* action — thin wrapper around\n * {@link submitAction} that re-labels any unknown error as `submitSwap` to\n * aid log-line triage. Behaviourally identical to `submitAction`; shares\n * its pre-flight guards.\n */\nexport async function submitSwap(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitSwap\");\n }\n}\n\n/**\n * Broadcast a periphery *approval* action (ERC-20 approve to the source\n * chain's periphery contract) — thin wrapper around {@link submitAction}.\n * See {@link submitSwap} for labeling rationale.\n */\nexport async function submitApproval(\n wallet: WalletClient,\n params: SubmitActionParams,\n mode: EnvModeWithConfig,\n): Promise<Hex> {\n try {\n return await submitAction(wallet, params, mode);\n } catch (err) {\n if (err instanceof EvmWriteError) throw err;\n throw wrapWriteError(err, \"submitApproval\");\n }\n}\n","/**\n * Pure ABI encoders for periphery-pool `swap` / `mint` / `burn` /\n * `increaseLiquidity` / `decreaseLiquidity` calldata.\n *\n * No client, no signing, no submission — quote routes use these to mirror\n * the on-chain calldata shape without paying for an RPC round-trip. For the\n * full submit-and-confirm flow, use the submitters in `./submit.ts`.\n *\n * Each `build*` function resolves the EVM periphery contract address for the\n * given `poolKey` + `chain` via `AmmCore`, encodes the calldata, and returns\n * a `CalldataCall` ready for submission.\n *\n * Encoding does NOT change — only call signatures and return types are new.\n */\n\nimport {\n encodeAbiParameters,\n encodeFunctionData,\n maxUint256,\n parseAbiParameters,\n} from \"viem\";\nimport { PeripheryPoolABI } from \"@skate-org/amm-bindings\";\nimport {\n AmmCore,\n type CHAIN,\n type EnvModeWithConfig,\n type CalldataCall,\n type EvmPeripheryInfo,\n} from \"@skate-org/amm-core-v2\";\n\n/**\n * Resolve the EVM periphery pool contract address for a `(poolKey, chain, mode)` triple.\n * Throws with a descriptive message if the poolKey is unknown or has no periphery on `chain`.\n *\n * Resolves by poolKey via the aggregated catalog — deliberately not reusing\n * `getPeripheryDetailsByKernelPoolAndChainId`, which is keyed by kernelPool.\n */\nfunction resolvePeripheryTarget(\n poolKey: string,\n chain: CHAIN,\n mode: EnvModeWithConfig,\n): `0x${string}` {\n const core = new AmmCore(mode);\n const info = core.getPoolInfoByKey(poolKey);\n if (!info) throw new Error(`unknown poolKey: ${poolKey}`);\n const periphery = info.peripheryInfo[chain] as EvmPeripheryInfo | undefined;\n if (!periphery?.address) {\n throw new Error(`pool ${poolKey} has no periphery on chain ${chain}`);\n }\n return periphery.address;\n}\n\n// ── Param types ───────────────────────────────────────────────────────────────\n\n/** Common fields injected into every Build*Params type. */\ninterface BuildBaseParams {\n /** Pool key, e.g. \"USDC_USDT\" — resolves the source periphery pool target. */\n poolKey: string;\n /** Source chain the action is submitted on. */\n chain: CHAIN;\n /** Env mode. Omitted when called via AmmEvm (injected). */\n mode: EnvModeWithConfig;\n}\n\nexport interface BuildSwapParams extends BuildBaseParams {\n /** Swap recipient address in bytes32 format. */\n recipient: `0x${string}`;\n destChainId: number;\n destVmType: number;\n zeroForOne: boolean;\n /** Raw amount, subject to token native decimals. */\n amount: bigint;\n sqrtPriceLimitX96: bigint;\n /** Raw amount, subject to token native decimals. Default 0n. */\n minAmountOut?: bigint;\n /** Enforced at kernel timestamp. Default `maxUint256`. */\n deadline?: bigint;\n}\n\nexport interface BuildMintParams extends BuildBaseParams {\n recipient: `0x${string}`;\n tickLower: number;\n tickUpper: number;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildBurnParams extends BuildBaseParams {\n tokenId: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildIncreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n amount0: bigint;\n amount1: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\nexport interface BuildDecreaseLiquidityParams extends BuildBaseParams {\n tokenId: bigint;\n /** Kernel-side liquidity amount — `sqrt(normalizedAmount0 * normalizedAmount1)` in 18-decimal space. */\n liquidityAmount: bigint;\n amount0Min?: bigint;\n amount1Min?: bigint;\n deadline?: bigint;\n}\n\n// ── Internal encoders (pure, NOT exported) ────────────────────────────────────\n\nfunction encodeSwap(params: Omit<BuildSwapParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n zeroForOne,\n amount,\n sqrtPriceLimitX96,\n destVmType,\n destChainId,\n minAmountOut,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256,uint256\"),\n [\n minAmountOut ?? 0n,\n BigInt(destChainId),\n BigInt(destVmType),\n deadline ?? maxUint256,\n ],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"swap\",\n args: [recipient, zeroForOne, amount, sqrtPriceLimitX96, extraData],\n });\n}\n\nfunction encodeMint(params: Omit<BuildMintParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const {\n recipient,\n tickLower,\n tickUpper,\n amount0,\n amount1,\n amount0Min,\n amount1Min,\n deadline,\n } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"mint\",\n args: [recipient, tickLower, tickUpper, amount0, amount1, extraData],\n });\n}\n\nfunction encodeBurn(params: Omit<BuildBurnParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"burn\",\n args: [tokenId, extraData] as const,\n });\n}\n\nfunction encodeIncreaseLiquidity(params: Omit<BuildIncreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, amount0, amount1, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"increaseLiquidity\",\n args: [tokenId, amount0, amount1, extraData],\n });\n}\n\nfunction encodeDecreaseLiquidity(params: Omit<BuildDecreaseLiquidityParams, \"poolKey\" | \"chain\" | \"mode\">): `0x${string}` {\n const { tokenId, liquidityAmount, amount0Min, amount1Min, deadline } = params;\n const extraData = encodeAbiParameters(\n parseAbiParameters(\"uint256,uint256,uint256\"),\n [amount0Min ?? 0n, amount1Min ?? 0n, deadline ?? maxUint256],\n );\n return encodeFunctionData({\n abi: PeripheryPoolABI,\n functionName: \"decreaseLiquidity\",\n args: [tokenId, liquidityAmount, extraData],\n });\n}\n\n// ── Public async builders ─────────────────────────────────────────────────────\n\n/** Build calldata for a `swap` on the resolved EVM periphery pool. */\nexport async function buildSwap(params: BuildSwapParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeSwap(encodeParams),\n };\n}\n\n/** Build calldata for a `mint` on the resolved EVM periphery pool. */\nexport async function buildMint(params: BuildMintParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeMint(encodeParams),\n };\n}\n\n/** Build calldata for a `burn` on the resolved EVM periphery pool. */\nexport async function buildBurn(params: BuildBurnParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeBurn(encodeParams),\n };\n}\n\n/** Build calldata for `increaseLiquidity` on the resolved EVM periphery pool. */\nexport async function buildIncreaseLiquidity(params: BuildIncreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeIncreaseLiquidity(encodeParams),\n };\n}\n\n/**\n * Build calldata for `decreaseLiquidity` on the resolved EVM periphery pool.\n *\n * WARN: `liquidityAmount` is kernel-side, computed as\n * `sqrt(normalizedAmount0 * normalizedAmount1)` (18-decimal space).\n */\nexport async function buildDecreaseLiquidity(params: BuildDecreaseLiquidityParams): Promise<CalldataCall> {\n const { poolKey, chain, mode, ...encodeParams } = params;\n return {\n target: resolvePeripheryTarget(poolKey, chain, mode),\n calldata: encodeDecreaseLiquidity(encodeParams),\n };\n}\n","import type { PublicClient, Transport, WalletClient } from \"viem\";\nimport type { EnvModeWithConfig, CHAIN, CalldataCall, AmmVmClient } from \"@skate-org/amm-core-v2\";\nimport {\n readPool,\n readKernelBalances,\n readPosition,\n readTickBitmap,\n readTick,\n computePositionAmounts,\n} from \"./kernel/reader\";\nimport {\n simulateSwap,\n simulateMint,\n simulateBurn,\n simulateDecreaseLiquidity,\n type SimulateSwapParams,\n type SimulateMintParams,\n type SimulateBurnParams,\n type SimulateDecreaseLiquidityParams,\n} from \"./kernel/lens\";\nimport {\n readPeripheryPool,\n readUserPoolBalances,\n type PeripheryPoolState,\n type UserPoolBalances,\n} from \"./periphery/reader\";\nimport {\n submitAction,\n submitSwap,\n submitApproval,\n type SubmitActionParams,\n} from \"./periphery/submit\";\nimport {\n buildSwap,\n buildMint,\n buildBurn,\n buildIncreaseLiquidity,\n buildDecreaseLiquidity,\n type BuildSwapParams,\n type BuildMintParams,\n type BuildBurnParams,\n type BuildIncreaseLiquidityParams,\n type BuildDecreaseLiquidityParams,\n} from \"./periphery/calldata\";\nimport {\n getKernelPublicClient,\n getSourcePublicClient,\n} from \"./chain-clients\";\n\n/**\n * Env-bound client that wraps all EVM mode-taking functions with a fixed\n * `EnvModeWithConfig`. Construct once with the desired env and call methods\n * without the `mode` parameter.\n *\n * The raw `EnvModeWithConfig` is stored as-is (not normalized) so that\n * `config.rpcEndpoints` overrides pass through intact to the underlying\n * readers and chain-client factories.\n *\n * Implements `AmmVmClient<CalldataCall, WalletClient, 0x${string}, PeripheryPoolState, UserPoolBalances>`.\n * EVM submits any action type through the same `submitAction` path — the four\n * extra `AmmVmClient` submit methods are thin aliases.\n *\n * @example\n * const evm = new AmmEvm('PRODUCTION');\n * const pool = await evm.readPool({ kernelPool: '0x...' });\n * const call = await evm.buildSwap({ poolKey: 'USDC_USDT', chain: CHAIN.ARBITRUM, ... });\n */\nexport class AmmEvm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n }\n\n // ── Kernel readers ────────────────────────────────────────────────────────\n\n readPool(p: Omit<Parameters<typeof readPool>[0], \"mode\">) {\n return readPool({ ...p, mode: this.env, client: p.client });\n }\n\n readKernelBalances(p: Omit<Parameters<typeof readKernelBalances>[0], \"mode\">) {\n return readKernelBalances({ ...p, mode: this.env, client: p.client });\n }\n\n readPosition(p: Omit<Parameters<typeof readPosition>[0], \"mode\">) {\n return readPosition({ ...p, mode: this.env, client: p.client });\n }\n\n readTickBitmap(p: Omit<Parameters<typeof readTickBitmap>[0], \"mode\">) {\n return readTickBitmap({ ...p, mode: this.env, client: p.client });\n }\n\n readTick(p: Omit<Parameters<typeof readTick>[0], \"mode\">) {\n return readTick({ ...p, mode: this.env, client: p.client });\n }\n\n computePositionAmounts(p: Omit<Parameters<typeof computePositionAmounts>[0], \"mode\">) {\n return computePositionAmounts({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Kernel lens (simulate) ────────────────────────────────────────────────\n\n simulateSwap(p: { params: SimulateSwapParams; client?: PublicClient }) {\n return simulateSwap({ ...p, mode: this.env, client: p.client });\n }\n\n simulateMint(p: { params: SimulateMintParams; client?: PublicClient }) {\n return simulateMint({ ...p, mode: this.env, client: p.client });\n }\n\n simulateBurn(p: { params: SimulateBurnParams; client?: PublicClient }) {\n return simulateBurn({ ...p, mode: this.env, client: p.client });\n }\n\n simulateDecreaseLiquidity(p: { params: SimulateDecreaseLiquidityParams; client?: PublicClient }) {\n return simulateDecreaseLiquidity({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Omit<Parameters<typeof readPeripheryPool>[0], \"mode\">): Promise<PeripheryPoolState> {\n return readPeripheryPool({ ...p, mode: this.env, client: p.client });\n }\n\n readUserPoolBalances(p: Omit<Parameters<typeof readUserPoolBalances>[0], \"mode\">): Promise<UserPoolBalances> {\n return readUserPoolBalances({ ...p, mode: this.env, client: p.client });\n }\n\n // ── Periphery calldata builders ───────────────────────────────────────────\n\n buildSwap(p: Omit<BuildSwapParams, \"mode\">): Promise<CalldataCall> {\n return buildSwap({ ...p, mode: this.env });\n }\n\n buildMint(p: Omit<BuildMintParams, \"mode\">): Promise<CalldataCall> {\n return buildMint({ ...p, mode: this.env });\n }\n\n buildBurn(p: Omit<BuildBurnParams, \"mode\">): Promise<CalldataCall> {\n return buildBurn({ ...p, mode: this.env });\n }\n\n buildIncreaseLiquidity(p: Omit<BuildIncreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildIncreaseLiquidity({ ...p, mode: this.env });\n }\n\n buildDecreaseLiquidity(p: Omit<BuildDecreaseLiquidityParams, \"mode\">): Promise<CalldataCall> {\n return buildDecreaseLiquidity({ ...p, mode: this.env });\n }\n\n // ── Periphery submitters ──────────────────────────────────────────────────\n\n submitAction(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n submitSwap(wallet: WalletClient, params: SubmitActionParams) {\n return submitSwap(wallet, params, this.env);\n }\n\n submitApproval(wallet: WalletClient, params: SubmitActionParams) {\n return submitApproval(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitMint(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitBurn(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitIncreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n /** EVM submits any action via the same path — alias of `submitAction`. */\n submitDecreaseLiquidity(wallet: WalletClient, params: SubmitActionParams) {\n return submitAction(wallet, params, this.env);\n }\n\n // ── Chain-client factories ────────────────────────────────────────────────\n\n getKernelPublicClient(transport?: Transport) {\n return getKernelPublicClient(this.env, transport);\n }\n\n getSourcePublicClient(chain: CHAIN, transport?: Transport) {\n return getSourcePublicClient(chain, this.env, transport);\n }\n}\n","import { AmmCore, type EnvModeWithConfig, type AmmVmClient, type CalldataCall } from \"@skate-org/amm-core-v2\";\nimport { AmmApi } from \"@skate-org/amm-api-v2\";\nimport type { WalletClient } from \"viem\";\nimport { AmmEvm } from \"./client\";\nimport type { PeripheryPoolState, UserPoolBalances } from \"./periphery/reader\";\n\n/**\n * Single entry point for EVM consumers: quotes + actions (AmmApi), pool\n * catalog (AmmCore), and EVM build/submit/read (AmmEvm) behind one env-bound\n * object.\n *\n * `import { SkateAmm } from \"@skate-org/amm-evm-v2\"`\n *\n * @remarks\n * `quote.*`, `actions.*`, and `pools.*` are bound to the composed instances at\n * construction time. Patching `amm.api` or `amm.core` methods after construction\n * does not propagate to those namespaces.\n *\n * @example\n * const amm = new SkateAmm(\"PRODUCTION\");\n * const call = await amm.buildSwap({ poolKey: \"USDC_USDT\", chain: CHAIN.ARBITRUM, ... });\n * const quote = await amm.quote.swap({ poolKey: \"USDC_USDT\", ... });\n */\nexport class SkateAmm implements AmmVmClient<CalldataCall, WalletClient, `0x${string}`, PeripheryPoolState, UserPoolBalances> {\n readonly env: EnvModeWithConfig;\n readonly core: AmmCore;\n readonly api: AmmApi;\n readonly vm: AmmEvm;\n\n readonly quote: {\n swap: AmmApi[\"swapQuote\"];\n mint: AmmApi[\"mintQuote\"];\n burn: AmmApi[\"burnQuote\"];\n increaseLiquidity: AmmApi[\"increaseLiquidityQuote\"];\n decreaseLiquidity: AmmApi[\"decreaseLiquidityQuote\"];\n boostedMint: AmmApi[\"boostedMintQuote\"];\n boostedRange: AmmApi[\"boostedRangeQuote\"];\n streamSwap: AmmApi[\"streamSwapQuote\"];\n subscribeSwap: AmmApi[\"subscribeSwapQuote\"];\n };\n\n readonly actions: {\n get: AmmApi[\"getAction\"];\n byUser: AmmApi[\"getActionsByUser\"];\n byUserTimeRange: AmmApi[\"getActionsByUserTimeRange\"];\n waitForExecuted: AmmApi[\"waitForExecuted\"];\n position: AmmApi[\"getPosition\"];\n };\n\n readonly pools: {\n all: AmmCore[\"getAllPoolInfo\"];\n keys: AmmCore[\"getAllPoolKeys\"];\n byKey: AmmCore[\"getPoolInfoByKey\"];\n supportedChains: AmmCore[\"getSupportedChains\"];\n supportedPairs: AmmCore[\"getSupportedPairs\"];\n supportedTokens: AmmCore[\"getSupportedTokens\"];\n keyByKernelPool: AmmCore[\"kernelPoolToPoolKey\"];\n };\n\n constructor(env: EnvModeWithConfig) {\n this.env = env;\n this.core = new AmmCore(env);\n this.api = new AmmApi(env);\n this.vm = new AmmEvm(env);\n\n const api = this.api;\n const core = this.core;\n\n this.quote = {\n swap: api.swapQuote.bind(api),\n mint: api.mintQuote.bind(api),\n burn: api.burnQuote.bind(api),\n increaseLiquidity: api.increaseLiquidityQuote.bind(api),\n decreaseLiquidity: api.decreaseLiquidityQuote.bind(api),\n boostedMint: api.boostedMintQuote.bind(api),\n boostedRange: api.boostedRangeQuote.bind(api),\n streamSwap: api.streamSwapQuote.bind(api),\n subscribeSwap: api.subscribeSwapQuote.bind(api),\n };\n\n this.actions = {\n get: api.getAction.bind(api),\n byUser: api.getActionsByUser.bind(api),\n byUserTimeRange: api.getActionsByUserTimeRange.bind(api),\n waitForExecuted: api.waitForExecuted.bind(api),\n position: api.getPosition.bind(api),\n };\n\n this.pools = {\n all: core.getAllPoolInfo.bind(core),\n keys: core.getAllPoolKeys.bind(core),\n byKey: core.getPoolInfoByKey.bind(core),\n supportedChains: core.getSupportedChains.bind(core),\n supportedPairs: core.getSupportedPairs.bind(core),\n supportedTokens: core.getSupportedTokens.bind(core),\n keyByKernelPool: core.kernelPoolToPoolKey.bind(core),\n };\n }\n\n // ── AmmVmClient: builders ────────────────────────────────────────────────────\n\n buildSwap(p: Parameters<AmmEvm[\"buildSwap\"]>[0]) { return this.vm.buildSwap(p); }\n buildMint(p: Parameters<AmmEvm[\"buildMint\"]>[0]) { return this.vm.buildMint(p); }\n buildBurn(p: Parameters<AmmEvm[\"buildBurn\"]>[0]) { return this.vm.buildBurn(p); }\n buildIncreaseLiquidity(p: Parameters<AmmEvm[\"buildIncreaseLiquidity\"]>[0]) { return this.vm.buildIncreaseLiquidity(p); }\n buildDecreaseLiquidity(p: Parameters<AmmEvm[\"buildDecreaseLiquidity\"]>[0]) { return this.vm.buildDecreaseLiquidity(p); }\n\n // ── AmmVmClient: submitters ──────────────────────────────────────────────────\n\n submitSwap(w: WalletClient, p: Parameters<AmmEvm[\"submitSwap\"]>[1]) { return this.vm.submitSwap(w, p); }\n submitMint(w: WalletClient, p: Parameters<AmmEvm[\"submitMint\"]>[1]) { return this.vm.submitMint(w, p); }\n submitBurn(w: WalletClient, p: Parameters<AmmEvm[\"submitBurn\"]>[1]) { return this.vm.submitBurn(w, p); }\n submitIncreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitIncreaseLiquidity\"]>[1]) { return this.vm.submitIncreaseLiquidity(w, p); }\n submitDecreaseLiquidity(w: WalletClient, p: Parameters<AmmEvm[\"submitDecreaseLiquidity\"]>[1]) { return this.vm.submitDecreaseLiquidity(w, p); }\n\n // ── AmmVmClient: readers ─────────────────────────────────────────────────────\n\n readPeripheryPool(p: Parameters<AmmEvm[\"readPeripheryPool\"]>[0]) { return this.vm.readPeripheryPool(p); }\n readUserPoolBalances(p: Parameters<AmmEvm[\"readUserPoolBalances\"]>[0]) { return this.vm.readUserPoolBalances(p); }\n\n // ── EVM extras ───────────────────────────────────────────────────────────────\n\n /** Read raw kernel pool slot. */\n readPool(p: Parameters<AmmEvm[\"readPool\"]>[0]) { return this.vm.readPool(p); }\n readKernelBalances(p: Parameters<AmmEvm[\"readKernelBalances\"]>[0]) { return this.vm.readKernelBalances(p); }\n readPosition(p: Parameters<AmmEvm[\"readPosition\"]>[0]) { return this.vm.readPosition(p); }\n readTickBitmap(p: Parameters<AmmEvm[\"readTickBitmap\"]>[0]) { return this.vm.readTickBitmap(p); }\n readTick(p: Parameters<AmmEvm[\"readTick\"]>[0]) { return this.vm.readTick(p); }\n computePositionAmounts(p: Parameters<AmmEvm[\"computePositionAmounts\"]>[0]) { return this.vm.computePositionAmounts(p); }\n\n simulateSwap(p: Parameters<AmmEvm[\"simulateSwap\"]>[0]) { return this.vm.simulateSwap(p); }\n simulateMint(p: Parameters<AmmEvm[\"simulateMint\"]>[0]) { return this.vm.simulateMint(p); }\n simulateBurn(p: Parameters<AmmEvm[\"simulateBurn\"]>[0]) { return this.vm.simulateBurn(p); }\n simulateDecreaseLiquidity(p: Parameters<AmmEvm[\"simulateDecreaseLiquidity\"]>[0]) { return this.vm.simulateDecreaseLiquidity(p); }\n\n submitAction(w: WalletClient, p: Parameters<AmmEvm[\"submitAction\"]>[1]) { return this.vm.submitAction(w, p); }\n submitApproval(w: WalletClient, p: Parameters<AmmEvm[\"submitApproval\"]>[1]) { return this.vm.submitApproval(w, p); }\n\n getKernelPublicClient(...args: Parameters<AmmEvm[\"getKernelPublicClient\"]>) { return this.vm.getKernelPublicClient(...args); }\n getSourcePublicClient(...args: Parameters<AmmEvm[\"getSourcePublicClient\"]>) { return this.vm.getSourcePublicClient(...args); }\n}\n","import type { DevModeConfig } from \"@skate-org/amm-core-v2\";\n\n/** Default DEV api endpoint — matches Phase 1's api client default. */\nconst DEFAULT_DEV_API_ENDPOINT =\n \"https://dev.api.skatechain.org/amm-action-v2\";\n\n/**\n * Convenience factory for the `{ mode: \"DEV\"; config: DevModeConfig }` tuple.\n *\n * Reduces ceremony at call sites that want to override a single field (e.g.,\n * `rpcEndpoints`) without reconstructing the full object:\n *\n * ```ts\n * const mode = createDevConfig({\n * rpcEndpoints: { [CHAIN.MEGAETH]: \"https://my-private-megaeth/rpc\" },\n * });\n * submitAction(wallet, params, mode);\n * ```\n *\n * Pass nothing to use all defaults.\n */\nexport function createDevConfig(\n overrides: Partial<DevModeConfig> = {},\n): { mode: \"DEV\"; config: DevModeConfig } {\n return {\n mode: \"DEV\",\n config: {\n apiEndpoint: overrides.apiEndpoint ?? DEFAULT_DEV_API_ENDPOINT,\n ...(overrides.rpcEndpoints\n ? { rpcEndpoints: overrides.rpcEndpoints }\n : {}),\n },\n };\n}\n","/**\n * Decode a single Uniswap-v3 tick-bitmap `uint256` word into the list of\n * real (non-compressed) ticks it marks as initialized.\n *\n * A tick bitmap word covers 256 compressed ticks. For a given `wordPos`\n * (int16) the word spans compressed ticks `wordPos * 256` through\n * `(wordPos + 1) * 256 - 1`, and bit `k` (0..255) corresponds to the\n * compressed tick `wordPos * 256 + k`. The real tick at bit `k` is\n * `(wordPos * 256 + k) * tickSpacing`.\n *\n * Intended composition with the reader:\n *\n * ```ts\n * const word = await readTickBitmap(pool, wordPos, mode);\n * const ticks = decodeTickBitmapWord(word, wordPos, tickSpacing);\n * ```\n *\n * Pure function: no network, no viem, no external deps.\n *\n * @param word The 256-bit bitmap word returned by PoolAbi.tickBitmap(int16).\n * @param wordPos The int16 word position (-128 .. 127 per Uniswap, but\n * we accept any safe-integer int16-shaped value).\n * @param tickSpacing The pool's tickSpacing (positive integer, typically 1,\n * 10, 60, 200, etc.).\n * @returns Real ticks whose bits are set in the word, ascending.\n *\n * @throws {RangeError} if `tickSpacing <= 0` or if `wordPos` is not a safe integer.\n */\nexport function decodeTickBitmapWord(\n word: bigint,\n wordPos: number,\n tickSpacing: number,\n): number[] {\n if (!Number.isSafeInteger(wordPos)) {\n throw new RangeError(\n `decodeTickBitmapWord: wordPos must be a safe integer, got ${wordPos}`,\n );\n }\n if (!Number.isSafeInteger(tickSpacing) || tickSpacing <= 0) {\n throw new RangeError(\n `decodeTickBitmapWord: tickSpacing must be a positive integer, got ${tickSpacing}`,\n );\n }\n const result: number[] = [];\n // wordPos * 256 gives the base compressed-tick of this word. Each set bit k\n // contributes compressed-tick (wordPos * 256 + k), which becomes real tick\n // (wordPos * 256 + k) * tickSpacing.\n const base = wordPos * 256;\n for (let k = 0; k < 256; k++) {\n if (((word >> BigInt(k)) & 1n) === 1n) {\n result.push((base + k) * tickSpacing);\n }\n }\n return result;\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { KernelEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by the Skate kernel's `KernelEventEmitter`, sourced\n * directly from `@skate-org/amm-bindings`.\n */\nexport type KernelEventName =\n | \"Burn\"\n | \"Collect\"\n | \"CollectProtocol\"\n | \"IncreaseObservationCardinalityNext\"\n | \"Initialize\"\n | \"Mint\"\n | \"PeripheryPoolAdded\"\n | \"PeripheryPoolChanged\"\n | \"PoolCreated\"\n | \"PoolDescriptionUpdated\"\n | \"SetFeeProtocol\"\n | \"Swap\";\n\n/** Exhaustive list of known kernel event names — same values as {@link KernelEventName}. */\nexport const KERNEL_EVENT_NAMES: readonly KernelEventName[] = [\n \"Burn\",\n \"Collect\",\n \"CollectProtocol\",\n \"IncreaseObservationCardinalityNext\",\n \"Initialize\",\n \"Mint\",\n \"PeripheryPoolAdded\",\n \"PeripheryPoolChanged\",\n \"PoolCreated\",\n \"PoolDescriptionUpdated\",\n \"SetFeeProtocol\",\n \"Swap\",\n];\n\n/**\n * A decoded kernel event — the event name, its named args, and the original\n * viem `Log` for context (tx hash, block number, etc.).\n */\nexport interface KernelParsedEvent {\n eventName: KernelEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by the Skate kernel's `KernelEventEmitter`.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known kernel event\n * or if ABI decoding fails.\n */\nexport function parseKernelEventLog(log: Log): KernelParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: KernelEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as KernelEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parseKernelEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import { decodeEventLog, type Log } from \"viem\";\nimport { PeripheryEventEmitterABI } from \"@skate-org/amm-bindings\";\nimport { EvmReadError } from \"../errors\";\n\n/**\n * Event names emitted by `PeripheryEventEmitter` on the source chain.\n */\nexport type PeripheryEventName =\n | \"AmountSettled\"\n | \"Burned\"\n | \"LiquidityDecreased\"\n | \"LiquidityIncreased\"\n | \"MintSettled\"\n | \"Minted\"\n | \"PoolCreated\"\n | \"PoolDeployed\"\n | \"Swapped\"\n | \"TransferredTo\";\n\n/** Exhaustive list of known periphery event names. */\nexport const PERIPHERY_EVENT_NAMES: readonly PeripheryEventName[] = [\n \"AmountSettled\",\n \"Burned\",\n \"LiquidityDecreased\",\n \"LiquidityIncreased\",\n \"MintSettled\",\n \"Minted\",\n \"PoolCreated\",\n \"PoolDeployed\",\n \"Swapped\",\n \"TransferredTo\",\n];\n\n/** A decoded periphery event — name, named args, and the original viem `Log`. */\nexport interface PeripheryParsedEvent {\n eventName: PeripheryEventName;\n args: Record<string, unknown>;\n log: Log;\n}\n\n/**\n * Decode a viem `Log` emitted by `PeripheryEventEmitter` on a source chain.\n *\n * Throws {@link EvmReadError} if the log's topic0 is not a known periphery\n * event or if ABI decoding fails.\n */\nexport function parsePeripheryEventLog(log: Log): PeripheryParsedEvent {\n try {\n const decoded = decodeEventLog({\n abi: PeripheryEventEmitterABI,\n data: log.data,\n topics: log.topics,\n });\n return {\n eventName: decoded.eventName as PeripheryEventName,\n args: (decoded.args ?? {}) as Record<string, unknown>,\n log,\n };\n } catch (err) {\n const message = (err as { shortMessage?: string; message?: string })\n .shortMessage ??\n (err as { message?: string }).message ??\n String(err);\n throw new EvmReadError(\n \"parsePeripheryEventLog\",\n `failed to decode log: ${message}`,\n { cause: err as Error },\n );\n }\n}\n","import type { Address, Log, PublicClient } from \"viem\";\nimport {\n KernelEventEmitterABI,\n PeripheryEventEmitterABI,\n} from \"@skate-org/amm-bindings\";\nimport {\n parseKernelEventLog,\n type KernelParsedEvent,\n} from \"./kernel\";\nimport {\n parsePeripheryEventLog,\n type PeripheryParsedEvent,\n} from \"./periphery\";\n\nexport interface EventSubscriptionOptions<E> {\n /** Called for each decoded event. */\n onEvent: (event: E) => void;\n /** Called when a log fails to decode (subscription stays alive). */\n onError?: (err: unknown) => void;\n}\n\n/**\n * Subscribe to kernel events emitted by the `KernelEventEmitter` contract\n * at `address`. Returns an unsubscribe function.\n *\n * Decode failures are surfaced via `opts.onError` (if provided) rather than\n * throwing — the subscription continues.\n */\nexport function watchKernelEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<KernelParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: KernelEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parseKernelEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n\n/**\n * Subscribe to periphery events emitted by `PeripheryEventEmitter` at\n * `address` on the source chain the `client` is connected to.\n */\nexport function watchPeripheryEvents(\n client: PublicClient,\n address: Address,\n opts: EventSubscriptionOptions<PeripheryParsedEvent>,\n): () => void {\n return client.watchContractEvent({\n abi: PeripheryEventEmitterABI,\n address,\n onLogs: (logs: Log[]) => {\n for (const log of logs) {\n try {\n opts.onEvent(parsePeripheryEventLog(log));\n } catch (err) {\n opts.onError?.(err);\n }\n }\n },\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,UAAU,eAAe;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAgBA,IAAM,eAAsB,YAAY;AAAA,EAC7C,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,gBAAgB,EAAE,MAAM,SAAS,QAAQ,OAAO,UAAU,GAAG;AAAA,EAC7D,SAAS;AAAA,IACP,SAAS,EAAE,MAAM,CAAC,iCAAiC,EAAE;AAAA,IACrD,QAAQ,EAAE,MAAM,CAAC,iCAAiC,EAAE;AAAA,EACtD;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS,EAAE,MAAM,cAAc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A,EACF,CAAC;AACH;","names":["normalizeMode","normalizeMode","KernelManagerABI","KernelManagerAddress","normalizeMode","normalizeMode","KernelManagerAddress","KernelManagerABI","normalizeMode","normalizeMode","PeripheryPoolABI","AmmCore","AmmCore","AmmCore","decodeEventLog","decodeEventLog","KernelEventEmitterABI","PeripheryEventEmitterABI","KernelEventEmitterABI","PeripheryEventEmitterABI"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skate-org/amm-evm-v2",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.24",
|
|
4
4
|
"description": "Skate AMM v2 SDK — EVM clients, kernel/periphery readers, uniswap-v3 math, submitters",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@skate-org/amm-bindings": "^1.0.0",
|
|
29
29
|
"viem": "^2.21.0",
|
|
30
|
-
"@skate-org/amm-api-v2": "2.0.0-beta.
|
|
31
|
-
"@skate-org/amm-core-v2": "2.0.0-beta.
|
|
30
|
+
"@skate-org/amm-api-v2": "2.0.0-beta.24",
|
|
31
|
+
"@skate-org/amm-core-v2": "2.0.0-beta.24"
|
|
32
32
|
},
|
|
33
33
|
"publishConfig": {
|
|
34
34
|
"access": "public",
|