lpsignal 0.9.0 → 0.11.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.
@@ -0,0 +1,398 @@
1
+ /**
2
+ * `lpsignal/liquidity` — add and remove concentrated liquidity from your own wallet, on the pools' official position
3
+ * managers (Uniswap v3, PancakeSwap v3, Aerodrome / Velodrome Slipstream): no LPSignal contract, no fee, the position
4
+ * always minted to / collected by your own address. Uses viem (a peer dependency): you pass a PublicClient to read the
5
+ * chain and, to send, your own WalletClient — your keys never reach this SDK.
6
+ *
7
+ * const pool = (await lps.pool('base', '0x…')).pool; // tokens, decimals, fee, tick spacing
8
+ * const plan = await planAddLiquidity(publicClient, pool, { owner, amount0: parseEther('1'), rangeBp: 500 });
9
+ * await sendPlan(walletClient, publicClient, [...plan.approvals, plan.mint]);
10
+ *
11
+ * Never re-send a mint whose receipt you have not seen: a second one would add the same amounts again (sendPlan
12
+ * throws TxPending with the hash instead of guessing).
13
+ *
14
+ * Swapping one pool token for the other (e.g. for the side you are short of) goes through the KyberSwap aggregator with
15
+ * LPSignal's fee (0.25%, 0.05% in stable pools, taken from the input) — planSwap checks every answer of the aggregator
16
+ * against the pool's own price and the calldata it builds, then sendPlan sends it like any other plan.
17
+ */
18
+ import { defineChain } from 'viem';
19
+ import { decodeFunctionData } from 'viem';
20
+ import { approvalsNeeded, CHAIN_ID, COLLECT_ABI, ERC20, isSlipstream, NPM, NPM_READ, otherAmount, planMint, rangeTicks, removeAmounts, removeCall, SLOT0, WRAPPED, } from './core.js';
21
+ import { buildSwap, checkSwapCall, fetchQuote, KYBER_ROUTER, KYBER_ROUTER_ABI, maxImpactBps, minOutFloor, requiredMinOut, spotOut, swapFeeBps, SwapRefused } from './swap.js';
22
+ export * from './core.js';
23
+ export * from './swap.js';
24
+ const MULTICALL3 = '0xcA11bde05977b3631167028862bE2a173976CA11';
25
+ const DEFAULT_SLIPPAGE_BPS = 50;
26
+ const DEFAULT_DEADLINE_S = 20 * 60;
27
+ function lpPool(p) {
28
+ if (!NPM[p.chain]?.[p.dex])
29
+ throw new Error(`adding liquidity is not supported for ${p.dex} on ${p.chain} (Uniswap v4: use the Uniswap app)`);
30
+ return { chain: p.chain, dex: p.dex, address: p.address, token0: p.token0, token1: p.token1, decimals0: p.decimals0, decimals1: p.decimals1, fee: p.fee, tickSpacing: p.tickSpacing };
31
+ }
32
+ async function assertChain(client, chain) {
33
+ const id = await client.getChainId();
34
+ if (id !== CHAIN_ID[chain])
35
+ throw new Error(`the client is on chain ${id}, the pool on ${chain} (${CHAIN_ID[chain]})`);
36
+ }
37
+ const bind = (c, chain, from) => ({ ...c, chainId: CHAIN_ID[chain], from });
38
+ /** the approvals (exact amounts) and the mint for adding liquidity now, read from the chain */
39
+ export async function planAddLiquidity(client, pool, o) {
40
+ const lp = lpPool(pool);
41
+ await assertChain(client, lp.chain);
42
+ const npm = NPM[lp.chain][lp.dex];
43
+ const [[sqrtPriceX96, tick], allowance0, allowance1] = await Promise.all([
44
+ client.readContract({ address: lp.address, abi: SLOT0, functionName: 'slot0' }),
45
+ client.readContract({ address: lp.token0, abi: ERC20, functionName: 'allowance', args: [o.owner, npm] }),
46
+ client.readContract({ address: lp.token1, abi: ERC20, functionName: 'allowance', args: [o.owner, npm] }),
47
+ ]);
48
+ let amount0 = o.amount0, amount1 = o.amount1;
49
+ if (amount0 === undefined && amount1 === undefined)
50
+ throw new Error('give amount0 or amount1');
51
+ const [lo, hi] = rangeTicks(tick, o.rangeBp, lp.tickSpacing);
52
+ if (amount1 === undefined)
53
+ amount1 = otherAmount(0, amount0, sqrtPriceX96, lo, hi) ?? 0n;
54
+ if (amount0 === undefined)
55
+ amount0 = otherAmount(1, amount1, sqrtPriceX96, lo, hi) ?? 0n;
56
+ const deadline = Math.floor(Date.now() / 1000) + (o.deadlineS ?? DEFAULT_DEADLINE_S);
57
+ const plan = planMint(lp, { sqrtPriceX96, tick }, {
58
+ rangeBp: o.rangeBp, desired0: amount0, desired1: amount1, slippageBps: o.slippageBps ?? DEFAULT_SLIPPAGE_BPS, nativeSide: o.nativeSide ?? null,
59
+ recipient: o.owner, deadline: BigInt(deadline), allowance0, allowance1,
60
+ });
61
+ return { ...plan, approvals: plan.approvals.map((c) => bind(c, lp.chain, o.owner)), mint: bind(plan.mint, lp.chain, o.owner), amount0, amount1, deadline };
62
+ }
63
+ /** NFTs read per multicall page */
64
+ const PAGE = 200;
65
+ const FACTORY = [{ type: 'function', name: 'factory', stateMutability: 'view', inputs: [], outputs: [{ type: 'address' }] }];
66
+ const GET_POOL_FEE = [{ type: 'function', name: 'getPool', stateMutability: 'view', inputs: [{ type: 'address' }, { type: 'address' }, { type: 'uint24' }], outputs: [{ type: 'address' }] }];
67
+ const GET_POOL_SPACING = [{ type: 'function', name: 'getPool', stateMutability: 'view', inputs: [{ type: 'address' }, { type: 'address' }, { type: 'int24' }], outputs: [{ type: 'address' }] }];
68
+ /**
69
+ * The wallet's positions on one chain's position managers that still hold liquidity or fees, each with its pool
70
+ * (from the manager's factory). Positions staked in a Slipstream gauge belong to the gauge and are not listed.
71
+ */
72
+ export async function positions(client, chain, owner) {
73
+ await assertChain(client, chain);
74
+ const out = [];
75
+ // one snapshot for every read: NFTs moving between pages (ERC721Enumerable swaps the last one into a hole) could
76
+ // otherwise hide a live position or fail the walk
77
+ const blockNumber = await client.getBlockNumber({ cacheTime: 0 });
78
+ for (const [dex, npm] of Object.entries(NPM[chain] ?? {})) {
79
+ const n = await client.readContract({ address: npm, abi: NPM_READ, functionName: 'balanceOf', args: [owner], blockNumber });
80
+ if (n === 0n)
81
+ continue;
82
+ // every NFT the wallet holds, a page at a time (emptied positions are never burned: they keep their indexes, so
83
+ // stopping at the first N could hide a live position behind them)
84
+ const readPositions = (part) => client.multicall({ contracts: part.map((id) => ({ address: npm, abi: NPM_READ, functionName: 'positions', args: [id] })), allowFailure: false, multicallAddress: MULTICALL3, blockNumber });
85
+ const ids = [];
86
+ const raw = [];
87
+ for (let from = 0n; from < n; from += BigInt(PAGE)) {
88
+ const count = Number(n - from < BigInt(PAGE) ? n - from : BigInt(PAGE));
89
+ const part = await client.multicall({
90
+ contracts: Array.from({ length: count }, (_, i) => ({ address: npm, abi: NPM_READ, functionName: 'tokenOfOwnerByIndex', args: [owner, from + BigInt(i)] })),
91
+ allowFailure: false, multicallAddress: MULTICALL3, blockNumber,
92
+ });
93
+ ids.push(...part);
94
+ raw.push(...await readPositions(part));
95
+ }
96
+ const live = raw.map((p, i) => ({ id: ids[i], p })).filter(({ p }) => p[7] > 0n || p[10] > 0n || p[11] > 0n);
97
+ if (!live.length)
98
+ continue;
99
+ const factory = await client.readContract({ address: npm, abi: FACTORY, functionName: 'factory', blockNumber });
100
+ const pools = await client.multicall({
101
+ contracts: live.map(({ p }) => (isSlipstream(dex)
102
+ ? { address: factory, abi: GET_POOL_SPACING, functionName: 'getPool', args: [p[2], p[3], p[4]] }
103
+ : { address: factory, abi: GET_POOL_FEE, functionName: 'getPool', args: [p[2], p[3], p[4]] })),
104
+ allowFailure: false, multicallAddress: MULTICALL3, blockNumber,
105
+ });
106
+ live.forEach(({ id, p }, i) => out.push({
107
+ chain, dex, npm, pool: pools[i].toLowerCase(),
108
+ tokenId: id, token0: p[2], token1: p[3], feeOrSpacing: p[4], tickLower: p[5], tickUpper: p[6], liquidity: p[7],
109
+ }));
110
+ }
111
+ return out;
112
+ }
113
+ /** what collecting now would pay (fees owed, incl. those accrued since the last update) */
114
+ export async function uncollectedFees(client, pos, owner) {
115
+ const MAX = (1n << 128n) - 1n;
116
+ const { result } = await client.simulateContract({ address: pos.npm, abi: COLLECT_ABI, functionName: 'collect', args: [{ tokenId: pos.tokenId, recipient: owner, amount0Max: MAX, amount1Max: MAX }], account: owner });
117
+ return result;
118
+ }
119
+ /** the RPC is behind a block this plan must see */
120
+ export class StaleRead extends Error {
121
+ head;
122
+ minBlock;
123
+ constructor(head, minBlock) {
124
+ super(`the RPC is at block ${head}, behind ${minBlock}: try again shortly`);
125
+ this.head = head;
126
+ this.minBlock = minBlock;
127
+ }
128
+ }
129
+ /**
130
+ * One transaction: decrease `shareBps` of what the position holds NOW (read from the chain) and collect it all —
131
+ * principal and fees — to the owner. A repeated partial removal would take that share again: send it once.
132
+ */
133
+ export async function planRemoveLiquidity(client, pos, o) {
134
+ await assertChain(client, pos.chain);
135
+ const OWNER_OF = [{ type: 'function', name: 'ownerOf', stateMutability: 'view', inputs: [{ type: 'uint256' }], outputs: [{ type: 'address' }] }];
136
+ // one explicit block for every read, no older than the caller's last removal
137
+ const blockNumber = await client.getBlockNumber({ cacheTime: 0 });
138
+ if (o.minBlock !== undefined && blockNumber < o.minBlock)
139
+ throw new StaleRead(blockNumber, o.minBlock);
140
+ const [now, holder, [sqrtPriceX96]] = await Promise.all([
141
+ client.readContract({ address: pos.npm, abi: NPM_READ, functionName: 'positions', args: [pos.tokenId], blockNumber }),
142
+ client.readContract({ address: pos.npm, abi: OWNER_OF, functionName: 'ownerOf', args: [pos.tokenId], blockNumber }),
143
+ client.readContract({ address: pos.pool, abi: SLOT0, functionName: 'slot0', blockNumber }),
144
+ ]);
145
+ if (holder.toLowerCase() !== o.owner.toLowerCase())
146
+ throw new Error(`position ${pos.tokenId} is held by ${holder}, not ${o.owner}`);
147
+ const live = { ...pos, liquidity: now[7] };
148
+ const deadline = Math.floor(Date.now() / 1000) + (o.deadlineS ?? DEFAULT_DEADLINE_S);
149
+ const a = o.shareBps === 0 || live.liquidity === 0n
150
+ ? { liquidity: 0n, amount0: 0n, amount1: 0n, amount0Min: 0n, amount1Min: 0n }
151
+ : removeAmounts(sqrtPriceX96, live, o.shareBps, o.slippageBps ?? DEFAULT_SLIPPAGE_BPS);
152
+ return { ...a, deadline, call: bind(removeCall(pos.chain, pos.dex, pos.tokenId, a, o.owner, BigInt(deadline)), pos.chain, o.owner) };
153
+ }
154
+ /**
155
+ * A swap between the pool's two tokens through the KyberSwap aggregator, with LPSignal's fee. The aggregator's answers
156
+ * are checked, never trusted: the quote must be within the allowed impact of the pool's own price (SwapRefused
157
+ * 'impact'), and the calldata is decoded — router, swap() only, tokens, amount, value, recipient = owner, exactly our
158
+ * fee, flags, no permit, the split, and a minimum no lower than the pool-price floor, `minOut` and the quote less the
159
+ * slippage (SwapRefused 'calldata'); then simulated (SwapRefused 'simulation'). The router itself pays at least that
160
+ * minimum or reverts. Send it with sendPlan; a swap's deadline is in calldata nobody can check, so a send of unknown
161
+ * outcome must be resolved by its own transaction before swapping again (sendPlan blocks the account meanwhile).
162
+ */
163
+ export async function planSwap(client, pool, o) {
164
+ if (pool.dex === 'uniswap_v4')
165
+ throw new Error('swapping is offered for v3-style pools (their price bounds the quote); not Uniswap v4');
166
+ await assertChain(client, pool.chain);
167
+ const pairClass = pool.pairClass ?? 'volatile';
168
+ const token = (side) => (side === 0 ? pool.token0 : pool.token1).toLowerCase();
169
+ const toSide = o.fromSide === 0 ? 1 : 0;
170
+ for (const [side, native] of [[o.fromSide, o.fromNative], [toSide, o.toNative]]) {
171
+ if (native && token(side) !== WRAPPED[pool.chain])
172
+ throw new Error(`side ${side} is not the wrapped native token: it cannot be paid / received as the native coin`);
173
+ }
174
+ if (o.amountIn <= 0n)
175
+ throw new Error('amountIn must be positive');
176
+ const slippageBps = o.slippageBps ?? DEFAULT_SLIPPAGE_BPS;
177
+ // (10000 or more would take the minimum out to nothing: any price would do)
178
+ if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps >= 10_000)
179
+ throw new RangeError('slippageBps must be an integer from 0 to 9999');
180
+ if (o.minOut !== undefined && o.minOut < 0n)
181
+ throw new RangeError('minOut must not be negative');
182
+ const from = { token: token(o.fromSide), native: !!o.fromNative }, to = { token: token(toSide), native: !!o.toNative };
183
+ const feeBps = swapFeeBps(pairClass), impactBps = maxImpactBps(pairClass);
184
+ const [[sqrtPriceX96], allowance] = await Promise.all([
185
+ client.readContract({ address: pool.address, abi: SLOT0, functionName: 'slot0' }),
186
+ from.native ? Promise.resolve(0n) : client.readContract({ address: from.token, abi: ERC20, functionName: 'allowance', args: [o.owner, KYBER_ROUTER] }),
187
+ ]);
188
+ const approvals = from.native ? [] : approvalsNeeded(pool.chain, KYBER_ROUTER, [{ token: from.token, amount: o.amountIn, allowance }]);
189
+ const spot = spotOut(sqrtPriceX96, o.fromSide === 0, o.amountIn, feeBps);
190
+ const q = await fetchQuote(pool.chain, from, to, o.amountIn, feeBps);
191
+ if (q.amountOut < minOutFloor(spot, impactBps, 0))
192
+ throw new SwapRefused('impact', `quote ${q.amountOut} vs pool ${spot}`);
193
+ const need = o.minOut ?? 0n;
194
+ if ((q.amountOut * BigInt(10_000 - slippageBps)) / 10000n < need)
195
+ throw new SwapRefused('moved', `quote ${q.amountOut} for ${need}`);
196
+ const deadline = Math.floor(Date.now() / 1000) + (o.deadlineS ?? 10 * 60);
197
+ const c = await buildSwap(pool.chain, q, o.owner, slippageBps, deadline);
198
+ checkSwapCall(c, { from, to, amountIn: o.amountIn, account: o.owner, feeBps, minOut: requiredMinOut({ spot, impactBps, slippageBps, need, quoteOut: q.amountOut }) });
199
+ const simulated = approvals.length === 0;
200
+ if (simulated) {
201
+ try {
202
+ await client.call({ account: o.owner, to: c.to, data: c.data, value: c.value });
203
+ }
204
+ catch (e) {
205
+ throw new SwapRefused('simulation', String(e.message ?? e).slice(0, 200));
206
+ }
207
+ }
208
+ const minReturn = decodeFunctionData({ abi: KYBER_ROUTER_ABI, data: c.data }).args[0].desc.minReturnAmount;
209
+ return {
210
+ approvals: approvals.map((a) => bind(a, pool.chain, o.owner)), swap: bind(c, pool.chain, o.owner),
211
+ amountIn: o.amountIn, quoteOut: q.amountOut, minReturn, feeBps, simulated, deadline,
212
+ };
213
+ }
214
+ /** a transaction was sent but its receipt was not seen in time: it may still land — do not send it again blindly */
215
+ export class TxPending extends Error {
216
+ hash;
217
+ constructor(hash, cause) {
218
+ super(`transaction ${hash} sent, its outcome not confirmed yet: check it before sending again`, cause === undefined ? undefined : { cause });
219
+ this.hash = hash;
220
+ }
221
+ }
222
+ /** a transaction that landed and reverted */
223
+ export class TxReverted extends Error {
224
+ hash;
225
+ constructor(hash) {
226
+ super(`transaction ${hash} reverted`);
227
+ this.hash = hash;
228
+ }
229
+ }
230
+ /**
231
+ * the wallet failed while sending, without saying whether the transaction went out (no hash): it may have been
232
+ * broadcast. Check whether `nonce` of `from` was used (your wallet's history, or the account's nonce on chain) before
233
+ * sending anything again.
234
+ */
235
+ export class TxUnknown extends Error {
236
+ from;
237
+ nonce;
238
+ /** `nonce` null = the account's nonce manager chose it: check the wallet's history */
239
+ constructor(from, nonce, cause) {
240
+ super(`sending from ${from} failed with an unknown outcome (${nonce === null ? 'nonce chosen by your nonce manager' : `nonce ${nonce}`}): check whether it went out before sending again`, { cause });
241
+ this.from = from;
242
+ this.nonce = nonce;
243
+ }
244
+ }
245
+ /**
246
+ * After a send of unknown outcome (TxUnknown, TxPending) or one replaced in the wallet (TxReplaced) nothing more is sent from that account on that chain in this
247
+ * process until you have checked what became of it and call `unblock` — a queued plan would otherwise read the same
248
+ * nonce and replace or duplicate it.
249
+ */
250
+ export class AccountBlocked extends Error {
251
+ chainId;
252
+ account;
253
+ reason;
254
+ constructor(chainId, account, reason) {
255
+ super(`sending from ${account} on chain ${chainId} is blocked after an unknown outcome (${reason.message}); check it, then call unblock(${chainId}, '${account}')`);
256
+ this.chainId = chainId;
257
+ this.account = account;
258
+ this.reason = reason;
259
+ }
260
+ }
261
+ const blocked = new Map();
262
+ const keyOf = (chainId, account) => `${chainId}:${account.toLowerCase()}`;
263
+ /** you checked the transaction that made sending from this account unsafe: sending may go on */
264
+ export function unblock(chainId, account) { blocked.delete(keyOf(chainId, account)); }
265
+ /** plans of one account on one chain run one after another in this process (they would race for the same nonce) */
266
+ const accountQueues = new Map();
267
+ function inQueue(key, fn) {
268
+ const run = (accountQueues.get(key) ?? Promise.resolve()).then(fn, fn);
269
+ const tail = run.catch(() => undefined);
270
+ accountQueues.set(key, tail);
271
+ void tail.then(() => { if (accountQueues.get(key) === tail)
272
+ accountQueues.delete(key); });
273
+ return run;
274
+ }
275
+ /** a transaction cancelled or replaced by a different one in the wallet: the plan stops (a speed-up is fine) */
276
+ export class TxReplaced extends Error {
277
+ hash;
278
+ reason;
279
+ replacement;
280
+ constructor(hash, reason, replacement) {
281
+ super(`transaction ${hash} was ${reason} by ${replacement}: the plan stopped`);
282
+ this.hash = hash;
283
+ this.reason = reason;
284
+ this.replacement = replacement;
285
+ }
286
+ }
287
+ /** any failure here (RPC error, receipt gone after a reorg, timeout) is TxPending with the hash: never a bare error */
288
+ /** the user declined in the wallet (EIP-1193 4001 anywhere in the cause chain) */
289
+ function declined(e) {
290
+ for (let x = e, i = 0; x && i < 6; x = x.cause, i++) {
291
+ if (x.code === 4001 || x.name === 'UserRejectedRequestError')
292
+ return true;
293
+ }
294
+ return false;
295
+ }
296
+ async function waitFinal(client, block, hash, timeoutMs = 60 * 60_000, requireSuccess = true) {
297
+ const until = Date.now() + timeoutMs;
298
+ try {
299
+ for (;;) {
300
+ const fin = await client.getBlock({ blockTag: 'finalized' });
301
+ if (fin.number >= block) {
302
+ const rc = await client.getTransactionReceipt({ hash });
303
+ if (rc.blockNumber !== block || (await client.getBlock({ blockNumber: block })).hash !== rc.blockHash)
304
+ throw new TxPending(hash); // reorged: unknown again
305
+ // re-executed after a reorg it may have failed this time: only a final, canonical SUCCESS counts
306
+ if (requireSuccess && rc.status !== 'success')
307
+ throw new TxReverted(hash);
308
+ return;
309
+ }
310
+ if (Date.now() > until)
311
+ throw new TxPending(hash);
312
+ await new Promise((r) => setTimeout(r, 6_000));
313
+ }
314
+ }
315
+ catch (e) {
316
+ throw e instanceof TxPending || e instanceof TxReverted ? e : new TxPending(hash, e);
317
+ }
318
+ }
319
+ /**
320
+ * Sends a plan's calls in order from your wallet, each after the previous one's receipt (approvals before the mint).
321
+ * Every call must be for the chain and the account the wallet is on (refused otherwise). Returns each one's hash and
322
+ * block (pass the last block as `minBlock` to your next removal from the same position). Throws TxReverted, TxReplaced
323
+ * (cancelled or replaced in the wallet; a speed-up of the same call is accepted), or TxPending if a receipt is not seen.
324
+ */
325
+ export async function sendPlan(wallet, client, calls, opts = {}) {
326
+ if (!wallet.account)
327
+ throw new Error('the wallet client needs an account');
328
+ const account = wallet.account;
329
+ const chainId = calls[0]?.chainId ?? 0, key = keyOf(chainId, account.address);
330
+ return inQueue(key, async () => {
331
+ const why = blocked.get(key);
332
+ if (why)
333
+ throw new AccountBlocked(chainId, account.address, why);
334
+ try {
335
+ return await sendQueued(wallet, client, calls, opts);
336
+ }
337
+ catch (e) {
338
+ // an outcome the caller must look at before anything else goes out from this account
339
+ if (e instanceof TxUnknown || e instanceof TxPending || e instanceof TxReplaced)
340
+ blocked.set(key, e);
341
+ throw e;
342
+ }
343
+ });
344
+ }
345
+ async function sendQueued(wallet, client, calls, opts) {
346
+ if (!wallet.account)
347
+ throw new Error('the wallet client needs an account');
348
+ const sent = [];
349
+ for (const c of calls) {
350
+ const [walletChain, clientChain] = await Promise.all([wallet.getChainId(), client.getChainId()]);
351
+ if (walletChain !== c.chainId || clientChain !== c.chainId)
352
+ throw new Error(`the call is for chain ${c.chainId}; the wallet is on ${walletChain}, the public client on ${clientChain}`);
353
+ if (wallet.account.address.toLowerCase() !== c.from.toLowerCase())
354
+ throw new Error(`the call was planned for ${c.from}, the wallet is ${wallet.account.address}`);
355
+ // the send itself carries the planned chain: viem checks the wallet is on it and signs/sends with that chainId
356
+ const chain = wallet.chain?.id === c.chainId ? wallet.chain : defineChain({ id: c.chainId, name: `chain ${c.chainId}`, nativeCurrency: { name: 'native', symbol: 'native', decimals: 18 }, rpcUrls: { default: { http: [] } } });
357
+ // the nonce: the account's own nonce manager, if it has one (never overridden); otherwise the account's next one,
358
+ // pinned in the transaction so TxUnknown names the one it used (plans of an account are queued, see inQueue)
359
+ const managed = 'nonceManager' in wallet.account && !!wallet.account.nonceManager;
360
+ const nonce = managed ? null : await client.getTransactionCount({ address: c.from, blockTag: 'pending' });
361
+ let hash;
362
+ try {
363
+ hash = await wallet.sendTransaction({ account: wallet.account, chain, to: c.to, data: c.data, value: c.value, ...(nonce === null ? {} : { nonce }) });
364
+ }
365
+ catch (e) {
366
+ if (declined(e))
367
+ throw e; // declined in the wallet: certainly not sent
368
+ throw new TxUnknown(c.from, nonce, e);
369
+ }
370
+ let replaced = null;
371
+ const rc = await client.waitForTransactionReceipt({
372
+ hash, timeout: opts.timeoutMs ?? 180_000,
373
+ // a speed-up (same call, new fee) counts; a cancel or another transaction in its place stops the plan
374
+ onReplaced: (x) => { if (x.reason !== 'repriced')
375
+ replaced = { reason: x.reason, hash: x.transaction.hash }; },
376
+ }).catch(() => null);
377
+ // finalized: the final canonical receipt decides (a first revert may re-run and succeed after a reorg, and the
378
+ // other way round): a resend on a first, unfinal outcome could double the operation
379
+ if (opts.finalized && rc && !replaced) {
380
+ await waitFinal(client, rc.blockNumber, rc.transactionHash);
381
+ sent.push({ hash: rc.transactionHash, blockNumber: rc.blockNumber });
382
+ continue;
383
+ }
384
+ if (replaced && rc && opts.finalized) {
385
+ // the replacement must be final too: a reorg dropping a cancel could let the original run after all
386
+ await waitFinal(client, rc.blockNumber, rc.transactionHash, undefined, false);
387
+ }
388
+ if (replaced)
389
+ throw new TxReplaced(hash, replaced.reason, replaced.hash);
390
+ if (!rc)
391
+ throw new TxPending(hash);
392
+ if (rc.status !== 'success')
393
+ throw new TxReverted(rc.transactionHash);
394
+ sent.push({ hash: rc.transactionHash, blockNumber: rc.blockNumber });
395
+ }
396
+ return sent;
397
+ }
398
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/liquidity/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,WAAW,EAAgE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,kBAAkB,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,EACL,eAAe,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,E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IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,eAAe,EAAE,WAAW,EAAE,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;YACrE,SAAS;QACX,CAAC;QACD,IAAI,QAAQ,IAAI,EAAE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACrC,oGAAoG;YACpG,MAAM,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,eAAe,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAChF,CAAC;QACD,IAAI,QAAQ;YAAE,MAAM,IAAI,UAAU,CAAC,IAAI,EAAG,QAAiD,CAAC,MAAM,EAAG,QAA0B,CAAC,IAAI,CAAC,CAAC;QACtI,IAAI,CAAC,EAAE;YAAE,MAAM,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,EAAE,CAAC,MAAM,KAAK,SAAS;YAAE,MAAM,IAAI,UAAU,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,eAAe,EAAE,WAAW,EAAE,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;IACvE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Swapping one pool token for the other (e.g. to top up an add) through the KyberSwap aggregator, with LPSignal's fee:
3
+ * `swapFeeBps` of the input, sent by the router to SWAP_FEE_RECEIVER — the same code the lpsignal.app web app runs,
4
+ * kept in step with it. Your own wallet sends it; nothing of LPSignal's holds funds.
5
+ *
6
+ * The aggregator's answers are never trusted as they come: the quote must be within `maxImpactBps` of the pool's own
7
+ * price (read on chain), and the calldata is decoded and checked before the wallet is asked — the router, `swap()`
8
+ * only, tokens, amount, the recipient = the wallet, our fee and no other, the exact flags, no permit, and a minimum out
9
+ * no lower than the pool price allows. The router itself pays the recipient at least that minimum or reverts.
10
+ */
11
+ import { type Address } from 'viem';
12
+ import type { Call } from './core.js';
13
+ export declare const KYBER_ROUTER: Address;
14
+ export declare const SWAP_FEE_RECEIVER: Address;
15
+ /** the aggregator's name for a chain's native coin */
16
+ export declare const KYBER_NATIVE: Address;
17
+ /** our fee: 0.05% between stablecoins, else 0.25% (of the input) */
18
+ export declare const swapFeeBps: (pairClass: string) => number;
19
+ /** how far the quote may fall short of the pool's own price (pool fees, route costs, impact) before it is refused */
20
+ export declare const maxImpactBps: (pairClass: string) => number;
21
+ export declare class SwapRefused extends Error {
22
+ readonly reason: 'impact' | 'quote' | 'calldata' | 'simulation' | 'moved';
23
+ constructor(reason: 'impact' | 'quote' | 'calldata' | 'simulation' | 'moved', detail: string);
24
+ }
25
+ export interface SwapSide {
26
+ token: Address;
27
+ native: boolean;
28
+ }
29
+ export interface Quote {
30
+ summary: Record<string, unknown>;
31
+ amountIn: bigint;
32
+ amountOut: bigint;
33
+ }
34
+ /** the best route for `amountIn` with our fee in it (its echo checked: tokens, amount, fee, router) */
35
+ export declare function fetchQuote(chain: string, from: SwapSide, to: SwapSide, amountIn: bigint, feeBps: number): Promise<Quote>;
36
+ /** the swap transaction for a quote (to be checked with checkSwapCall before sending) */
37
+ export declare function buildSwap(chain: string, q: Quote, account: Address, slippageBps: number, deadline: number): Promise<Call>;
38
+ /** what `amountIn` buys at the pool's own price, after our fee (raw units; sqrtPriceX96 = √(token1/token0)) */
39
+ export declare function spotOut(sqrtPriceX96: bigint, inIsToken0: boolean, amountIn: bigint, feeBps: number): bigint;
40
+ /** the least a swap may promise: the pool price, less the impact allowed, less the slippage */
41
+ export declare const minOutFloor: (spot: bigint, impactBps: number, slippageBps: number) => bigint;
42
+ /**
43
+ * The minimum a built swap must promise: no lower than the pool-price floor, the shortfall it is for (`need`), or the
44
+ * quote less the user's slippage — with 0.01% for the build's rounding (it re-reads the route, a unit or so under).
45
+ */
46
+ export declare function requiredMinOut(o: {
47
+ spot: bigint;
48
+ impactBps: number;
49
+ slippageBps: number;
50
+ need: bigint;
51
+ quoteOut: bigint;
52
+ }): bigint;
53
+ declare const ROUTER_ABI: readonly [{
54
+ readonly name: "swap";
55
+ readonly type: "function";
56
+ readonly stateMutability: "payable";
57
+ readonly inputs: readonly [{
58
+ readonly type: "tuple";
59
+ readonly components: readonly [{
60
+ readonly type: "address";
61
+ readonly name: "callTarget";
62
+ }, {
63
+ readonly type: "address";
64
+ readonly name: "approveTarget";
65
+ }, {
66
+ readonly type: "bytes";
67
+ readonly name: "targetData";
68
+ }, {
69
+ readonly name: "desc";
70
+ readonly type: "tuple";
71
+ readonly components: readonly [{
72
+ readonly type: "address";
73
+ readonly name: "srcToken";
74
+ }, {
75
+ readonly type: "address";
76
+ readonly name: "dstToken";
77
+ }, {
78
+ readonly type: "address[]";
79
+ readonly name: "srcReceivers";
80
+ }, {
81
+ readonly type: "uint256[]";
82
+ readonly name: "srcAmounts";
83
+ }, {
84
+ readonly type: "address[]";
85
+ readonly name: "feeReceivers";
86
+ }, {
87
+ readonly type: "uint256[]";
88
+ readonly name: "feeAmounts";
89
+ }, {
90
+ readonly type: "address";
91
+ readonly name: "dstReceiver";
92
+ }, {
93
+ readonly type: "uint256";
94
+ readonly name: "amount";
95
+ }, {
96
+ readonly type: "uint256";
97
+ readonly name: "minReturnAmount";
98
+ }, {
99
+ readonly type: "uint256";
100
+ readonly name: "flags";
101
+ }, {
102
+ readonly type: "bytes";
103
+ readonly name: "permit";
104
+ }];
105
+ }, {
106
+ readonly type: "bytes";
107
+ readonly name: "clientData";
108
+ }];
109
+ readonly name: "execution";
110
+ }];
111
+ readonly outputs: readonly [{
112
+ readonly type: "uint256";
113
+ readonly name: "returnAmount";
114
+ }, {
115
+ readonly type: "uint256";
116
+ readonly name: "gasUsed";
117
+ }];
118
+ }];
119
+ export { ROUTER_ABI as KYBER_ROUTER_ABI };
120
+ /** throws SwapRefused unless the call is exactly the swap meant: see the module comment */
121
+ export declare function checkSwapCall(c: Call, exp: {
122
+ from: SwapSide;
123
+ to: SwapSide;
124
+ amountIn: bigint;
125
+ account: Address;
126
+ feeBps: number;
127
+ minOut: bigint;
128
+ }): void;