@seer-pm/lens 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,6 +1,24 @@
1
1
  import { PublicClient, Address } from 'viem';
2
- import { ChainId, QuoteParams, QuoteResult } from './index.js';
3
- export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, LENS_QUOTER_ABI, defaultDeadline } from './index.js';
2
+ import { QuoteResult, ChainId, QuoteParams } from './index.js';
3
+ export { AMM, AMM_NAMES, BaseQuoteParams, CHAINS, ETH, GNOSIS_sDAI, InsufficientLiquidityError, LENS_QUOTER_ABI, SwapRevertsError, defaultDeadline } from './index.js';
4
+
5
+ /**
6
+ * After LensQuoter builds calldata, verify the swap fits in a block.
7
+ *
8
+ * 1. `eth_call` with ERC20 allowance/balance overrides (no prior approve needed).
9
+ * 2. If that succeeds, repeat with `gas = 90% of block.gasLimit`.
10
+ * 3. Unlimited OK + capped fail → {@link InsufficientLiquidityError}.
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
14
+ * quietly — never false-positive as liquidity.
15
+ */
16
+ declare function assertSwapExecutable(client: PublicClient, params: {
17
+ account: Address;
18
+ tokenIn: string;
19
+ amountIn: bigint;
20
+ result: QuoteResult;
21
+ }): Promise<void>;
4
22
 
5
23
  /**
6
24
  * Lens SDK client: quotes best routes via the unified on-chain LensQuoter
@@ -33,8 +51,12 @@ declare class Lens {
33
51
  * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;
34
52
  * elsewhere `buildBestSwapViaETH`
35
53
  * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)
54
+ *
55
+ * After building calldata, simulates the swap with a gas cap of 90% of
56
+ * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw
57
+ * {@link InsufficientLiquidityError}.
36
58
  */
37
59
  quote(params: QuoteParams): Promise<QuoteResult>;
38
60
  }
39
61
 
40
- export { ChainId, Lens, QuoteParams, QuoteResult };
62
+ export { ChainId, Lens, QuoteParams, QuoteResult, assertSwapExecutable };
package/dist/client.js CHANGED
@@ -4,12 +4,192 @@ import {
4
4
  CHAINS,
5
5
  ETH,
6
6
  GNOSIS_sDAI,
7
+ InsufficientLiquidityError,
7
8
  LENS_QUOTER_ABI,
9
+ SwapRevertsError,
8
10
  defaultDeadline
9
- } from "./chunk-W6IFHZ77.js";
11
+ } from "./chunk-STF3B72X.js";
12
+
13
+ // src/client.ts
14
+ import { parseAbi, isAddressEqual as isAddressEqual2, zeroAddress as zeroAddress2 } from "viem";
15
+
16
+ // src/gasGuard.ts
17
+ import {
18
+ encodeAbiParameters,
19
+ isAddressEqual,
20
+ keccak256,
21
+ maxUint256,
22
+ numberToHex,
23
+ zeroAddress
24
+ } from "viem";
25
+ var GAS_LIMIT_BPS = 9000n;
26
+ function erc20BalanceSlot(owner) {
27
+ return keccak256(
28
+ encodeAbiParameters(
29
+ [{ type: "address" }, { type: "uint256" }],
30
+ [owner, 0n]
31
+ )
32
+ );
33
+ }
34
+ function erc20AllowanceSlot(owner, spender) {
35
+ const inner = keccak256(
36
+ encodeAbiParameters(
37
+ [{ type: "address" }, { type: "uint256" }],
38
+ [owner, 1n]
39
+ )
40
+ );
41
+ return keccak256(
42
+ encodeAbiParameters(
43
+ [{ type: "address" }, { type: "bytes32" }],
44
+ [spender, inner]
45
+ )
46
+ );
47
+ }
48
+ function erc20SpendOverride(token, owner, spender, amount) {
49
+ const bal = amount > 0n ? amount : 1n;
50
+ return {
51
+ address: token,
52
+ stateDiff: [
53
+ { slot: erc20BalanceSlot(owner), value: numberToHex(bal, { size: 32 }) },
54
+ {
55
+ slot: erc20AllowanceSlot(owner, spender),
56
+ value: numberToHex(maxUint256, { size: 32 })
57
+ }
58
+ ]
59
+ };
60
+ }
61
+ function isNative(token) {
62
+ return isAddressEqual(token, zeroAddress);
63
+ }
64
+ function buildSwapStateOverride(params) {
65
+ const { account, tokenIn, amountIn, target, msgValue } = params;
66
+ const overrides = [
67
+ {
68
+ address: account,
69
+ balance: msgValue + 10n ** 18n
70
+ }
71
+ ];
72
+ if (!isNative(tokenIn)) {
73
+ overrides.push(
74
+ erc20SpendOverride(tokenIn, account, target, amountIn)
75
+ );
76
+ }
77
+ return overrides;
78
+ }
79
+ function maxGasForBlock(gasLimit) {
80
+ return gasLimit * GAS_LIMIT_BPS / 10000n;
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
+ }
139
+ async function assertSwapExecutable(client, params) {
140
+ const { account, tokenIn, amountIn, result } = params;
141
+ const target = result.target;
142
+ const data = result.data;
143
+ let block;
144
+ try {
145
+ block = await client.getBlock({ blockTag: "latest" });
146
+ } catch {
147
+ return;
148
+ }
149
+ const maxGas = maxGasForBlock(block.gasLimit);
150
+ if (maxGas === 0n) return;
151
+ const stateOverride = buildSwapStateOverride({
152
+ account,
153
+ tokenIn,
154
+ amountIn,
155
+ target,
156
+ msgValue: result.msgValue
157
+ });
158
+ const base = {
159
+ account,
160
+ to: target,
161
+ data,
162
+ value: result.msgValue,
163
+ stateOverride
164
+ };
165
+ try {
166
+ await client.call(base);
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) });
178
+ }
179
+ try {
180
+ await client.call({ ...base, gas: maxGas });
181
+ } catch {
182
+ throw new InsufficientLiquidityError();
183
+ }
184
+ try {
185
+ const gas = await client.estimateGas(base);
186
+ if (gas > maxGas) throw new InsufficientLiquidityError();
187
+ } catch (e) {
188
+ if (e instanceof InsufficientLiquidityError) throw e;
189
+ }
190
+ }
10
191
 
