@logswap/sdk 0.5.101 → 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.
Files changed (64) hide show
  1. package/README.md +14 -418
  2. package/dist/actions.d.ts +0 -39
  3. package/dist/actions.js +0 -39
  4. package/dist/admin.d.ts +0 -106
  5. package/dist/admin.js +1 -96
  6. package/dist/chains.d.ts +0 -49
  7. package/dist/chains.js +0 -30
  8. package/dist/claims.d.ts +0 -32
  9. package/dist/claims.js +0 -30
  10. package/dist/client.d.ts +0 -116
  11. package/dist/client.js +1 -231
  12. package/dist/fees.d.ts +1 -45
  13. package/dist/fees.js +0 -44
  14. package/dist/fpool.d.ts +4 -612
  15. package/dist/fpool.js +14 -490
  16. package/dist/generated.js +0 -30
  17. package/dist/history.d.ts +0 -61
  18. package/dist/history.js +5 -74
  19. package/dist/ids.d.ts +0 -30
  20. package/dist/ids.js +0 -31
  21. package/dist/index.d.ts +0 -7
  22. package/dist/index.js +0 -7
  23. package/dist/indexer.d.ts +0 -68
  24. package/dist/indexer.js +1 -77
  25. package/dist/keys.d.ts +0 -50
  26. package/dist/keys.js +0 -35
  27. package/dist/liquidity.d.ts +0 -128
  28. package/dist/liquidity.js +1 -107
  29. package/dist/onboard.d.ts +0 -52
  30. package/dist/onboard.js +1 -59
  31. package/dist/pools.d.ts +3 -157
  32. package/dist/pools.js +1 -164
  33. package/dist/positions.d.ts +0 -102
  34. package/dist/positions.js +1 -90
  35. package/dist/quote.d.ts +0 -14
  36. package/dist/quote.js +0 -14
  37. package/dist/swap.d.ts +0 -31
  38. package/dist/swap.js +5 -37
  39. package/dist/tokencache.d.ts +0 -48
  40. package/dist/tokencache.js +1 -73
  41. package/dist/write.d.ts +1 -87
  42. package/dist/write.js +1 -87
  43. package/package.json +3 -8
  44. package/src/actions.ts +0 -208
  45. package/src/admin.ts +0 -350
  46. package/src/chains.ts +0 -278
  47. package/src/claims.ts +0 -111
  48. package/src/client.ts +0 -436
  49. package/src/fees.ts +0 -138
  50. package/src/fpool.ts +0 -2049
  51. package/src/generated.ts +0 -4345
  52. package/src/history.ts +0 -383
  53. package/src/ids.ts +0 -78
  54. package/src/index.ts +0 -26
  55. package/src/indexer.ts +0 -264
  56. package/src/keys.ts +0 -138
  57. package/src/liquidity.ts +0 -456
  58. package/src/onboard.ts +0 -253
  59. package/src/pools.ts +0 -465
  60. package/src/positions.ts +0 -297
  61. package/src/quote.ts +0 -36
  62. package/src/swap.ts +0 -181
  63. package/src/tokencache.ts +0 -178
  64. package/src/write.ts +0 -236
package/dist/liquidity.js CHANGED
@@ -1,26 +1,3 @@
1
- /**
2
- * liquidity.ts — providing, editing and exiting a C position.
3
- *
4
- * A class is (ξ, μ, L): floor, cap, exposure. One primitive sets all three — `update` — and every
5
- * edit is a constraint on it. The vocabulary follows the geometry: **the verb
6
- * names the axis, the direction is a signed rung count**, and only two direction-words survive,
7
- * because each names a wallet flow the user must see.
8
- *
9
- * update(ξ', μ', L') the primitive
10
- * ├─ move(ξ', μ') L pinned
11
- * │ ├─ floor(±n) μ pinned · ↑ harvest (receive quote) · ↓ deepen (pay quote)
12
- * │ ├─ cap(±n) ξ pinned · no direction words
13
- * │ └─ shift(±n) width pinned — the translation
14
- * ├─ resize(L') ξ, μ pinned; L' = 0 is the exit
15
- * └─ reprice(ξ') R pinned: L' = L·e^{ξ' − ξ}, dormant only
16
- * mint · burn · claim
17
- *
18
- * Every edit is ONE action of the router's batch (`actions.ts`), which is what
19
- * lets it settle in kind, or in base, or in quote: `settleIn` appends the one swap that nets the
20
- * other side, and the batch moves a single token. `previewEdit` is the lens's `previewUpdate` —
21
- * the exact flows, mint fee and swept fees included — and is what an editor shows before its one
22
- * apply.
23
- */
24
1
  import { lensCAbi, routerCAbi } from "./generated.js";
25
2
  import { lensC } from "./client.js";
26
3
  import { poolId as keyId, tickSpacingOf } from "./keys.js";
@@ -29,16 +6,6 @@ import { describeId, getPositionClass } from "./positions.js";
29
6
  import { execute, OPEN_DELTA, settleInKind, settleOnly, swapExactInAction, swapExactOutAction, updateAction, } from "./actions.js";
30
7
  import { requireWallet, resolveDeadline, resolveRecipient, sendRouterWrite, sendRouterWriteWithPermits, withSlippage, } from "./write.js";
31
8
  import { quoteExactIn, quoteExactOut } from "./swap.js";
