@logswap/sdk 0.5.100 → 0.5.102

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/src/history.ts CHANGED
@@ -105,7 +105,7 @@ function contractName(c: LogswapClient, address: Address, event: string): string
105
105
  * A policy's name in the indexer for one of its events: `Policy`. Pass it as {@link EventLogsQuery.contract} for a policy outside the artifact.
106
106
  */
107
107
  export function indexedContractOf(kind: FPoolKind, event: string): string {
108
- void kind; // one contract serves every F kind (F 41) and the C sponsored policy's events do not clash with its: every policy event is unshared
108
+ void kind; // one contract serves every F kind (F 41) and `PolicyC` emits the same set (C 18): every policy event is unshared
109
109
  return "Policy";
110
110
  }
111
111
 
package/src/index.ts CHANGED
@@ -22,5 +22,5 @@ export * from "./tokencache.js";
22
22
  export * from "./fpool.js";
23
23
  export * from "./fees.js";
24
24
  export * from "./history.js";
25
- export { managerCAbi, managerFAbi, lensCAbi, lensFAbi, routerCAbi, routerFAbi, routerActionsAbi, policyFAbi, policyRegistryAbi, sponsorPolicyCAbi } from "./generated.js";
25
+ export { managerCAbi, managerFAbi, lensCAbi, lensFAbi, routerCAbi, routerFAbi, routerActionsAbi, policyFAbi, policyCAbi, policyRegistryAbi } from "./generated.js";
26
26
  export * from "./admin.js";
package/src/indexer.ts CHANGED
@@ -178,30 +178,23 @@ export async function indexerHealthy(url: string, signal?: AbortSignal): Promise
178
178
  * the more durable path and should be preferred wherever an indexer is configured, with the log
179
179
  * scan as the fallback for when it is not.
180
180
  *