11
192
  // src/client.ts
12
- import { parseAbi, isAddressEqual, zeroAddress } from "viem";
13
193
  var QUOTE_TUPLE = "tuple(uint8 source, uint256 feeBps, uint256 amountIn, uint256 amountOut)";
14
194
  var QUOTE_STRUCT = "struct Quote { uint8 source; uint256 feeBps; uint256 amountIn; uint256 amountOut; }";
15
195
  var toQuoterAbi = (lines) => parseAbi([QUOTE_STRUCT, ...lines.map((l) => l.split(QUOTE_TUPLE).join("Quote"))]);
@@ -33,7 +213,7 @@ function mapViaResult(value) {
33
213
  };
34
214
  }
35
215
  function involvesNativeOrWnative(tokenIn, tokenOut, wnative) {
36
- return isAddressEqual(tokenIn, zeroAddress) || isAddressEqual(tokenOut, zeroAddress) || isAddressEqual(tokenIn, wnative) || isAddressEqual(tokenOut, wnative);
216
+ return isAddressEqual2(tokenIn, zeroAddress2) || isAddressEqual2(tokenOut, zeroAddress2) || isAddressEqual2(tokenIn, wnative) || isAddressEqual2(tokenOut, wnative);
37
217
  }
38
218
  var Lens = class {
39
219
  client;
@@ -88,6 +268,10 @@ var Lens = class {
88
268
  * - native / WNATIVE ↔ ERC20 → on Gnosis, `ViaToken(sDAI)` directly;
89
269
  * elsewhere `buildBestSwapViaETH`
90
270
  * - ERC20 ↔ ERC20 → `buildBestSwap` only (optional V4 hooked candidate)
271
+ *
272
+ * After building calldata, simulates the swap with a gas cap of 90% of
273
+ * `block.gasLimit`. Thin pools that quote but cannot fit in a block throw
274
+ * {@link InsufficientLiquidityError}.
91
275
  */
92
276
  async quote(params) {
93
277
  const {
@@ -100,7 +284,7 @@ var Lens = class {
100
284
  exactOut = false,
101
285
  hookPoolFee = 0,
102
286
  hookTickSpacing = 0,
103
- hookAddress = zeroAddress,
287
+ hookAddress = zeroAddress2,
104
288
  intermediate
105
289
  } = params;
106
290
  const routeArgs = {
@@ -115,60 +299,71 @@ var Lens = class {
115
299
  hookTickSpacing,
116
300
  hookAddress
117
301
  };
302
+ let result;
118
303
  if (intermediate) {
119
- return mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));
120
- }
121
- const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);
122
- if (useViaEth) {
123
- if (this.chainId === 100) {
124
- return mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));
304
+ result = mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));
305
+ } else {
306
+ const useViaEth = involvesNativeOrWnative(tokenIn, tokenOut, this.wnative);
307
+ if (useViaEth) {
308
+ if (this.chainId === 100) {
309
+ result = mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));
310
+ } else {
311
+ const value = await this.client.readContract({
312
+ address: this.lensQuoter,
313
+ abi: this.quoterAbi,
314
+ functionName: "buildBestSwapViaETH",
315
+ args: [
316
+ recipient,
317
+ exactOut,
318
+ tokenIn,
319
+ tokenOut,
320
+ amount,
321
+ BigInt(slippageBps),
322
+ deadline,
323
+ hookPoolFee,
324
+ hookTickSpacing,
325
+ hookAddress
326
+ ]
327
+ });
328
+ result = mapViaResult(value);
329
+ }
330
+ } else {
331
+ const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({
332
+ address: this.lensQuoter,
333
+ abi: this.quoterAbi,
334
+ functionName: "buildBestSwap",
335
+ args: [
336
+ recipient,
337
+ exactOut,
338
+ tokenIn,
339
+ tokenOut,
340
+ amount,
341
+ BigInt(slippageBps),
342
+ deadline,
343
+ hookPoolFee,
344
+ hookTickSpacing,
345
+ hookAddress
346
+ ]
347
+ });
348
+ result = {
349
+ amountIn: best.amountIn,
350
+ amountOut: best.amountOut,
351
+ target,
352
+ data: callData,
353
+ msgValue: msgValue ?? 0n,
354
+ isTwoHop: false,
355
+ sourceA: ammName(best.source),
356
+ sourceB: null
357
+ };
125
358
  }
