@seer-pm/lens 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,15 @@ var InsufficientLiquidityError = class extends Error {
6
6
  this.name = "InsufficientLiquidityError";
7
7
  }
8
8
  };
9
+ var SwapRevertsError = class extends Error {
10
+ code = "SWAP_REVERTS";
11
+ constructor(options, message = "Swap simulation reverted; the router rejected the built calldata.") {
12
+ super(options?.detail ? `${message} (${options.detail})` : message, {
13
+ cause: options?.cause
14
+ });
15
+ this.name = "SwapRevertsError";
16
+ }
17
+ };
9
18
 
10
19
  // src/index.ts
11
20
  var AMM = /* @__PURE__ */ ((AMM2) => {
@@ -28,7 +37,11 @@ var LENS_QUOTER_ABI = [
28
37
  "function V3_SWAP_ROUTER() view returns (address)",
29
38
  "function V4_ROUTER() view returns (address)",
30
39
  "function SWAPR_SWAP_ROUTER() view returns (address)",
31
- "function V4_QUOTER() view returns (address)"
40
+ "function V4_QUOTER() view returns (address)",
41
+ // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.
42
+ "error NoRoute()",
43
+ "error ZeroAmount()",
44
+ "error UnsupportedAMM()"
32
45
  ];
33
46
  var CHAINS = {
34
47
  1: {
@@ -46,7 +59,7 @@ var CHAINS = {
46
59
  wnative: "0x4200000000000000000000000000000000000006"
47
60
  },
48
61
  100: {
49
- lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA",
62
+ lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8",
50
63
  v3SwapRouter: "0x0000000000000000000000000000000000000000",
51
64
  v4Router: "0x0000000000000000000000000000000000000000",
52
65
  swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1",
@@ -68,6 +81,7 @@ function defaultDeadline() {
68
81
 
69
82
  export {
70
83
  InsufficientLiquidityError,
84
+ SwapRevertsError,
71
85
  AMM,
72
86
  AMM_NAMES,
73
87
  LENS_QUOTER_ABI,
@@ -76,4 +90,4 @@ export {
76
90
  GNOSIS_sDAI,
77
91
  defaultDeadline
78
92
  };
79
- //# sourceMappingURL=chunk-5UNFCMSF.js.map
93
+ //# sourceMappingURL=chunk-M4WEBPX7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/index.ts"],"sourcesContent":["/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n\n/**\n * Thrown when the pre-flight simulation shows the built calldata reverts, and the\n * state overrides that make it executable are confirmed to have applied — so the\n * revert is the router's, not an artifact of the simulation.\n *\n * Sending such a swap would waste gas and surface as an opaque wallet failure.\n */\nexport class SwapRevertsError extends Error {\n readonly code = \"SWAP_REVERTS\" as const;\n\n constructor(\n options?: { cause?: unknown; detail?: string },\n message = \"Swap simulation reverted; the router rejected the built calldata.\",\n ) {\n super(options?.detail ? `${message} (${options.detail})` : message, {\n cause: options?.cause,\n });\n this.name = \"SwapRevertsError\";\n }\n}\n","// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.\n \"error NoRoute()\",\n \"error ZeroAmount()\",\n \"error UnsupportedAMM()\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0x82150d38288e53AfcF20a5eEee47682c5Ef796d8\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError, SwapRevertsError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n"],"mappings":";AAKO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AASO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC,OAAO;AAAA,EAEhB,YACE,SACA,UAAU,qEACV;AACA,UAAM,SAAS,SAAS,GAAG,OAAO,KAAK,QAAQ,MAAM,MAAM,SAAS;AAAA,MAClE,OAAO,SAAS;AAAA,IAClB,CAAC;AACD,SAAK,OAAO;AAAA,EACd;AACF;;;AC9BO,IAAK,MAAL,kBAAKA,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;AAOL,IAAM,YAAiC;AAAA,EAC5C,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,qBAAiB,GAAG;AAAA,EACrB,CAAC,gBAAY,GAAG;AAClB;AAGO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,SAAS;AAAA,EACpB,GAAG;AAAA,IACD,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,IAAI;AAAA,IACF,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AACF;AAIO,IAAM,MAAM;AAGZ,IAAM,cAAc;AA+CpB,SAAS,kBAA0B;AACxC,SAAO,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,GAAG;AACnD;","names":["AMM"]}
package/dist/client.cjs CHANGED
@@ -28,6 +28,7 @@ __export(client_exports, {
28
28
  InsufficientLiquidityError: () => InsufficientLiquidityError,
29
29
  LENS_QUOTER_ABI: () => LENS_QUOTER_ABI,
30
30
  Lens: () => Lens,
31
+ SwapRevertsError: () => SwapRevertsError,
31
32
  assertSwapExecutable: () => assertSwapExecutable,
32
33
  defaultDeadline: () => defaultDeadline
33
34
  });
@@ -42,6 +43,15 @@ var InsufficientLiquidityError = class extends Error {
42
43
  this.name = "InsufficientLiquidityError";
43
44
  }
44
45
  };
46
+ var SwapRevertsError = class extends Error {
47
+ code = "SWAP_REVERTS";
48
+ constructor(options, message = "Swap simulation reverted; the router rejected the built calldata.") {
49
+ super(options?.detail ? `${message} (${options.detail})` : message, {
50
+ cause: options?.cause
51
+ });
52
+ this.name = "SwapRevertsError";
53
+ }
54
+ };
45
55
 
46
56
  // src/index.ts
47
57
  var AMM = /* @__PURE__ */ ((AMM2) => {
@@ -64,7 +74,11 @@ var LENS_QUOTER_ABI = [
64
74
  "function V3_SWAP_ROUTER() view returns (address)",
65
75
  "function V4_ROUTER() view returns (address)",
66
76
  "function SWAPR_SWAP_ROUTER() view returns (address)",
67
- "function V4_QUOTER() view returns (address)"
77
+ "function V4_QUOTER() view returns (address)",
78
+ // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.
79
+ "error NoRoute()",
80
+ "error ZeroAmount()",
81
+ "error UnsupportedAMM()"
68
82
  ];
69
83
  var CHAINS = {
70
84
  1: {
@@ -82,7 +96,7 @@ var CHAINS = {
82
96
  wnative: "0x4200000000000000000000000000000000000006"
83
97
  },
84
98
  100: {
85
- lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA",
99
+ lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8",
86
100
  v3SwapRouter: "0x0000000000000000000000000000000000000000",
87
101
  v4Router: "0x0000000000000000000000000000000000000000",
88
102
  swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1",
@@ -161,6 +175,63 @@ function buildSwapStateOverride(params) {
161
175
  function maxGasForBlock(gasLimit) {
162
176
  return gasLimit * GAS_LIMIT_BPS / 10000n;
163
177
  }
178
+ var PROBE_ADDRESS = "0x0000000000000000000000000000000000f0f0f0";
179
+ var PROBE_CODE = "0x600160005260206000f3";
180
+ var ONE_WORD = (0, import_viem.numberToHex)(1n, { size: 32 });
181
+ var BALANCE_OF_SELECTOR = "0x70a08231";
182
+ var ALLOWANCE_SELECTOR = "0xdd62ed3e";
183
+ function encodeAddressArgs(...args) {
184
+ return (0, import_viem.encodeAbiParameters)(
185
+ args.map(() => ({ type: "address" })),
186
+ args
187
+ );
188
+ }
189
+ async function nodeAppliesStateOverrides(client) {
190
+ try {
191
+ const res = await client.call({
192
+ to: PROBE_ADDRESS,
193
+ data: "0x",
194
+ stateOverride: [{ address: PROBE_ADDRESS, code: PROBE_CODE }]
195
+ });
196
+ return res.data === ONE_WORD;
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ async function readWord(client, to, data, stateOverride) {
202
+ try {
203
+ const res = await client.call({ to, data, stateOverride });
204
+ return res.data;
205
+ } catch {
206
+ return void 0;
207
+ }
208
+ }
209
+ async function swapOverridesApplied(params) {
210
+ const { client, account, tokenIn, amountIn, target, stateOverride } = params;
211
+ if (!await nodeAppliesStateOverrides(client)) return false;
212
+ if (isNative(tokenIn)) return true;
213
+ const token = tokenIn;
214
+ const expectedBalance = (0, import_viem.numberToHex)(amountIn > 0n ? amountIn : 1n, { size: 32 });
215
+ const balance = await readWord(
216
+ client,
217
+ token,
218
+ `${BALANCE_OF_SELECTOR}${encodeAddressArgs(account).slice(2)}`,
219
+ stateOverride
220
+ );
221
+ if (balance !== expectedBalance) return false;
222
+ const allowance = await readWord(
223
+ client,
224
+ token,
225
+ `${ALLOWANCE_SELECTOR}${encodeAddressArgs(account, target).slice(2)}`,
226
+ stateOverride
227
+ );
228
+ return allowance === (0, import_viem.numberToHex)(import_viem.maxUint256, { size: 32 });
229
+ }
230
+ function revertDetail(error) {
231
+ if (!(error instanceof Error)) return void 0;
232
+ const short = error.shortMessage;
233
+ return (short ?? error.message).split("\n")[0]?.trim() || void 0;
234
+ }
164
235
  async function assertSwapExecutable(client, params) {
165
236
  const { account, tokenIn, amountIn, result } = params;
166
237
  const target = result.target;
@@ -189,8 +260,17 @@ async function assertSwapExecutable(client, params) {
189
260
  };
190
261
  try {
191
262
  await client.call(base);
192
- } catch {
193
- return;
263
+ } catch (e) {
264
+ const applied = await swapOverridesApplied({
265
+ client,
266
+ account,
267
+ tokenIn,
268
+ amountIn,
269
+ target,
270
+ stateOverride
271
+ });
272
+ if (!applied) return;
273
+ throw new SwapRevertsError({ cause: e, detail: revertDetail(e) });
194
274
  }
195
275
  try {
196
276
  await client.call({ ...base, gas: maxGas });
@@ -392,6 +472,7 @@ var Lens = class {
392
472
  InsufficientLiquidityError,
393
473
  LENS_QUOTER_ABI,
394
474
  Lens,
475
+ SwapRevertsError,
395
476
  assertSwapExecutable,
396
477
  defaultDeadline
397
478
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/errors.ts","../src/index.ts","../src/gasGuard.ts"],"sourcesContent":["// Lens SDK — client\n\nimport { parseAbi, isAddressEqual, zeroAddress } from \"viem\";\nimport type { PublicClient, Address, Abi } from \"viem\";\nimport {\n CHAINS, GNOSIS_sDAI,\n LENS_QUOTER_ABI,\n AMM_NAMES,\n defaultDeadline,\n type ChainId,\n type QuoteParams,\n type QuoteResult,\n} from \"./index.js\";\nimport { assertSwapExecutable } from \"./gasGuard.js\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\n\n// viem's parseAbi (abitype) doesn't support inline `tuple(...)` syntax,\n// so rewrite the shared quoter ABI strings to use a named struct.\nconst QUOTE_TUPLE = \"tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut)\";\nconst QUOTE_STRUCT = \"struct Quote { uint8 source; uint256 feeBps; uint256 amountIn; uint256 amountOut; }\";\n\n/** Rewrites inline `tuple(...)` quoter ABI lines to a named `Quote` struct for `parseAbi`. */\nconst toQuoterAbi = (lines: readonly string[]): Abi =>\n parseAbi([QUOTE_STRUCT, ...lines.map((l) => l.split(QUOTE_TUPLE).join(\"Quote\"))]);\n\nconst quoterAbi = toQuoterAbi(LENS_QUOTER_ABI);\n\nexport {\n ETH, GNOSIS_sDAI, AMM, AMM_NAMES,\n CHAINS,\n LENS_QUOTER_ABI, defaultDeadline,\n InsufficientLiquidityError,\n} from \"./index.js\";\nexport type { QuoteResult, BaseQuoteParams, QuoteParams, ChainId } from \"./index.js\";\nexport { assertSwapExecutable } from \"./gasGuard.js\";\n\nconst DEFAULT_SLIPPAGE = 50; // 0.5%\n\ntype QuoteStruct = { source: number; feeBps: bigint; amountIn: bigint; amountOut: bigint };\ntype BestSwapResult = readonly [\n QuoteStruct,\n QuoteStruct,\n Address,\n `0x${string}`,\n bigint,\n];\ntype BuildBestSwapResult = readonly [QuoteStruct, Address, `0x${string}`, bigint, bigint];\n\n/** Resolves a human-readable AMM name from an on-chain `source` id. */\nfunction ammName(source: number): string {\n return (AMM_NAMES as Record<number, string>)[source] || `AMM #${source}`;\n}\n\n/**\n * Maps a `buildBestSwapViaETH` / `buildBestSwapViaToken` return value to `QuoteResult`.\n * Hop B is zeroed for single-hop; `b.amountOut > 0` means a real two-hop\n * route, so final `amountOut` comes from hop B.\n */\nfunction mapViaResult(value: BestSwapResult): QuoteResult {\n const [a, b, target, data, msgValue] = value;\n const isTwoHop = b.amountOut > 0n;\n return {\n amountIn: a.amountIn,\n amountOut: isTwoHop ? b.amountOut : a.amountOut,\n target: target as string,\n data: data as string,\n msgValue: msgValue ?? 0n,\n isTwoHop,\n sourceA: ammName(a.source),\n sourceB: isTwoHop ? ammName(b.source) : null,\n };\n}\n\n/**\n * True when either endpoint is native (`address(0)`) or the chain's wrapped native.\n * On non-Gnosis those pairs use ViaETH; on Gnosis they use ViaToken(sDAI).\n * Pure ERC20↔ERC20 uses `buildBestSwap`.\n */\nfunction involvesNativeOrWnative(\n tokenIn: string,\n tokenOut: string,\n wnative: Address,\n): boolean {\n return (\n isAddressEqual(tokenIn as Address, zeroAddress)\n || isAddressEqual(tokenOut as Address, zeroAddress)\n || isAddressEqual(tokenIn as Address, wnative)\n || isAddressEqual(tokenOut as Address, wnative)\n );\n}\n\n/**\n * Lens SDK client: quotes best routes via the unified on-chain LensQuoter\n * and builds ready-to-send txs for official DEX routers.\n */\nexport class Lens {\n private client: PublicClient;\n private chainId: ChainId;\n private lensQuoter: Address;\n private wnative: Address;\n private quoterAbi: Abi;\n\n /**\n * @param client - viem public client for the target chain\n * @param chainId - chain id (`1` | `10` | `100` | `8453`)\n * @param lensQuoter - optional LensQuoter address; defaults to `CHAINS[chainId].lensQuoter`\n */\n constructor(client: PublicClient, chainId: ChainId, lensQuoter?: Address) {\n this.client = client;\n this.chainId = chainId;\n const chain = CHAINS[chainId];\n this.lensQuoter = lensQuoter ?? (chain.lensQuoter as Address);\n this.wnative = chain.wnative as Address;\n this.quoterAbi = quoterAbi;\n }\n\n /**\n * Builds calldata for a two-hop (or one-hop if mid is unused) route via a\n * mid token — used when the caller sets `intermediate`, or as the default\n * Gnosis path for native/WXDAI↔ERC20 (`mid = GNOSIS_sDAI`).\n */\n private async viaToken(\n params: {\n recipient: string;\n exactOut: boolean;\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n slippageBps: number;\n deadline: bigint;\n hookPoolFee: number;\n hookTickSpacing: number;\n hookAddress: string;\n mid: string;\n },\n ): Promise<BestSwapResult> {\n return this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaToken\",\n args: [\n params.recipient as Address,\n params.exactOut,\n params.tokenIn as Address,\n params.tokenOut as Address,\n params.amount,\n BigInt(params.slippageBps),\n params.deadline,\n params.hookPoolFee,\n params.hookTickSpacing,\n params.hookAddress as Address,\n params.mid as Address,\n ],\n }) as Promise<BestSwapResult>;\n }\n\n /**\n * Finds a swap route via LensQuoter and returns amounts plus ready-to-send\n * calldata for an official DEX router.\n *\n * Route selection by request shape:\n * - `intermediate` set → `buildBestSwapViaToken(mid)` only\n * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;\n * elsewhere `buildBestSwapViaETH`\n * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)\n *\n * After building calldata, simulates the swap with a gas cap of 90% of\n * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw\n * {@link InsufficientLiquidityError}.\n */\n async quote(params: QuoteParams): Promise<QuoteResult> {\n const {\n tokenIn, tokenOut, amount, recipient,\n slippageBps = DEFAULT_SLIPPAGE, deadline = defaultDeadline(),\n exactOut = false,\n hookPoolFee = 0, hookTickSpacing = 0, hookAddress = zeroAddress,\n intermediate,\n } = params;\n\n const routeArgs = {\n recipient, exactOut, tokenIn, tokenOut, amount,\n slippageBps, deadline, hookPoolFee, hookTickSpacing, hookAddress,\n };\n\n let result: QuoteResult;\n\n // Caller forced a mid token: skip native/ERC20 cascade.\n if (intermediate) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));\n } else {\n const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);\n\n if (useViaEth) {\n // Gnosis (Seer): outcomes trade vs sDAI — skip ViaETH entirely.\n if (this.chainId === 100) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));\n } else {\n // Other chains: single-hop ViaETH (router wrap/unwrap).\n const value = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaETH\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BestSwapResult;\n result = mapViaResult(value);\n }\n } else {\n // Pure ERC20 ↔ ERC20: direct single-hop only (optional V4 hooked candidate).\n const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwap\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BuildBestSwapResult;\n\n result = {\n amountIn: best.amountIn,\n amountOut: best.amountOut,\n target: target as string,\n data: callData as string,\n msgValue: msgValue ?? 0n,\n isTwoHop: false,\n sourceA: ammName(best.source),\n sourceB: null,\n };\n }\n }\n\n await assertSwapExecutable(this.client, {\n account: recipient as Address,\n tokenIn,\n amountIn: result.amountIn,\n result,\n });\n\n return result;\n }\n}\n","/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n","// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0xE8E3d230C1c17C7249126036F170027a664d1FbA\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n","// Post-quote gas executability check (block gas limit / thin pools)\n\nimport {\n encodeAbiParameters,\n isAddressEqual,\n keccak256,\n maxUint256,\n numberToHex,\n zeroAddress,\n type Address,\n type Hex,\n type PublicClient,\n type StateOverride,\n} from \"viem\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\nimport type { QuoteResult } from \"./index.js\";\n\n/** Fraction of block.gasLimit the swap is allowed to consume (90%). */\nexport const GAS_LIMIT_BPS = 9000n;\n\n/**\n * OpenZeppelin ERC20 layout: `balanceOf` at mapping slot 0, `allowance` at 1.\n * Covers sDAI and most Seer collateral / outcome tokens.\n */\nexport function erc20BalanceSlot(owner: Address): Hex {\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 0n],\n ),\n );\n}\n\nexport function erc20AllowanceSlot(owner: Address, spender: Address): Hex {\n const inner = keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 1n],\n ),\n );\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"bytes32\" }],\n [spender, inner],\n ),\n );\n}\n\n/** stateDiff so `owner` can pay `spender` at least `amount` without a prior approve. */\nexport function erc20SpendOverride(\n token: Address,\n owner: Address,\n spender: Address,\n amount: bigint,\n): StateOverride[number] {\n const bal = amount > 0n ? amount : 1n;\n return {\n address: token,\n stateDiff: [\n { slot: erc20BalanceSlot(owner), value: numberToHex(bal, { size: 32 }) },\n {\n slot: erc20AllowanceSlot(owner, spender),\n value: numberToHex(maxUint256, { size: 32 }),\n },\n ],\n };\n}\n\nfunction isNative(token: string): boolean {\n return isAddressEqual(token as Address, zeroAddress);\n}\n\n/**\n * Builds state overrides so the router sim does not depend on a prior approve.\n * Native `tokenIn` only needs a funded account for `msg.value` + gas.\n */\nexport function buildSwapStateOverride(params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n msgValue: bigint;\n}): StateOverride {\n const { account, tokenIn, amountIn, target, msgValue } = params;\n const overrides: StateOverride = [\n {\n address: account,\n balance: msgValue + 10n ** 18n,\n },\n ];\n if (!isNative(tokenIn)) {\n overrides.push(\n erc20SpendOverride(tokenIn as Address, account, target, amountIn),\n );\n }\n return overrides;\n}\n\nfunction maxGasForBlock(gasLimit: bigint): bigint {\n return (gasLimit * GAS_LIMIT_BPS) / 10000n;\n}\n\n/**\n * After LensQuoter builds calldata, verify the swap fits in a block.\n *\n * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).\n * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.\n * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.\n * 4. If the unlimited sim fails (non-standard token storage, flaky RPC), skip\n * quietly — never false-positive as liquidity.\n */\nexport async function assertSwapExecutable(\n client: PublicClient,\n params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n result: QuoteResult;\n },\n): Promise<void> {\n const { account, tokenIn, amountIn, result } = params;\n const target = result.target as Address;\n const data = result.data as Hex;\n\n let block: { gasLimit: bigint };\n try {\n block = await client.getBlock({ blockTag: \"latest\" });\n } catch {\n return;\n }\n const maxGas = maxGasForBlock(block.gasLimit);\n if (maxGas === 0n) return;\n\n const stateOverride = buildSwapStateOverride({\n account,\n tokenIn,\n amountIn,\n target,\n msgValue: result.msgValue,\n });\n\n const base = {\n account,\n to: target,\n data,\n value: result.msgValue,\n stateOverride,\n } as const;\n\n try {\n await client.call(base);\n } catch {\n return;\n }\n\n try {\n await client.call({ ...base, gas: maxGas });\n } catch {\n throw new InsufficientLiquidityError();\n }\n\n try {\n const gas = await client.estimateGas(base);\n if (gas > maxGas) throw new InsufficientLiquidityError();\n } catch (e) {\n if (e instanceof InsufficientLiquidityError) throw e;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,IAAAA,eAAsD;;;ACG/C,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACTO,IAAK,MAAL,kBAAKC,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;AAOL,IAAM,YAAiC;AAAA,EAC5C,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,qBAAiB,GAAG;AAAA,EACrB,CAA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B,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAEA,UAAM,qBAAqB,KAAK,QAAQ;AAAA,MACtC,SAAS;AAAA,MACT;AAAA,MACA,UAAU,OAAO;AAAA,MACjB;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":["import_viem","AMM"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/errors.ts","../src/index.ts","../src/gasGuard.ts"],"sourcesContent":["// Lens SDK — client\n\nimport { parseAbi, isAddressEqual, zeroAddress } from \"viem\";\nimport type { PublicClient, Address, Abi } from \"viem\";\nimport {\n CHAINS, GNOSIS_sDAI,\n LENS_QUOTER_ABI,\n AMM_NAMES,\n defaultDeadline,\n type ChainId,\n type QuoteParams,\n type QuoteResult,\n} from \"./index.js\";\nimport { assertSwapExecutable } from \"./gasGuard.js\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\n\n// viem's parseAbi (abitype) doesn't support inline `tuple(...)` syntax,\n// so rewrite the shared quoter ABI strings to use a named struct.\nconst QUOTE_TUPLE = \"tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut)\";\nconst QUOTE_STRUCT = \"struct Quote { uint8 source; uint256 feeBps; uint256 amountIn; uint256 amountOut; }\";\n\n/** Rewrites inline `tuple(...)` quoter ABI lines to a named `Quote` struct for `parseAbi`. */\nconst toQuoterAbi = (lines: readonly string[]): Abi =>\n parseAbi([QUOTE_STRUCT, ...lines.map((l) => l.split(QUOTE_TUPLE).join(\"Quote\"))]);\n\nconst quoterAbi = toQuoterAbi(LENS_QUOTER_ABI);\n\nexport {\n ETH, GNOSIS_sDAI, AMM, AMM_NAMES,\n CHAINS,\n LENS_QUOTER_ABI, defaultDeadline,\n InsufficientLiquidityError,\n SwapRevertsError,\n} from \"./index.js\";\nexport type { QuoteResult, BaseQuoteParams, QuoteParams, ChainId } from \"./index.js\";\nexport { assertSwapExecutable } from \"./gasGuard.js\";\n\nconst DEFAULT_SLIPPAGE = 50; // 0.5%\n\ntype QuoteStruct = { source: number; feeBps: bigint; amountIn: bigint; amountOut: bigint };\ntype BestSwapResult = readonly [\n QuoteStruct,\n QuoteStruct,\n Address,\n `0x${string}`,\n bigint,\n];\ntype BuildBestSwapResult = readonly [QuoteStruct, Address, `0x${string}`, bigint, bigint];\n\n/** Resolves a human-readable AMM name from an on-chain `source` id. */\nfunction ammName(source: number): string {\n return (AMM_NAMES as Record<number, string>)[source] || `AMM #${source}`;\n}\n\n/**\n * Maps a `buildBestSwapViaETH` / `buildBestSwapViaToken` return value to `QuoteResult`.\n * Hop B is zeroed for single-hop; `b.amountOut > 0` means a real two-hop\n * route, so final `amountOut` comes from hop B.\n */\nfunction mapViaResult(value: BestSwapResult): QuoteResult {\n const [a, b, target, data, msgValue] = value;\n const isTwoHop = b.amountOut > 0n;\n return {\n amountIn: a.amountIn,\n amountOut: isTwoHop ? b.amountOut : a.amountOut,\n target: target as string,\n data: data as string,\n msgValue: msgValue ?? 0n,\n isTwoHop,\n sourceA: ammName(a.source),\n sourceB: isTwoHop ? ammName(b.source) : null,\n };\n}\n\n/**\n * True when either endpoint is native (`address(0)`) or the chain's wrapped native.\n * On non-Gnosis those pairs use ViaETH; on Gnosis they use ViaToken(sDAI).\n * Pure ERC20↔ERC20 uses `buildBestSwap`.\n */\nfunction involvesNativeOrWnative(\n tokenIn: string,\n tokenOut: string,\n wnative: Address,\n): boolean {\n return (\n isAddressEqual(tokenIn as Address, zeroAddress)\n || isAddressEqual(tokenOut as Address, zeroAddress)\n || isAddressEqual(tokenIn as Address, wnative)\n || isAddressEqual(tokenOut as Address, wnative)\n );\n}\n\n/**\n * Lens SDK client: quotes best routes via the unified on-chain LensQuoter\n * and builds ready-to-send txs for official DEX routers.\n */\nexport class Lens {\n private client: PublicClient;\n private chainId: ChainId;\n private lensQuoter: Address;\n private wnative: Address;\n private quoterAbi: Abi;\n\n /**\n * @param client - viem public client for the target chain\n * @param chainId - chain id (`1` | `10` | `100` | `8453`)\n * @param lensQuoter - optional LensQuoter address; defaults to `CHAINS[chainId].lensQuoter`\n */\n constructor(client: PublicClient, chainId: ChainId, lensQuoter?: Address) {\n this.client = client;\n this.chainId = chainId;\n const chain = CHAINS[chainId];\n this.lensQuoter = lensQuoter ?? (chain.lensQuoter as Address);\n this.wnative = chain.wnative as Address;\n this.quoterAbi = quoterAbi;\n }\n\n /**\n * Builds calldata for a two-hop (or one-hop if mid is unused) route via a\n * mid token — used when the caller sets `intermediate`, or as the default\n * Gnosis path for native/WXDAI↔ERC20 (`mid = GNOSIS_sDAI`).\n */\n private async viaToken(\n params: {\n recipient: string;\n exactOut: boolean;\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n slippageBps: number;\n deadline: bigint;\n hookPoolFee: number;\n hookTickSpacing: number;\n hookAddress: string;\n mid: string;\n },\n ): Promise<BestSwapResult> {\n return this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaToken\",\n args: [\n params.recipient as Address,\n params.exactOut,\n params.tokenIn as Address,\n params.tokenOut as Address,\n params.amount,\n BigInt(params.slippageBps),\n params.deadline,\n params.hookPoolFee,\n params.hookTickSpacing,\n params.hookAddress as Address,\n params.mid as Address,\n ],\n }) as Promise<BestSwapResult>;\n }\n\n /**\n * Finds a swap route via LensQuoter and returns amounts plus ready-to-send\n * calldata for an official DEX router.\n *\n * Route selection by request shape:\n * - `intermediate` set → `buildBestSwapViaToken(mid)` only\n * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;\n * elsewhere `buildBestSwapViaETH`\n * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)\n *\n * After building calldata, simulates the swap with a gas cap of 90% of\n * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw\n * {@link InsufficientLiquidityError}.\n */\n async quote(params: QuoteParams): Promise<QuoteResult> {\n const {\n tokenIn, tokenOut, amount, recipient,\n slippageBps = DEFAULT_SLIPPAGE, deadline = defaultDeadline(),\n exactOut = false,\n hookPoolFee = 0, hookTickSpacing = 0, hookAddress = zeroAddress,\n intermediate,\n } = params;\n\n const routeArgs = {\n recipient, exactOut, tokenIn, tokenOut, amount,\n slippageBps, deadline, hookPoolFee, hookTickSpacing, hookAddress,\n };\n\n let result: QuoteResult;\n\n // Caller forced a mid token: skip native/ERC20 cascade.\n if (intermediate) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));\n } else {\n const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);\n\n if (useViaEth) {\n // Gnosis (Seer): outcomes trade vs sDAI — skip ViaETH entirely.\n if (this.chainId === 100) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));\n } else {\n // Other chains: single-hop ViaETH (router wrap/unwrap).\n const value = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaETH\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BestSwapResult;\n result = mapViaResult(value);\n }\n } else {\n // Pure ERC20 ↔ ERC20: direct single-hop only (optional V4 hooked candidate).\n const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwap\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BuildBestSwapResult;\n\n result = {\n amountIn: best.amountIn,\n amountOut: best.amountOut,\n target: target as string,\n data: callData as string,\n msgValue: msgValue ?? 0n,\n isTwoHop: false,\n sourceA: ammName(best.source),\n sourceB: null,\n };\n }\n }\n\n await assertSwapExecutable(this.client, {\n account: recipient as Address,\n tokenIn,\n amountIn: result.amountIn,\n result,\n });\n\n return result;\n }\n}\n","/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n\n/**\n * Thrown when the pre-flight simulation shows the built calldata reverts, and the\n * state overrides that make it executable are confirmed to have applied — so the\n * revert is the router's, not an artifact of the simulation.\n *\n * Sending such a swap would waste gas and surface as an opaque wallet failure.\n */\nexport class SwapRevertsError extends Error {\n readonly code = \"SWAP_REVERTS\" as const;\n\n constructor(\n options?: { cause?: unknown; detail?: string },\n message = \"Swap simulation reverted; the router rejected the built calldata.\",\n ) {\n super(options?.detail ? `${message} (${options.detail})` : message, {\n cause: options?.cause,\n });\n this.name = \"SwapRevertsError\";\n }\n}\n","// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.\n \"error NoRoute()\",\n \"error ZeroAmount()\",\n \"error UnsupportedAMM()\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0x82150d38288e53AfcF20a5eEee47682c5Ef796d8\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError, SwapRevertsError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n","// Post-quote gas executability check (block gas limit / thin pools)\n\nimport {\n encodeAbiParameters,\n isAddressEqual,\n keccak256,\n maxUint256,\n numberToHex,\n zeroAddress,\n type Address,\n type Hex,\n type PublicClient,\n type StateOverride,\n} from \"viem\";\nimport { InsufficientLiquidityError, SwapRevertsError } from \"./errors.js\";\nimport type { QuoteResult } from \"./index.js\";\n\n/** Fraction of block.gasLimit the swap is allowed to consume (90%). */\nexport const GAS_LIMIT_BPS = 9000n;\n\n/**\n * OpenZeppelin ERC20 layout: `balanceOf` at mapping slot 0, `allowance` at 1.\n * Covers sDAI and most Seer collateral / outcome tokens.\n */\nexport function erc20BalanceSlot(owner: Address): Hex {\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 0n],\n ),\n );\n}\n\nexport function erc20AllowanceSlot(owner: Address, spender: Address): Hex {\n const inner = keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 1n],\n ),\n );\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"bytes32\" }],\n [spender, inner],\n ),\n );\n}\n\n/** stateDiff so `owner` can pay `spender` at least `amount` without a prior approve. */\nexport function erc20SpendOverride(\n token: Address,\n owner: Address,\n spender: Address,\n amount: bigint,\n): StateOverride[number] {\n const bal = amount > 0n ? amount : 1n;\n return {\n address: token,\n stateDiff: [\n { slot: erc20BalanceSlot(owner), value: numberToHex(bal, { size: 32 }) },\n {\n slot: erc20AllowanceSlot(owner, spender),\n value: numberToHex(maxUint256, { size: 32 }),\n },\n ],\n };\n}\n\nfunction isNative(token: string): boolean {\n return isAddressEqual(token as Address, zeroAddress);\n}\n\n/**\n * Builds state overrides so the router sim does not depend on a prior approve.\n * Native `tokenIn` only needs a funded account for `msg.value` + gas.\n */\nexport function buildSwapStateOverride(params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n msgValue: bigint;\n}): StateOverride {\n const { account, tokenIn, amountIn, target, msgValue } = params;\n const overrides: StateOverride = [\n {\n address: account,\n balance: msgValue + 10n ** 18n,\n },\n ];\n if (!isNative(tokenIn)) {\n overrides.push(\n erc20SpendOverride(tokenIn as Address, account, target, amountIn),\n );\n }\n return overrides;\n}\n\nfunction maxGasForBlock(gasLimit: bigint): bigint {\n return (gasLimit * GAS_LIMIT_BPS) / 10000n;\n}\n\n/** Scratch address for the override-support probe; holds no real code on any chain. */\nconst PROBE_ADDRESS = \"0x0000000000000000000000000000000000f0f0f0\" as const;\n/** Runtime that returns uint256(1): PUSH1 01, PUSH1 00, MSTORE, PUSH1 20, PUSH1 00, RETURN. */\nconst PROBE_CODE = \"0x600160005260206000f3\" as const;\nconst ONE_WORD = numberToHex(1n, { size: 32 });\n\nconst BALANCE_OF_SELECTOR = \"0x70a08231\";\nconst ALLOWANCE_SELECTOR = \"0xdd62ed3e\";\n\nfunction encodeAddressArgs(...args: Address[]): Hex {\n return encodeAbiParameters(\n args.map(() => ({ type: \"address\" }) as const),\n args,\n );\n}\n\n/** `true` when the node applied our `code` override — i.e. it honours state overrides at all. */\nasync function nodeAppliesStateOverrides(client: PublicClient): Promise<boolean> {\n try {\n const res = await client.call({\n to: PROBE_ADDRESS,\n data: \"0x\",\n stateOverride: [{ address: PROBE_ADDRESS, code: PROBE_CODE }],\n });\n return res.data === ONE_WORD;\n } catch {\n return false;\n }\n}\n\nasync function readWord(\n client: PublicClient,\n to: Address,\n data: Hex,\n stateOverride: StateOverride,\n): Promise<Hex | undefined> {\n try {\n const res = await client.call({ to, data, stateOverride });\n return res.data;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Confirms the overrides that make the swap payable actually took effect.\n *\n * `erc20SpendOverride` guesses the OpenZeppelin storage layout (balances in slot 0,\n * allowances in slot 1). For a token that lays its storage out differently the\n * injected balance/allowance never lands, and the swap then reverts for reasons that\n * have nothing to do with the router — so we must not blame the calldata.\n */\nasync function swapOverridesApplied(params: {\n client: PublicClient;\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n stateOverride: StateOverride;\n}): Promise<boolean> {\n const { client, account, tokenIn, amountIn, target, stateOverride } = params;\n\n if (!(await nodeAppliesStateOverrides(client))) return false;\n if (isNative(tokenIn)) return true; // only the plain `balance` override is involved\n\n const token = tokenIn as Address;\n const expectedBalance = numberToHex(amountIn > 0n ? amountIn : 1n, { size: 32 });\n\n const balance = await readWord(\n client,\n token,\n `${BALANCE_OF_SELECTOR}${encodeAddressArgs(account).slice(2)}`,\n stateOverride,\n );\n if (balance !== expectedBalance) return false;\n\n const allowance = await readWord(\n client,\n token,\n `${ALLOWANCE_SELECTOR}${encodeAddressArgs(account, target).slice(2)}`,\n stateOverride,\n );\n return allowance === numberToHex(maxUint256, { size: 32 });\n}\n\nfunction revertDetail(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined;\n const short = (error as { shortMessage?: string }).shortMessage;\n return (short ?? error.message).split(\"\\n\")[0]?.trim() || undefined;\n}\n\n/**\n * After LensQuoter builds calldata, verify the swap fits in a block.\n *\n * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).\n * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.\n * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.\n * 4. If the unlimited sim reverts, re-check that the overrides applied. If they\n * did, the router really rejects the calldata → {@link SwapRevertsError}. If\n * they did not (non-standard token storage, RPC without state overrides), skip\n * quietly — never false-positive as liquidity.\n */\nexport async function assertSwapExecutable(\n client: PublicClient,\n params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n result: QuoteResult;\n },\n): Promise<void> {\n const { account, tokenIn, amountIn, result } = params;\n const target = result.target as Address;\n const data = result.data as Hex;\n\n let block: { gasLimit: bigint };\n try {\n block = await client.getBlock({ blockTag: \"latest\" });\n } catch {\n return;\n }\n const maxGas = maxGasForBlock(block.gasLimit);\n if (maxGas === 0n) return;\n\n const stateOverride = buildSwapStateOverride({\n account,\n tokenIn,\n amountIn,\n target,\n msgValue: result.msgValue,\n });\n\n const base = {\n account,\n to: target,\n data,\n value: result.msgValue,\n stateOverride,\n } as const;\n\n try {\n await client.call(base);\n } catch (e) {\n const applied = await swapOverridesApplied({\n client,\n account,\n tokenIn,\n amountIn,\n target,\n stateOverride,\n });\n if (!applied) return;\n throw new SwapRevertsError({ cause: e, detail: revertDetail(e) });\n }\n\n try {\n await client.call({ ...base, gas: maxGas });\n } catch {\n throw new InsufficientLiquidityError();\n }\n\n try {\n const gas = await client.estimateGas(base);\n if (gas > maxGas) throw new InsufficientLiquidityError();\n } catch (e) {\n if (e instanceof InsufficientLiquidityError) throw e;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,IAAAA,eAAsD;;;ACG/C,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AASO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC,OAAO;AAAA,EAEhB,YACE,SACA,UAAU,qEACV;AACA,UAAM,SAAS,SAAS,GAAG,OAAO,KAAK,QAAQ,MAAM,MAAM,SAAS;AAAA,MAClE,OAAO,SAAS;AAAA,IAClB,CAAC;AACD,SAAK,OAAO;AAAA,EACd;AACF;;;AC9BO,IAAK,MAAL,kBAAKC,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;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AAAA,cACpB;AAAA,cAAQ,OAAO,WAAW;AAAA,cAAG;AAAA,cAC7B;AAAA,cAAa;AAAA,cAAiB;AAAA,YAChC;AAAA,UACF,CAAC;AACD,mBAAS,aAAa,KAAK;AAAA,QAC7B;AAAA,MACF,OAAO;AAEL,cAAM,CAAC,MAAM,QAAQ,UAAU,cAAc,QAAQ,IAAI,MAAM,KAAK,OAAO,aAAa;AAAA,UACtF,SAAS,KAAK;AAAA,UACd,KAAK,KAAK;AAAA,UACV,cAAc;AAAA,UACd,MAAM;AAAA,YACJ;AAAA,YAAsB;AAAA,YACtB;AAAA,YAAoB;AAAA,YACpB;AAAA,YAAQ,OAAO,WAAW;AAAA,YAAG;AAAA,YAC7B;AAAA,YAAa;AAAA,YAAiB;AAAA,UAChC;AAAA,QACF,CAAC;AAED,iBAAS;AAAA,UACP,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB;AAAA,UACA,MAAM;AAAA,UACN,UAAU,YAAY;AAAA,UACtB,UAAU;AAAA,UACV,SAAS,QAAQ,KAAK,MAAM;AAAA,UAC5B,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAEA,UAAM,qBAAqB,KAAK,QAAQ;AAAA,MACtC,SAAS;AAAA,MACT;AAAA,MACA,UAAU,OAAO;AAAA,MACjB;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":["import_viem","AMM"]}
package/dist/client.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PublicClient, Address } from 'viem';
2
2
  import { QuoteResult, ChainId, QuoteParams } from './index.cjs';
3
- export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, defaultDeadline } from './index.cjs';
3
+ export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, SwapRevertsError, defaultDeadline } from './index.cjs';
4
4
 
5
5
  /**
6
6
  * After LensQuoter builds calldata, verify the swap fits in a block.
@@ -8,7 +8,9 @@ export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, Insufficient
8
8
  * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).
9
9
  * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.
10
10
  * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.
11
- * 4. If the unlimited sim fails (non-standard token storage, flaky RPC), skip
11
+ * 4. If the unlimited sim reverts, re-check that the overrides applied. If they
12
+ * did, the router really rejects the calldata → {@link SwapRevertsError}. If
13
+ * they did not (non-standard token storage, RPC without state overrides), skip
12
14
  * quietly — never false-positive as liquidity.
13
15
  */
14
16
  declare function assertSwapExecutable(client: PublicClient, params: {
package/dist/client.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PublicClient, Address } from 'viem';
2
2
  import { QuoteResult, ChainId, QuoteParams } from './index.js';
3
- export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, defaultDeadline } from './index.js';
3
+ export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, SwapRevertsError, defaultDeadline } from './index.js';
4
4
 
5
5
  /**
6
6
  * After LensQuoter builds calldata, verify the swap fits in a block.
@@ -8,7 +8,9 @@ export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, Insufficient
8
8
  * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).
9
9
  * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.
10
10
  * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.
11
- * 4. If the unlimited sim fails (non-standard token storage, flaky RPC), skip
11
+ * 4. If the unlimited sim reverts, re-check that the overrides applied. If they
12
+ * did, the router really rejects the calldata → {@link SwapRevertsError}. If
13
+ * they did not (non-standard token storage, RPC without state overrides), skip
12
14
  * quietly — never false-positive as liquidity.
13
15
  */
14
16
  declare function assertSwapExecutable(client: PublicClient, params: {
package/dist/client.js CHANGED
@@ -6,8 +6,9 @@ import {
6
6
  GNOSIS_sDAI,
7
7
  InsufficientLiquidityError,
8
8
  LENS_QUOTER_ABI,
9
+ SwapRevertsError,
9
10
  defaultDeadline
10
- } from "./chunk-5UNFCMSF.js";
11
+ } from "./chunk-M4WEBPX7.js";
11
12
 
12
13
  // src/client.ts
13
14
  import { parseAbi, isAddressEqual as isAddressEqual2, zeroAddress as zeroAddress2 } from "viem";
@@ -78,6 +79,63 @@ function buildSwapStateOverride(params) {
78
79
  function maxGasForBlock(gasLimit) {
79
80
  return gasLimit * GAS_LIMIT_BPS / 10000n;
80
81
  }
82
+ var PROBE_ADDRESS = "0x0000000000000000000000000000000000f0f0f0";
83
+ var PROBE_CODE = "0x600160005260206000f3";
84
+ var ONE_WORD = numberToHex(1n, { size: 32 });
85
+ var BALANCE_OF_SELECTOR = "0x70a08231";
86
+ var ALLOWANCE_SELECTOR = "0xdd62ed3e";
87
+ function encodeAddressArgs(...args) {
88
+ return encodeAbiParameters(
89
+ args.map(() => ({ type: "address" })),
90
+ args
91
+ );
92
+ }
93
+ async function nodeAppliesStateOverrides(client) {
94
+ try {
95
+ const res = await client.call({
96
+ to: PROBE_ADDRESS,
97
+ data: "0x",
98
+ stateOverride: [{ address: PROBE_ADDRESS, code: PROBE_CODE }]
99
+ });
100
+ return res.data === ONE_WORD;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+ async function readWord(client, to, data, stateOverride) {
106
+ try {
107
+ const res = await client.call({ to, data, stateOverride });
108
+ return res.data;
109
+ } catch {
110
+ return void 0;
111
+ }
112
+ }
113
+ async function swapOverridesApplied(params) {
114
+ const { client, account, tokenIn, amountIn, target, stateOverride } = params;
115
+ if (!await nodeAppliesStateOverrides(client)) return false;
116
+ if (isNative(tokenIn)) return true;
117
+ const token = tokenIn;
118
+ const expectedBalance = numberToHex(amountIn > 0n ? amountIn : 1n, { size: 32 });
119
+ const balance = await readWord(
120
+ client,
121
+ token,
122
+ `${BALANCE_OF_SELECTOR}${encodeAddressArgs(account).slice(2)}`,
123
+ stateOverride
124
+ );
125
+ if (balance !== expectedBalance) return false;
126
+ const allowance = await readWord(
127
+ client,
128
+ token,
129
+ `${ALLOWANCE_SELECTOR}${encodeAddressArgs(account, target).slice(2)}`,
130
+ stateOverride
131
+ );
132
+ return allowance === numberToHex(maxUint256, { size: 32 });
133
+ }
134
+ function revertDetail(error) {
135
+ if (!(error instanceof Error)) return void 0;
136
+ const short = error.shortMessage;
137
+ return (short ?? error.message).split("\n")[0]?.trim() || void 0;
138
+ }
81
139
  async function assertSwapExecutable(client, params) {
82
140
  const { account, tokenIn, amountIn, result } = params;
83
141
  const target = result.target;
@@ -106,8 +164,17 @@ async function assertSwapExecutable(client, params) {
106
164
  };
107
165
  try {
108
166
  await client.call(base);
109
- } catch {
110
- return;
167
+ } catch (e) {
168
+ const applied = await swapOverridesApplied({
169
+ client,
170
+ account,
171
+ tokenIn,
172
+ amountIn,
173
+ target,
174
+ stateOverride
175
+ });
176
+ if (!applied) return;
177
+ throw new SwapRevertsError({ cause: e, detail: revertDetail(e) });
111
178
  }
112
179
  try {
113
180
  await client.call({ ...base, gas: maxGas });
@@ -308,6 +375,7 @@ export {
308
375
  InsufficientLiquidityError,
309
376
  LENS_QUOTER_ABI,
310
377
  Lens,
378
+ SwapRevertsError,
311
379
  assertSwapExecutable,
312
380
  defaultDeadline
313
381
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/gasGuard.ts"],"sourcesContent":["// Lens SDK — client\n\nimport { parseAbi, isAddressEqual, zeroAddress } from \"viem\";\nimport type { PublicClient, Address, Abi } from \"viem\";\nimport {\n CHAINS, GNOSIS_sDAI,\n LENS_QUOTER_ABI,\n AMM_NAMES,\n defaultDeadline,\n type ChainId,\n type QuoteParams,\n type QuoteResult,\n} from \"./index.js\";\nimport { assertSwapExecutable } from \"./gasGuard.js\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\n\n// viem's parseAbi (abitype) doesn't support inline `tuple(...)` syntax,\n// so rewrite the shared quoter ABI strings to use a named struct.\nconst QUOTE_TUPLE = \"tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut)\";\nconst QUOTE_STRUCT = \"struct Quote { uint8 source; uint256 feeBps; uint256 amountIn; uint256 amountOut; }\";\n\n/** Rewrites inline `tuple(...)` quoter ABI lines to a named `Quote` struct for `parseAbi`. */\nconst toQuoterAbi = (lines: readonly string[]): Abi =>\n parseAbi([QUOTE_STRUCT, ...lines.map((l) => l.split(QUOTE_TUPLE).join(\"Quote\"))]);\n\nconst quoterAbi = toQuoterAbi(LENS_QUOTER_ABI);\n\nexport {\n ETH, GNOSIS_sDAI, AMM, AMM_NAMES,\n CHAINS,\n LENS_QUOTER_ABI, defaultDeadline,\n InsufficientLiquidityError,\n} from \"./index.js\";\nexport type { QuoteResult, BaseQuoteParams, QuoteParams, ChainId } from \"./index.js\";\nexport { assertSwapExecutable } from \"./gasGuard.js\";\n\nconst DEFAULT_SLIPPAGE = 50; // 0.5%\n\ntype QuoteStruct = { source: number; feeBps: bigint; amountIn: bigint; amountOut: bigint };\ntype BestSwapResult = readonly [\n QuoteStruct,\n QuoteStruct,\n Address,\n `0x${string}`,\n bigint,\n];\ntype BuildBestSwapResult = readonly [QuoteStruct, Address, `0x${string}`, bigint, bigint];\n\n/** Resolves a human-readable AMM name from an on-chain `source` id. */\nfunction ammName(source: number): string {\n return (AMM_NAMES as Record<number, string>)[source] || `AMM #${source}`;\n}\n\n/**\n * Maps a `buildBestSwapViaETH` / `buildBestSwapViaToken` return value to `QuoteResult`.\n * Hop B is zeroed for single-hop; `b.amountOut > 0` means a real two-hop\n * route, so final `amountOut` comes from hop B.\n */\nfunction mapViaResult(value: BestSwapResult): QuoteResult {\n const [a, b, target, data, msgValue] = value;\n const isTwoHop = b.amountOut > 0n;\n return {\n amountIn: a.amountIn,\n amountOut: isTwoHop ? b.amountOut : a.amountOut,\n target: target as string,\n data: data as string,\n msgValue: msgValue ?? 0n,\n isTwoHop,\n sourceA: ammName(a.source),\n sourceB: isTwoHop ? ammName(b.source) : null,\n };\n}\n\n/**\n * True when either endpoint is native (`address(0)`) or the chain's wrapped native.\n * On non-Gnosis those pairs use ViaETH; on Gnosis they use ViaToken(sDAI).\n * Pure ERC20↔ERC20 uses `buildBestSwap`.\n */\nfunction involvesNativeOrWnative(\n tokenIn: string,\n tokenOut: string,\n wnative: Address,\n): boolean {\n return (\n isAddressEqual(tokenIn as Address, zeroAddress)\n || isAddressEqual(tokenOut as Address, zeroAddress)\n || isAddressEqual(tokenIn as Address, wnative)\n || isAddressEqual(tokenOut as Address, wnative)\n );\n}\n\n/**\n * Lens SDK client: quotes best routes via the unified on-chain LensQuoter\n * and builds ready-to-send txs for official DEX routers.\n */\nexport class Lens {\n private client: PublicClient;\n private chainId: ChainId;\n private lensQuoter: Address;\n private wnative: Address;\n private quoterAbi: Abi;\n\n /**\n * @param client - viem public client for the target chain\n * @param chainId - chain id (`1` | `10` | `100` | `8453`)\n * @param lensQuoter - optional LensQuoter address; defaults to `CHAINS[chainId].lensQuoter`\n */\n constructor(client: PublicClient, chainId: ChainId, lensQuoter?: Address) {\n this.client = client;\n this.chainId = chainId;\n const chain = CHAINS[chainId];\n this.lensQuoter = lensQuoter ?? (chain.lensQuoter as Address);\n this.wnative = chain.wnative as Address;\n this.quoterAbi = quoterAbi;\n }\n\n /**\n * Builds calldata for a two-hop (or one-hop if mid is unused) route via a\n * mid token — used when the caller sets `intermediate`, or as the default\n * Gnosis path for native/WXDAI↔ERC20 (`mid = GNOSIS_sDAI`).\n */\n private async viaToken(\n params: {\n recipient: string;\n exactOut: boolean;\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n slippageBps: number;\n deadline: bigint;\n hookPoolFee: number;\n hookTickSpacing: number;\n hookAddress: string;\n mid: string;\n },\n ): Promise<BestSwapResult> {\n return this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaToken\",\n args: [\n params.recipient as Address,\n params.exactOut,\n params.tokenIn as Address,\n params.tokenOut as Address,\n params.amount,\n BigInt(params.slippageBps),\n params.deadline,\n params.hookPoolFee,\n params.hookTickSpacing,\n params.hookAddress as Address,\n params.mid as Address,\n ],\n }) as Promise<BestSwapResult>;\n }\n\n /**\n * Finds a swap route via LensQuoter and returns amounts plus ready-to-send\n * calldata for an official DEX router.\n *\n * Route selection by request shape:\n * - `intermediate` set → `buildBestSwapViaToken(mid)` only\n * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;\n * elsewhere `buildBestSwapViaETH`\n * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)\n *\n * After building calldata, simulates the swap with a gas cap of 90% of\n * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw\n * {@link InsufficientLiquidityError}.\n */\n async quote(params: QuoteParams): Promise<QuoteResult> {\n const {\n tokenIn, tokenOut, amount, recipient,\n slippageBps = DEFAULT_SLIPPAGE, deadline = defaultDeadline(),\n exactOut = false,\n hookPoolFee = 0, hookTickSpacing = 0, hookAddress = zeroAddress,\n intermediate,\n } = params;\n\n const routeArgs = {\n recipient, exactOut, tokenIn, tokenOut, amount,\n slippageBps, deadline, hookPoolFee, hookTickSpacing, hookAddress,\n };\n\n let result: QuoteResult;\n\n // Caller forced a mid token: skip native/ERC20 cascade.\n if (intermediate) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));\n } else {\n const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);\n\n if (useViaEth) {\n // Gnosis (Seer): outcomes trade vs sDAI — skip ViaETH entirely.\n if (this.chainId === 100) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));\n } else {\n // Other chains: single-hop ViaETH (router wrap/unwrap).\n const value = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaETH\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BestSwapResult;\n result = mapViaResult(value);\n }\n } else {\n // Pure ERC20 ↔ ERC20: direct single-hop only (optional V4 hooked candidate).\n const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwap\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BuildBestSwapResult;\n\n result = {\n amountIn: best.amountIn,\n amountOut: best.amountOut,\n target: target as string,\n data: callData as string,\n msgValue: msgValue ?? 0n,\n isTwoHop: false,\n sourceA: ammName(best.source),\n sourceB: null,\n };\n }\n }\n\n await assertSwapExecutable(this.client, {\n account: recipient as Address,\n tokenIn,\n amountIn: result.amountIn,\n result,\n });\n\n return result;\n }\n}\n","// Post-quote gas executability check (block gas limit / thin pools)\n\nimport {\n encodeAbiParameters,\n isAddressEqual,\n keccak256,\n maxUint256,\n numberToHex,\n zeroAddress,\n type Address,\n type Hex,\n type PublicClient,\n type StateOverride,\n} from \"viem\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\nimport type { QuoteResult } from \"./index.js\";\n\n/** Fraction of block.gasLimit the swap is allowed to consume (90%). */\nexport const GAS_LIMIT_BPS = 9000n;\n\n/**\n * OpenZeppelin ERC20 layout: `balanceOf` at mapping slot 0, `allowance` at 1.\n * Covers sDAI and most Seer collateral / outcome tokens.\n */\nexport function erc20BalanceSlot(owner: Address): Hex {\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 0n],\n ),\n );\n}\n\nexport function erc20AllowanceSlot(owner: Address, spender: Address): Hex {\n const inner = keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 1n],\n ),\n );\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"bytes32\" }],\n [spender, inner],\n ),\n );\n}\n\n/** stateDiff so `owner` can pay `spender` at least `amount` without a prior approve. */\nexport function erc20SpendOverride(\n token: Address,\n owner: Address,\n spender: Address,\n amount: bigint,\n): StateOverride[number] {\n const bal = amount > 0n ? amount : 1n;\n return {\n address: token,\n stateDiff: [\n { slot: erc20BalanceSlot(owner), value: numberToHex(bal, { size: 32 }) },\n {\n slot: erc20AllowanceSlot(owner, spender),\n value: numberToHex(maxUint256, { size: 32 }),\n },\n ],\n };\n}\n\nfunction isNative(token: string): boolean {\n return isAddressEqual(token as Address, zeroAddress);\n}\n\n/**\n * Builds state overrides so the router sim does not depend on a prior approve.\n * Native `tokenIn` only needs a funded account for `msg.value` + gas.\n */\nexport function buildSwapStateOverride(params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n msgValue: bigint;\n}): StateOverride {\n const { account, tokenIn, amountIn, target, msgValue } = params;\n const overrides: StateOverride = [\n {\n address: account,\n balance: msgValue + 10n ** 18n,\n },\n ];\n if (!isNative(tokenIn)) {\n overrides.push(\n erc20SpendOverride(tokenIn as Address, account, target, amountIn),\n );\n }\n return overrides;\n}\n\nfunction maxGasForBlock(gasLimit: bigint): bigint {\n return (gasLimit * GAS_LIMIT_BPS) / 10000n;\n}\n\n/**\n * After LensQuoter builds calldata, verify the swap fits in a block.\n *\n * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).\n * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.\n * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.\n * 4. If the unlimited sim fails (non-standard token storage, flaky RPC), skip\n * quietly — never false-positive as liquidity.\n */\nexport async function assertSwapExecutable(\n client: PublicClient,\n params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n result: QuoteResult;\n },\n): Promise<void> {\n const { account, tokenIn, amountIn, result } = params;\n const target = result.target as Address;\n const data = result.data as Hex;\n\n let block: { gasLimit: bigint };\n try {\n block = await client.getBlock({ blockTag: \"latest\" });\n } catch {\n return;\n }\n const maxGas = maxGasForBlock(block.gasLimit);\n if (maxGas === 0n) return;\n\n const stateOverride = buildSwapStateOverride({\n account,\n tokenIn,\n amountIn,\n target,\n msgValue: result.msgValue,\n });\n\n const base = {\n account,\n to: target,\n data,\n value: result.msgValue,\n stateOverride,\n } as const;\n\n try {\n await client.call(base);\n } catch {\n return;\n }\n\n try {\n await client.call({ ...base, gas: maxGas });\n } catch {\n throw new InsufficientLiquidityError();\n }\n\n try {\n const gas = await client.estimateGas(base);\n if (gas > maxGas) throw new InsufficientLiquidityError();\n } catch (e) {\n if (e instanceof InsufficientLiquidityError) throw e;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAEA,SAAS,UAAU,kBAAAA,iBAAgB,eAAAC,oBAAmB;;;ACAtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAKA,IAAM,gBAAgB;AAMtB,SAAS,iBAAiB,OAAqB;AACpD,SAAO;AAAA,IACL;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,OAAO,EAAE;AAAA,IACZ;AAAA,EACF;AACF;AAEO,SAAS,mBAAmB,OAAgB,SAAuB;AACxE,QAAM,QAAQ;AAAA,IACZ;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,OAAO,EAAE;AAAA,IACZ;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,SAAS,KAAK;AAAA,IACjB;A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EA,UAAM,qBAAqB,KAAK,QAAQ;AAAA,MACtC,SAAS;AAAA,MACT;AAAA,MACA,UAAU,OAAO;AAAA,MACjB;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":["isAddressEqual","zeroAddress","isAddressEqual","zeroAddress"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/gasGuard.ts"],"sourcesContent":["// Lens SDK — client\n\nimport { parseAbi, isAddressEqual, zeroAddress } from \"viem\";\nimport type { PublicClient, Address, Abi } from \"viem\";\nimport {\n CHAINS, GNOSIS_sDAI,\n LENS_QUOTER_ABI,\n AMM_NAMES,\n defaultDeadline,\n type ChainId,\n type QuoteParams,\n type QuoteResult,\n} from \"./index.js\";\nimport { assertSwapExecutable } from \"./gasGuard.js\";\nimport { InsufficientLiquidityError } from \"./errors.js\";\n\n// viem's parseAbi (abitype) doesn't support inline `tuple(...)` syntax,\n// so rewrite the shared quoter ABI strings to use a named struct.\nconst QUOTE_TUPLE = \"tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut)\";\nconst QUOTE_STRUCT = \"struct Quote { uint8 source; uint256 feeBps; uint256 amountIn; uint256 amountOut; }\";\n\n/** Rewrites inline `tuple(...)` quoter ABI lines to a named `Quote` struct for `parseAbi`. */\nconst toQuoterAbi = (lines: readonly string[]): Abi =>\n parseAbi([QUOTE_STRUCT, ...lines.map((l) => l.split(QUOTE_TUPLE).join(\"Quote\"))]);\n\nconst quoterAbi = toQuoterAbi(LENS_QUOTER_ABI);\n\nexport {\n ETH, GNOSIS_sDAI, AMM, AMM_NAMES,\n CHAINS,\n LENS_QUOTER_ABI, defaultDeadline,\n InsufficientLiquidityError,\n SwapRevertsError,\n} from \"./index.js\";\nexport type { QuoteResult, BaseQuoteParams, QuoteParams, ChainId } from \"./index.js\";\nexport { assertSwapExecutable } from \"./gasGuard.js\";\n\nconst DEFAULT_SLIPPAGE = 50; // 0.5%\n\ntype QuoteStruct = { source: number; feeBps: bigint; amountIn: bigint; amountOut: bigint };\ntype BestSwapResult = readonly [\n QuoteStruct,\n QuoteStruct,\n Address,\n `0x${string}`,\n bigint,\n];\ntype BuildBestSwapResult = readonly [QuoteStruct, Address, `0x${string}`, bigint, bigint];\n\n/** Resolves a human-readable AMM name from an on-chain `source` id. */\nfunction ammName(source: number): string {\n return (AMM_NAMES as Record<number, string>)[source] || `AMM #${source}`;\n}\n\n/**\n * Maps a `buildBestSwapViaETH` / `buildBestSwapViaToken` return value to `QuoteResult`.\n * Hop B is zeroed for single-hop; `b.amountOut > 0` means a real two-hop\n * route, so final `amountOut` comes from hop B.\n */\nfunction mapViaResult(value: BestSwapResult): QuoteResult {\n const [a, b, target, data, msgValue] = value;\n const isTwoHop = b.amountOut > 0n;\n return {\n amountIn: a.amountIn,\n amountOut: isTwoHop ? b.amountOut : a.amountOut,\n target: target as string,\n data: data as string,\n msgValue: msgValue ?? 0n,\n isTwoHop,\n sourceA: ammName(a.source),\n sourceB: isTwoHop ? ammName(b.source) : null,\n };\n}\n\n/**\n * True when either endpoint is native (`address(0)`) or the chain's wrapped native.\n * On non-Gnosis those pairs use ViaETH; on Gnosis they use ViaToken(sDAI).\n * Pure ERC20↔ERC20 uses `buildBestSwap`.\n */\nfunction involvesNativeOrWnative(\n tokenIn: string,\n tokenOut: string,\n wnative: Address,\n): boolean {\n return (\n isAddressEqual(tokenIn as Address, zeroAddress)\n || isAddressEqual(tokenOut as Address, zeroAddress)\n || isAddressEqual(tokenIn as Address, wnative)\n || isAddressEqual(tokenOut as Address, wnative)\n );\n}\n\n/**\n * Lens SDK client: quotes best routes via the unified on-chain LensQuoter\n * and builds ready-to-send txs for official DEX routers.\n */\nexport class Lens {\n private client: PublicClient;\n private chainId: ChainId;\n private lensQuoter: Address;\n private wnative: Address;\n private quoterAbi: Abi;\n\n /**\n * @param client - viem public client for the target chain\n * @param chainId - chain id (`1` | `10` | `100` | `8453`)\n * @param lensQuoter - optional LensQuoter address; defaults to `CHAINS[chainId].lensQuoter`\n */\n constructor(client: PublicClient, chainId: ChainId, lensQuoter?: Address) {\n this.client = client;\n this.chainId = chainId;\n const chain = CHAINS[chainId];\n this.lensQuoter = lensQuoter ?? (chain.lensQuoter as Address);\n this.wnative = chain.wnative as Address;\n this.quoterAbi = quoterAbi;\n }\n\n /**\n * Builds calldata for a two-hop (or one-hop if mid is unused) route via a\n * mid token — used when the caller sets `intermediate`, or as the default\n * Gnosis path for native/WXDAI↔ERC20 (`mid = GNOSIS_sDAI`).\n */\n private async viaToken(\n params: {\n recipient: string;\n exactOut: boolean;\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n slippageBps: number;\n deadline: bigint;\n hookPoolFee: number;\n hookTickSpacing: number;\n hookAddress: string;\n mid: string;\n },\n ): Promise<BestSwapResult> {\n return this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaToken\",\n args: [\n params.recipient as Address,\n params.exactOut,\n params.tokenIn as Address,\n params.tokenOut as Address,\n params.amount,\n BigInt(params.slippageBps),\n params.deadline,\n params.hookPoolFee,\n params.hookTickSpacing,\n params.hookAddress as Address,\n params.mid as Address,\n ],\n }) as Promise<BestSwapResult>;\n }\n\n /**\n * Finds a swap route via LensQuoter and returns amounts plus ready-to-send\n * calldata for an official DEX router.\n *\n * Route selection by request shape:\n * - `intermediate` set → `buildBestSwapViaToken(mid)` only\n * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;\n * elsewhere `buildBestSwapViaETH`\n * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)\n *\n * After building calldata, simulates the swap with a gas cap of 90% of\n * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw\n * {@link InsufficientLiquidityError}.\n */\n async quote(params: QuoteParams): Promise<QuoteResult> {\n const {\n tokenIn, tokenOut, amount, recipient,\n slippageBps = DEFAULT_SLIPPAGE, deadline = defaultDeadline(),\n exactOut = false,\n hookPoolFee = 0, hookTickSpacing = 0, hookAddress = zeroAddress,\n intermediate,\n } = params;\n\n const routeArgs = {\n recipient, exactOut, tokenIn, tokenOut, amount,\n slippageBps, deadline, hookPoolFee, hookTickSpacing, hookAddress,\n };\n\n let result: QuoteResult;\n\n // Caller forced a mid token: skip native/ERC20 cascade.\n if (intermediate) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));\n } else {\n const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);\n\n if (useViaEth) {\n // Gnosis (Seer): outcomes trade vs sDAI — skip ViaETH entirely.\n if (this.chainId === 100) {\n result = mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));\n } else {\n // Other chains: single-hop ViaETH (router wrap/unwrap).\n const value = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwapViaETH\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BestSwapResult;\n result = mapViaResult(value);\n }\n } else {\n // Pure ERC20 ↔ ERC20: direct single-hop only (optional V4 hooked candidate).\n const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({\n address: this.lensQuoter,\n abi: this.quoterAbi,\n functionName: \"buildBestSwap\",\n args: [\n recipient as Address, exactOut,\n tokenIn as Address, tokenOut as Address,\n amount, BigInt(slippageBps), deadline,\n hookPoolFee, hookTickSpacing, hookAddress as Address,\n ],\n }) as BuildBestSwapResult;\n\n result = {\n amountIn: best.amountIn,\n amountOut: best.amountOut,\n target: target as string,\n data: callData as string,\n msgValue: msgValue ?? 0n,\n isTwoHop: false,\n sourceA: ammName(best.source),\n sourceB: null,\n };\n }\n }\n\n await assertSwapExecutable(this.client, {\n account: recipient as Address,\n tokenIn,\n amountIn: result.amountIn,\n result,\n });\n\n return result;\n }\n}\n","// Post-quote gas executability check (block gas limit / thin pools)\n\nimport {\n encodeAbiParameters,\n isAddressEqual,\n keccak256,\n maxUint256,\n numberToHex,\n zeroAddress,\n type Address,\n type Hex,\n type PublicClient,\n type StateOverride,\n} from \"viem\";\nimport { InsufficientLiquidityError, SwapRevertsError } from \"./errors.js\";\nimport type { QuoteResult } from \"./index.js\";\n\n/** Fraction of block.gasLimit the swap is allowed to consume (90%). */\nexport const GAS_LIMIT_BPS = 9000n;\n\n/**\n * OpenZeppelin ERC20 layout: `balanceOf` at mapping slot 0, `allowance` at 1.\n * Covers sDAI and most Seer collateral / outcome tokens.\n */\nexport function erc20BalanceSlot(owner: Address): Hex {\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 0n],\n ),\n );\n}\n\nexport function erc20AllowanceSlot(owner: Address, spender: Address): Hex {\n const inner = keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"uint256\" }],\n [owner, 1n],\n ),\n );\n return keccak256(\n encodeAbiParameters(\n [{ type: \"address\" }, { type: \"bytes32\" }],\n [spender, inner],\n ),\n );\n}\n\n/** stateDiff so `owner` can pay `spender` at least `amount` without a prior approve. */\nexport function erc20SpendOverride(\n token: Address,\n owner: Address,\n spender: Address,\n amount: bigint,\n): StateOverride[number] {\n const bal = amount > 0n ? amount : 1n;\n return {\n address: token,\n stateDiff: [\n { slot: erc20BalanceSlot(owner), value: numberToHex(bal, { size: 32 }) },\n {\n slot: erc20AllowanceSlot(owner, spender),\n value: numberToHex(maxUint256, { size: 32 }),\n },\n ],\n };\n}\n\nfunction isNative(token: string): boolean {\n return isAddressEqual(token as Address, zeroAddress);\n}\n\n/**\n * Builds state overrides so the router sim does not depend on a prior approve.\n * Native `tokenIn` only needs a funded account for `msg.value` + gas.\n */\nexport function buildSwapStateOverride(params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n msgValue: bigint;\n}): StateOverride {\n const { account, tokenIn, amountIn, target, msgValue } = params;\n const overrides: StateOverride = [\n {\n address: account,\n balance: msgValue + 10n ** 18n,\n },\n ];\n if (!isNative(tokenIn)) {\n overrides.push(\n erc20SpendOverride(tokenIn as Address, account, target, amountIn),\n );\n }\n return overrides;\n}\n\nfunction maxGasForBlock(gasLimit: bigint): bigint {\n return (gasLimit * GAS_LIMIT_BPS) / 10000n;\n}\n\n/** Scratch address for the override-support probe; holds no real code on any chain. */\nconst PROBE_ADDRESS = \"0x0000000000000000000000000000000000f0f0f0\" as const;\n/** Runtime that returns uint256(1): PUSH1 01, PUSH1 00, MSTORE, PUSH1 20, PUSH1 00, RETURN. */\nconst PROBE_CODE = \"0x600160005260206000f3\" as const;\nconst ONE_WORD = numberToHex(1n, { size: 32 });\n\nconst BALANCE_OF_SELECTOR = \"0x70a08231\";\nconst ALLOWANCE_SELECTOR = \"0xdd62ed3e\";\n\nfunction encodeAddressArgs(...args: Address[]): Hex {\n return encodeAbiParameters(\n args.map(() => ({ type: \"address\" }) as const),\n args,\n );\n}\n\n/** `true` when the node applied our `code` override — i.e. it honours state overrides at all. */\nasync function nodeAppliesStateOverrides(client: PublicClient): Promise<boolean> {\n try {\n const res = await client.call({\n to: PROBE_ADDRESS,\n data: \"0x\",\n stateOverride: [{ address: PROBE_ADDRESS, code: PROBE_CODE }],\n });\n return res.data === ONE_WORD;\n } catch {\n return false;\n }\n}\n\nasync function readWord(\n client: PublicClient,\n to: Address,\n data: Hex,\n stateOverride: StateOverride,\n): Promise<Hex | undefined> {\n try {\n const res = await client.call({ to, data, stateOverride });\n return res.data;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Confirms the overrides that make the swap payable actually took effect.\n *\n * `erc20SpendOverride` guesses the OpenZeppelin storage layout (balances in slot 0,\n * allowances in slot 1). For a token that lays its storage out differently the\n * injected balance/allowance never lands, and the swap then reverts for reasons that\n * have nothing to do with the router — so we must not blame the calldata.\n */\nasync function swapOverridesApplied(params: {\n client: PublicClient;\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n target: Address;\n stateOverride: StateOverride;\n}): Promise<boolean> {\n const { client, account, tokenIn, amountIn, target, stateOverride } = params;\n\n if (!(await nodeAppliesStateOverrides(client))) return false;\n if (isNative(tokenIn)) return true; // only the plain `balance` override is involved\n\n const token = tokenIn as Address;\n const expectedBalance = numberToHex(amountIn > 0n ? amountIn : 1n, { size: 32 });\n\n const balance = await readWord(\n client,\n token,\n `${BALANCE_OF_SELECTOR}${encodeAddressArgs(account).slice(2)}`,\n stateOverride,\n );\n if (balance !== expectedBalance) return false;\n\n const allowance = await readWord(\n client,\n token,\n `${ALLOWANCE_SELECTOR}${encodeAddressArgs(account, target).slice(2)}`,\n stateOverride,\n );\n return allowance === numberToHex(maxUint256, { size: 32 });\n}\n\nfunction revertDetail(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined;\n const short = (error as { shortMessage?: string }).shortMessage;\n return (short ?? error.message).split(\"\\n\")[0]?.trim() || undefined;\n}\n\n/**\n * After LensQuoter builds calldata, verify the swap fits in a block.\n *\n * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).\n * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.\n * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.\n * 4. If the unlimited sim reverts, re-check that the overrides applied. If they\n * did, the router really rejects the calldata → {@link SwapRevertsError}. If\n * they did not (non-standard token storage, RPC without state overrides), skip\n * quietly — never false-positive as liquidity.\n */\nexport async function assertSwapExecutable(\n client: PublicClient,\n params: {\n account: Address;\n tokenIn: string;\n amountIn: bigint;\n result: QuoteResult;\n },\n): Promise<void> {\n const { account, tokenIn, amountIn, result } = params;\n const target = result.target as Address;\n const data = result.data as Hex;\n\n let block: { gasLimit: bigint };\n try {\n block = await client.getBlock({ blockTag: \"latest\" });\n } catch {\n return;\n }\n const maxGas = maxGasForBlock(block.gasLimit);\n if (maxGas === 0n) return;\n\n const stateOverride = buildSwapStateOverride({\n account,\n tokenIn,\n amountIn,\n target,\n msgValue: result.msgValue,\n });\n\n const base = {\n account,\n to: target,\n data,\n value: result.msgValue,\n stateOverride,\n } as const;\n\n try {\n await client.call(base);\n } catch (e) {\n const applied = await swapOverridesApplied({\n client,\n account,\n tokenIn,\n amountIn,\n target,\n stateOverride,\n });\n if (!applied) return;\n throw new SwapRevertsError({ cause: e, detail: revertDetail(e) });\n }\n\n try {\n await client.call({ ...base, gas: maxGas });\n } catch {\n throw new InsufficientLiquidityError();\n }\n\n try {\n const gas = await client.estimateGas(base);\n if (gas > maxGas) throw new InsufficientLiquidityError();\n } catch (e) {\n if (e instanceof InsufficientLiquidityError) throw e;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,SAAS,UAAU,kBAAAA,iBAAgB,eAAAC,oBAAmB;;;ACAtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAKA,IAAM,gBAAgB;AAMtB,SAAS,iBAAiB,OAAqB;AACpD,SAAO;AAAA,IACL;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,OAAO,EAAE;AAAA,IACZ;AAAA,EACF;AACF;AAEO,SAAS,mBAAmB,OAAgB,SAAuB;AACxE,QAAM,QAAQ;AAAA,IACZ;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,OAAO,EAAE;AAAA,IACZ;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MACzC,CAAC,SAAS,KAAK;AAAA,IACjB;AAAA,EACF;AACF;AAGO,SAAS,mBACd,OACA,OACA,SACA,QACuB;AACvB,QAAM,MAAM,SAAS,KAAK,SAAS;AACnC,SAAO;AAAA,IACL,SAAS;AAAA,IACT,WAAW;AAAA,MACT,EAAE,MAAM,iBAAiB,KAAK,GAAG,OAAO,YAAY,KAAK,EAAE,MAAM,GAAG,CAAC,EAAE;AAAA,MACvE;AAAA,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A,YAAiB;AAAA,UAChC;AAAA,QACF,CAAC;AAED,iBAAS;AAAA,UACP,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB;AAAA,UACA,MAAM;AAAA,UACN,UAAU,YAAY;AAAA,UACtB,UAAU;AAAA,UACV,SAAS,QAAQ,KAAK,MAAM;AAAA,UAC5B,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAEA,UAAM,qBAAqB,KAAK,QAAQ;AAAA,MACtC,SAAS;AAAA,MACT;AAAA,MACA,UAAU,OAAO;AAAA,MACjB;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":["isAddressEqual","zeroAddress","isAddressEqual","zeroAddress"]}
package/dist/index.cjs CHANGED
@@ -27,6 +27,7 @@ __export(index_exports, {
27
27
  GNOSIS_sDAI: () => GNOSIS_sDAI,
28
28
  InsufficientLiquidityError: () => InsufficientLiquidityError,
29
29
  LENS_QUOTER_ABI: () => LENS_QUOTER_ABI,
30
+ SwapRevertsError: () => SwapRevertsError,
30
31
  defaultDeadline: () => defaultDeadline
31
32
  });
32
33
  module.exports = __toCommonJS(index_exports);
@@ -39,6 +40,15 @@ var InsufficientLiquidityError = class extends Error {
39
40
  this.name = "InsufficientLiquidityError";
40
41
  }
41
42
  };
43
+ var SwapRevertsError = class extends Error {
44
+ code = "SWAP_REVERTS";
45
+ constructor(options, message = "Swap simulation reverted; the router rejected the built calldata.") {
46
+ super(options?.detail ? `${message} (${options.detail})` : message, {
47
+ cause: options?.cause
48
+ });
49
+ this.name = "SwapRevertsError";
50
+ }
51
+ };
42
52
 
43
53
  // src/index.ts
44
54
  var AMM = /* @__PURE__ */ ((AMM2) => {
@@ -61,7 +71,11 @@ var LENS_QUOTER_ABI = [
61
71
  "function V3_SWAP_ROUTER() view returns (address)",
62
72
  "function V4_ROUTER() view returns (address)",
63
73
  "function SWAPR_SWAP_ROUTER() view returns (address)",
64
- "function V4_QUOTER() view returns (address)"
74
+ "function V4_QUOTER() view returns (address)",
75
+ // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.
76
+ "error NoRoute()",
77
+ "error ZeroAmount()",
78
+ "error UnsupportedAMM()"
65
79
  ];
66
80
  var CHAINS = {
67
81
  1: {
@@ -79,7 +93,7 @@ var CHAINS = {
79
93
  wnative: "0x4200000000000000000000000000000000000006"
80
94
  },
81
95
  100: {
82
- lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA",
96
+ lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8",
83
97
  v3SwapRouter: "0x0000000000000000000000000000000000000000",
84
98
  v4Router: "0x0000000000000000000000000000000000000000",
85
99
  swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1",
@@ -107,6 +121,7 @@ function defaultDeadline() {
107
121
  GNOSIS_sDAI,
108
122
  InsufficientLiquidityError,
109
123
  LENS_QUOTER_ABI,
124
+ SwapRevertsError,
110
125
  defaultDeadline
111
126
  });
112
127
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts"],"sourcesContent":["// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0xE8E3d230C1c17C7249126036F170027a664d1FbA\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n","/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ADTO,IAAK,MAAL,kBAAKA,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;AAOL,IAAM,YAAiC;AAAA,EAC5C,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,qBAAiB,GAAG;AAAA,EACrB,CAAC,gBAAY,GAAG;AAClB;AAGO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,SAAS;AAAA,EACpB,GAAG;AAAA,IACD,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,IAAI;AAAA,IACF,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AACF;AAIO,IAAM,MAAM;AAGZ,IAAM,cAAc;AA+CpB,SAAS,kBAA0B;AACxC,SAAO,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,GAAG;AACnD;","names":["AMM"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts"],"sourcesContent":["// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n // Custom errors from ILensQuoter.sol, so viem decodes reverts by name instead of a bare selector.\n \"error NoRoute()\",\n \"error ZeroAmount()\",\n \"error UnsupportedAMM()\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0x82150d38288e53AfcF20a5eEee47682c5Ef796d8\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError, SwapRevertsError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n","/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n\n/**\n * Thrown when the pre-flight simulation shows the built calldata reverts, and the\n * state overrides that make it executable are confirmed to have applied — so the\n * revert is the router's, not an artifact of the simulation.\n *\n * Sending such a swap would waste gas and surface as an opaque wallet failure.\n */\nexport class SwapRevertsError extends Error {\n readonly code = \"SWAP_REVERTS\" as const;\n\n constructor(\n options?: { cause?: unknown; detail?: string },\n message = \"Swap simulation reverted; the router rejected the built calldata.\",\n ) {\n super(options?.detail ? `${message} (${options.detail})` : message, {\n cause: options?.cause,\n });\n this.name = \"SwapRevertsError\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AASO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC,OAAO;AAAA,EAEhB,YACE,SACA,UAAU,qEACV;AACA,UAAM,SAAS,SAAS,GAAG,OAAO,KAAK,QAAQ,MAAM,MAAM,SAAS;AAAA,MAClE,OAAO,SAAS;AAAA,IAClB,CAAC;AACD,SAAK,OAAO;AAAA,EACd;AACF;;;AD9BO,IAAK,MAAL,kBAAKA,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;AAOL,IAAM,YAAiC;AAAA,EAC5C,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,qBAAiB,GAAG;AAAA,EACrB,CAAC,gBAAY,GAAG;AAClB;AAGO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,SAAS;AAAA,EACpB,GAAG;AAAA,IACD,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,IAAI;AAAA,IACF,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AACF;AAIO,IAAM,MAAM;AAGZ,IAAM,cAAc;AA+CpB,SAAS,kBAA0B;AACxC,SAAO,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,GAAG;AACnD;","names":["AMM"]}
package/dist/index.d.cts CHANGED
@@ -7,6 +7,20 @@ declare class InsufficientLiquidityError extends Error {
7
7
  readonly code: "INSUFFICIENT_LIQUIDITY";
8
8
  constructor(message?: string);
9
9
  }
10
+ /**
11
+ * Thrown when the pre-flight simulation shows the built calldata reverts, and the
12
+ * state overrides that make it executable are confirmed to have applied — so the
13
+ * revert is the router's, not an artifact of the simulation.
14
+ *
15
+ * Sending such a swap would waste gas and surface as an opaque wallet failure.
16
+ */
17
+ declare class SwapRevertsError extends Error {
18
+ readonly code: "SWAP_REVERTS";
19
+ constructor(options?: {
20
+ cause?: unknown;
21
+ detail?: string;
22
+ }, message?: string);
23
+ }
10
24
 
11
25
  /** Unified AMM enum (same ordinals on every chain). */
12
26
  declare enum AMM {
@@ -17,7 +31,7 @@ declare enum AMM {
17
31
  }
18
32
  declare const AMM_NAMES: Record<AMM, string>;
19
33
  /** Shared LensQuoter ABI for the unified contract on all chains. */
20
- declare const LENS_QUOTER_ABI: readonly ["function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)", "function V3_SWAP_ROUTER() view returns (address)", "function V4_ROUTER() view returns (address)", "function SWAPR_SWAP_ROUTER() view returns (address)", "function V4_QUOTER() view returns (address)"];
34
+ declare const LENS_QUOTER_ABI: readonly ["function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)", "function V3_SWAP_ROUTER() view returns (address)", "function V4_ROUTER() view returns (address)", "function SWAPR_SWAP_ROUTER() view returns (address)", "function V4_QUOTER() view returns (address)", "error NoRoute()", "error ZeroAmount()", "error UnsupportedAMM()"];
21
35
  /** Per-chain LensQuoter, official DEX routers, and wrapped native. */
22
36
  declare const CHAINS: {
23
37
  readonly 1: {
@@ -35,7 +49,7 @@ declare const CHAINS: {
35
49
  readonly wnative: "0x4200000000000000000000000000000000000006";
36
50
  };
37
51
  readonly 100: {
38
- readonly lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA";
52
+ readonly lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8";
39
53
  readonly v3SwapRouter: "0x0000000000000000000000000000000000000000";
40
54
  readonly v4Router: "0x0000000000000000000000000000000000000000";
41
55
  readonly swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1";
@@ -90,4 +104,4 @@ interface QuoteParams extends BaseQuoteParams {
90
104
 
91
105
  declare function defaultDeadline(): bigint;
92
106
 
93
- export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, type QuoteParams, type QuoteResult, defaultDeadline };
107
+ export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, type QuoteParams, type QuoteResult, SwapRevertsError, defaultDeadline };
package/dist/index.d.ts CHANGED
@@ -7,6 +7,20 @@ declare class InsufficientLiquidityError extends Error {
7
7
  readonly code: "INSUFFICIENT_LIQUIDITY";
8
8
  constructor(message?: string);
9
9
  }
10
+ /**
11
+ * Thrown when the pre-flight simulation shows the built calldata reverts, and the
12
+ * state overrides that make it executable are confirmed to have applied — so the
13
+ * revert is the router's, not an artifact of the simulation.
14
+ *
15
+ * Sending such a swap would waste gas and surface as an opaque wallet failure.
16
+ */
17
+ declare class SwapRevertsError extends Error {
18
+ readonly code: "SWAP_REVERTS";
19
+ constructor(options?: {
20
+ cause?: unknown;
21
+ detail?: string;
22
+ }, message?: string);
23
+ }
10
24
 
11
25
  /** Unified AMM enum (same ordinals on every chain). */
12
26
  declare enum AMM {
@@ -17,7 +31,7 @@ declare enum AMM {
17
31
  }
18
32
  declare const AMM_NAMES: Record<AMM, string>;
19
33
  /** Shared LensQuoter ABI for the unified contract on all chains. */
20
- declare const LENS_QUOTER_ABI: readonly ["function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)", "function V3_SWAP_ROUTER() view returns (address)", "function V4_ROUTER() view returns (address)", "function SWAPR_SWAP_ROUTER() view returns (address)", "function V4_QUOTER() view returns (address)"];
34
+ declare const LENS_QUOTER_ABI: readonly ["function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)", "function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)", "function V3_SWAP_ROUTER() view returns (address)", "function V4_ROUTER() view returns (address)", "function SWAPR_SWAP_ROUTER() view returns (address)", "function V4_QUOTER() view returns (address)", "error NoRoute()", "error ZeroAmount()", "error UnsupportedAMM()"];
21
35
  /** Per-chain LensQuoter, official DEX routers, and wrapped native. */
22
36
  declare const CHAINS: {
23
37
  readonly 1: {
@@ -35,7 +49,7 @@ declare const CHAINS: {
35
49
  readonly wnative: "0x4200000000000000000000000000000000000006";
36
50
  };
37
51
  readonly 100: {
38
- readonly lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA";
52
+ readonly lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8";
39
53
  readonly v3SwapRouter: "0x0000000000000000000000000000000000000000";
40
54
  readonly v4Router: "0x0000000000000000000000000000000000000000";
41
55
  readonly swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1";
@@ -90,4 +104,4 @@ interface QuoteParams extends BaseQuoteParams {
90
104
 
91
105
  declare function defaultDeadline(): bigint;
92
106
 
93
- export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, type QuoteParams, type QuoteResult, defaultDeadline };
107
+ export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, type QuoteParams, type QuoteResult, SwapRevertsError, defaultDeadline };
package/dist/index.js CHANGED
@@ -6,8 +6,9 @@ import {
6
6
  GNOSIS_sDAI,
7
7
  InsufficientLiquidityError,
8
8
  LENS_QUOTER_ABI,
9
+ SwapRevertsError,
9
10
  defaultDeadline
10
- } from "./chunk-5UNFCMSF.js";
11
+ } from "./chunk-M4WEBPX7.js";
11
12
  export {
12
13
  AMM,
13
14
  AMM_NAMES,
@@ -16,6 +17,7 @@ export {
16
17
  GNOSIS_sDAI,
17
18
  InsufficientLiquidityError,
18
19
  LENS_QUOTER_ABI,
20
+ SwapRevertsError,
19
21
  defaultDeadline
20
22
  };
21
23
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seer-pm/lens",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "description": "TypeScript SDK for Seer market swaps (collateral ↔ outcome) via LensQuoter",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/index.ts"],"sourcesContent":["/**\n * Thrown when a route quotes successfully but the swap cannot execute within\n * the chain's block gas limit — typically a thin concentrated-liquidity pool\n * that would cross too many ticks for the requested size.\n */\nexport class InsufficientLiquidityError extends Error {\n readonly code = \"INSUFFICIENT_LIQUIDITY\" as const;\n\n constructor(\n message = \"Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.\",\n ) {\n super(message);\n this.name = \"InsufficientLiquidityError\";\n }\n}\n","// Lens SDK — Core constants, ABIs, types, token list (zero dependencies)\n\n// ---- Chain config ----\n\n/** Unified AMM enum (same ordinals on every chain). */\nexport enum AMM {\n UNI_V3 = 0,\n UNI_V4 = 1,\n UNI_V4_HOOKED = 2,\n SWAPR_V3 = 3,\n}\n\nexport const AMM_NAMES: Record<AMM, string> = {\n [AMM.UNI_V3]: \"Uniswap V3\",\n [AMM.UNI_V4]: \"Uniswap V4\",\n [AMM.UNI_V4_HOOKED]: \"Uniswap V4 Hooked\",\n [AMM.SWAPR_V3]: \"Swapr V3\",\n};\n\n/** Shared LensQuoter ABI for the unified contract on all chains. */\nexport const LENS_QUOTER_ABI = [\n \"function buildBestSwapViaETH(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwapViaToken(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress, address mid) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) a, tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) b, address target, bytes data, uint256 msgValue)\",\n \"function buildBestSwap(address to, bool exactOut, address tokenIn, address tokenOut, uint256 swapAmount, uint256 slippageBps, uint256 deadline, uint24 hookPoolFee, int24 hookTickSpacing, address hookAddress) returns (tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut) best, address target, bytes callData, uint256 amountLimit, uint256 msgValue)\",\n \"function V3_SWAP_ROUTER() view returns (address)\",\n \"function V4_ROUTER() view returns (address)\",\n \"function SWAPR_SWAP_ROUTER() view returns (address)\",\n \"function V4_QUOTER() view returns (address)\",\n] as const;\n\n/** Per-chain LensQuoter, official DEX routers, and wrapped native. */\nexport const CHAINS = {\n 1: {\n lensQuoter: \"0xaCE2C61E250c2d019b9Ed7FEf6A441022D6Ec7d2\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\",\n },\n 10: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n 100: {\n lensQuoter: \"0xE8E3d230C1c17C7249126036F170027a664d1FbA\",\n v3SwapRouter: \"0x0000000000000000000000000000000000000000\",\n v4Router: \"0x0000000000000000000000000000000000000000\",\n swaprSwapRouter: \"0xfFB643E73f280B97809A8b41f7232AB401a04ee1\",\n wnative: \"0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d\",\n },\n 8453: {\n lensQuoter: \"0x591aF101cAf2b7351C74c25F5E64bC2E062D2843\",\n v3SwapRouter: \"0x2626664c2603336E57B271c5C0b26F421741e481\",\n v4Router: \"0x00000000000044a361Ae3cAc094c9D1b14Eece97\",\n swaprSwapRouter: \"0x0000000000000000000000000000000000000000\",\n wnative: \"0x4200000000000000000000000000000000000006\",\n },\n} as const;\n\nexport type ChainId = keyof typeof CHAINS;\n\nexport const ETH = \"0x0000000000000000000000000000000000000000\" as const;\n\n/** Gnosis sDAI — default ViaToken mid for native/WXDAI↔ERC20 on Gnosis (Seer). */\nexport const GNOSIS_sDAI = \"0xaf204776c7245bF4147c2612BF6e5972Ee483701\" as const;\n\n// ---- Types ----\n\nexport interface QuoteResult {\n amountIn: bigint;\n amountOut: bigint;\n /** Official DEX router to call. */\n target: string;\n /** Ready-to-send calldata for `target`. */\n data: string;\n msgValue: bigint;\n isTwoHop: boolean;\n sourceA: string;\n sourceB: string | null;\n}\n\nexport interface BaseQuoteParams {\n tokenIn: string;\n tokenOut: string;\n amount: bigint;\n}\n\nexport interface QuoteParams extends BaseQuoteParams {\n recipient: string;\n slippageBps?: number;\n deadline?: bigint;\n /** false = exactIn (default); true = exactOut. `amount` is amountIn or desired amountOut accordingly. */\n exactOut?: boolean;\n /** Optional V4 hooked-pool candidate (exactIn/exactOut; can beat the primary route). */\n hookPoolFee?: number;\n hookTickSpacing?: number;\n hookAddress?: string;\n /**\n * Intermediate token for two-hop routes (`buildBestSwapViaToken`).\n * When set, skips the native/ERC20 cascade. On Gnosis, native/WXDAI↔ERC20\n * already defaults to ViaToken(sDAI); use this only to force a different mid.\n */\n intermediate?: string;\n}\n\n// ---- Errors ----\n\nexport { InsufficientLiquidityError } from \"./errors.js\";\n\n// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n"],"mappings":";AAKO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YACE,UAAU,gGACV;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACTO,IAAK,MAAL,kBAAKA,SAAL;AACL,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,YAAS,KAAT;AACA,EAAAA,UAAA,mBAAgB,KAAhB;AACA,EAAAA,UAAA,cAAW,KAAX;AAJU,SAAAA;AAAA,GAAA;AAOL,IAAM,YAAiC;AAAA,EAC5C,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,cAAU,GAAG;AAAA,EACd,CAAC,qBAAiB,GAAG;AAAA,EACrB,CAAC,gBAAY,GAAG;AAClB;AAGO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,SAAS;AAAA,EACpB,GAAG;AAAA,IACD,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,IAAI;AAAA,IACF,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,SAAS;AAAA,EACX;AACF;AAIO,IAAM,MAAM;AAGZ,IAAM,cAAc;AA+CpB,SAAS,kBAA0B;AACxC,SAAO,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