32
- /**
33
- * Mint at `targetFloor`, blending across the two adjacent rungs when it is off-grid.
34
- *
35
- * This is why the floor ladder can be coarse without the UX being coarse: a blend of two adjacent
36
- * classes IS exactly one position at the weighted-mean floor, so a continuous floor slider works
37
- * over a discrete ladder. The router settles once per token, not once per rung.
38
- *
39
- * **A mint at floor == spot costs zero quote** ($Q(\xi) = 0$), and one above spot is dormant and
40
- * costs zero quote too — that is what makes single-asset entry possible in both directions.
41
- */
42
9
  export async function mint(c, a) {
43
10
  return sendRouterWriteWithPermits(c, {
44
11
  side: "C",
@@ -58,14 +25,6 @@ export async function mint(c, a) {
58
25
  ],
59
26
  }, [a.key.base, a.key.quote]);
60
27
  }
61
- /**
62
- * Fund a mint from a single asset: the router swaps the imbalanced part through the curve, then
63
- * mints, all inside one lock — the two-action batch `[swapExactIn, mint]`.
64
- *
65
- * Routing the imbalanced part through the CURVE is the point, not an implementation detail. A
66
- * pro-rata deposit of one asset would be a zero-slippage, zero-fee swap at stale spot — a subsidy
67
- * paid by the incumbent LPs. Paying the curve removes it.
68
- */
69
28
  export async function zapIn(c, a) {
70
29
  return sendRouterWriteWithPermits(c, {
71
30
  side: "C",
@@ -87,7 +46,6 @@ export async function zapIn(c, a) {
87
46
  ],
88
47
  }, [a.fundWithBase ? a.key.base : a.key.quote]);
89
48
  }
90
- /** The primitive, through the router's named entry: resize and reposition in one call, in kind. */
91
49
  export async function update(c, a) {
92
50
  return sendRouterWriteWithPermits(c, {
93
51
  side: "C",
@@ -109,13 +67,6 @@ export async function update(c, a) {
109
67
  ],
110
68
  }, [a.key.base, a.key.quote]);
111
69
  }
112
- /**
113
- * Reposition at constant exposure — the L-pinned parent of `floor`, `cap` and `shift`; in kind.
114
- *
115
- * **Bound it.** The router used to settle this entry with no limit, which meant a reposition that
116
- * priced differently by inclusion time could pull the whole allowance.
117
- * The bounds are required; {@link UNBOUNDED} is an explicit, visible opt-out.
118
- */
119
70
  export async function move(c, a) {
120
71
  return sendRouterWrite(c, {
121
72
  side: "C",
@@ -136,7 +87,6 @@ export async function move(c, a) {
136
87
  ],
137
88
  });
138
89
  }