126
- const value = await this.client.readContract({
127
- address: this.lensQuoter,
128
- abi: this.quoterAbi,
129
- functionName: "buildBestSwapViaETH",
130
- args: [
131
- recipient,
132
- exactOut,
133
- tokenIn,
134
- tokenOut,
135
- amount,
136
- BigInt(slippageBps),
137
- deadline,
138
- hookPoolFee,
139
- hookTickSpacing,
140
- hookAddress
141
- ]
142
- });
143
- return mapViaResult(value);
144
359
  }
145
- const [best, target, callData, _amountLimit, msgValue] = await this.client.readContract({
146
- address: this.lensQuoter,
147
- abi: this.quoterAbi,
148
- functionName: "buildBestSwap",
149
- args: [
150
- recipient,
151
- exactOut,
152
- tokenIn,
153
- tokenOut,
154
- amount,
155
- BigInt(slippageBps),
156
- deadline,
157
- hookPoolFee,
158
- hookTickSpacing,
159
- hookAddress
160
- ]
360
+ await assertSwapExecutable(this.client, {
361
+ account: recipient,
362
+ tokenIn,
363
+ amountIn: result.amountIn,
364
+ result
161
365
  });
162
- return {
163
- amountIn: best.amountIn,
164
- amountOut: best.amountOut,
165
- target,
166
- data: callData,
167
- msgValue: msgValue ?? 0n,
168
- isTwoHop: false,
169
- sourceA: ammName(best.source),
170
- sourceB: null
171
- };
366
+ return result;
172
367
  }
173
368
  };
