@logswap/sdk 0.5.102 → 0.5.104

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/src/claims.ts DELETED
@@ -1,111 +0,0 @@
1
- /**
2
- * claims.ts — fee claims, and the ERC-6909 operator grant every router write depends on.
3
- *
4
- * Note the two unrelated meanings of "claim" in this protocol, kept apart here:
5
- * - a FEE claim — `claimFees`, withdrawing accrued quote while the position stays whole
6
- * - a TOKEN claim — a bearer IOU (bit-255-clear id) for inventory parked inside the manager
7
- */
8
-
9
- import type { Address, Hash } from "viem";
10
- import { managerCAbi, routerCAbi } from "./generated.js";
11
- import { managerC, routerC, type LogswapClient } from "./client.js";
12
- import { poolId as keyId, type PoolKey } from "./keys.js";
13
- import { isPosition } from "./ids.js";
14
- import { requireWallet, resolveDeadline, resolveRecipient, sendRouterWrite, type WriteOptions } from "./write.js";
15
-
16
- export interface ClaimFeesArgs extends WriteOptions {
17
- key: PoolKey;
18
- ids: readonly bigint[];
19
- }
20
-
21
- /**
22
- * Claim accrued fees across one or more classes: one transfer, positions untouched.
23
- *
24
- * **Every id must be REGISTERED** — one the manager has seen minted. An id for a class that has
25
- * never existed reverts the whole batch with `WrongPool`, because an unregistered id has
26
- * `poolId == 0` and cannot be shown to belong to this pool. In a contract holding every market's
27
- * assets, "cannot be shown to belong" must not be read as "belongs". A class that exists but which
28
- * the caller does not hold is fine — that is a no-op, not a revert.
29
- */
30
- export async function claimFees(c: LogswapClient, a: ClaimFeesArgs): Promise<Hash> {
31
- for (const id of a.ids) {
32
- if (!isPosition(id)) {
33
- throw new Error(
34
- `logswap: id ${id} is a TOKEN claim (bit 255 clear), not a position — it has no fees to claim.`,
35
- );
36
- }
37
- }
38
- return sendRouterWrite(c, {
39
- side: "C",
40
- abi: routerCAbi,
41
- functionName: "claim",
42
- args: [keyId(a.key), a.key.quote, a.ids, resolveRecipient(c, a), resolveDeadline(a)],
43
- });
44
- }
45
-
46
- /**
47
- * Grant the router operator rights over your ERC-6909 positions.
48
- *
49
- * **Required before any burn, update, move or harvest** — those pull the shares to the router
50
- * first. Without it they revert on the transfer, which reads as an unrelated balance error. Swaps
51
- * and mints do not need it.
52
- *
53
- * One grant covers every market, because the positions all live in the one manager.
54
- */
55
- export async function approveRouterAsOperator(c: LogswapClient, approved = true): Promise<Hash> {
56
- const { account } = requireWallet(c);
57
- return c.wallet!.writeContract({
58
- address: managerC(c),
59
- abi: managerCAbi,
60
- functionName: "setOperator",
61
- args: [routerC(c), approved],
62
- account,
63
- chain: c.wallet!.chain,
64
- } as never);
65
- }
66
-
67
- /** Is the router already an operator for `owner`? Check before prompting for a signature. */
68
- export async function isRouterApproved(c: LogswapClient, owner: Address): Promise<boolean> {
69
- return c.public.readContract({
70
- address: managerC(c),
71
- abi: managerCAbi,
72
- functionName: "isOperator",
73
- args: [owner, routerC(c)],
74
- }) as Promise<boolean>;
75
- }
76
-
77
- /**
78
- * What a wallet still has to approve before a given action.
79
- *
80
- * Surfacing this up front is the difference between one prompt and a failed transaction: the ERC-20
81
- * allowances and the 6909 operator grant are separate approvals with separate failure modes.
82
- */
83
- export interface Readiness {
84
- needsOperator: boolean;
85
- needsBaseAllowance: boolean;
86
- needsQuoteAllowance: boolean;
87
- }
88
-
89
- export async function checkReadiness(
90
- c: LogswapClient,
91
- key: PoolKey,
92
- owner: Address,
93
- need: { base?: bigint; quote?: bigint; positions?: boolean } = {},
94
- ): Promise<Readiness> {
95
- // A token is ready when BOTH legs of its pull path are: the ERC-20 allowance to whoever pulls
96
- // (Permit2 when wired) and, with Permit2, its unexpired allowance to the router. This used to
97
- // read the ERC-20 allowance to the ROUTER, which on a Permit2 deployment is never granted — so
98
- // it said "approve" forever, and approving the router changed nothing.
99
- const { checkTokenReadiness } = await import("./onboard.js");
100
- const ready = async (token: Address, amount?: bigint) => {
101
- if (amount === undefined) return true;
102
- const r = await checkTokenReadiness(c, "C", token, owner, amount);
103
- return !r.needsTokenApproval && !r.needsPermit2Approval;
104
- };
105
- const [operator, baseOk, quoteOk] = await Promise.all([
106
- need.positions ? isRouterApproved(c, owner) : Promise.resolve(true),
107
- ready(key.base, need.base),
108
- ready(key.quote, need.quote),
109
- ]);
110
- return { needsOperator: !operator, needsBaseAllowance: !baseOk, needsQuoteAllowance: !quoteOk };
111
- }
package/src/client.ts DELETED
@@ -1,436 +0,0 @@
1
- /**
2
- * client.ts — the SDK handle: addresses + viem clients.
3
- *
4
- * Construct once and pass to every helper. `wallet` is optional: read helpers need only `public`.
5
- *
6
- * **One stack per manager, permanently** (decision 096): a manager, its router and its lens, for F and for
7
- * C. Not per market — every market lives in the one manager of its side, and a market is an
8
- * `initialize` call rather than a deployment. F ships first, so the C stack is optional: a chain
9
- * that has not opted into C carries `address(0)` for it, and every C call throws a plain error there.
10
- */
11
-
12
- import type { Address, PublicClient, WalletClient } from "viem";
13
- import { addressesOfDeployment, DEFAULT_MAX_LOG_RANGE, logswapChain, type LogswapChain, type LogswapDeployment } from "./chains.js";
14
-
15
- /** The two singletons: `C` is the concentrated one (a floor per position, a tick ladder), `F` the fungible one. */
16
- export type Side = "C" | "F";
17
-
18
- export interface LogswapAddresses {
19
- /** The F singleton — fungible claims, one shared floor, n bases. ERC-6909 shares and token claims live here. */
20
- managerF: Address;
21
- /** F's user entry: swaps, zaps, roll-in, Permit2. Its own Permit2 spender. */
22
- routerF: Address;
23
- /** F's read-only lens: pool views and previews. */
24
- lensF: Address;
25
- /**
26
- * The C singleton — a floor per position, on a tick ladder. ERC-6909 positions and token claims live here.
27
- * The C stack is optional: F ships first, and a chain that has not opted into C carries none.
28
- */
29
- managerC?: Address;
30
- /** C's user entry: the batch, the named one-action entries, Permit2 (a market is opened on the manager). Its own Permit2 spender. */
31
- routerC?: Address;
32
- /** C's read-only lens: ladder derivations and views. */
33
- lensC?: Address;
34
- /**
35
- * The LOG's policies (decision 098: immutable, deployed by the LOG): every pool names one in its key for life, and the pool's
36
- * roles, gates and terms live on it. On F the four are instances of one contract, `PolicyF` (F 41, policy.md), told apart by
37
- * their immutables: `publicPolicy` is the open one (anyone creates at salt zero, no gate ever), `privatePolicy` the LOG's desk
38
- * (closed, gates by pool), `polPolicy` and `padPolicy` the treasury's and the launch's. The artifact keys predate 098 and are
39
- * kept. A deployment predating the policies carries none.
40
- */
41
- publicPolicy?: Address;
42
- privatePolicy?: Address;
43
- polPolicy?: Address;
44
- padPolicy?: Address;
45
- /** The LOG's open policy on C (`PolicyC`): the policy of a public market. Absent with no C stack. */
46
- publicPolicyC?: Address;
47
- /**
48
- * The policy registry: what a pool of each kind may be born under, and the
49
- * owner that may move a pool between policies. Read from the F manager (`registry()`) when
50
- * absent; a deployment with none asks nobody.
51
- */
52
- policyRegistry?: Address;
53
- /** The devnet's token factory (`TokenFactory`, a mock): where launchable tokens come from. Optional. */
54
- tokenFactory?: Address;
55
- /** Optional — each router falls back to plain approvals when absent. */
56
- permit2?: Address;
57
- }
58
-
59
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
60
- const NO_C = "logswap: this deployment has no C stack (managerC / routerC / lensC) — F ships first, C lands with its own deployment";
61
-
62
- /** Whether the deployment carries the C stack. */
63
- export function hasC(c: LogswapClient): boolean {
64
- const a = c.addresses;
65
- return has(a.managerC) && has(a.routerC) && has(a.lensC);
66
- }
67
-
68
- const has = (a?: Address): a is Address => !!a && a !== ZERO_ADDRESS;
69
-
70
- /** The C manager; throws where the deployment has none. */
71
- export function managerC(c: LogswapClient): Address {
72
- const a = c.addresses.managerC;
73
- if (!has(a)) throw new Error(NO_C);
74
- return a;
75
- }
76
- /** The C router; throws where the deployment has none. */
77
- export function routerC(c: LogswapClient): Address {
78
- const a = c.addresses.routerC;
79
- if (!has(a)) throw new Error(NO_C);
80
- return a;
81
- }
82
- /** The C lens; throws where the deployment has none. */
83
- export function lensC(c: LogswapClient): Address {
84
- const a = c.addresses.lensC;
85
- if (!has(a)) throw new Error(NO_C);
86
- return a;
87
- }
88
- /** The router of `side` — the contract that pulls the caller's tokens, and the spender to approve. */
89
- export function routerOf(c: LogswapClient, side: Side): Address {
90
- return side === "F" ? c.addresses.routerF : routerC(c);
91
- }
92
-
93
- export interface LogswapClient {
94
- public: PublicClient;
95
- wallet?: WalletClient;
96
- addresses: LogswapAddresses;
97
- /** The chain the client reads: the deployment's, else the public client's. Unset when neither says. */
98
- chainId?: number;
99
- /** The deployment's first block: the default `fromBlock` of every log scan. */
100
- deployBlock?: bigint;
101
- /** Block span of one `eth_getLogs` call on the chain path; wider scans are split. {@link DEFAULT_MAX_LOG_RANGE} when unset. */
102
- maxLogRange?: bigint;
103
- /**
104
- * The rindexer GraphQL endpoint of THIS chain's indexer: the default `indexer` of every history
105
- * read. The contracts sit at one address on every release chain, so an indexer's rows carry no
106
- * chain a reader could filter on: one URL per chain.
107
- */
108
- indexerUrl?: string;
109
- }
110
-
111
- export interface CreateLogswapClientArgs {
112
- public: PublicClient;
113
- wallet?: WalletClient;
114
- /** The addresses; derived from `deployment` when absent. One of the two is required. */
115
- addresses?: LogswapAddresses;
116
- /** A deployment ({@link deploymentFromArtifact}, {@link deploymentFor}): addresses, chain and deploy block. */
117
- deployment?: LogswapDeployment;
118
- /** Overrides the deployment's. */
119
- deployBlock?: bigint;
120
- /** Overrides the chain's default ({@link LogswapChain.maxLogRange}, else {@link DEFAULT_MAX_LOG_RANGE}). */
121
- maxLogRange?: bigint;
122
- indexerUrl?: string;
123
- }
124
-
125
- export function createLogswapClient(args: CreateLogswapClientArgs): LogswapClient {
126
- const d = args.deployment;
127
- const addresses = args.addresses ?? (d && addressesOfDeployment(d));
128
- if (!addresses) throw new Error("logswap: createLogswapClient needs `addresses` or `deployment`");
129
- const readChain = args.public.chain?.id;
130
- if (d && readChain !== undefined && readChain !== d.chainId) {
131
- throw new Error(`logswap: the deployment is on chain ${d.chainId} but the public client reads chain ${readChain}`);
132
- }
133
- const chainId = d?.chainId ?? readChain;
134
- const maxLogRange = args.maxLogRange ?? (chainId !== undefined ? logswapChain(chainId)?.maxLogRange : undefined) ?? DEFAULT_MAX_LOG_RANGE;
135
- if (maxLogRange <= 0n) throw new Error("logswap: maxLogRange must be positive");
136
- const deployBlock = args.deployBlock ?? d?.deployBlock;
137
- return {
138
- public: args.public,
139
- wallet: args.wallet && guardChain(args.wallet, args.public),
140
- addresses,
141
- maxLogRange,
142
- ...(chainId !== undefined ? { chainId } : {}),
143
- ...(deployBlock !== undefined ? { deployBlock } : {}),
144
- ...(args.indexerUrl ? { indexerUrl: args.indexerUrl } : {}),
145
- };
146
- }
147
-
148
- /** The chain id the client reads: set at construction when known, else asked of the node. */
149
- export async function clientChainId(c: LogswapClient): Promise<number> {
150
- return c.chainId ?? c.public.chain?.id ?? (await c.public.getChainId());
151
- }
152
-
153
- /**
154
- * The wallet, with every signing call first checking that it is on the chain the reads come from.
155
- *
156
- * An injected wallet switched to another network would otherwise estimate and simulate against
157
- * the public client's chain and then sign and send on its own — with deterministic deploy
158
- * addresses, possibly into a different contract. Checked at each call, not once: a user can
159
- * switch networks mid-session.
160
- */
161
- function guardChain(wallet: WalletClient, pub: PublicClient): WalletClient {
162
- if (typeof wallet.getChainId !== "function") return wallet; // a test double
163
- let readChain: number | undefined = pub.chain?.id;
164
- const check = async () => {
165
- readChain ??= await pub.getChainId();
166
- const walletChain = await wallet.getChainId();
167
- if (walletChain !== readChain) {
168
- throw new Error(`logswap: the wallet is on chain ${walletChain} but this app reads chain ${readChain} — switch the wallet's network`);
169
- }
170
- };
171
- const guarded = new Set<PropertyKey>(["writeContract", "sendTransaction", "signTypedData"]);
172
- return new Proxy(wallet, {
173
- get(target, prop, receiver) {
174
- const v = Reflect.get(target, prop, receiver);
175
- if (!guarded.has(prop) || typeof v !== "function") return v;
176
- return async (...a: unknown[]) => {
177
- await check();
178
- return (v as (...x: unknown[]) => unknown).apply(target, a);
179
- };
180
- },
181
- });
182
- }
183
-
184
- /**
185
- * Assert the deployment matches the ABI this build was generated against.
186
- *
187
- * Cheap insurance worth taking at construction: without it, a manager from a different deployment
188
- * decodes into plausible-looking garbage rather than failing. `version` is bumped on any tier-1 or
189
- * tier-2 change (docs/app.md).
190
- *
191
- * **2** since 2026-09-01. It sat at 1 across a read surface that changed underneath it — the nine
192
- * `public constant` getters left the manager for `CParams`, `move` gained its settlement bounds,
193
- * `createMarket` arrived — so a 1 answered for two incompatible ABIs and this check passed against
194
- * a manager it should have rejected. Observed, not theorised: a local chain running a pre-trim
195
- * manager sailed through `assertVersion` while `FEE_MAX()` still answered on it. Move this in the
196
- * same change as `CParams.VERSION`, never after it.
197
- *
198
- * **3** since 2026-09-03: `burnById` and `update` take an `owner`, `update`
199
- * mints to `to`, `positions()` returns `aps` as uint128 — and a returned quote flow now carries the
200
- * swept fees, which is why `exit`'s settle-to-one-asset math changed with it.
201
- *
202
- * **4** since 2026-09-18: `PoolKey` is `(base, quote, tickSpacing, phi)` —
203
- * the variance kernel and its two key fields are gone, so every pool id changed; `phiEff` is
204
- * `phiOf`; `getPool` lost `sigma2Ema`; `Initialize` lost two fields; the cut is
205
- * `MINT_FEE_PROTOCOL_CUT` / `setFeeParams`.
206
- *
207
- * **6** since 2026-10-09 (logswap-contract#58): the whole mint fee is the protocol's
208
- * (`MINT_FEE_PROTOCOL_CUT` and `setFeeParams` are gone, decisions 058); the swap-fee tax at payout,
209
- * `swapFeeTax` / `setSwapFeeTax` (060); `phi` is `swapFee` and `phiOf` `swapFeeOf` (059) — field
210
- * names only, no pool id moved.
211
- *
212
- * **7** since 2026-10-12 (logswap-contract#60, decisions 064–065): the typed views (`getPool`,
213
- * `ticks`, `tickBitmapWord`, `positions`, `feeAcct`, `idInfo`) are behind `extsload` — the pool
214
- * reads through the lens's `getPools`, a class through `CPoolState`'s layout; a fee of 0 is no
215
- * fee (`swapFeeOf` and `DEFAULT_FEE` are gone); the mint fee is the market's, proposed at
216
- * `initialize` / `createMarket` and answered by the gate; the gate (`gate`, `setGate`) is the
217
- * public policy, set at construction. No pool id moved.
218
- *
219
- * **8** since 2026-10-13 (logswap-contract decision 066): the collector is split into two roles —
220
- * `feeCollector` / `proposeCollector` / `acceptCollector` are `treasury` / `proposeTreasury` (the
221
- * LOG Authority's) / `acceptTreasury`; `setSwapFeeTax` and `setGate` leave the manager: the tax is
222
- * each market's, answered by its policy at birth (`PolicyC.swapFeeTax`, an immutable; `SponsorPolicyC` before C 18) and
223
- * read as `getPool(key).swapFeeTax`; the gate is fixed at construction; `collectProtocolFees(key)` is
224
- * permissionless and pays the treasury. No pool id moved.
225
- * 9 (decision 071): the events — one `Swap` on both managers (`taker`, `feeToken`), `CSwapState`, C's `swap`
226
- * takes `SwapParams` (the router's ABI does not move), object-word event names (`MarketCreated`,
227
- * `PositionMinted`, ...), `MarketCreated` carries creator, mintFee and swapFeeTax. No pool id moved.
228
- */
229
- // 11 (decision 078): `mintFee` is a key field (the creator's pick, `2 * swapFee <= mintFee <= 2%`); `initialize(key, x0)`
230
- // takes no separate mint fee, `createMarket` neither; `getPool` drops `mintFee` and the gates' mint-fee menus are gone.
231
- // Every C pool id moved.
232
- // 12 (decisions 079-081): `Action` ordinals, the key is `CPoolKey` (names only). No pool id moved.
233
- // 13 (decisions 088-090): a C pool is addressed by its `bytes32 poolId` after `initialize` (the key rides in calldata at `initialize`
234
- // only; no pool id moved), the router's named entries take the tokens the caller expects (`WrongToken`), `claimById` / `burnById` /
235
- // `claimManyFor` are `claim` / `burn` / `claimMany`, `mint(poolId, to, floor, cap, L)`, `MarketCreated` is `PoolCreated` (in F's field
236
- // order), `x0` is `initialLogPrice`, `PoolView.x` / `.F` are `logPrice` / `feeGrowth`, `swapFee` / `mintFee` are `uint56`.
237
- // 14 (decision 092): the C quoter is the router's (`Router.quoteSwap(poolId, exactIn, baseSide, amount, taker)`); `CPoolManager.quoteSwap`
238
- // and the Lens's `previewSwapExactIn` / `Out` / `InBatch` are gone. No pool id moved.
239
- // 15 (decision 097): `PoolKeyC` is `(base, quote, tickSpacing, policy, creator, salt, swapFee, mintFee)` — every C pool id moved; the creator
240
- // initializes and makes the first mint (`NotCreator`); `PoolCreated` carries the salt; the backstop is held by 0xdead; a malformed policy
241
- // answer is `BadTerms`. The names are decision 096's (no `c` prefix on a function or an event; `SwapState`); a router and a lens per manager.
242
- // 16 (decision 098): the policies are immutable and the LOG's — `SponsorPolicyC` replaces `PublicPolicy` / `PrivatePolicy`; `setPermissions` /
243
- // `PermissionsSet` are `setGates(poolId, gates, operator)` / `GatesSet`; the birth answer is `(flags, tax, operator)`; the policy's
244
- // numbers (tiers, quotes, spacings, tax) are constructor immutables; the swap and mint gates are one bit each (`GATE_SWAP`,
245
- // `GATE_MINT`) and the cached operator passes with no policy call. No pool id moved.
246
- // 17 (decision 107): every event names its actor and the routers emit none (`RouterCall` is gone). `mint(poolId, payer, to, floor, cap, L)`;
247
- // `PositionMinted(poolId, to, id, sender, payer, shares, dBase, dQuote)`; `ProtocolFeesCollected(poolId, sender, to, amount)`;
248
- // `ClassRegistered(poolId, id, floor, cap, capped)` (poolId first); the account acted on is `owner` on `PositionBurned` (was `from`),
249
- // `PositionUpdated` and `FeesClaimed` (was `holder`); `RouterC`'s entries and `Settle` name the receiver `to` (was `recipient`). No pool id moved.
250
- // 18 (decisions 099, 100): `PoolKeyC` is `(quote, base, swapFeeIdx, spacingIdx, policy, salt)` — every C pool id and position id moved; the
251
- // fee is an index into the family's list (the mint fee the next entry) and the spacing an index into `[1e15, 1e16, 1e17]`; `initialize(key, x0)`
252
- // mints the backstop in the call (the caller pays dust of both tokens by allowance to the manager) and `RouterC.createMarket` is gone;
253
- // `PoolCreated` carries the two indices; `claim(poolId, id, owner, to)`; `PoolView` has no `backstopSeeded`; `LensC.params()` is
254
- // `(spacingList, noCap, cVersion)`; `PolicyC` replaces `SponsorPolicyC` (F's gate surface plus `baseListed`, `swapFeeTax`, `mayInit`); the
255
- // registry lost its creation modes (`admit`, `creationMode`, `setCreationMode`, `sponsorOf`). `SpacingZero`, `BackstopTooSmall`,
256
- // `BackstopMustBeUncapped` and `NotCreator` are gone, `PolicyNotApproved` is new.
257
- export const EXPECTED_VERSION = 20n;
258
- /**
259
- * The F manager's own tag (5 — the key's salt, pool names, the sponsor registry;
260
- * 4 was the income-only harvest cut).
261
- *
262
- * A FLOOR, not an equality — unlike `EXPECTED_VERSION` above. The F primitive is iterating fast and
263
- * its bumps are mostly additive (6 is `multicall`, which nothing this SDK calls goes near), so an
264
- * exact match meant each one bricked every app on the deployment until the SDK was republished — a
265
- * version wall in front of a change that broke nothing. The cost is that a genuinely breaking bump
266
- * passes it; when one lands, raise this constant in the same change, which is the discipline
267
- * `EXPECTED_VERSION` enforces mechanically and this one asks for.
268
- */
269
- // 7 (2026-09-15): the reserves are the state and the marks derived, `lockStrike`, the dividend
270
- // harvest, the relaunch (`dissolve(poolId, successor)`, `rollIn`), the reserve-named seed, the
271
- // sponsor facet.
272
- // 8 (2026-09-15): the relaunch is in place — every share id carries the
273
- // generation (`fPoolShareId(poolId, gen)`), `dissolve(poolId)`, `redeem`, `claim` / `dividendOf`
274
- // / `rollIn` / `previewRollIn` take the generation, `Pool.gen` replaces `dissolved` and
275
- // `successor`. A 7 deployment's share ids do not even resolve with this SDK.
276
- // 9 (2026-09-16): `deepen` is gone, `Pool.leverTheta` is `harvestedTheta`.
277
- // 10 (2026-09-17): no floor guard — `Pool.minBuffer`, `raiseMinBuffer`, `LEVER_FLOOR` gone;
278
- // `dissolve` needs an empty bid on every pool; the key bit is the CLASS, `pad`
279
- // (036): `seed` mints a pad's shares to 0xdead, and the operator, the gates and the list are
280
- // refused on it — `fPoolLaunch` no longer transfers the seed itself.
281
- // 11 (2026-09-17): roles and entries — the operator runs the pool (`harvest`,
282
- // `dissolve`, `setLegs`) and is the authority until appointed, two-step (`acceptOperator`,
283
- // `Pool.pendingOperator`); `setLegL`/`admitLeg` are gone, `setLegs` edits the next generation's
284
- // table while unseeded; `fPoolRelaunch` takes `legs`.
285
- // `getPool` decodes one field fewer, so a 9 deployment's struct no longer matches this SDK.
286
- // 12 (2026-09-17): one contract — the sponsor facet is folded back into the
287
- // manager; `sponsor()` and the fallback are gone, every entry, error and event unchanged, so
288
- // `fPoolManagerAbi` is the manager's own ABI and no longer a union. Layout unchanged.
289
- // 13 (2026-09-18): one vocabulary — `HARVEST_FEE` is `HARVEST_PROTOCOL_CUT` (a
290
- // cut of harvested income, not a fee on the harvest) and the exemption is `harvestCutExempt` /
291
- // `setHarvestCutExempt`; `acceptAuthority` clears the operator, pending and accepted (a mandate
292
- // is voided by the handover of the role that granted it); `setLegs` needs a generation to have
293
- // lived (`gen > 0`); `initialize` refuses a codeless base and `mint` refuses `to = address(0)`
294
- // on both managers. Layout unchanged.
295
- // 14 (2026-09-20): the policy — `FPoolKey.policy`, every pool id moves; `dissolve` is
296
- // `retire`, `regenerate` releases the dead shares' pot, `harvestable`/`unharvested` are the
297
- // readouts; `feePerL`, `edgePerL`, `HARVEST_PROTOCOL_CUT`, `harvestCutExempt` are gone.
298
- // 15 (2026-09-20): the policy answers every question — `FPoolKey.authority` is
299
- // `creator` (every pool id moves again); the roles, gates and list are the pool's POLICY's
300
- // (`FPolicyBase` / `PrivatePolicy`), not the manager's: `getPool` has `policy` and `asks` and no
301
- // role; `proposeAuthority`, `appointOperator`, `setGates`, `setAllowed` (`setMinters` / `setTakers` since 17) are policy writes;
302
- // `policyApproved(kind, policy)` / `setPolicyApproved(kind, policy, ok)`; `Regenerated` names the payee;
303
- // `HARVEST_CUT_MAX` / `POT_CUT_MAX` cap what a policy may route to the protocol.
304
- // 16 (2026-09-21): the word is POLICY — a rename, no pool id moves: `FPoolKey.policy`,
305
- // `IFPolicy`, `FPolicyBase`, `PublicPolicy` … `PadPolicy`, `policyApproved` / `setPolicyApproved`,
306
- // `PolicyApproved`; `PolPolicy.setPolicy` / `PolicySet` are `setRules` / `RulesSet`.
307
- // 17 (2026-09-21): the registry, the move, the stamp, two lists, one base — no
308
- // pool id moves: the F manager takes a `PolicyRegistry` at construction and asks it at a birth
309
- // (`policyApproved` / `setPolicyApproved` left the manager: `registryApprove` …); the key's policy
310
- // is the policy at birth, `migrate` moves a pool for the registry's owner; `stamp` / `setAsks` are
311
- // the policy's; the desk's `setAllowed` / `isAllowed` are `setMinters` / `setTakers` / `isMinter` /
312
- // `isTaker`; a pad and a POL hold one base (`OneBase`).
313
- // 18–19: no role, no kind and no name on the manager (049); the events carry what a reader needs (050).
314
- // 20 (2026-09-25, logswap-contract #53): policy isolation — `PolicyRegistry.migrate(manager, key, to)`
315
- // takes the pool's KEY (was its id), `kindOf(policy)` is the tag recorded at approval, the
316
- // registry emits `Migrated`; `IFPolicy.onMigrate` is brought the creator, authority and name;
317
- // the desk's lists are keyed by `listEpoch`. The manager's ABI did not move.
318
- // 21 (2026-09-26, #54): `regenerate` is the generation step — the policy's `Terms` name a
319
- // `carried` holder (a fifth word, 160 B), every other holder is frozen out pro rata into
320
- // generation g's bundle and redeems it (`fPoolRedeem` / `fPoolRollIn` with gen = g), and the
321
- // pool goes on as g + 1. The manager lost `FEE_MIN` / `FEE_MAX` (see keys.ts), `harvestable`
322
- // (the bid: `getPool().Q` when L > 0), `idOf(FPoolKey)` (hashed locally, `fPoolIdOfKey`) and
323
- // `reserveOf` (`legOf`'s fourth word). `PadPolicy.rung` is gone: the pad's rung is `gen`, the
324
- // next threshold `threshold(gen)`. A pad never retires; a public pool refuses `regenerate`.
325
- // 23: a harvest asks `may(Harvest)` and takes no terms and no cut (decisions 056): `onHarvest`, `HARVEST_CUT_MAX`,
326
- // `harvestCut`, `setHarvestCut` are gone; a pad's split (creator's cut, token burn) rides in the key's salt.
327
- // 24 (logswap-contract#58): the pot splits in quote — `Terms.burn` is quote spent on a buy-and-burn, the
328
- // rest deepens the bid, no buy-in, `Regenerated` is (pot, payee, toPayee, cut, burnt, deepened), a pad's
329
- // salt carries `burnShare` of the pot (057); the mint fee all to the treasury (058, 066); `phi` → `swapFee`,
330
- // `MINT_FEE()` → `mintFee()`, the policies' fee tiers, a canonical public pool (059).
331
- // 25 (logswap-contract#59): the views moved behind `extsload` (062) — this SDK reads them through the
332
- // lens (`fPool`, `getFPools`, `fBundleOf`, `fDividendOf`, `fLienOf`); the capped F pool, `FPoolKey.cap` (`lnCapOverFloor` since 27)
333
- // appended so every pool id moved (061); the lien, `lock` / `unlock` (063); the floor is `logFloor`, its reference `refLogFloor`.
334
- // 26 (logswap-contract#60): the mint fee is per pool, proposed at `initialize(key, mintFee)` and answered
335
- // by the policy's `onInitialize` from its menu (065); `MINT_FEE` is gone; a fee of 0 is no fee; the
336
- // policies curate creators, a public pool is uncapped, one pad per base (064). No pool id moved.
337
- // 27 (decision 066): `FPoolKey.cap` → `lnCapOverFloor` (a name: no id moved); `feeCollector` → `treasury` (proposed by the LOG Authority, accepted by itself);
338
- // the registry's `owner` → `logAuthority`, administering every policy's lists and numbers; a public pool
339
- // is born to the LOG Authority. No pool id moved.
340
- // 28 (decision 067): no buy-and-burn — `Terms` is four words, `Regenerated` loses `burnt`; on a pad the manager caps the
341
- // payee at `PAYEE_CUT_MAX` and carries only the dead shares, and refuses `retire`; `PadPolicy.pack(creatorShare, nonce)`,
342
- // `setSchedule` without a burn range, `splitOf` → (creatorShare, protocolShare). No pool id moved.
343
- // 29 (decision 068): the restructure guard and the registry's sunset read `block.timestamp` —
344
- // `Pool.restructureBlock` is `restructureTime` (unix seconds, same slot), `PolicyRegistry.sunset(policy, untilTime)`.
345
- // Names only: no pool id moved.
346
- // 30 (decision 071): the events — `FSwap` is the shared `Swap` plus `FSwapState`, object-word names
347
- // (`PoolCreated`, `GenerationSeeded`, `SharesMinted`, ...), `PoolCreated` carries the mint fee.
348
- // No pool id moved.
349
- // 31 (decision 072): `DividendClaimed` names the generation (`gen`, indexed, after `poolId`); `lock` / `unlock` emit
350
- // `LienLocked` / `LienUnlocked`. No selector, storage layout or pool id moved.
351
- // 33 (decisions 073, 074): sponsor-bound policies, the income fee, registry admission.
352
- // 34-38 (decisions 075-085): one liquidity routine. `FPoolKey` holds no weights and no cap and gains `mintFee` (every pool
353
- // id moved); `initialize(key)`; `seed` / `retire` / `setLegs` are gone for `deployLiquidity(poolId, baseAssets,
354
- // quoteAmount, lnCapOverSeed, to)` (it SETS THE BOOK on an unfunded or a live pool), `close(poolId, to)` and
355
- // `regenerate(poolId, to)`; asset membership is fixed by the key; `LiquidityDeployed` echoes the input,
356
- // `GenerationSeeded` / `LegsSet` are gone; the lens `fPool` field is `baseAssets` (`baseLegs` before decision 090), the cap `lnCapOverSeed`; the pot and the
357
- // income fee are the income and the income tax (`IncomeReleased`, `incomeHeld`, `incomeTax`); a pad is uncapped.
358
- // 39 (decision 087): `swapFeeB4B` is gone; base-for-base pays `swapFee` once, not 2·swapFee.
359
- // A breaking bump: raised in the same change.
360
- // 40 (decision 098): the policies are immutable and the LOG's — `SponsorPolicyF` replaces `PublicPolicy` / `PrivatePolicy`, `PolPolicy` /
361
- // `PadPolicy` lose their setters (and the lists, the handover and `creator`: the authority is `key.creator` for life); `Pool.asks` is
362
- // `Pool.flags` (`GATE_SWAP` 1, `GATE_MINT` 2, `SEED_TO_DEAD` 4) and `Pool.operator` caches the operator; `setPermissions` /
363
- // `PermissionsSet` are `setGates` / `GatesSet`; the registry's `migrate(manager, key, to, permissions)` replaces `migratePrivate`,
364
- // `orphan(manager, key)` moves a pool to `OrphanPolicyF`. No pool id moved.
365
- // 41 (policy.md): one policy contract, `PolicyF`, whose kinds are parameter sets — `SponsorPolicyF`, `PolPolicy`, `PadPolicy` and
366
- // `OrphanPolicyF` are gone. The AUTHORITY is the policy's (immutable) and appoints each pool's OPERATOR, who funds, harvests, closes
367
- // and sets the modes and the name. `PoolKeyF` is `(quote, bases, swapFeeIdx, policy, salt)` — no creator, no mint fee: the swap fee is
368
- // an index into `FEE_LIST` (1, 2, 5, 10, 20, 50, 100, 200 bp) and the mint fee the next entry — so EVERY POOL ID MOVED.
369
- // `deployLiquidity(poolId, baseAssets, quoteAmount, lnCapOverSeed)` on an inactive pool only (no `to`: the operator holds the
370
- // shares); `harvest(poolId, extra, to)` takes the income and `extra` capital; `close(poolId, to)` at any bid, harvesting first,
371
- // refused on a pad; `regenerate` is gone (`multicall(close, redeem, deployLiquidity)`); the registry's `migrate`, `orphan` and
372
- // `setOrphanPolicy` are gone, `sunset` also refuses `deployLiquidity`. `PoolCreated(poolId, quote, policy, bases, swapFeeIdx, salt)`;
373
- // `IncomeHarvested(poolId, to, gen, income, capital, tax, toOperator, Q)`; `GenerationFrozen` from `close` alone; `IncomeReleased` and
374
- // `PolicyMigrated` are gone. The policy's name is an event (`NameSet`), its lists are per policy (`setRights`, `RightsSet`), its
375
- // modes per pool (`setSwapMode` / `setMintMode`, each Open < Listed < Operator with `mintMode ≥ swapMode`).
376
- // 42 (decision 107): every event names its actor and the routers emit none (`RouterCall` is gone). `mint(poolId, payer, to, L, maxQuoteIn)`;
377
- // `claim(poolId, gen, owner, to)` (the owner or its ERC-6909 operator); `SharesMinted(poolId, to, gen, sender, payer, L, shares, dQuote,
378
- // poolL, supply)`; `SharesBurned` indexes `gen` and names `owner` (was `from`), `DividendClaimed` names `owner` (was `holder`);
379
- // `PoolCreated(poolId, quote, creator, policy, bases, swapFeeIdx, salt)` (`creator` a topic, `policy` data); `LiquidityDeployed`,
380
- // `IncomeHarvested` and `GenerationFrozen` carry `operator` as a topic; `RouterF.BadToken` is `WrongToken`. No pool id moved.
381
- export const EXPECTED_F_VERSION = 44n;
382
-
383
- export async function assertVersion(c: LogswapClient, expected = EXPECTED_VERSION): Promise<void> {
384
- const { managerCAbi, managerFAbi } = await import("./generated.js");
385
- const withC = hasC(c);
386
- // independent reads: one round trip, not one per manager
387
- const [gotC, gotF, wiring] = await Promise.all([
388
- // the C stack is optional (F ships first); asserted the same way when deployed
389
- withC ? c.public.readContract({ address: c.addresses.managerC!, abi: managerCAbi, functionName: "version" }) : Promise.resolve(null),
390
- c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "version" }),
391
- assertWiring(c).then(() => null, (e: unknown) => e),
392
- ]);
393
- if (gotC !== null && gotC !== expected) {
394
- throw new Error(
395
- `logswap: C manager at ${c.addresses.managerC} reports version ${gotC}, but this SDK was built ` +
396
- `against version ${expected}. Upgrade the SDK or point at the matching deployment.`,
397
- );
398
- }
399
- if (gotF < EXPECTED_F_VERSION) {
400
- throw new Error(
401
- `logswap: F manager at ${c.addresses.managerF} reports version ${gotF}, but this SDK needs ` +
402
- `at least F version ${EXPECTED_F_VERSION}. Upgrade the deployment or point at a newer one.`,
403
- );
404
- }
405
- // the wiring's error is the less specific one, so a version mismatch is reported first
406
- if (wiring) throw wiring;
407
- }
408
-
409
- /**
410
- * The versions say the managers are the right code; this says the rest of the addresses belong
411
- * to THEM. A stale router or lens from a previous deployment passes every version check and then
412
- * fails in the worst way: approvals go to a router that pulls for another manager, or every pull
413
- * reverts because the router's Permit2 is not the one the user approved. Each side is checked on its
414
- * own: the router and the lens name their manager (`mgr()`), and the router its Permit2.
415
- */
416
- export async function assertWiring(c: LogswapClient): Promise<void> {
417
- const { routerCAbi, routerFAbi, lensCAbi, lensFAbi } = await import("./generated.js");
418
- const rd = (address: Address, abi: readonly unknown[], functionName: string) =>
419
- c.public.readContract({ address, abi, functionName } as never) as Promise<Address>;
420
- const ZERO = "0x0000000000000000000000000000000000000000";
421
- const want: Array<[string, Promise<Address>, Address]> = [
422
- ["routerF.mgr()", rd(c.addresses.routerF, routerFAbi, "mgr"), c.addresses.managerF],
423
- ["routerF.permit2()", rd(c.addresses.routerF, routerFAbi, "permit2"), c.addresses.permit2 ?? ZERO],
424
- ["lensF.mgr()", rd(c.addresses.lensF, lensFAbi, "mgr"), c.addresses.managerF],
425
- ];
426
- if (hasC(c)) {
427
- want.push(["routerC.mgr()", rd(c.addresses.routerC!, routerCAbi, "mgr"), c.addresses.managerC!]);
428
- want.push(["routerC.permit2()", rd(c.addresses.routerC!, routerCAbi, "permit2"), c.addresses.permit2 ?? ZERO]);
429
- want.push(["lensC.mgr()", rd(c.addresses.lensC!, lensCAbi, "mgr"), c.addresses.managerC!]);
430
- }
431
- const got = await Promise.all(want.map((w) => w[1]));
432
- const bad = want.flatMap(([what, , expected], i) =>
433
- got[i]!.toLowerCase() === expected.toLowerCase() ? [] : [`${what} is ${got[i]}, expected ${expected}`],
434
- );
435
- if (bad.length) throw new Error(`logswap: the deployment's addresses do not belong together — ${bad.join("; ")}`);
436
- }