181
- * `PoolCreated` (the C manager's) carries every field of the `PoolKey` (`mintFee` since C 12, `creator` and `salt` since C 15), so the key is rebuilt exactly and `poolId` is
181
+ * `PoolCreated` (the C manager's) carries every field of the `PoolKey` (C 18: quote, base, swapFeeIdx, spacingIdx, policy, salt), so the key is rebuilt exactly and `poolId` is
182
182
  * recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
183
183
  * everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
184
184
  */
185
185
  export async function discoverMarketsIndexed(url: string, signal?: AbortSignal): Promise<DiscoveredMarket[]> {
186
186
  type Row = {
187
- poolId: Hex; base: Hex; quote: Hex; creator: Hex; salt: Hex; tickSpacing: string; swapFee: string; mintFee: string; policy: Hex;
187
+ poolId: Hex; base: Hex; quote: Hex; creator: Hex; salt: Hex; swapFeeIdx: string | number; spacingIdx: string | number; policy: Hex;
188
188
  initialLogPrice: string; blockNumber: string; txHash: Hex; contractAddress: Hex;
189
189
  };
190
- const nodes = await gqlAll<Row>(url, "allCPoolManagerPoolCreateds", "poolId base quote creator salt tickSpacing swapFee mintFee policy initialLogPrice blockNumber txHash contractAddress", { signal });
190
+ const nodes = await gqlAll<Row>(url, "allCPoolManagerPoolCreateds", "poolId base quote creator salt swapFeeIdx spacingIdx policy initialLogPrice blockNumber txHash contractAddress", { signal });
191
191
  return nodes.map((n) => {
192
- const key: PoolKey = {
193
- base: n.base as Address,
194
- quote: n.quote as Address,
195
- tickSpacing: BigInt(n.tickSpacing),
196
- policy: n.policy as Address,
197
- creator: n.creator as Address, // a key field since C 15 (097): the event carries it, and the salt
198
- salt: n.salt,
199
- swapFee: BigInt(n.swapFee), // rindexer names the column after the event's field: `swapFee` since C version 6 (logswap-be #40)
200
- mintFee: BigInt(n.mintFee), // a key field since C 12 (078): the event carries it
201
- };
192
+ // rindexer names a column after the event's field: `swapFeeIdx` / `spacingIdx` since C 18 (decision 099)
193
+ const key: PoolKey = { quote: n.quote as Address, base: n.base as Address, swapFeeIdx: Number(n.swapFeeIdx), spacingIdx: Number(n.spacingIdx), policy: n.policy as Address, salt: n.salt };
202
194
  return {
203
195
  key,
204
196
  poolId: poolId(key),
197
+ creator: n.creator as Address,
205
198
  initialLogPrice: BigInt(n.initialLogPrice),
206
199
  blockNumber: BigInt(n.blockNumber),
207
200
  transactionHash: n.txHash,
package/src/keys.ts CHANGED
@@ -14,114 +14,120 @@
14
14
  import { encodeAbiParameters, keccak256, type Address, type Hex } from "viem";
15
15
 
16
16
  /**
17
- * The fee domain of the family, `FeeParams.FEE_MIN` / `FEE_MAX` (decisions 043): one bound for a
18
- * C market's φ and an F pool's alike, WAD. 1 bp and 1% — plus 0, which since C version 7 / F
19
- * version 26 is a fee-free market or pool, admitted only if the policy lists it (decisions 065).
20
- * The mint fee lives in the same domain. The F manager no longer answers
21
- * `FEE_MIN()` / `FEE_MAX()` (F version 21 cut the getters for bytecode); every F policy still
22
- * checks φ against these at `onInitialize`, and the C side re-exposes them through the lens's
23
- * `params()` (`LensC`, decision 096). Constants here, so a create form bounds φ with no read.
17
+ * `FeeParams.FEE_LIST` in bp: the eight swap fees a C market or an F pool may be born with, one list for both managers
18
+ * (decisions 099, 102). A key carries the index; the list is the whole fee domain, with no fee-free entry.
24
19
  */
20
+ export const FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200] as const;
21
+ /** {@link FEE_LIST_BP} in WAD. */
22
+ export const FEE_LIST: readonly bigint[] = FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
23
+
24
+ /** The least and the most swap fee of the family, WAD: the ends of {@link FEE_LIST} (1 bp, 200 bp). */
25
25
  export const FEE_MIN = 10n ** 14n;
26
- export const FEE_MAX = 10n ** 16n;
26
+ export const FEE_MAX = 2n * 10n ** 16n;
27
27
 
28
- /**
29
- * The most a pool's creator-selected mint fee may be, WAD (2%): `2 * swapFee <= mintFee <= MINT_FEE_MAX`
30
- * (C 12 / F 38, decision 078). Both managers check it at `initialize` and revert `BadParam`; the mint fee is a
31
- * key field, fixed for the life of the pool.
32
- */
28
+ /** The most a mint fee is, WAD (2%): the top of {@link FEE_LIST}, which a 200 bp swap fee mints at. */
33
29
  export const MINT_FEE_MAX = 2n * 10n ** 16n;
34
30
 
35
- /** The least a pool's mint fee may be for this swap fee: twice it. */
36
- export function minMintFee(swapFee: bigint): bigint {
37
- return 2n * swapFee;
38
- }
39
-
40
- /** Is `mintFee` inside the domain for this `swapFee`? Pure; the managers enforce the same bound. */
41
- export function isValidMintFee(swapFee: bigint, mintFee: bigint): boolean {
42
- return mintFee <= MINT_FEE_MAX && swapFee <= mintFee / 2n;
43
- }
31
+ /**
32
+ * `MarketParams.SPACING_LIST` (decision 099): the log-tick spacings a C market may be born on, WAD steps of log-price
33
+ * (0.1%, about 1% and about 10.5%). A key names one by `spacingIdx`.
34
+ */
35
+ export const SPACING_LIST: readonly bigint[] = [10n ** 15n, 10n ** 16n, 10n ** 17n];
44
36
 
45
37
  /**
46
- * The tuple that IS the market (`PoolKeyC`: base, quote, tickSpacing, policy, creator, salt, swapFee, mintFee). Field order is load-bearing: it is the ABI encoding order,
47
- * so it must match `src/types/PoolKeyC.sol` exactly.
38
+ * The tuple that IS the market (`PoolKeyC`, C 18, decision 099: quote, base, swapFeeIdx, spacingIdx, policy, salt). Field
39
+ * order is load-bearing: it is the ABI encoding order, so it must match `src/types/PoolKeyC.sol` exactly. The resolved
40
+ * swap fee, mint fee and tick spacing are no key fields: {@link swapFeeOfKey}, {@link mintFeeOfKey}, {@link tickSpacingOf}.
48
41
  */
49
42
  export interface PoolKey {
50
- base: Address;
51
43
  quote: Address;
52
- /** Log-tick spacing, WAD. The LP-boundary ladder — position floors and caps. */
53
- tickSpacing: bigint;
44
+ base: Address;
45
+ /** The swap fee, as its index into {@link FEE_LIST}; fixed for the life of the market. The mint fee is the next entry (the same at the top). */
46
+ swapFeeIdx: number;
47
+ /** The log-tick spacing (the LP-boundary ladder: position floors and caps), as its index into {@link SPACING_LIST}. */
48
+ spacingIdx: number;
54
49
  /**
55
- * The C policy that admits this market (C version 10, decision 073): `PoolKey.policy`, a registry-approved
56
- * policy, fixed for the market's life. Part of the id: the same pair under two policies is two markets.
57
- * `address(0)` is a bare deployment with no registry.
50
+ * The C policy that admits this market (`PolicyC`, decision 100): registry-approved, fixed for the market's life. Part
51
+ * of the id: the same pair under two policies is two markets.
58
52
  */
59
53
  policy: Address;
60
54
  /**
61
- * Who started the market (C 15, decision 097): the caller of `initialize`, checked by the manager and the registry
62
- * (`NotCreator`). It prices the market at birth and is the only account that may make the FIRST mint, which seeds
63
- * the backstop; after that, minting is open. Part of the id: two creators' markets of one shape are two markets.
64
- * On a router-routed call the creator is the trusted forwarder's user (the connected account), not the router.
65
- */
66
- creator: Address;
67
- /**
68
- * A creator's way to open a second market of the same shape (C 15, decision 097). Part of the id. Zero on the
69
- * public policy, which refuses any other value (`NotCanonical`): a public market is canonical per exact key.
55
+ * A second market of one shape under a closed policy. Part of the id. Zero on an open policy, which refuses any other
56
+ * value (`NotCanonical`): a public market is canonical per exact key.
70
57
  */
71
58
  salt: Hex;
72
- /**
73
- * The swap fee, WAD, fixed for the life of the market: {@link FEE_MIN} (1 bp) ≤ φ ≤ {@link FEE_MAX} (1%),
74
- * or `0n`, which since C version 7 is NO fee (decisions 065; `DEFAULT_FEE` is gone). The gate
75
- * admits only its listed tiers (064: 2, 5, 10, 25, 50, 100 bp). Four fields since C version 4
76
- *: `kappa` and `alpha` left with the variance kernel, and `phiMin` — a floor with
77
- * nothing above it — became `phi`, named `swapFee` since C version 6 (decisions 059). The name
78
- * is not part of the encoding: no pool id changed with it.
79
- */
80
- swapFee: bigint;
81
- /**
82
- * The mint fee, WAD, selected by the creator and fixed for the life of the market (C version 12, decision
83
- * 078): `2 * swapFee <= mintFee <= {@link MINT_FEE_MAX}`. The fee on newly earning `L`; part of the id, so the
84
- * same pair and swap fee at two mint fees is two markets. `initialize` takes no separate mint-fee argument.
85
- */
86
- mintFee: bigint;
59
+ }
60
+
61
+ function listed<T>(list: readonly T[], idx: number, what: string): T {
62
+ const v = Number.isInteger(idx) ? list[idx] : undefined;
63
+ if (v === undefined) throw new Error(`logswap: ${what} index ${idx} is off the list (0..${list.length - 1})`);
64
+ return v;
65
+ }
66
+
67
+ /** The swap fee at `idx` of {@link FEE_LIST}, WAD. Throws off the list. */
68
+ export function feeOfIdx(idx: number): bigint {
69
+ return listed(FEE_LIST, idx, "swap fee");
70
+ }
71
+
72
+ /** The index in {@link FEE_LIST} of the mint fee a swap fee at `swapFeeIdx` goes with: the next entry, the same at the top. */
73
+ export function mintFeeIdxOf(swapFeeIdx: number): number {
74
+ feeOfIdx(swapFeeIdx);
75
+ return Math.min(swapFeeIdx + 1, FEE_LIST.length - 1);
76
+ }
77
+
78
+ /** The index of `fee` (WAD) in {@link FEE_LIST}. Throws for a fee off the list. */
79
+ export function feeIdxOf(fee: bigint): number {
80
+ const idx = FEE_LIST.indexOf(fee);
81
+ if (idx < 0) throw new Error(`logswap: swap fee ${fee} is not on the fee list (${FEE_LIST_BP.join(", ")} bp)`);
82
+ return idx;
83
+ }
84
+
85
+ /** The index of `tickSpacing` (WAD) in {@link SPACING_LIST}. Throws for a spacing off the list. */
86
+ export function spacingIdxOf(tickSpacing: bigint): number {
87
+ const idx = SPACING_LIST.indexOf(tickSpacing);
88
+ if (idx < 0) throw new Error(`logswap: tick spacing ${tickSpacing} is not on the spacing list (${SPACING_LIST.join(", ")})`);
89
+ return idx;
90
+ }
91
+
92
+ /** A market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]`, what the manager resolves at `initialize`. */
93
+ export function swapFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint {
94
+ return feeOfIdx(key.swapFeeIdx);
95
+ }
96
+
97
+ /** A market's mint fee, WAD of newly earning L: the list's next entry after the swap fee (the same at the top). */
98
+ export function mintFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint {
99
+ return feeOfIdx(mintFeeIdxOf(key.swapFeeIdx));
100
+ }
101
+
102
+ /** A market's log-tick spacing, WAD: `SPACING_LIST[key.spacingIdx]`. */
103
+ export function tickSpacingOf(key: Pick<PoolKey, "spacingIdx">): bigint {
104
+ return listed(SPACING_LIST, key.spacingIdx, "spacing");
87
105
  }
88
106
 
89
107
  const POOL_KEY_ABI = [
90
108
  {
91
109
  type: "tuple",
92
110
  components: [
93
- { name: "base", type: "address" },
94
111
  { name: "quote", type: "address" },
95
- { name: "tickSpacing", type: "int256" },
112
+ { name: "base", type: "address" },
113
+ { name: "swapFeeIdx", type: "uint8" },
114
+ { name: "spacingIdx", type: "uint8" },
96
115
  { name: "policy", type: "address" },
97
- { name: "creator", type: "address" },
98
116
  { name: "salt", type: "bytes32" },
99
- { name: "swapFee", type: "uint256" },
100
- { name: "mintFee", type: "uint256" },
101
117
  ],
102
118
  },
103
119
  ] as const;
104
120
 
105
121
  /**
106
- * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model.
107
- *
108
- * A key's `swapFee` is the market's fee as written — `0n` is a fee-free market since C version 7
109
- * (decisions 065), not the 2 bp default it selected before. Always address a market by the key it
110
- * was initialized with.
122
+ * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model. Always address a market by the key
123
+ * it was initialized with. Throws for an index off its list: the manager refuses such a key (`BadParam`).
111
124
  */
112
125
  export function poolId(key: PoolKey): Hex {
126
+ swapFeeOfKey(key);
127
+ tickSpacingOf(key);
113
128
  return keccak256(
114
129
  encodeAbiParameters(POOL_KEY_ABI, [
115
- {
116
- base: key.base,
117
- quote: key.quote,
118
- tickSpacing: key.tickSpacing,
119
- policy: key.policy,
120
- creator: key.creator,
121
- salt: key.salt,
122
- swapFee: key.swapFee,
123
- mintFee: key.mintFee,
124
- },
130
+ { quote: key.quote, base: key.base, swapFeeIdx: key.swapFeeIdx, spacingIdx: key.spacingIdx, policy: key.policy, salt: key.salt },
125
131
  ]),
126
132
  );
127
133
  }
package/src/liquidity.ts CHANGED
@@ -25,7 +25,7 @@
25
25
  import type { Address, Hash } from "viem";
26
26
  import { lensCAbi, routerCAbi } from "./generated.js";
27
27
  import { lensC, type LogswapClient } from "./client.js";
28
- import { poolId as keyId, type PoolKey } from "./keys.js";
28
+ import { poolId as keyId, tickSpacingOf, type PoolKey } from "./keys.js";
29
29
  import { NO_CAP } from "./ids.js";
30
30
  import { describeId, getPositionClass } from "./positions.js";
31
31
  import {
@@ -100,47 +100,6 @@ export async function mint(c: LogswapClient, a: MintArgs): Promise<Hash> {
100
100
  }, [a.key.base, a.key.quote]);
101
101
  }
102
102
 
103
- export interface CreateMarketArgs extends WriteOptions {
104
- key: PoolKey;
105
- /** Launch log-price. Bounded by the manager to ±46 (the price domain). */
106
- initialLogPrice: bigint;
107
- /** The backstop's floor — the first mint's rung, permanent for the pool's life. */
108
- targetFloor: bigint;
109
- /** The founding exposure; must exceed the manager's `minBackstopL` lock. */
110
- L: bigint;
111
- /** Required, as on {@link mint}. Creation is atomic at `initialLogPrice`, so the flows are fixed by the arguments; {@link UNBOUNDED} is safe here only for that reason. */
112
- maxBaseIn: bigint;
113
- maxQuoteIn: bigint;
114
- }
115
-
116
- /**
117
- * Create a market ATOMICALLY: `initialize` at `initialLogPrice` plus the backstop-establishing first mint in
118
- * one transaction — the canonical creation path. Under the C gate (064) the router is a trusted
119
- * forwarder: the gate checks the router's `user()` — the wallet sending this — against the
120
- * creator list, so a listed creator opens and funds a market in this one call. The
121
- * two-step path let an attacker seat the PERMANENT backstop at a hostile rung between an honest
122
- * `initialize` and its first mint; here either both land or neither, and a front-run of the whole
123
- * call reverts it without moving a wei. No cap: the first mint IS the backstop and must be
124
- * uncapped.
125
- */
126
- export async function createMarket(c: LogswapClient, a: CreateMarketArgs): Promise<Hash> {
127
- return sendRouterWriteWithPermits(c, {
128
- side: "C",
129
- abi: routerCAbi,
130
- functionName: "createMarket",
131
- args: [
132
- a.key,
133
- a.initialLogPrice,
134
- a.targetFloor,
135
- a.L,
136
- a.maxBaseIn,
137
- a.maxQuoteIn,
138
- resolveRecipient(c, a),
139
- resolveDeadline(a),
140
- ],
141
- }, [a.key.base, a.key.quote]);
142
- }
143
-
144
103
  export interface ZapArgs extends WriteOptions {
145
104
  key: PoolKey;
146
105
  /** Fund entirely from base (true) or entirely from quote (false). */
@@ -370,7 +329,7 @@ function defined(b: PairBounds): PairBounds {
370
329
 
371
330
  /** The class behind `shares` of `id`: its floor, cap, and the exposure those shares carry. */
372
331
  async function classOf(c: LogswapClient, key: PoolKey, id: bigint, shares: bigint) {
373
- const [d, cls] = await Promise.all([describeId(c, id, key.tickSpacing), getPositionClass(c, id)]);
332
+ const [d, cls] = await Promise.all([describeId(c, id, tickSpacingOf(key)), getPositionClass(c, id)]);
374
333
  if (d.poolId === `0x${"0".repeat(64)}`) throw new Error(`logswap: id ${id} was never minted`);
375
334
  const L = cls.shares === 0n ? 0n : (cls.L * shares) / cls.shares;
376
335
  return { floor: d.floor!, cap: d.cap!, capped: d.capped, L };
@@ -379,7 +338,7 @@ async function classOf(c: LogswapClient, key: PoolKey, id: bigint, shares: bigin
379
338
  /** Move the floor by `rungs` (signed), cap and L pinned. Positive = harvest, negative = deepen. */
380
339
  export async function floor(c: LogswapClient, a: EditArgs & { rungs: bigint }): Promise<Hash> {
381
340
  const k = await classOf(c, a.key, a.fromId, a.shares);
382
- return edit(c, { ...a, toFloor: k.floor + a.rungs * a.key.tickSpacing, toCap: k.capped ? k.cap : undefined, newL: k.L });
341
+ return edit(c, { ...a, toFloor: k.floor + a.rungs * tickSpacingOf(a.key), toCap: k.capped ? k.cap : undefined, newL: k.L });
383
342
  }
384
343
 
385
344
  /**
@@ -415,7 +374,7 @@ export async function deepen(c: LogswapClient, a: EditArgs & { rungs?: bigint })
415
374
  export async function cap(c: LogswapClient, a: EditArgs & { rungs: bigint }): Promise<Hash> {
416
375
  const k = await classOf(c, a.key, a.fromId, a.shares);
417
376
  if (!k.capped) throw new Error("logswap: cap() needs a capped class — an uncapped one has no cap to move");
418
- const toCap = k.cap + a.rungs * a.key.tickSpacing;
377
+ const toCap = k.cap + a.rungs * tickSpacingOf(a.key);
419
378
  if (toCap <= k.floor) throw new Error("logswap: the cap cannot sit at or below the floor");
420
379
  return edit(c, { ...a, toFloor: k.floor, toCap, newL: k.L });
421
380
  }
@@ -423,7 +382,7 @@ export async function cap(c: LogswapClient, a: EditArgs & { rungs: bigint }): Pr
423
382
  /** Translate the class by `rungs` (signed): floor and cap together, width and L pinned. */
424
383
  export async function shift(c: LogswapClient, a: EditArgs & { rungs: bigint }): Promise<Hash> {
425
384
  const k = await classOf(c, a.key, a.fromId, a.shares);
426
- const d = a.rungs * a.key.tickSpacing;
385
+ const d = a.rungs * tickSpacingOf(a.key);
427
386
  return edit(c, { ...a, toFloor: k.floor + d, toCap: k.capped ? k.cap + d : undefined, newL: k.L });
428
387
  }
429
388
 
package/src/pools.ts CHANGED
@@ -17,16 +17,16 @@ import { lensCAbi, managerCAbi } from "./generated.js";
17
17
  import { lensC, managerC, clientChainId, type LogswapClient } from "./client.js";
18
18
  import { signerFor } from "./write.js";
19
19
  import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
20
- import { poolId, type PoolKey } from "./keys.js";
20
+ import { poolId, swapFeeOfKey, type PoolKey } from "./keys.js";
21
21
  import { getEventLogs } from "./history.js";
22
22
 
23
23
  /**
24
- * A market's scalar state, field-for-field with `CPoolState.PoolView` — what the manager's `getPool`
25
- * returned before C version 7 moved it behind `extsload` (decisions 065); read through the lens.
24
+ * A market's scalar state, as `PoolStateC.PoolView` names it — what the manager's `getPool`
25
+ * returned before C version 7 moved it behind `extsload` (decisions 065); read through the lens. No `backstopSeeded`
26
+ * since C 18 (decision 099): `initialize` mints the backstop, so an initialized market has one.
26
27
  */
27
28
  export interface PoolState {
28
29
  initialized: boolean;
29
- backstopSeeded: boolean;
30
30
  /** $x = \log p$, WAD — the stored state (`logPrice`; `x` before C 13). */
31
31
  logPrice: bigint;
32
32
  /** Exposure currently earning. Steps only when a floor or cap is crossed. */
@@ -57,15 +57,14 @@ export async function getPool(c: LogswapClient, key: PoolKey): Promise<PoolState
57
57
  }
58
58
 
59
59
  /**
60
- * The market's swap fee — the key's own `swapFee` since C version 7: a fee of 0 is no fee, and
61
- * `DEFAULT_FEE` / the manager's `swapFeeOf` are gone (decisions 065). Constant for the market's
60
+ * The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
62
61
  * life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
63
- * drop a stale indexer's rows. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
62
+ * drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
64
63
  */
65
64
  export async function marketSwapFee(c: LogswapClient, key: PoolKey): Promise<bigint> {
66
65
  const s = await getPool(c, key);
67
66
  if (!s.initialized) throw new Error(`logswap: market ${poolId(key)} is not initialized`);
68
- return key.swapFee;
67
+ return swapFeeOfKey(key);
69
68
  }
70
69
 
71
70
  /**
@@ -149,6 +148,8 @@ export interface DiscoveredMarket {
149
148
  initialLogPrice: bigint;
150
149
  blockNumber: bigint;
151
150
  transactionHash: Hex;
151
+ /** The account that opened the market (`PoolCreated.creator`): it paid the backstop and holds no role by it. Not a key field (C 18). */
152
+ creator?: Address;
152
153
  /** The manager that emitted the `PoolCreated` — set when the row came from the indexer. */
153
154
  manager?: Address;
154
155
  }
@@ -162,7 +163,7 @@ export interface DiscoveredMarket {
162
163
  */
163
164
  export async function discoverMarkets(
164
165
  c: LogswapClient,
165
- opts: { fromBlock?: bigint; toBlock?: bigint; base?: Address; quote?: Address; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */ indexer?: string } = {},
166
+ opts: { fromBlock?: bigint; toBlock?: bigint; base?: Address; quote?: Address; /** Only markets under this policy (an indexed topic, C 19). */ policy?: Address; /** Only markets this account opened (data since C 20: filtered after decoding). */ creator?: Address; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */ indexer?: string } = {},
166
167
  ): Promise<DiscoveredMarket[]> {
167
168
  // Narrow the const ABI to the PoolCreated entry while KEEPING its literal type, so viem can infer
168
169
  // the log shape. `as never` would compile but collapse every arg to `never` at the call site.
@@ -171,10 +172,12 @@ export async function discoverMarkets(
171
172
  if (!ev) throw new Error("logswap: PoolCreated event missing from the generated ABI");
172
173
 
173
174
  const args: Record<string, unknown> = {};
174
- // `quote` is an indexed topic (C 13: `PoolCreated(poolId, quote, creator, base, …)`); `base` no longer is, so it filters below.
175
- // C 15 (decision 097): the event ends with the key's `salt`, so the whole key — `creator` and `salt` included — is rebuilt from the log.
175
+ // C 20: the topics are `poolId`, `quote`, `policy`; `base` and `creator` are data and filter below.
176
+ // C 18 (decision 099): the event carries the six key fields, so the whole key is rebuilt from the log; `creator` is the account
177
+ // that opened the market and no key field.
176
178
  if (opts.quote) args.quote = opts.quote;
177
- const { logs } = await getEventLogs<{ base: Address; quote: Address; creator: Address; salt: Hex; tickSpacing: bigint; policy: Address; swapFee: bigint; mintFee: bigint; initialLogPrice: bigint }>(c, {
179
+ if (opts.policy) args.policy = opts.policy;
180
+ const { logs } = await getEventLogs<{ base: Address; quote: Address; creator: Address; salt: Hex; swapFeeIdx: number | bigint; spacingIdx: number | bigint; policy: Address; initialLogPrice: bigint }>(c, {
178
181
  indexer: opts.indexer,
179
182
  address: managerC(c),
180
183
  event: ev,
@@ -184,21 +187,16 @@ export async function discoverMarkets(
184
187
  });
185
188
 
186
189
  const wantBase = opts.base?.toLowerCase();
187
- return logs.filter((l) => wantBase === undefined || l.args.base.toLowerCase() === wantBase).map((l) => {
190
+ const wantCreator = opts.creator?.toLowerCase();
191
+ return logs
192
+ .filter((l) => (wantBase === undefined || l.args.base.toLowerCase() === wantBase) && (wantCreator === undefined || l.args.creator.toLowerCase() === wantCreator))
193
+ .map((l) => {
188
194
  const a = l.args;
189
- const key: PoolKey = {
190
- base: a.base,
191
- quote: a.quote,
192
- tickSpacing: a.tickSpacing,
193
- policy: a.policy,
194
- creator: a.creator,
195
- salt: a.salt,
196
- swapFee: a.swapFee,
197
- mintFee: a.mintFee,
198
- };
195
+ const key: PoolKey = { quote: a.quote, base: a.base, swapFeeIdx: Number(a.swapFeeIdx), spacingIdx: Number(a.spacingIdx), policy: a.policy, salt: a.salt };
199
196
  return {
200
197
  key,
201
198
  poolId: poolId(key),
199
+ creator: a.creator,
202
200
  initialLogPrice: a.initialLogPrice,
203
201
  blockNumber: l.blockNumber,
204
202
  transactionHash: l.transactionHash,
@@ -430,18 +428,14 @@ export async function marketOpenedAt(c: LogswapClient, m: DiscoveredMarket): Pro
430
428
  }
431
429
 
432
430
  /**
433
- * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and no funds move. The
434
- * caller must BE the key's `creator` (C 15, decision 097: `NotCreator`; the registry resolves a routed caller to its user), and only
435
- * the creator may make the first mint, which seeds the backstop. The
436
- * creator-selected mint fee is part of the key (C 12, decision 078: `2 * swapFee <= mintFee <= MINT_FEE_MAX`,
437
- * preset at twice the swap fee by {@link presetMintFee}); there is no separate argument. Under a curated gate the
438
- * CALLER must be a listed creator; the canonical path is the router's {@link createMarket}, which forwards its
439
- * user to the gate and mints the backstop in the same transaction (064).
431
+ * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and the one creation path
432
+ * (C 18, decisions 099, 100: `RouterC.createMarket` is gone). The call mints the permanent backstop (`minBackstopL` of uncapped
433
+ * liquidity to 0xdead on the rung under the opening price), so the market is born live and `account` pays dust of BOTH tokens,
434
+ * and the mint fee on it, by plain ERC-20 allowance to the MANAGER: {@link approveTokenForCManager} for each first. Whoever opens
435
+ * a market holds nothing of it. The policy answers who may create (`PolicyC.mayInit`): anyone at salt zero on an open policy,
436
+ * the policy's authority on a closed one; {@link cGateRules} reads the same checks before a wallet is asked.
440
437
  */
441
438
  export async function initializeMarket(c: LogswapClient, a: { key: PoolKey; initialLogPrice: bigint; account: Address }) {
442
- if (a.account.toLowerCase() !== a.key.creator.toLowerCase()) {
443
- throw new Error(`logswap: the key's creator ${a.key.creator} must be the account that initializes it (${a.account}) — NotCreator`);
444
- }
445
439
  const { request } = await c.public.simulateContract({
446
440
  address: managerC(c),
447
441
  abi: managerCAbi,
@@ -451,3 +445,21 @@ export async function initializeMarket(c: LogswapClient, a: { key: PoolKey; init
451
445
  } as never);
452
446
  return c.wallet!.writeContract(request as never);
453
447
  }
448
+
449
+ const ERC20_APPROVE = [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }] as const;
450
+ const ERC20_ALLOWANCE = [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }] as const;
451
+
452
+ /**
453
+ * Plain ERC-20 approval to the C manager — the allowance {@link initializeMarket} pulls the backstop against (C 18). Every
454
+ * other C write goes through the router and Permit2 (`onboardToken`). `amount` defaults to the maximum; the backstop is dust.
455
+ */
456
+ export async function approveTokenForCManager(c: LogswapClient, token: Address, account: Address, amount: bigint = (1n << 256n) - 1n): Promise<Hex> {
457
+ const { request } = await c.public.simulateContract({ address: token, abi: ERC20_APPROVE, functionName: "approve", args: [managerC(c), amount], account: signerFor(c, account) } as never);
458
+ return c.wallet!.writeContract(request as never);
459
+ }
460
+
461
+ /** Does `owner` have enough allowance on `token` for the C MANAGER to pull `need`? */
462
+ export async function cManagerAllowanceOk(c: LogswapClient, token: Address, owner: Address, need: bigint): Promise<boolean> {
463
+ const allowance = (await c.public.readContract({ address: token, abi: ERC20_ALLOWANCE, functionName: "allowance", args: [owner, managerC(c)] } as never)) as bigint;
464
+ return allowance >= need;
465
+ }
package/src/positions.ts CHANGED
@@ -10,7 +10,7 @@ import { encodeAbiParameters, keccak256, parseAbiItem } from "viem";
10
10
  import type { Address, Hex } from "viem";
11
11
  import { lensCAbi, managerCAbi } from "./generated.js";
12
12
  import { managerC, lensC, type LogswapClient } from "./client.js";
13
- import { MINT_FEE_MAX, poolId, type PoolKey } from "./keys.js";
13
+ import { poolId, tickSpacingOf, type PoolKey } from "./keys.js";
14
14
 
15
15
  /** `CPoolState.POSITIONS_SLOT`: the manager's `positions` mapping (`forge inspect CPoolManager storageLayout`). */
16
16
  const C_POSITIONS_SLOT = 4n;
@@ -98,7 +98,7 @@ export async function getHolderPosition(
98
98
  floor: bigint,
99
99
  cap: bigint = NO_CAP,
100
100
  ): Promise<HolderPosition> {
101
- const id = positionId(poolId(key), key.tickSpacing, floor, cap);
101
+ const id = positionId(poolId(key), tickSpacingOf(key), floor, cap);
102
102
  const [cls, shares, claimableFees] = await Promise.all([
103
103
  getPositionClass(c, id),
104
104
  balanceOf(c, owner, id),
@@ -197,20 +197,11 @@ export function positionQuote(
197
197
  return (p.L * (upper - p.floor)) / 10n ** 18n;
198
198
  }
199
199
 
200
- /**
201
- * The mint fee a create form presets: the least the managers accept, twice the swap fee (C 12 / F 38, decision
202
- * 078: `2 * swapFee <= mintFee <= {@link MINT_FEE_MAX}`). The creator selects it in the key; there is no menu.
203
- */
204
- export function presetMintFee(swapFee: bigint): bigint {
205
- const m = 2n * swapFee;
206
- return m > MINT_FEE_MAX ? MINT_FEE_MAX : m;
207
- }
208
-
209
200
  /**
210
201
  * The one-time mint fee at log-price `x`, in quote units — the amount `_mintCore` pulls ON TOP of
211
202
  * the position's own legs, so a mint's total quote pull is `positionQuote(p, x) + mintFee(p, x, rate)`.
212
- * `rate` is the MARKET's mint fee (`key.mintFee`, WAD of L): the creator-selected key field since C 12 (078),
213
- * fixed for life; there is no global `MINT_FEE`.
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`.
214
205
  *
215
206
  * Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
216
207
  * capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it