174
369
  export {
@@ -177,8 +372,11 @@ export {
177
372
  CHAINS,
178
373
  ETH,
179
374
  GNOSIS_sDAI,
375
+ InsufficientLiquidityError,
180
376
  LENS_QUOTER_ABI,
181
377
  Lens,
378
+ SwapRevertsError,
379
+ assertSwapExecutable,
182
380
  defaultDeadline
183
381
  };
184
382
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.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\";\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} from \"./index.js\";\nexport type { QuoteResult, BaseQuoteParams, QuoteParams, ChainId } from \"./index.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 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 // Caller forced a mid token: skip native/ERC20 cascade.\n if (intermediate) {\n return mapViaResult(await this.viaToken({ ...routeArgs, mid: intermediate }));\n }\n\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 return mapViaResult(await this.viaToken({ ...routeArgs, mid: GNOSIS_sDAI }));\n }\n\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 return mapViaResult(value);\n }\n\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 return {\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"],"mappings":";;;;;;;;;;;AAEA,SAAS,UAAU,gBAAgB,mBAAmB;AActD,IAAM,cAAc;AACpB,IAAM,eAAe;AAGrB,IAAM,cAAc,CAAC,UACnB,SAAS,CAAC,cAAc,GAAG,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,WAAW,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC;AAElF,IAAM,YAAY,YAAY,eAAe;AAS7C,IAAM,mBAAmB;AAazB,SAAS,QAAQ,QAAwB;AACvC,SAAQ,UAAqC,MAAM,KAAK,QAAQ,MAAM;AACxE;AAOA,SAAS,aAAa,OAAoC;AACxD,QAAM,CAAC,GAAG,GAAG,QAAQ,MAAM,QAAQ,IAAI;AACvC,QAAM,WAAW,EAAE,YAAY;AAC/B,SAAO;AAAA,IACL,UAAU,EAAE;AAAA,IACZ,WAAW,WAAW,EAAE,YAAY,EAAE;AAAA,IACtC;AAAA,IACA;AAAA,IACA,UAAU,YAAY;AAAA,IACtB;AAAA,IACA,SAAS,QAAQ,EAAE,MAAM;AAAA,IACzB,SAAS,WAAW,QAAQ,EAAE,MAAM,IAAI;AAAA,EAC1C;AACF;AAOA,SAAS,wBACP,SACA,UACA,SACS;AACT,SACE,eAAe,SAAoB,WAAW,KAC3C,eAAe,UAAqB,WAAW,KAC/C,eAAe,SAAoB,OAAO,KAC1C,eAAe,UAAqB,OAAO;AAElD;AAMO,IAAM,OAAN,MAAW;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,YAAY,QAAsB,SAAkB,YAAsB;AACxE,SAAK,SAAS;AACd,SAAK,UAAU;AACf,UAAM,QAAQ,OAAO,OAAO;AAC5B,SAAK,aAAa,cAAe,MAAM;AACvC,SAAK,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M,KAAK,OAAO,aAAa;AAAA,QAC3C,SAAS,KAAK;AAAA,QACd,KAAK,KAAK;AAAA,QACV,cAAc;AAAA,QACd,MAAM;AAAA,UACJ;AAAA,UAAsB;AAAA,UACtB;AAAA,UAAoB;AAAA,UACpB;AAAA,UAAQ,OAAO,WAAW;AAAA,UAAG;AAAA,UAC7B;AAAA,UAAa;AAAA,UAAiB;AAAA,QAChC;AAAA,MACF,CAAC;AACD,aAAO,aAAa,KAAK;AAAA,IAC3B;AAGA,UAAM,CAAC,MAAM,QAAQ,UAAU,cAAc,QAAQ,IAAI,MAAM,KAAK,OAAO,aAAa;AAAA,MACtF,SAAS,KAAK;AAAA,MACd,KAAK,KAAK;AAAA,MACV,cAAc;AAAA,MACd,MAAM;AAAA,QACJ;AAAA,QAAsB;AAAA,QACtB;AAAA,QAAoB;AAAA,QACpB;AAAA,QAAQ,OAAO,WAAW;AAAA,QAAG;AAAA,QAC7B;AAAA,QAAa;AAAA,QAAiB;AAAA,MAChC;AAAA,IACF,CAAC;AAED,WAAO;AAAA,MACL,UAAU,KAAK;AAAA,MACf,WAAW,KAAK;AAAA,MAChB;AAAA,MACA,MAAM;AAAA,MACN,UAAU,YAAY;AAAA,MACtB,UAAU;AAAA,MACV,SAAS,QAAQ,KAAK,MAAM;AAAA,MAC5B,SAAS;AAAA,IACX;AAAA,EACF;AACF;","names":[]}
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,CA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AAC,CAAC;AAAA,QAC/E,OAAO;AAEL,gBAAM,QAAQ,MAAM,KAAK,OAAO,aAAa;AAAA,YAC3C,SAAS,KAAK;AAAA,YACd,KAAK,KAAK;AAAA,YACV,cAAc;AAAA,YACd,MAAM;AAAA,cACJ;AAAA,cAAsB;AAAA,cACtB;AAAA,cAAoB;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":["isAddressEqual","zeroAddress","isAddressEqual","zeroAddress"]}
package/dist/index.cjs CHANGED
@@ -25,10 +25,32 @@ __export(index_exports, {
25
25
  CHAINS: () => CHAINS,
26
26
  ETH: () => ETH,
27
27
  GNOSIS_sDAI: () => GNOSIS_sDAI,
28
+ InsufficientLiquidityError: () => InsufficientLiquidityError,
28
29
  LENS_QUOTER_ABI: () => LENS_QUOTER_ABI,
30
+ SwapRevertsError: () => SwapRevertsError,
29
31
  defaultDeadline: () => defaultDeadline
30
32
  });
31
33
  module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/errors.ts