139
- /** The exact flows of an edit before it is sent — the lens's `previewUpdate`. */
140
90
  export async function previewEdit(c, a) {
141
91
  const holder = a.holder ?? requireWallet(c).address;
142
92
  const r = (await c.public.readContract({
@@ -147,27 +97,11 @@ export async function previewEdit(c, a) {
147
97
  }));
148
98
  return { dBase: r[0], dQuote: r[1], fees: r[2] };
149
99
  }
150
- /**
151
- * Bounds for a pair of signed flows (+ = the caller pays, − = the caller receives), at `bps` of
152
- * tolerance: a payment is capped from above, a receipt floored from below, and a token that does
153
- * not move in that direction is bound to zero.
154
- */
155
100
  export function boundsFromFlows(dBase, dQuote, bps) {
156
101
  const inb = (d) => (d > 0n ? withSlippage(d, bps, "input") : 0n);
157
102
  const outb = (d) => (d < 0n ? withSlippage(-d, bps, "output") : 0n);
158
103
  return { maxBaseIn: inb(dBase), maxQuoteIn: inb(dQuote), minBaseOut: outb(dBase), minQuoteOut: outb(dQuote) };
159
104
  }
160
- /**
161
- * The general edit as a batch: `[update]`, plus — when `settleIn` is one token — the one swap that
162
- * nets the other. The other side's flow is read off the preview: released → sold with an exact-in
163
- * of `OPEN_DELTA`; owed → bought with an exact-out of `OPEN_DELTA`. The settlement then binds the
164
- * other token to zero both ways, so a stale preview fails loudly rather than moving it.
165
- *
166
- * **Bounded by default.** The preview gives the edit's exact flows at today's state; `slippageBps`
167
- * turns them into the settlement's bounds. With `settleIn` one token, the netting swap is quoted
168
- * on today's curve, before the update changes the active liquidity — close for a small edit, and
169
- * for a large one a bound that reverts rather than one that lets a sandwich through.
170
- */
171
105
  export async function edit(c, a) {
172
106
  const { key } = a;
173
107
  const recipient = resolveRecipient(c, a);
@@ -181,9 +115,7 @@ export async function edit(c, a) {
181
115
  settle = settleInKind(key, recipient, { ...boundsFromFlows(p.dBase, p.dQuote, a.slippageBps), ...defined(a) });
182
116
  }
183
117
  else {
184
- // the swept fees ride INSIDE dQuote (the manager burns by owner and nets them),
185
- // so quote's open delta after the update is dQuote itself — `fees` is reported for display only
186
- const otherFlow = settleIn === "base" ? p.dQuote : p.dBase; // + = owed, − = released
118
+ const otherFlow = settleIn === "base" ? p.dQuote : p.dBase;
187
119
  const otherIsBase = settleIn === "quote";
188
120
  let own = settleIn === "base" ? p.dBase : p.dQuote;
189
121
  if (otherFlow < 0n) {
@@ -202,11 +134,9 @@ export async function edit(c, a) {
202
134
  }
203
135
  return execute(c, { actions, settle, deadline: a.deadline, recipient });
204
136
  }
205
- /** The explicit bounds a caller passed, without the undefined ones (so they do not erase derived ones). */
206
137
  function defined(b) {
207
138
  return Object.fromEntries(["maxBaseIn", "maxQuoteIn", "minBaseOut", "minQuoteOut"].filter((k) => b[k] !== undefined).map((k) => [k, b[k]]));
208
139
  }
209
- /** The class behind `shares` of `id`: its floor, cap, and the exposure those shares carry. */
210
140
  async function classOf(c, key, id, shares) {
211
141
  const [d, cls] = await Promise.all([describeId(c, id, tickSpacingOf(key)), getPositionClass(c, id)]);
212
142
  if (d.poolId === `0x${"0".repeat(64)}`)
@@ -214,41 +144,22 @@ async function classOf(c, key, id, shares) {
214
144
  const L = cls.shares === 0n ? 0n : (cls.L * shares) / cls.shares;
215
145
  return { floor: d.floor, cap: d.cap, capped: d.capped, L };
216
146
  }
217
- /** Move the floor by `rungs` (signed), cap and L pinned. Positive = harvest, negative = deepen. */
218
147
  export async function floor(c, a) {
219
148
  const k = await classOf(c, a.key, a.fromId, a.shares);
220
149
  return edit(c, { ...a, toFloor: k.floor + a.rungs * tickSpacingOf(a.key), toCap: k.capped ? k.cap : undefined, newL: k.L });
221
150
  }
222
- /**
223
- * Raise the floor by `rungs` (default 1) and withdraw PURE QUOTE — the base leg untouched.
224
- *
225
- * A burn is in kind: it returns base and quote pro rata, so taking α of the proceeds also takes α
226
- * of the unsold inventory off the market. Raising the floor instead releases
227
- *
228
- * ΔQ = L (ξ' − ξ), ΔR = 0
229
- *
230
- * because $R = Le^{-x}$ depends on neither the floor nor the withdrawal. No base moves beyond one
231
- * wei (the edit's mint half rounds what it pays in up; the preview returns it), the price
232
- * does not move, and depth is unchanged. **The cost, which a UI must show:** the position stops
233
- * bidding below ξ'. `settleIn: "base"` swaps the proceeds into base in the same batch.
234
- */
235
151
  export async function harvest(c, a) {
236
152
  const n = a.rungs ?? 1n;
237
153
  if (n <= 0n)
238
154
  throw new Error("logswap: harvest raises the floor — rungs must be positive; to lower it, deepen()");
239
155
  return floor(c, { ...a, rungs: n });
240
156
  }
241
- /**
242
- * Lower the floor by `rungs` (default 1), paying L·Δξ of quote for the deeper bid — harvest's
243
- * mirror. `settleIn: "base"` pays it in base instead (an exact-out of the quote owed).
244
- */
245
157
  export async function deepen(c, a) {
246
158
  const n = a.rungs ?? 1n;
247
159
  if (n <= 0n)
248
160
  throw new Error("logswap: deepen lowers the floor — rungs must be positive; to raise it, harvest()");
249
161
  return floor(c, { ...a, rungs: -n });
250
162
  }
251
- /** Move the cap by `rungs` (signed), floor and L pinned. Base flows while the class converts; quote once capped out. */
252
163
  export async function cap(c, a) {
253
164
  const k = await classOf(c, a.key, a.fromId, a.shares);
254
165
  if (!k.capped)
@@ -258,47 +169,30 @@ export async function cap(c, a) {
258
169
  throw new Error("logswap: the cap cannot sit at or below the floor");
259
170
  return edit(c, { ...a, toFloor: k.floor, toCap, newL: k.L });
260
171
  }
261
- /** Translate the class by `rungs` (signed): floor and cap together, width and L pinned. */
262
172
  export async function shift(c, a) {
263
173
  const k = await classOf(c, a.key, a.fromId, a.shares);
264
174
  const d = a.rungs * tickSpacingOf(a.key);
265
175
  return edit(c, { ...a, toFloor: k.floor + d, toCap: k.capped ? k.cap + d : undefined, newL: k.L });
266
176
  }
267
- /** Set the exposure to `newL`, floor and cap pinned; both legs pro rata. The mint fee bites on an increase only. */
268
177
  export async function resize(c, a) {
269
178
  const k = await classOf(c, a.key, a.fromId, a.shares);
270
179
  return edit(c, { ...a, toFloor: k.floor, toCap: k.capped ? k.cap : undefined, newL: a.newL });
271
180
  }
272
- /** Exit `shares` — `resize(0)`. `settleIn: "quote"` (or `"base"`) leaves with one asset. */
273
181
  export async function exit(c, a) {
274
182
  const k = await classOf(c, a.key, a.fromId, a.shares);
275
183
  return edit(c, { ...a, toFloor: k.floor, toCap: k.capped ? k.cap : undefined, newL: 0n });
276
184
  }
277
- /**
278
- * Re-express a DORMANT class's base at a new trigger price: the base is pinned, so
279
- * L' = L·e^{ξ' − ξ} and nothing moves but the trigger. `toFloor` must stay above spot.
280
- *
281
- * The exponential is evaluated in double precision (~1e-16 relative), which is far inside the
282
- * wei-rounding of the class it produces; an exact L' is not what a trigger edit is about.
283
- */
284
185
  export async function reprice(c, a) {
285
186
  const k = await classOf(c, a.key, a.fromId, a.shares);
286
187
  const ratio = Math.exp(Number(a.toFloor - k.floor) / 1e18);
287
188
  const newL = (k.L * BigInt(Math.round(ratio * 1e18))) / 10n ** 18n;
288
189
  return edit(c, { ...a, toFloor: a.toFloor, toCap: k.capped ? k.cap : undefined, newL });
289
190
  }
290
- /** Quote released by a harvest, exactly: ΔQ = L(ξ' − ξ). Base is untouched. */
291
191
  export function harvestProceeds(L, fromFloor, toFloor) {
292
192
  if (toFloor <= fromFloor)
293
193
  return 0n;
294
194
  return (L * (toFloor - fromFloor)) / 10n ** 18n;
295
195
  }
296
- /**
297
- * Exit, in kind, across one or more classes. Accrued fees are swept into the same settlement.
298
- *
299
- * In kind means both legs, pro rata. To take proceeds while leaving inventory in the market, that
300
- * is {@link harvest}; to leave with one asset, {@link exit} with `settleIn`.
301
- */
302
196
  export async function burn(c, a) {
303
197
  if (a.ids.length !== a.shares.length)
304
198
  throw new Error("logswap: ids and shares length mismatch");
package/dist/onboard.d.ts CHANGED
@@ -1,72 +1,20 @@
1
- /**
2
- * onboard.ts — getting a wallet to the point where router writes actually work.
3
- *
4
- * There are **three separate approvals** with three separate failure modes, and a UI that surfaces
5
- * them late produces failed transactions instead of prompts:
6
- *
7
- * 1. ERC-20 → Permit2 once per token, forever. Only when the router is Permit2-wired.
8
- * 2. Permit2 → router a standing allowance, by transaction or by signature.
9
- * 3. 6909 operator grant once per wallet, covers every market. Needed by burn/update/move.
10
- *
11
- * **The trap this module exists for:** when the router is deployed with Permit2, approving the
12
- * ERC-20 to the *router* is not enough and not used — the pull goes through Permit2, and the
13
- * failure is `NotAllowed()` from Permit2 rather than anything naming an allowance. Approving the
14
- * router directly looks correct and does nothing.
15
- *
16
- * **One router per manager** (decision 096), and each is its own Permit2 spender: step 1 is shared by
17
- * both (the ERC-20 goes to Permit2 once per token), steps 2 and 3 are per `side` — a wallet that trades
18
- * on both singletons signs one Permit2 allowance per router, and grants the operator on each manager.
19
- * Every helper here that depends on the router takes the `side` (`"F"` or `"C"`) right after the client.
20
- */
21
1
  import { type Address, type Hash, type Hex } from "viem";
22
2
  import { type LogswapClient, type Side } from "./client.js";
23
3
  export declare const MAX_UINT256: bigint;
24
4
  export declare const MAX_UINT160: bigint;
25
5
  export declare const MAX_UINT48: bigint;
26
- /**
27
- * How long a Permit2 allowance to the router lives: 30 days, as Uniswap's own interface does. It
28
- * used to be `MAX_UINT48` — never — so a router bug or a compromised router could pull every
29
- * approved token from every user indefinitely. A lapsed allowance is re-granted by one more
30
- * signature, riding inside the next write ({@link permit2SigCalls}).
31
- */
32
6
  export declare const PERMIT2_EXPIRY_SECONDS: bigint;
33
- /** The expiry to grant now. */
34
7
  export declare const permit2Expiry: () => bigint;
35
- /** Whether a Permit2 allowance (amount, expiration) covers `need` for long enough to land. */
36
8
  export declare const permit2Covers: (amount: bigint, expiration: number, need: bigint) => boolean;
37
- /** Is this deployment's router wired to Permit2? Decides which approval path applies. */
38
9
  export declare function usesPermit2(c: LogswapClient): boolean;
39
- /** The contract that will actually pull tokens: Permit2 when wired, otherwise the `side`'s router. */
40
10
  export declare function spenderFor(c: LogswapClient, side: Side): Address;
41
- /** Step 1 — approve the *puller* on an ERC-20. Once per token. */
42
11
  export declare function approveToken(c: LogswapClient, side: Side, token: Address, amount?: bigint): Promise<Hash>;
43
- /**
44
- * Step 2 — the standing Permit2 allowance for the `side`'s router.
45
- *
46
- * No-op when the deployment has no Permit2. Prefer the signature flow (`applyPermit2` on the
47
- * router, bundled through `multicall`) in production; this transaction form is what a test or a
48
- * simple UI wants.
49
- */
50
12
  export declare function approvePermit2ForRouter(c: LogswapClient, side: Side, token: Address, amount?: bigint, expiration?: bigint): Promise<Hash | null>;
51
- /**
52
- * Both token-side steps in order, skipping any already satisfied.
53
- *
54
- * Returns the hashes actually sent, so a UI can report "2 approvals" honestly rather than always
55
- * prompting twice.
56
- */
57
13
  export declare function onboardToken(c: LogswapClient, side: Side, token: Address, need: bigint): Promise<Hash[]>;
58
- /** What still stands between this wallet and a working write. */
59
14
  export interface TokenReadiness {
60
15
  usesPermit2: boolean;
61
- /** ERC-20 allowance to whoever pulls (Permit2 when wired, else the side's router). */
62
16
  needsTokenApproval: boolean;
63
- /** Permit2's standing allowance for the side's router. Always false when Permit2 is not wired. */
64
17
  needsPermit2Approval: boolean;
65
18
  }
66
19
  export declare function checkTokenReadiness(c: LogswapClient, side: Side, token: Address, owner: Address, need: bigint): Promise<TokenReadiness>;
67
- /**
68
- * For each token whose Permit2→router allowance is missing: read the nonce, have the wallet SIGN
69
- * a PermitSingle (a signature prompt, not a transaction), and return the encoded `applyPermit2`
70
- * calls ready to ride in a router multicall. Tokens already allowed produce nothing.
71
- */
72
20
  export declare function permit2SigCalls(c: LogswapClient, side: Side, tokens: Address[]): Promise<Hex[]>;
package/dist/onboard.js CHANGED
@@ -1,42 +1,13 @@
1
- /**
2
- * onboard.ts — getting a wallet to the point where router writes actually work.
3
- *
4
- * There are **three separate approvals** with three separate failure modes, and a UI that surfaces
5
- * them late produces failed transactions instead of prompts:
6
- *
7
- * 1. ERC-20 → Permit2 once per token, forever. Only when the router is Permit2-wired.
8
- * 2. Permit2 → router a standing allowance, by transaction or by signature.
9
- * 3. 6909 operator grant once per wallet, covers every market. Needed by burn/update/move.
10
- *
11
- * **The trap this module exists for:** when the router is deployed with Permit2, approving the
12
- * ERC-20 to the *router* is not enough and not used — the pull goes through Permit2, and the
13
- * failure is `NotAllowed()` from Permit2 rather than anything naming an allowance. Approving the
14
- * router directly looks correct and does nothing.
15
- *
16
- * **One router per manager** (decision 096), and each is its own Permit2 spender: step 1 is shared by
17
- * both (the ERC-20 goes to Permit2 once per token), steps 2 and 3 are per `side` — a wallet that trades
18
- * on both singletons signs one Permit2 allowance per router, and grants the operator on each manager.
19
- * Every helper here that depends on the router takes the `side` (`"F"` or `"C"`) right after the client.
20
- */
21
1
  import { parseAbi, zeroAddress } from "viem";
22
2
  import { routerOf } from "./client.js";
23
3
  import { requireWallet } from "./write.js";
24
4
  export const MAX_UINT256 = (1n << 256n) - 1n;
25
5
  export const MAX_UINT160 = (1n << 160n) - 1n;
26
6
  export const MAX_UINT48 = (1n << 48n) - 1n;
27
- /**
28
- * How long a Permit2 allowance to the router lives: 30 days, as Uniswap's own interface does. It
29
- * used to be `MAX_UINT48` — never — so a router bug or a compromised router could pull every
30
- * approved token from every user indefinitely. A lapsed allowance is re-granted by one more
31
- * signature, riding inside the next write ({@link permit2SigCalls}).
32
- */
33
7
  export const PERMIT2_EXPIRY_SECONDS = 30n * 24n * 3600n;
34
- /** An allowance that lapses within this window is treated as already lapsed: it could die in flight. */
35
8
  const EXPIRY_MARGIN_SECONDS = 3600;
36
9
  const nowSeconds = () => Math.floor(Date.now() / 1000);
37
- /** The expiry to grant now. */
38
10
  export const permit2Expiry = () => BigInt(nowSeconds()) + PERMIT2_EXPIRY_SECONDS;
39
- /** Whether a Permit2 allowance (amount, expiration) covers `need` for long enough to land. */
40
11
  export const permit2Covers = (amount, expiration, need) => amount >= need && expiration > nowSeconds() + EXPIRY_MARGIN_SECONDS;
41
12
  const ERC20 = parseAbi([
42
13
  "function approve(address spender, uint256 amount) returns (bool)",
@@ -47,15 +18,12 @@ const PERMIT2 = parseAbi([
47
18
  "function allowance(address owner, address token, address spender) view returns (uint160 amount, uint48 expiration, uint48 nonce)",
48
19
  "function transferFrom(address from, address to, uint160 amount, address token)",
49
20
  ]);
50
- /** Is this deployment's router wired to Permit2? Decides which approval path applies. */
51
21
  export function usesPermit2(c) {
52
22
  return !!c.addresses.permit2 && c.addresses.permit2 !== zeroAddress;
53
23
  }
54
- /** The contract that will actually pull tokens: Permit2 when wired, otherwise the `side`'s router. */
55
24
  export function spenderFor(c, side) {
56
25
  return usesPermit2(c) ? c.addresses.permit2 : routerOf(c, side);
57
26
  }
58
- /** Step 1 — approve the *puller* on an ERC-20. Once per token. */
59
27
  export async function approveToken(c, side, token, amount = MAX_UINT256) {
60
28
  const { account } = requireWallet(c);
61
29
  return c.wallet.writeContract({
@@ -67,13 +35,6 @@ export async function approveToken(c, side, token, amount = MAX_UINT256) {
67
35
  chain: c.wallet.chain,
68
36
  });
69
37
  }
70
- /**
71
- * Step 2 — the standing Permit2 allowance for the `side`'s router.
72
- *
73
- * No-op when the deployment has no Permit2. Prefer the signature flow (`applyPermit2` on the
74
- * router, bundled through `multicall`) in production; this transaction form is what a test or a
75
- * simple UI wants.
76
- */
77
38
  export async function approvePermit2ForRouter(c, side, token, amount = MAX_UINT160, expiration = permit2Expiry()) {
78
39
  if (!usesPermit2(c))
79
40
  return null;
@@ -87,14 +48,7 @@ export async function approvePermit2ForRouter(c, side, token, amount = MAX_UINT1
87
48
  chain: c.wallet.chain,
88
49
  });
89
50
  }
90
- /**
91
- * Both token-side steps in order, skipping any already satisfied.
92
- *
93
- * Returns the hashes actually sent, so a UI can report "2 approvals" honestly rather than always
94
- * prompting twice.
95
- */
96
51
  export async function onboardToken(c, side, token, need) {
97
- // The address, not the account object: these two are READS. Signing paths take the object.
98
52
  const { address } = requireWallet(c);
99
53
  const sent = [];
100
54
  const allowance = (await c.public.readContract({
@@ -144,13 +98,6 @@ export async function checkTokenReadiness(c, side, token, owner, need) {
144
98
  }
145
99
  return { usesPermit2: usesPermit2(c), needsTokenApproval: allowance < need, needsPermit2Approval };
146
100
  }
147
- // ─── the signature path: allowances that ride inside the action's own transaction ─────────────
148
- //
149
- // The rationalized flow. A token's ONLY unavoidable transaction is its one-time ERC-20 approval
150
- // to Permit2; the Permit2→router allowance is set by an EIP-712 SIGNATURE (free, instant, no
151
- // gas) submitted as an `applyPermit2` call INSIDE the same multicall as the action. Minting on a
152
- // fresh token is then one transaction, not three — the pattern the router's `applyPermit2` +
153
- // `multicall` were built for, and the one canonical Permit2 UX uses.
154
101
  const PERMIT2_TYPES = {
155
102
  PermitDetails: [
156
103
  { name: "token", type: "address" },
@@ -164,11 +111,6 @@ const PERMIT2_TYPES = {
164
111
  { name: "sigDeadline", type: "uint256" },
165
112
  ],
166
113
  };
167
- /**
168
- * For each token whose Permit2→router allowance is missing: read the nonce, have the wallet SIGN
169
- * a PermitSingle (a signature prompt, not a transaction), and return the encoded `applyPermit2`
170
- * calls ready to ride in a router multicall. Tokens already allowed produce nothing.
171
- */
172
114
  export async function permit2SigCalls(c, side, tokens) {
173
115
  if (!usesPermit2(c))
174
116
  return [];
@@ -183,7 +125,7 @@ export async function permit2SigCalls(c, side, tokens) {
183
125
  args: [owner, token, routerOf(c, side)],
184
126
  }));
185
127
  if (permit2Covers(amt, expiration, 1n << 120n))
186
- continue; // effectively unlimited, and not lapsing
128
+ continue;
187
129
  const message = {
188
130
  details: { token, amount: MAX_UINT160, expiration: Number(permit2Expiry()), nonce },
189
131
  spender: routerOf(c, side),
package/dist/pools.d.ts CHANGED
@@ -1,233 +1,79 @@
1
- /**
2
- * pools.ts — market state and discovery.
3
- *
4
- * Two things worth knowing before reading further.
5
- *
6
- * **Markets are discovered from logs, not configuration.** `MarketCreated` carries the ENTIRE
7
- * `PoolKey` in the clear, so a client can reconstruct any market's key — and therefore call any
8
- * keyed function — having never been told the market exists. There is no registry to maintain.
9
- *
10
- * **`x` is the state, price is derived.** The contract stores $x = \log p$ and materialises the
11
- * price only where unavoidable; `priceOf` below mirrors that, and is lossy in the way any float
12
- * conversion is. Prefer comparing in log space when precision matters.
13
- */
14
1
  import { type Address, type Hex } from "viem";
15
2
  import { type LogswapClient } from "./client.js";
16
3
  import { type PoolKey } from "./keys.js";
17
- /**
18
- * A market's scalar state, as `PoolStateC.PoolView` names it — what the manager's `getPool`
19
- * returned before C version 7 moved it behind `extsload` (decisions 065); read through the lens. No `backstopSeeded`
20
- * since C 18 (decision 099): `initialize` mints the backstop, so an initialized market has one.
21
- */
22
4
  export interface PoolState {
23
5
  initialized: boolean;
24
- /** $x = \log p$, WAD — the stored state (`logPrice`; `x` before C 13). */
25
6
  logPrice: bigint;
26
- /** Exposure currently earning. Steps only when a floor or cap is crossed. */
27
7
  lActive: bigint;
28
8
  reserveBase: bigint;
29
9
  reserveQuote: bigint;
30
- /** Fee-per-unit-L accumulator $F = \phi \cdot \mathrm{TV}(\log p)$ (`feeGrowth`; `F` before C 13). */
31
10
  feeGrowth: bigint;
32
- /** Quadratic variation of log-price, $\Sigma = \sum_{\text{swaps}} (\Delta x_{\text{swap}})^2$ — one term per swap. */
33
11
  realizedVariance: bigint;
34
12
  currentK: bigint;
35
13
  protocolOwed: bigint;
36
14
  minBackstopL: bigint;
37
15
  backstopFloor: bigint;
38
- /** The market's swap-fee tax, WAD of every fee paid out: the gate's answer at birth, fixed for life (066). */
39
16
  swapFeeTax: bigint;
40
17
  }
41
- /** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
42
18
  export declare function getPool(c: LogswapClient, key: PoolKey): Promise<PoolState>;
43
- /**
44
- * The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
45
- * life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
46
- * drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
47
- */
48
19
  export declare function marketSwapFee(c: LogswapClient, key: PoolKey): Promise<bigint>;
49
- /**
50
- * Price from the stored log-price. **Lossy** — `x` is exact and this is a float, so use it for
51
- * display and never for arithmetic you intend to send back on-chain.
52
- */
53
20
  export declare function priceOf(state: Pick<PoolState, "logPrice">, scale?: number): number;
54
- /**
55
- * The factor between the chain's price and the human one. The chain's log-price is of the WEI
56
- * ratio, so with a 6-dec USDC quote and an 18-dec base the human price is `e^x · 10^12`. Pass
57
- * this as `scale` to {@link priceOf}, {@link floorPrice} and `fPoolPriceOf` — with 18/18 tokens
58
- * it is 1 and nothing changes.
59
- */
60
21
  export declare function priceScale(baseDecimals: number, quoteDecimals: number): number;
61
- /** The C manager's log-price wall: |x| ≤ 46 on the WEI ratio (`MAX_ABS_FLOOR`). */
62
22
  export declare const C_MAX_ABS_X = 46;
63
- /** The least derived base reserve a C book keeps, in base wei (`MIN_RESERVE`, decisions 023). */
64
23
  export declare const C_MIN_RESERVE: bigint;
65
- /**
66
- * The prices a C market can hold, in human units — quote per whole base token (decisions 054).
67
- *
68
- * - `listMin`, `listMax`: the wall, `10^(base − quote) · e^{∓46}`. A market cannot be initialized,
69
- * and no floor or cap placed, outside it. An 18-dec token against 6-dec USDC cannot list under
70
- * 1.05e-8; against an 18-dec quote the same token lists down to 1.05e-20.
71
- * - `ceiling`: the highest price the book can trade to with `lActive` of active exposure (quote
72
- * wei): the derived reserve `lActive / p` must stay at or above `C_MIN_RESERVE` base wei, so
73
- * `ceiling = lActive · 10^(base − quote) / 1e6`, capped by `listMax`. In whole units that is
74
- * `L · 10^(base − 6)`: the quote's decimals cancel and the base's set it — harmless on an
75
- * 18-dec base, but a WBTC book of 1,000 USDC of depth stops at 100,000. Omit `lActive` for the
76
- * wall alone.
77
- *
78
- * Floats, for display and warnings; the chain is the authority.
79
- */
80
24
  export declare function cPriceRange(baseDecimals: number, quoteDecimals: number, lActive?: bigint): {
81
25
  listMin: number;
82
26
  listMax: number;
83
27
  ceiling: number;
84
28
  };
85
- /** Whether a C market can be initialized at `price` (human units) for this pair's decimals. */
86
29
  export declare function cListable(price: number, baseDecimals: number, quoteDecimals: number): boolean;
87
- /**
88
- * The model-free LP edge, $F - \tfrac12\Sigma$ — the protocol's headline metric, in quote per unit
89
- * of exposure.
90
- *
91
- * $F$ is fee income per unit active $L$; $\Sigma$ is the realised quadratic variation, whose half
92
- * is the LVR a log pool pays. The difference is what an LP actually earns, with no model of the
93
- * price process assumed. Both ride on every `Swap` event, so this is reconstructible from logs
94
- * alone (docs/app.md) — no state read needed if you are already indexing.
95
- *
96
- * Signed: negative means variation has outrun fee income over the pool's life.
97
- */
98
30
  export declare function lpEdge(state: Pick<PoolState, "feeGrowth" | "realizedVariance">): bigint;
99
- /** A market discovered from a `PoolCreated` log — the full key, plus where it was created. */
100
31
  export interface DiscoveredMarket {
101
32
  key: PoolKey;
102
33
  poolId: Hex;
103
- /** The market's opening log-price (`x0` before C 13). */
104
34
  initialLogPrice: bigint;
105
35
  blockNumber: bigint;
106
36
  transactionHash: Hex;
107
- /** The account that opened the market (`PoolCreated.creator`): it paid the backstop and holds no role by it. Not a key field (C 18). */
108
37
  creator?: Address;
109
- /** The manager that emitted the `PoolCreated` — set when the row came from the indexer. */
110
38
  manager?: Address;
111
39
  }
112
- /**
113
- * Enumerate markets from the C manager's `PoolCreated` logs.
114
- *
115
- * This is the whole market registry: the event carries every key field rather than just the id,
116
- * deliberately, so nothing downstream needs a configured list. The scan starts at the client's
117
- * `deployBlock` unless `fromBlock` says otherwise.
118
- */
119
40
  export declare function discoverMarkets(c: LogswapClient, opts?: {
120
41
  fromBlock?: bigint;
121
42
  toBlock?: bigint;
122
43
  base?: Address;
123
- quote?: Address; /** Only markets under this policy (an indexed topic, C 19). */
124
- policy?: Address; /** Only markets this account opened (data since C 20: filtered after decoding). */
125
- creator?: Address; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */
44
+ quote?: Address;
45
+ policy?: Address;
46
+ creator?: Address;
126
47
  indexer?: string;
127
48
  }): Promise<DiscoveredMarket[]>;
128
- /**
129
- * Ladder shape: the live FLOORS, in log-price WAD — **not** tick indices.
130
- *
131
- * Named `liveFloors` deliberately. The lens function it wraps is called `liveTicks`, which reads as
132
- * if it returns `k`; it returns `k * tickSpacing`. Multiplying by the spacing again yields an
133
- * off-grid value and an `OffGrid` revert at the next call, which is a confusing place to discover
134
- * the mistake.
135
- */
136
49
  export declare function liveFloors(c: LogswapClient, key: PoolKey): Promise<readonly bigint[]>;
137
- /** Is this floor on the market's grid, and inside `MAX_ABS_FLOOR`? Pure — no RPC on the manager. */
138
50
  export declare function isValidFloor(c: LogswapClient, key: PoolKey, floor: bigint): Promise<boolean>;
139
- /**
140
- * A market's token decimals, read from the tokens themselves.
141
- *
142
- * **Never assume these.** A market's two tokens routinely differ (USDC 6 against WETH 18), the
143
- * manager itself probes `decimals()` to scale `minBackstopL`, and a token that does not implement
144
- * it falls back to 18. Hardcoding a guess makes every parse and every display wrong by orders of
145
- * magnitude while the contract behaves perfectly — which reads as "the app is broken".
146
- */
147
51
  export declare function marketDecimals(c: LogswapClient, key: PoolKey): Promise<{
148
52
  base: number;
149
53
  quote: number;
150
54
  }>;
151
- /** A token as a UI needs it: address, symbol and decimals, all read from the chain. */
152
55
  export interface TokenInfo {
153
56
  address: Address;
154
57
  symbol: string;
155
58
  decimals: number;
156
59
  }
157
- /**
158
- * Both sides of a market, for labelling and scaling.
159
- *
160
- * **Decimals are read from the token and never guessed.** They used to fall back to 18 on any
161
- * failure, which quietly reintroduced the worst bug this stack has had: an 18 assumed for a
162
- * 6-decimal token is a 10^12 error in a number that goes on to `parseUnits` and becomes a transfer
163
- * amount. A wrong scale is indistinguishable from a working app until somebody moves funds, so a
164
- * read that will not resolve must fail loudly instead.
165
- *
166
- * `symbol` keeps a fallback because it is a label: a market shown as `0x5FbD…` is ugly, not wrong.
167
- *
168
- * Retries first, because a blip on the transport is not the same as a token that has no `decimals`,
169
- * and killing a market over one dropped packet is its own kind of wrong.
170
- *
171
- * **Cached** per (chain, address) — see `tokencache.ts` for why only successes are stored and why
172
- * the chain id is part of the key. Concurrent calls for the same token share one read, which
173
- * matters because the quote asset is usually the same across every market in a deployment.
174
- */
175
60
  export declare function marketTokens(c: LogswapClient, key: PoolKey): Promise<{
176
61
  base: TokenInfo;
177
62
  quote: TokenInfo;
178
63
  }>;
179
- /** Format a quote-denominated amount for display, given the quote's decimals. */
180
64
  export declare function formatQuote(amount: bigint, quoteDecimals: number): string;
181
- /** Fees the pool has accrued over its life, in QUOTE units: $F \cdot L$. */
182
65
  export declare function feesQuote(state: Pick<PoolState, "feeGrowth" | "lActive">): bigint;
183
- /** The LP edge in QUOTE units: $(F - \tfrac12\Sigma) \cdot L$. Signed. */
184
66
  export declare function edgeQuote(state: Pick<PoolState, "feeGrowth" | "realizedVariance" | "lActive">): bigint;
185
- /** The pool floor as a price. **Lossy** — display only, like {@link priceOf}. */
186
67
  export declare function floorPrice(state: Pick<PoolState, "backstopFloor">, scale?: number): number;
187
- /** $\log(p / p_{\text{floor}}) = x - \xi$ — how far spot sits above the floor, in log units (WAD). */
188
68
  export declare function floorDistance(state: Pick<PoolState, "logPrice" | "backstopFloor">): bigint;
189
- /**
190
- * $-\log(p/p_{\text{floor}})$ as a fraction: the log-drawdown from spot down to the floor.
191
- *
192
- * **Negative** while price is above the floor — it is how far price has to fall, so a UI can print
193
- * it with its sign and mean it. Zero at the floor.
194
- *
195
- * This is the LOG measure, not the arithmetic one: the actual price drawdown is
196
- * $e^{-\Delta} - 1$, which differs materially once the distance is large (a log distance of 0.7
197
- * is a 50% price fall, not 70%).
198
- */
199
69
  export declare function floorDrawdown(state: Pick<PoolState, "logPrice" | "backstopFloor">): number;
200
- /** The arithmetic price drawdown to the floor, $p_{\text{floor}}/p - 1$. Negative above the floor. */
201
70
  export declare function floorDrawdownPrice(state: Pick<PoolState, "logPrice" | "backstopFloor">): number;
202
- /**
203
- * Annualise a per-unit-L WAD rate over the window it accrued in.
204
- *
205
- * `F` is cumulative fee income per unit of exposure since the pool opened, so dividing by the
206
- * elapsed time and scaling to a year gives a rate directly — no price process assumed. Returns a
207
- * fraction: 0.12 is 12%.
208
- *
209
- * Treat it as what it is: a *realised* rate over one short devnet window, not a forecast.
210
- */
211
71
  export declare function annualise(perUnitL: bigint, elapsedSeconds: bigint): number;
212
- /** When a market was created, as a unix timestamp — the denominator for {@link annualise}. */
213
72
  export declare function marketOpenedAt(c: LogswapClient, m: DiscoveredMarket): Promise<bigint>;
214
- /**
215
- * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and the one creation path
216
- * (C 18, decisions 099, 100: `RouterC.createMarket` is gone). The call mints the permanent backstop (`minBackstopL` of uncapped
217
- * liquidity to 0xdead on the rung under the opening price), so the market is born live and `account` pays dust of BOTH tokens,
218
- * and the mint fee on it, by plain ERC-20 allowance to the MANAGER: {@link approveTokenForCManager} for each first. Whoever opens
219
- * a market holds nothing of it. The policy answers who may create (`PolicyC.mayInit`): anyone at salt zero on an open policy,
220
- * the policy's authority on a closed one; {@link cGateRules} reads the same checks before a wallet is asked.
221
- */
222
73
  export declare function initializeMarket(c: LogswapClient, a: {
223
74
  key: PoolKey;
224
75
  initialLogPrice: bigint;
225
76
  account: Address;
226
77
  }): Promise<`0x${string}`>;
227
- /**
228
- * Plain ERC-20 approval to the C manager — the allowance {@link initializeMarket} pulls the backstop against (C 18). Every
229
- * other C write goes through the router and Permit2 (`onboardToken`). `amount` defaults to the maximum; the backstop is dust.
230
- */
231
78
  export declare function approveTokenForCManager(c: LogswapClient, token: Address, account: Address, amount?: bigint): Promise<Hex>;
232
- /** Does `owner` have enough allowance on `token` for the C MANAGER to pull `need`? */
233
79
  export declare function cManagerAllowanceOk(c: LogswapClient, token: Address, owner: Address, need: bigint): Promise<boolean>;