@logswap/sdk 0.5.102 → 0.5.103
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/README.md +14 -418
- package/dist/actions.d.ts +0 -39
- package/dist/actions.js +0 -39
- package/dist/admin.d.ts +0 -106
- package/dist/admin.js +1 -96
- package/dist/chains.d.ts +0 -49
- package/dist/chains.js +0 -30
- package/dist/claims.d.ts +0 -32
- package/dist/claims.js +0 -30
- package/dist/client.d.ts +0 -116
- package/dist/client.js +1 -231
- package/dist/fees.d.ts +1 -45
- package/dist/fees.js +0 -44
- package/dist/fpool.d.ts +4 -612
- package/dist/fpool.js +14 -490
- package/dist/generated.js +0 -30
- package/dist/history.d.ts +0 -61
- package/dist/history.js +5 -74
- package/dist/ids.d.ts +0 -30
- package/dist/ids.js +0 -31
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -7
- package/dist/indexer.d.ts +0 -68
- package/dist/indexer.js +1 -77
- package/dist/keys.d.ts +0 -50
- package/dist/keys.js +0 -35
- package/dist/liquidity.d.ts +0 -128
- package/dist/liquidity.js +1 -107
- package/dist/onboard.d.ts +0 -52
- package/dist/onboard.js +1 -59
- package/dist/pools.d.ts +3 -157
- package/dist/pools.js +1 -164
- package/dist/positions.d.ts +0 -102
- package/dist/positions.js +1 -90
- package/dist/quote.d.ts +0 -14
- package/dist/quote.js +0 -14
- package/dist/swap.d.ts +0 -31
- package/dist/swap.js +5 -37
- package/dist/tokencache.d.ts +0 -48
- package/dist/tokencache.js +1 -73
- package/dist/write.d.ts +1 -87
- package/dist/write.js +1 -87
- package/package.json +3 -8
- package/src/actions.ts +0 -208
- package/src/admin.ts +0 -350
- package/src/chains.ts +0 -278
- package/src/claims.ts +0 -111
- package/src/client.ts +0 -436
- package/src/fees.ts +0 -138
- package/src/fpool.ts +0 -2049
- package/src/generated.ts +0 -4345
- package/src/history.ts +0 -383
- package/src/ids.ts +0 -78
- package/src/index.ts +0 -26
- package/src/indexer.ts +0 -264
- package/src/keys.ts +0 -138
- package/src/liquidity.ts +0 -456
- package/src/onboard.ts +0 -253
- package/src/pools.ts +0 -465
- package/src/positions.ts +0 -297
- package/src/quote.ts +0 -36
- package/src/swap.ts +0 -181
- package/src/tokencache.ts +0 -178
- package/src/write.ts +0 -236
package/src/positions.ts
DELETED
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* positions.ts — position and fee reads.
|
|
3
|
-
*
|
|
4
|
-
* A position CLASS is fungible at its full key: uncapped by (pool, floor), capped by
|
|
5
|
-
* (pool, floor, cap). Holders own ERC-6909 shares of a class; fees are tracked per holder, so two
|
|
6
|
-
* accounts holding the same class can have different claimable amounts.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { encodeAbiParameters, keccak256, parseAbiItem } from "viem";
|
|
10
|
-
import type { Address, Hex } from "viem";
|
|
11
|
-
import { lensCAbi, managerCAbi } from "./generated.js";
|
|
12
|
-
import { managerC, lensC, type LogswapClient } from "./client.js";
|
|
13
|
-
import { poolId, tickSpacingOf, type PoolKey } from "./keys.js";
|
|
14
|
-
|
|
15
|
-
/** `CPoolState.POSITIONS_SLOT`: the manager's `positions` mapping (`forge inspect CPoolManager storageLayout`). */
|
|
16
|
-
const C_POSITIONS_SLOT = 4n;
|
|
17
|
-
const U128 = (1n << 128n) - 1n;
|
|
18
|
-
import { isPosition, NO_CAP, positionId, unpackFloorCap } from "./ids.js";
|
|
19
|
-
import { getEventLogs } from "./history.js";
|
|
20
|
-
|
|
21
|
-
/** A class's aggregate state — the whole class, not one holder's slice. */
|
|
22
|
-
export interface PositionClass {
|
|
23
|
-
/** Total exposure across every holder. */
|
|
24
|
-
L: bigint;
|
|
25
|
-
/** Total shares outstanding. */
|
|
26
|
-
shares: bigint;
|
|
27
|
-
/** Fee-per-share accumulator (masterchef-style). */
|
|
28
|
-
aps: bigint;
|
|
29
|
-
/** Snapshot of `F_above[floor] − F_above[cap]` at the class's last touch. */
|
|
30
|
-
insideLast: bigint;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* A class's aggregate state, read through `extsload` (C version 7: the manager's public
|
|
35
|
-
* `positions` mapping is gone behind it, decisions 065). The slot is `CPoolState`'s:
|
|
36
|
-
* `keccak256(abi.encode(id, POSITIONS_SLOT = 4))`, two words — (L | shares << 128) and
|
|
37
|
-
* (aps | insideLast << 128). Pinned on chain by the integration suite.
|
|
38
|
-
*/
|
|
39
|
-
export async function getPositionClass(c: LogswapClient, id: bigint): Promise<PositionClass> {
|
|
40
|
-
const slot = keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "uint256" }], [id, C_POSITIONS_SLOT]));
|
|
41
|
-
const w = (await c.public.readContract({
|
|
42
|
-
address: managerC(c),
|
|
43
|
-
abi: managerCAbi,
|
|
44
|
-
functionName: "extsload",
|
|
45
|
-
args: [slot, 2n],
|
|
46
|
-
} as never)) as readonly Hex[];
|
|
47
|
-
const w0 = BigInt(w[0]!), w1 = BigInt(w[1]!);
|
|
48
|
-
const hi = w1 >> 128n;
|
|
49
|
-
return { L: w0 & U128, shares: w0 >> 128n, aps: w1 & U128, insideLast: hi >= 1n << 127n ? hi - (1n << 128n) : hi };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** A holder's share balance in a class. */
|
|
53
|
-
export async function balanceOf(c: LogswapClient, owner: Address, id: bigint): Promise<bigint> {
|
|
54
|
-
return c.public.readContract({
|
|
55
|
-
address: managerC(c),
|
|
56
|
-
abi: managerCAbi,
|
|
57
|
-
functionName: "balanceOf",
|
|
58
|
-
args: [owner, id],
|
|
59
|
-
}) as Promise<bigint>;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* A holder's claimable fees, in quote.
|
|
64
|
-
*
|
|
65
|
-
* For a capped class this is credit-minus-debit — two accumulator reads, `F_above[floor]` less
|
|
66
|
-
* `F_above[cap]` — which is monotone non-decreasing, so a capped position can never owe fees.
|
|
67
|
-
*/
|
|
68
|
-
export async function feesOf(c: LogswapClient, id: bigint, owner: Address): Promise<bigint> {
|
|
69
|
-
return c.public.readContract({
|
|
70
|
-
address: lensC(c),
|
|
71
|
-
abi: lensCAbi,
|
|
72
|
-
functionName: "feesOfById",
|
|
73
|
-
args: [id, owner],
|
|
74
|
-
}) as Promise<bigint>;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** A holder's full view of one class: what they own and what they can claim. */
|
|
78
|
-
export interface HolderPosition {
|
|
79
|
-
id: bigint;
|
|
80
|
-
key: PoolKey;
|
|
81
|
-
floor: bigint;
|
|
82
|
-
cap: bigint;
|
|
83
|
-
capped: boolean;
|
|
84
|
-
shares: bigint;
|
|
85
|
-
/** The holder's pro-rata slice of the class's exposure. */
|
|
86
|
-
L: bigint;
|
|
87
|
-
claimableFees: bigint;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Everything a UI needs for one holder in one class. Computes the id offline, so this costs three
|
|
92
|
-
* reads and no id lookup.
|
|
93
|
-
*/
|
|
94
|
-
export async function getHolderPosition(
|
|
95
|
-
c: LogswapClient,
|
|
96
|
-
key: PoolKey,
|
|
97
|
-
owner: Address,
|
|
98
|
-
floor: bigint,
|
|
99
|
-
cap: bigint = NO_CAP,
|
|
100
|
-
): Promise<HolderPosition> {
|
|
101
|
-
const id = positionId(poolId(key), tickSpacingOf(key), floor, cap);
|
|
102
|
-
const [cls, shares, claimableFees] = await Promise.all([
|
|
103
|
-
getPositionClass(c, id),
|
|
104
|
-
balanceOf(c, owner, id),
|
|
105
|
-
feesOf(c, id, owner),
|
|
106
|
-
]);
|
|
107
|
-
return {
|
|
108
|
-
id,
|
|
109
|
-
key,
|
|
110
|
-
floor,
|
|
111
|
-
cap,
|
|
112
|
-
capped: cap !== NO_CAP,
|
|
113
|
-
shares,
|
|
114
|
-
L: cls.shares === 0n ? 0n : (cls.L * shares) / cls.shares,
|
|
115
|
-
claimableFees,
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Resolve an id the manager already knows back to its (pool, floor, cap).
|
|
121
|
-
*
|
|
122
|
-
* The inverse direction — id to class — needs the registry, because the id is a HASH: it cannot be
|
|
123
|
-
* unpacked offline the way `positionId` can be computed offline. `ClassRegistered` carries the same
|
|
124
|
-
* information in the clear, so an indexer never needs this call.
|
|
125
|
-
*
|
|
126
|
-
* **Units.** The lens is inconsistent here and this wrapper hides it: `unpack` returns tick
|
|
127
|
-
* INDICES (`kFloor`, `kCap`), while `liveFloors` returns log-price floors. Pass `tickSpacing` and
|
|
128
|
-
* you get `floor`/`cap` in log-price WAD, the same units `mint` takes; omit it and you get the raw
|
|
129
|
-
* indices, honestly named.
|
|
130
|
-
*/
|
|
131
|
-
export async function describeId(
|
|
132
|
-
c: LogswapClient,
|
|
133
|
-
id: bigint,
|
|
134
|
-
tickSpacing?: bigint,
|
|
135
|
-
): Promise<{
|
|
136
|
-
poolId: `0x${string}`;
|
|
137
|
-
kFloor: bigint;
|
|
138
|
-
kCap: bigint;
|
|
139
|
-
capped: boolean;
|
|
140
|
-
floor?: bigint;
|
|
141
|
-
cap?: bigint;
|
|
142
|
-
}> {
|
|
143
|
-
const r = (await c.public.readContract({
|
|
144
|
-
address: lensC(c),
|
|
145
|
-
abi: lensCAbi,
|
|
146
|
-
functionName: "unpack",
|
|
147
|
-
args: [id],
|
|
148
|
-
})) as readonly [`0x${string}`, bigint, bigint, boolean];
|
|
149
|
-
const out = { poolId: r[0], kFloor: r[1], kCap: r[2], capped: r[3] };
|
|
150
|
-
if (tickSpacing === undefined) return out;
|
|
151
|
-
return {
|
|
152
|
-
...out,
|
|
153
|
-
floor: r[1] * tickSpacing,
|
|
154
|
-
cap: r[3] ? r[2] * tickSpacing : NO_CAP,
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Split ERC-6909 ids into positions and token claims.
|
|
160
|
-
*
|
|
161
|
-
* **Do this before treating any `Transfer` as an LP event.** Bit 255 clear means a token claim — a
|
|
162
|
-
* bearer IOU a market maker uses to park inventory inside the manager — not a position. An indexer
|
|
163
|
-
* that skips this reports phantom LP positions for every parked balance.
|
|
164
|
-
*/
|
|
165
|
-
export function partitionIds(ids: readonly bigint[]): { positions: bigint[]; claims: bigint[] } {
|
|
166
|
-
const positions: bigint[] = [];
|
|
167
|
-
const claims: bigint[] = [];
|
|
168
|
-
for (const id of ids) (isPosition(id) ? positions : claims).push(id);
|
|
169
|
-
return { positions, claims };
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** Decode a class's floor and cap from its packed field (as carried by `ClassRegistered`). */
|
|
173
|
-
export function describePacked(tickSpacing: bigint, packed: bigint) {
|
|
174
|
-
return unpackFloorCap(tickSpacing, packed);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* The QUOTE leg of a position at log-price `x`, in quote units.
|
|
179
|
-
*
|
|
180
|
-
* Mirrors the manager's `_assets` exactly, in its three cases:
|
|
181
|
-
*
|
|
182
|
-
* - **floor above spot** — the position is all base and holds no quote at all.
|
|
183
|
-
* - **in range** — `L·(x − ξ)`: the buffer built up as price rose from the floor.
|
|
184
|
-
* - **capped out** (spot at or above the cap) — `L·(cap − ξ)`, frozen. Past its cap a position
|
|
185
|
-
* stops converting, which is what makes a capped position a resting limit order.
|
|
186
|
-
*
|
|
187
|
-
* Exact: this is bigint arithmetic throughout, unlike the base leg, which needs `L/p` and is
|
|
188
|
-
* therefore transcendental. If you need base, read it from the chain rather than approximating it
|
|
189
|
-
* here — a display-only float has no business being subtracted from a balance.
|
|
190
|
-
*/
|
|
191
|
-
export function positionQuote(
|
|
192
|
-
p: { L: bigint; floor: bigint; cap: bigint; capped: boolean },
|
|
193
|
-
x: bigint,
|
|
194
|
-
): bigint {
|
|
195
|
-
if (p.floor > x) return 0n;
|
|
196
|
-
const upper = p.capped && p.cap <= x ? p.cap : x;
|
|
197
|
-
return (p.L * (upper - p.floor)) / 10n ** 18n;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* The one-time mint fee at log-price `x`, in quote units — the amount `_mintCore` pulls ON TOP of
|
|
202
|
-
* the position's own legs, so a mint's total quote pull is `positionQuote(p, x) + mintFee(p, x, rate)`.
|
|
203
|
-
* `rate` is the MARKET's mint fee, WAD of L (`mintFeeOfKey(key)`): the fee list's next entry after the key's swap fee
|
|
204
|
-
* (C 18, decision 099), fixed for life; there is no global `MINT_FEE`.
|
|
205
|
-
*
|
|
206
|
-
* Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
|
|
207
|
-
* capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
|
|
208
|
-
* the protocol's (decisions 058); with no treasury it goes through `F` to the LPs already
|
|
209
|
-
* earning, and with none earning it is not charged. This is NOT the swap fee: that one is charged
|
|
210
|
-
* per unit of |Δ log p| on swaps; this is a flat charge on L, once, at mint.
|
|
211
|
-
*
|
|
212
|
-
* One rung of imprecision: for a floor or cap exactly AT spot the contract consults its `currentK`
|
|
213
|
-
* pointer (an up-move counts the tick, a down-move does not), which this offline mirror cannot see.
|
|
214
|
-
* Preview with it; let the chain be authoritative on that boundary.
|
|
215
|
-
*/
|
|
216
|
-
export function mintFee(
|
|
217
|
-
p: { L: bigint; floor: bigint; cap: bigint; capped: boolean },
|
|
218
|
-
x: bigint,
|
|
219
|
-
rate: bigint,
|
|
220
|
-
): bigint {
|
|
221
|
-
if (p.floor > x || (p.capped && p.cap <= x)) return 0n;
|
|
222
|
-
return (p.L * rate) / 10n ** 18n;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
* Every UNCAPPED position `owner` holds in a market, enumerated fully on-chain by the lens — a
|
|
227
|
-
* bitmap walk plus a balance check per live floor. No indexer, no log scan. Capped classes are
|
|
228
|
-
* not listed here by contract (their candidate set is quadratic in live ticks); they come from
|
|
229
|
-
* `ClassRegistered` replay when an indexer exists.
|
|
230
|
-
*/
|
|
231
|
-
export interface HeldPositionRow {
|
|
232
|
-
id: bigint;
|
|
233
|
-
floor: bigint;
|
|
234
|
-
/** NO_CAP for an uncapped class. */
|
|
235
|
-
cap: bigint;
|
|
236
|
-
capped: boolean;
|
|
237
|
-
shares: bigint;
|
|
238
|
-
/** The holder's slice of the class's exposure. */
|
|
239
|
-
L: bigint;
|
|
240
|
-
/** Claimable now, quote units. */
|
|
241
|
-
fees: bigint;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export async function positionsOf(c: LogswapClient, key: PoolKey, owner: Address): Promise<HeldPositionRow[]> {
|
|
245
|
-
const rows = (await c.public.readContract({
|
|
246
|
-
address: lensC(c),
|
|
247
|
-
abi: lensCAbi,
|
|
248
|
-
functionName: "positionsOf",
|
|
249
|
-
args: [poolId(key), owner],
|
|
250
|
-
} as never)) as readonly { id: bigint; floor: bigint; shares: bigint; L: bigint; fees: bigint }[];
|
|
251
|
-
return rows.map((r) => ({ id: r.id, floor: r.floor, cap: NO_CAP, capped: false, shares: r.shares, L: r.L, fees: r.fees }));
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
const ID_REGISTERED = parseAbiItem("event ClassRegistered(bytes32 indexed poolId, uint256 indexed id, int256 floor, int256 cap, bool capped)") // C 17: poolId first;
|
|
255
|
-
|
|
256
|
-
/** Every class id ever registered in `pool` (`ClassRegistered`), from the indexer's table or the node. */
|
|
257
|
-
async function registeredIds(c: LogswapClient, pool: Hex, fromBlock?: bigint, indexer?: string): Promise<bigint[]> {
|
|
258
|
-
const { logs } = await getEventLogs<{ id?: bigint }>(c, { indexer, address: managerC(c), event: ID_REGISTERED, args: { poolId: pool }, fromBlock });
|
|
259
|
-
return logs.map((l) => l.args.id ?? 0n).filter((id) => id !== 0n);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* EVERY class this owner holds in a pool, capped ones included — the complete book.
|
|
264
|
-
*
|
|
265
|
-
* `positionsOf` (the lens) enumerates the uncapped book from the ladder bitmap in one call and
|
|
266
|
-
* cannot list capped classes: a capped id is a (floor, cap) pair, quadratic in live ticks. This
|
|
267
|
-
* replays `ClassRegistered` — every class is registered once, on first mint, with its floor and
|
|
268
|
-
* cap — then checks the owner's ERC-6909 balance on each and reads the class for its L, so the
|
|
269
|
-
* holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
|
|
270
|
-
* a read per registered class; fine for a pool's lifetime of classes.
|
|
271
|
-
*/
|
|
272
|
-
export async function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock?: bigint, opts: { /** The rindexer GraphQL endpoint: the class registry from its tables, the node otherwise. Defaults to the client's. */ indexer?: string } = {}): Promise<HeldPositionRow[]> {
|
|
273
|
-
const pool = poolId(key);
|
|
274
|
-
const indexer = opts.indexer ?? c.indexerUrl;
|
|
275
|
-
const ids = await registeredIds(c, pool, fromBlock, indexer);
|
|
276
|
-
if (ids.length === 0) return [];
|
|
277
|
-
// one lens call: balance, class L, fees, floor and cap for every id the owner holds
|
|
278
|
-
const rows = (await c.public.readContract({
|
|
279
|
-
address: lensC(c),
|
|
280
|
-
abi: lensCAbi,
|
|
281
|
-
functionName: "heldByIds",
|
|
282
|
-
args: [poolId(key), owner, ids],
|
|
283
|
-
} as never)) as readonly { id: bigint; floor: bigint; cap: bigint; capped: boolean; shares: bigint; L: bigint; fees: bigint }[];
|
|
284
|
-
return rows.map((r) => ({ id: r.id, floor: r.floor, cap: r.capped ? r.cap : NO_CAP, capped: r.capped, shares: r.shares, L: r.L, fees: r.fees }));
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/** A holding's legs, exact from the lens: base (base units), the quote leg, claimable fees, and
|
|
288
|
-
* value = base·p + quote + fees in quote units — L + quote + fees for an uncapped active class. */
|
|
289
|
-
export async function legsOf(c: LogswapClient, key: PoolKey, id: bigint, holder: Address): Promise<{ base: bigint; quote: bigint; fees: bigint; value: bigint }> {
|
|
290
|
-
const [base, quote, fees, value] = (await c.public.readContract({
|
|
291
|
-
address: lensC(c),
|
|
292
|
-
abi: lensCAbi,
|
|
293
|
-
functionName: "legsOf",
|
|
294
|
-
args: [poolId(key), id, holder],
|
|
295
|
-
} as never)) as readonly [bigint, bigint, bigint, bigint];
|
|
296
|
-
return { base, quote, fees, value };
|
|
297
|
-
}
|
package/src/quote.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* quote.ts — reading a revert-quoter's answer.
|
|
3
|
-
*
|
|
4
|
-
* Both managers' quoters are the router's (`Router.quoteSwap`, F: decision 049, C: decision 092): the real swap runs
|
|
5
|
-
* in the manager's lock and the contract reverts with `QuoteResult(uint256)`. The value is therefore decoded out of the
|
|
6
|
-
* revert, not returned. There is no second pricing path to drift from the first.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { toFunctionSelector } from "viem";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* `QuoteResult(uint256)` — selector then one word. viem nests the revert data several layers deep
|
|
13
|
-
* depending on the transport, so walk for it rather than guessing the shape.
|
|
14
|
-
*
|
|
15
|
-
* The selector is DERIVED, not written down. A hardcoded one is wrong silently: the decode simply
|
|
16
|
-
* never matches and every quote rethrows as if the swap had failed.
|
|
17
|
-
*/
|
|
18
|
-
export function findQuoteResult(err: unknown): bigint | null {
|
|
19
|
-
const SELECTOR = toFunctionSelector("QuoteResult(uint256)");
|
|
20
|
-
const seen = new Set<unknown>();
|
|
21
|
-
const walk = (e: unknown): bigint | null => {
|
|
22
|
-
if (!e || typeof e !== "object" || seen.has(e)) return null;
|
|
23
|
-
seen.add(e);
|
|
24
|
-
const anyE = e as Record<string, unknown>;
|
|
25
|
-
const data = anyE.data;
|
|
26
|
-
if (typeof data === "string" && data.startsWith(SELECTOR) && data.length >= 10 + 64) {
|
|
27
|
-
return BigInt("0x" + data.slice(10, 10 + 64));
|
|
28
|
-
}
|
|
29
|
-
for (const k of ["cause", "walk", "error", "details"]) {
|
|
30
|
-
const found = walk(anyE[k]);
|
|
31
|
-
if (found !== null) return found;
|
|
32
|
-
}
|
|
33
|
-
return null;
|
|
34
|
-
};
|
|
35
|
-
return walk(err);
|
|
36
|
-
}
|
package/src/swap.ts
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* swap.ts — trading.
|
|
3
|
-
*
|
|
4
|
-
* All four shapes go through the router, which is where slippage and deadline live. The manager's
|
|
5
|
-
* merged `swap(key, baseSide, amount, limit)` uses a NEGATIVE amount for exact-out; that convention
|
|
6
|
-
* is deliberately not exposed here — callers say `swapExactOut`.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { zeroAddress, type Address, type Hash } from "viem";
|
|
10
|
-
import { routerCAbi } from "./generated.js";
|
|
11
|
-
import { routerC, type LogswapClient } from "./client.js";
|
|
12
|
-
import { poolId as keyId, type PoolKey } from "./keys.js";
|
|
13
|
-
import { findQuoteResult } from "./quote.js";
|
|
14
|
-
import { resolveDeadline, resolveRecipient, sendRouterWrite, type WriteOptions , sendRouterWriteWithPermits } from "./write.js";
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* The C quoter (C 14, decision 092): `Router.quoteSwap` runs the real swap in the manager's lock for `taker` and reverts
|
|
18
|
-
* with `QuoteResult`, so the answer is decoded out of the revert. `baseSide` says whether the SPECIFIED token is the base.
|
|
19
|
-
* The taker matters only on a gated market (the router must then be the taker's ERC-6909 operator, as for the swap):
|
|
20
|
-
* the connected account, or the zero address.
|
|
21
|
-
*/
|
|
22
|
-
async function quoteSwapC(
|
|
23
|
-
c: LogswapClient,
|
|
24
|
-
key: PoolKey,
|
|
25
|
-
exactIn: boolean,
|
|
26
|
-
baseSide: boolean,
|
|
27
|
-
amount: bigint,
|
|
28
|
-
taker?: Address,
|
|
29
|
-
): Promise<bigint> {
|
|
30
|
-
try {
|
|
31
|
-
await c.public.simulateContract({
|
|
32
|
-
address: routerC(c),
|
|
33
|
-
abi: routerCAbi,
|
|
34
|
-
functionName: "quoteSwap",
|
|
35
|
-
args: [keyId(key), exactIn, baseSide, amount, taker ?? c.wallet?.account?.address ?? zeroAddress],
|
|
36
|
-
} as never);
|
|
37
|
-
} catch (err) {
|
|
38
|
-
const hit = findQuoteResult(err);
|
|
39
|
-
if (hit !== null) return hit;
|
|
40
|
-
throw err; // a real revert — no liquidity, a gate, a bad amount — belongs to the caller
|
|
41
|
-
}
|
|
42
|
-
throw new Error("logswap: quoteSwap returned without reverting, which it must never do");
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Quote an exact-in swap. Exact, not approximate — the router runs the real swap and reverts with the result, so
|
|
47
|
-
* what it returns is what execution returns, bit for bit (including the dynamic fee, even across a block boundary
|
|
48
|
-
* with the variance fold pending).
|
|
49
|
-
*/
|
|
50
|
-
export async function quoteExactIn(
|
|
51
|
-
c: LogswapClient,
|
|
52
|
-
key: PoolKey,
|
|
53
|
-
baseIn: boolean,
|
|
54
|
-
amountIn: bigint,
|
|
55
|
-
taker?: Address,
|
|
56
|
-
): Promise<bigint> {
|
|
57
|
-
return quoteSwapC(c, key, true, baseIn, amountIn, taker);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Quote an exact-out swap: how much input it will cost. Exact, same mechanism as above. */
|
|
61
|
-
export async function quoteExactOut(
|
|
62
|
-
c: LogswapClient,
|
|
63
|
-
key: PoolKey,
|
|
64
|
-
baseOut: boolean,
|
|
65
|
-
amountOut: bigint,
|
|
66
|
-
taker?: Address,
|
|
67
|
-
): Promise<bigint> {
|
|
68
|
-
return quoteSwapC(c, key, false, baseOut, amountOut, taker);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export interface SwapExactInArgs extends WriteOptions {
|
|
72
|
-
key: PoolKey;
|
|
73
|
-
/** true = base in, quote out (price falls). false = quote in, base out (price rises). */
|
|
74
|
-
baseIn: boolean;
|
|
75
|
-
amountIn: bigint;
|
|
76
|
-
/** Reverts below this. Derive from a quote with `withSlippage(q, bps, "output")`. */
|
|
77
|
-
minOut: bigint;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export async function swapExactIn(c: LogswapClient, a: SwapExactInArgs): Promise<Hash> {
|
|
81
|
-
return sendRouterWriteWithPermits(c, {
|
|
82
|
-
side: "C",
|
|
83
|
-
abi: routerCAbi,
|
|
84
|
-
functionName: "swapExactIn",
|
|
85
|
-
args: [
|
|
86
|
-
keyId(a.key),
|
|
87
|
-
a.baseIn ? a.key.base : a.key.quote, // tokenIn: the router checks the tokens the caller names against the pool's
|
|
88
|
-
a.baseIn ? a.key.quote : a.key.base, // tokenOut
|
|
89
|
-
a.baseIn,
|
|
90
|
-
a.amountIn,
|
|
91
|
-
a.minOut,
|
|
92
|
-
resolveRecipient(c, a),
|
|
93
|
-
resolveDeadline(a),
|
|
94
|
-
],
|
|
95
|
-
}, [a.baseIn ? a.key.base : a.key.quote]);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export interface SwapExactOutArgs extends WriteOptions {
|
|
99
|
-
key: PoolKey;
|
|
100
|
-
/** true = base out (price rises). false = quote out (price falls). */
|
|
101
|
-
baseOut: boolean;
|
|
102
|
-
amountOut: bigint;
|
|
103
|
-
/** Reverts above this. Derive from a quote with `withSlippage(q, bps, "input")`. */
|
|
104
|
-
maxIn: bigint;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export async function swapExactOut(c: LogswapClient, a: SwapExactOutArgs): Promise<Hash> {
|
|
108
|
-
return sendRouterWriteWithPermits(c, {
|
|
109
|
-
side: "C",
|
|
110
|
-
abi: routerCAbi,
|
|
111
|
-
functionName: "swapExactOut",
|
|
112
|
-
args: [
|
|
113
|
-
keyId(a.key),
|
|
114
|
-
a.baseOut ? a.key.quote : a.key.base, // tokenIn
|
|
115
|
-
a.baseOut ? a.key.base : a.key.quote, // tokenOut
|
|
116
|
-
a.baseOut,
|
|
117
|
-
a.amountOut,
|
|
118
|
-
a.maxIn,
|
|
119
|
-
resolveRecipient(c, a),
|
|
120
|
-
resolveDeadline(a),
|
|
121
|
-
],
|
|
122
|
-
}, [a.baseOut ? a.key.quote : a.key.base]);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/** One leg of a route. `baseIn` is that hop's direction through its own market. */
|
|
126
|
-
export interface Hop {
|
|
127
|
-
key: PoolKey;
|
|
128
|
-
baseIn: boolean;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export interface SwapPathArgs extends WriteOptions {
|
|
132
|
-
hops: readonly Hop[];
|
|
133
|
-
amountIn: bigint;
|
|
134
|
-
minOut: bigint;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Multi-hop, all inside ONE lock.
|
|
139
|
-
*
|
|
140
|
-
* The singleton dividend: deltas accrue per TOKEN across the whole route, so an intermediate asset
|
|
141
|
-
* is never actually moved — a three-market route transfers only the tokens at the endpoints. The
|
|
142
|
-
* path is not validated on-chain, and it does not need to be: a mis-chained hop leaves a dangling
|
|
143
|
-
* delta and the lock refuses to close.
|
|
144
|
-
*/
|
|
145
|
-
export async function swapExactInPath(c: LogswapClient, a: SwapPathArgs): Promise<Hash> {
|
|
146
|
-
if (a.hops.length === 0) throw new Error("logswap: empty path");
|
|
147
|
-
return sendRouterWrite(c, {
|
|
148
|
-
side: "C",
|
|
149
|
-
abi: routerCAbi,
|
|
150
|
-
functionName: "swapExactInPath",
|
|
151
|
-
args: [
|
|
152
|
-
a.hops.map((h) => ({ poolId: keyId(h.key), baseIn: h.baseIn })),
|
|
153
|
-
hopTokens(a.hops[0]!).tokenIn,
|
|
154
|
-
hopTokens(a.hops[a.hops.length - 1]!).tokenOut,
|
|
155
|
-
a.amountIn,
|
|
156
|
-
a.minOut,
|
|
157
|
-
resolveRecipient(c, a),
|
|
158
|
-
resolveDeadline(a),
|
|
159
|
-
],
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Which token a hop takes in and pays out — the check a UI should run before building a route, so
|
|
165
|
-
* a mis-chained path fails in the form rather than at the lock.
|
|
166
|
-
*/
|
|
167
|
-
export function hopTokens(h: Hop): { tokenIn: Address; tokenOut: Address } {
|
|
168
|
-
return h.baseIn
|
|
169
|
-
? { tokenIn: h.key.base, tokenOut: h.key.quote }
|
|
170
|
-
: { tokenIn: h.key.quote, tokenOut: h.key.base };
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/** True when every hop's output feeds the next hop's input. */
|
|
174
|
-
export function isPathChained(hops: readonly Hop[]): boolean {
|
|
175
|
-
for (let i = 1; i < hops.length; i++) {
|
|
176
|
-
const prev = hopTokens(hops[i - 1]!);
|
|
177
|
-
const next = hopTokens(hops[i]!);
|
|
178
|
-
if (prev.tokenOut.toLowerCase() !== next.tokenIn.toLowerCase()) return false;
|
|
179
|
-
}
|
|
180
|
-
return true;
|
|
181
|
-
}
|
package/src/tokencache.ts
DELETED
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* tokencache.ts — remember token metadata so it is read once, not once per screen.
|
|
3
|
-
*
|
|
4
|
-
* `marketTokens` costs four reads per market and every screen calls it. On two markets that is
|
|
5
|
-
* free; on fifty it is a hundred round trips on every navigation, over a tunnel.
|
|
6
|
-
*
|
|
7
|
-
* **A cache over a value that becomes a transaction amount is a way to be wrong, so three rules
|
|
8
|
-
* hold here and are enforced by tests:**
|
|
9
|
-
*
|
|
10
|
-
* 1. **Only successes are stored.** The previous fix made a failed `decimals()` read throw rather
|
|
11
|
-
* than assume 18; caching a failure would reintroduce that bug with a longer half-life.
|
|
12
|
-
* 2. **The key includes the chain id.** The same address is a different token on a different
|
|
13
|
-
* chain — a mock USDC at 18 decimals on a devnet, the real one at 6 on mainnet. Keying on
|
|
14
|
-
* address alone is the classic version of this bug and it survives a page reload.
|
|
15
|
-
* 3. **A fallback symbol is never stored.** `symbol` degrades to `0x5FbD…` on failure, which is
|
|
16
|
-
* fine as a label but must not be persisted — one blip would name the token that forever.
|
|
17
|
-
*
|
|
18
|
-
* 4. **A resettable chain never reaches the persistent store.** Rule 3's premise is that decimals
|
|
19
|
-
* are immutable *for the life of a token*, and the key's premise is that an address names one
|
|
20
|
-
* token forever. Both hold on a public chain. Neither holds on a local one: restart anvil and
|
|
21
|
-
* the very same deterministic addresses come back holding DIFFERENT contracts. That is not
|
|
22
|
-
* hypothetical — a `logswap.token.31337:0x5fbd…` entry saying USDC has 18 decimals outlived the
|
|
23
|
-
* deploy that wrote it and made every quote-denominated number in the app read as zero, with
|
|
24
|
-
* nothing anywhere reporting a fault. Those chains get the memory store, so a page reload is
|
|
25
|
-
* enough to correct them.
|
|
26
|
-
*
|
|
27
|
-
* Decimals are immutable for the life of a token: ERC-20 exposes no way to change them, and a token
|
|
28
|
-
* that did would break every integration, not just this one. That is what makes an unbounded TTL
|
|
29
|
-
* correct rather than merely convenient — on a chain whose addresses are permanent.
|
|
30
|
-
*/
|
|
31
|
-
|
|
32
|
-
import { LOGSWAP_CHAINS } from "./chains.js";
|
|
33
|
-
import type { Address } from "viem";
|
|
34
|
-
|
|
35
|
-
export interface CachedToken {
|
|
36
|
-
symbol: string;
|
|
37
|
-
decimals: number;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Somewhere to keep entries. Sync and tiny on purpose — `localStorage` fits, and so does a Map. */
|
|
41
|
-
export interface TokenStore {
|
|
42
|
-
get(key: string): string | null;
|
|
43
|
-
set(key: string, value: string): void;
|
|
44
|
-
/** Drop everything this store owns. Optional: a store that cannot enumerate may omit it. */
|
|
45
|
-
clear?(): void;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const memory = new Map<string, string>();
|
|
49
|
-
|
|
50
|
-
/** The default: per-process, no persistence. Works in node, workers and a browser alike. */
|
|
51
|
-
export const memoryStore: TokenStore = {
|
|
52
|
-
get: (k) => memory.get(k) ?? null,
|
|
53
|
-
set: (k, v) => void memory.set(k, v),
|
|
54
|
-
clear: () => memory.clear(),
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* `localStorage`, when there is one. Returns the memory store otherwise, so a caller never has to
|
|
59
|
-
* branch on the environment — and a browser in private mode degrades instead of throwing.
|
|
60
|
-
*/
|
|
61
|
-
export function browserStore(prefix = "logswap.token."): TokenStore {
|
|
62
|
-
try {
|
|
63
|
-
if (typeof localStorage === "undefined") return memoryStore;
|
|
64
|
-
localStorage.getItem(`${prefix}probe`); // Safari private mode throws on access, not on use
|
|
65
|
-
return {
|
|
66
|
-
get: (k) => {
|
|
67
|
-
try {
|
|
68
|
-
return localStorage.getItem(prefix + k);
|
|
69
|
-
} catch {
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
},
|
|
73
|
-
set: (k, v) => {
|
|
74
|
-
try {
|
|
75
|
-
localStorage.setItem(prefix + k, v);
|
|
76
|
-
} catch {
|
|
77
|
-
/* quota or private mode — the cache is an optimisation, never a requirement */
|
|
78
|
-
}
|
|
79
|
-
},
|
|
80
|
-
// Only this prefix, never the whole of localStorage: the app's own keys live there too.
|
|
81
|
-
clear: () => {
|
|
82
|
-
try {
|
|
83
|
-
for (const k of Object.keys(localStorage)) if (k.startsWith(prefix)) localStorage.removeItem(k);
|
|
84
|
-
} catch {
|
|
85
|
-
/* nothing to do — see set */
|
|
86
|
-
}
|
|
87
|
-
},
|
|
88
|
-
};
|
|
89
|
-
} catch {
|
|
90
|
-
return memoryStore;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
let store: TokenStore = memoryStore;
|
|
95
|
-
|
|
96
|
-
/** Swap the backing store. Call once at startup; `browserStore()` is the usual argument. */
|
|
97
|
-
export function setTokenStore(s: TokenStore): void {
|
|
98
|
-
store = s;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Address casing varies by source, so normalise — otherwise the same token gets two entries. */
|
|
102
|
-
const keyOf = (chainId: number, address: Address) => `${chainId}:${address.toLowerCase()}`;
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Chains whose addresses are not permanent identities: a development node can be wiped and
|
|
106
|
-
* redeployed, and because deployment addresses are derived from a deterministic nonce sequence the
|
|
107
|
-
* SAME address comes back holding a different contract. Every chain the registry flags `devnet`
|
|
108
|
-
* (31337 anvil's and hardhat's default, 31339 the logswap devnet), plus 1337 (ganache's and
|
|
109
|
-
* hardhat's legacy id) and 31338 (the unimod devnet), persisted with `--state` and documented as
|
|
110
|
-
* resettable by deleting that file.
|
|
111
|
-
*
|
|
112
|
-
* Add to this set rather than removing from it ({@link addResettableChain}): a chain wrongly listed
|
|
113
|
-
* here costs some RPC round trips, while one wrongly absent silently serves a stale scale, which is
|
|
114
|
-
* the bug this exists for.
|
|
115
|
-
*/
|
|
116
|
-
const resettable = new Set<number>([1337, 31338, ...Object.values(LOGSWAP_CHAINS).filter((ch) => ch.devnet).map((ch) => ch.chainId)]);
|
|
117
|
-
export const RESETTABLE_CHAINS: ReadonlySet<number> = resettable;
|
|
118
|
-
|
|
119
|
-
/** Mark a development chain the registry does not list as resettable. There is no removal. */
|
|
120
|
-
export function addResettableChain(chainId: number): void {
|
|
121
|
-
resettable.add(chainId);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** True when a `(chainId, address)` pair cannot be trusted to name one contract forever. */
|
|
125
|
-
export function isResettableChain(chainId: number): boolean {
|
|
126
|
-
return RESETTABLE_CHAINS.has(chainId);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* The store an entry for this chain may use. A resettable chain gets memory — good enough to stop
|
|
131
|
-
* one navigation re-reading the same token fifty times, and gone on reload, which is exactly the
|
|
132
|
-
* lifetime over which its addresses can be trusted.
|
|
133
|
-
*/
|
|
134
|
-
const storeFor = (chainId: number): TokenStore => (isResettableChain(chainId) ? memoryStore : store);
|
|
135
|
-
|
|
136
|
-
export function readCachedToken(chainId: number, address: Address): CachedToken | null {
|
|
137
|
-
const raw = storeFor(chainId).get(keyOf(chainId, address));
|
|
138
|
-
if (!raw) return null;
|
|
139
|
-
try {
|
|
140
|
-
const v = JSON.parse(raw) as CachedToken;
|
|
141
|
-
// Validate on the way OUT as well as in: the store is shared with other tabs and other builds,
|
|
142
|
-
// and a corrupt entry must be ignored rather than trusted.
|
|
143
|
-
if (typeof v?.decimals !== "number" || !Number.isInteger(v.decimals) || v.decimals < 0 || v.decimals > 36) {
|
|
144
|
-
return null;
|
|
145
|
-
}
|
|
146
|
-
if (typeof v.symbol !== "string" || v.symbol === "") return null;
|
|
147
|
-
return v;
|
|
148
|
-
} catch {
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
export function writeCachedToken(chainId: number, address: Address, t: CachedToken): void {
|
|
154
|
-
storeFor(chainId).set(keyOf(chainId, address), JSON.stringify({ symbol: t.symbol, decimals: t.decimals }));
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Forget everything, including reads still in flight.
|
|
159
|
-
*
|
|
160
|
-
* For tests, and for a devnet that redeployed its mocks to the same addresses — the one case where
|
|
161
|
-
* a token at a known address legitimately changes its decimals, because it is a different contract
|
|
162
|
-
* wearing the same address.
|
|
163
|
-
*/
|
|
164
|
-
export function clearTokenCache(): void {
|
|
165
|
-
memory.clear();
|
|
166
|
-
// The persistent store too. It did not used to be, which made this function useless against the
|
|
167
|
-
// one situation its own doc names: the entry that survives a redeploy lives in `localStorage`,
|
|
168
|
-
// so clearing only memory left it in place and the next read served it straight back.
|
|
169
|
-
store.clear?.();
|
|
170
|
-
onClear.forEach((f) => f());
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const onClear = new Set<() => void>();
|
|
174
|
-
|
|
175
|
-
/** Internal: lets `pools.ts` drop its in-flight map when the cache is cleared. */
|
|
176
|
-
export function registerCacheClear(f: () => void): void {
|
|
177
|
-
onClear.add(f);
|
|
178
|
-
}
|