36
+ var InsufficientLiquidityError = class extends Error {
37
+ code = "INSUFFICIENT_LIQUIDITY";
38
+ constructor(message = "Swap too large for available liquidity (would exceed block gas limit). Try a smaller amount.") {
39
+ super(message);
40
+ this.name = "InsufficientLiquidityError";
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
+ };
52
+
53
+ // src/index.ts
32
54
  var AMM = /* @__PURE__ */ ((AMM2) => {
33
55
  AMM2[AMM2["UNI_V3"] = 0] = "UNI_V3";
34
56
  AMM2[AMM2["UNI_V4"] = 1] = "UNI_V4";
@@ -67,7 +89,7 @@ var CHAINS = {
67
89
  wnative: "0x4200000000000000000000000000000000000006"
68
90
  },
69
91
  100: {
70
- lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA",
92
+ lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8",
71
93
  v3SwapRouter: "0x0000000000000000000000000000000000000000",
72
94
  v4Router: "0x0000000000000000000000000000000000000000",
73
95
  swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1",
@@ -93,7 +115,9 @@ function defaultDeadline() {
93
115
  CHAINS,
94
116
  ETH,
95
117
  GNOSIS_sDAI,
118
+ InsufficientLiquidityError,
96
119
  LENS_QUOTER_ABI,
120
+ SwapRevertsError,
97
121
  defaultDeadline
98
122
  });
99
123
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.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// ---- Helpers ----\n\nexport function defaultDeadline(): bigint {\n return BigInt(Math.trunc(Date.now() / 1000) + 300);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,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;AA2CpB,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] 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;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
@@ -1,3 +1,27 @@
1
+ /**
2
+ * Thrown when a route quotes successfully but the swap cannot execute within
3
+ * the chain's block gas limit — typically a thin concentrated-liquidity pool
4
+ * that would cross too many ticks for the requested size.
5
+ */
6
+ declare class InsufficientLiquidityError extends Error {
7
+ readonly code: "INSUFFICIENT_LIQUIDITY";
8
+ constructor(message?: string);
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
+ }
24
+
1
25
  /** Unified AMM enum (same ordinals on every chain). */
2
26
  declare enum AMM {
3
27
  UNI_V3 = 0,
@@ -25,7 +49,7 @@ declare const CHAINS: {
25
49
  readonly wnative: "0x4200000000000000000000000000000000000006";
26
50
  };
27
51
  readonly 100: {
28
- readonly lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA";
52
+ readonly lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8";
29
53
  readonly v3SwapRouter: "0x0000000000000000000000000000000000000000";
30
54
  readonly v4Router: "0x0000000000000000000000000000000000000000";
31
55
  readonly swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1";
@@ -77,6 +101,7 @@ interface QuoteParams extends BaseQuoteParams {
77
101
  */
78
102
  intermediate?: string;
79
103
  }
104
+
80
105
  declare function defaultDeadline(): bigint;
81
106
 
82
- export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, 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
@@ -1,3 +1,27 @@
1
+ /**
2
+ * Thrown when a route quotes successfully but the swap cannot execute within
3
+ * the chain's block gas limit — typically a thin concentrated-liquidity pool
4
+ * that would cross too many ticks for the requested size.
5
+ */
6
+ declare class InsufficientLiquidityError extends Error {
7
+ readonly code: "INSUFFICIENT_LIQUIDITY";
8
+ constructor(message?: string);
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
+ }
24
+
1
25
  /** Unified AMM enum (same ordinals on every chain). */
2
26
  declare enum AMM {
3
27
  UNI_V3 = 0,
@@ -25,7 +49,7 @@ declare const CHAINS: {
25
49
  readonly wnative: "0x4200000000000000000000000000000000000006";
26
50
  };
27
51
  readonly 100: {
28
- readonly lensQuoter: "0xE8E3d230C1c17C7249126036F170027a664d1FbA";
52
+ readonly lensQuoter: "0x82150d38288e53AfcF20a5eEee47682c5Ef796d8";
29
53
  readonly v3SwapRouter: "0x0000000000000000000000000000000000000000";
30
54
  readonly v4Router: "0x0000000000000000000000000000000000000000";
31
55
  readonly swaprSwapRouter: "0xfFB643E73f280B97809A8b41f7232AB401a04ee1";
@@ -77,6 +101,7 @@ interface QuoteParams extends BaseQuoteParams {
77
101
  */
78
102
  intermediate?: string;
79
103
  }
104
+
80
105
  declare function defaultDeadline(): bigint;
81
106
 
82
- export { AMM, AMM_NAMES, type BaseQuoteParams, CHAINS, type ChainId, ETH, GNOSIS_sDAI, 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 };