@logswap/sdk 0.5.90 → 0.5.92

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 (59) hide show
  1. package/README.md +136 -31
  2. package/dist/actions.js +4 -3
  3. package/dist/admin.d.ts +96 -925
  4. package/dist/admin.js +113 -194
  5. package/dist/chains.d.ts +13 -4
  6. package/dist/chains.js +22 -9
  7. package/dist/claims.d.ts +1 -1
  8. package/dist/claims.js +11 -9
  9. package/dist/client.d.ts +42 -20
  10. package/dist/client.js +86 -26
  11. package/dist/fees.d.ts +1 -1
  12. package/dist/fees.js +5 -4
  13. package/dist/fpool.d.ts +327 -1120
  14. package/dist/fpool.js +408 -475
  15. package/dist/generated.d.ts +5017 -7631
  16. package/dist/generated.js +3040 -4879
  17. package/dist/history.js +12 -14
  18. package/dist/index.d.ts +5 -7
  19. package/dist/index.js +5 -7
  20. package/dist/indexer.d.ts +2 -2
  21. package/dist/indexer.js +12 -9
  22. package/dist/keys.d.ts +15 -3
  23. package/dist/keys.js +5 -1
  24. package/dist/liquidity.d.ts +1 -1
  25. package/dist/liquidity.js +16 -9
  26. package/dist/onboard.d.ts +16 -11
  27. package/dist/onboard.js +27 -21
  28. package/dist/pools.d.ts +2 -0
  29. package/dist/pools.js +21 -13
  30. package/dist/positions.d.ts +1 -1
  31. package/dist/positions.js +18 -17
  32. package/dist/quote.d.ts +15 -0
  33. package/dist/quote.js +36 -0
  34. package/dist/swap.d.ts +7 -9
  35. package/dist/swap.js +40 -25
  36. package/dist/views.d.ts +1 -1
  37. package/dist/write.d.ts +7 -2
  38. package/dist/write.js +10 -7
  39. package/package.json +3 -3
  40. package/src/actions.ts +4 -3
  41. package/src/admin.ts +143 -249
  42. package/src/chains.ts +32 -13
  43. package/src/claims.ts +11 -10
  44. package/src/client.ts +111 -39
  45. package/src/fees.ts +6 -6
  46. package/src/fpool.ts +555 -648
  47. package/src/generated.ts +3063 -4904
  48. package/src/history.ts +11 -11
  49. package/src/index.ts +5 -7
  50. package/src/indexer.ts +13 -11
  51. package/src/keys.ts +19 -3
  52. package/src/liquidity.ts +16 -10
  53. package/src/onboard.ts +29 -21
  54. package/src/pools.ts +23 -15
  55. package/src/positions.ts +18 -18
  56. package/src/quote.ts +36 -0
  57. package/src/swap.ts +46 -25
  58. package/src/views.ts +1 -2
  59. package/src/write.ts +11 -10
package/src/admin.ts CHANGED
@@ -1,22 +1,26 @@
1
1
  /**
2
- * admin — the protocol's writes: the C swap-fee tax (decisions 060), the policies a pool may be
3
- * born with (the registry's), the policies' own numbers (the quote list, the fee tiers, a pad's
4
- * schedule, a POL's rules), and the two roles' two-step handovers (decision 066): the LOG Authority
5
- * (the registry's `authority`) administers everything here; the LOG Treasury (`treasury` on each
6
- * manager) only receives, and is replaced by the authority's `proposeTreasury`. Plain writes to the managers, the
7
- * registry and the policies; no router.
2
+ * admin — the protocol's writes: the policies a pool may be born under (the registry's list, its sunsets), the C manager's
3
+ * creation modes, the two roles' two-step handovers (decision 066): the LOG Authority (the registry's `logAuthority`)
4
+ * administers the registry and both managers; the LOG Treasury (`treasury` on each manager) only receives, and is replaced by
5
+ * the authority's `proposeTreasury`. Plain writes to the managers and the registry; no router.
8
6
  *
9
- * The mint fee has no cut to set since C version 6 / F version 24 (decisions 058): the whole fee
10
- * is the protocol's on both managers. A harvest has no cut (056); a pad's protocol share of the income
11
- * is the policy's (`PadPolicy.setSchedule`), capped by the manager at `POT_CUT_MAX`.
7
+ * The policies are immutable and deployed by the LOG (decision 098; policy.md): a policy has no setter of its numbers — its fee
8
+ * mask, quotes, bases, buffer, tax and cap bound are constructor immutables — so there is no wrapper that writes one. A change is
9
+ * a new policy, approved ({@link registryApprove}); the old one is sunset ({@link registrySunset}) and its pools run to their next
10
+ * close. The key's policy is the pool's for life: the registry's `migrate` and `orphan` are gone (F 41). What remains here for the
11
+ * policies is reading their numbers; their per-pool settings are in `fpool.ts`.
12
+ *
13
+ * The mint fee has no cut to set since C version 6 / F version 24 (decisions 058): the whole fee is the protocol's on both
14
+ * managers. A harvest has no cut (056); the protocol's share of a harvest's income is the policy's `incomeTaxRate` on the
15
+ * payer's slice, capped by the manager at `INCOME_TAX_MAX`.
12
16
  */
13
17
 
14
- import type { Address, Hash, Hex } from "viem";
15
- import type { PoolKey } from "./keys.js";
16
- import type { LogswapClient } from "./client.js";
18
+ import type { Address, Hash } from "viem";
19
+ import { poolId as keyId, type PoolKey } from "./keys.js";
20
+ import { managerC, routerC, type LogswapClient, type Side } from "./client.js";
17
21
  import { getPool } from "./pools.js";
18
- import { cPoolManagerAbi, fPoolManagerAbi, padPolicyAbi, polPolicyAbi, policyRegistryAbi, publicPolicyAbi } from "./generated.js";
19
- import { bytes32ToText, fPolicyBaseAbi, fPoolKeyOfPool, fPoolKindOfPolicy, textToBytes32, type FPoolKey, type FPoolKind } from "./fpool.js";
22
+ import { managerCAbi, managerFAbi, policyFAbi, policyRegistryAbi, sponsorPolicyCAbi } from "./generated.js";
23
+ import { bytes32ToText, fFeeListed, fPoolKindOfPolicy, fPolicyTermsOf, textToBytes32, type FPoolKind } from "./fpool.js";
20
24
 
21
25
  function wallet(c: LogswapClient) {
22
26
  if (!c.wallet) throw new Error("a wallet client is required");
@@ -28,15 +32,18 @@ function write(c: LogswapClient, address: Address, abi: readonly unknown[], func
28
32
  }
29
33
 
30
34
  /**
31
- * The C swap-fee tax (decisions 060, 066): the protocol's share of every swap fee a C position is
32
- * paid (claims and the burn's auto-claim), WAD. `tax` is the level the gate (`PublicPolicy`) gives a
33
- * market born NOW; each market keeps the level of its birth for life — read it with
34
- * {@link cMarketSwapFeeTax} or `getPool(key).swapFeeTax`. `max` is the manager's bound.
35
+ * The C swap-fee tax (decisions 060, 066, 098): the protocol's share of every swap fee a C position is
36
+ * paid (claims and the burn's auto-claim), WAD. `tax` is the level a market born under `policy` (default: the deployment's
37
+ * `publicPolicyC`) is given — the policy's immutable `swapFeeTax`; each market keeps the level of its birth for
38
+ * life — read it with {@link cMarketSwapFeeTax} or `getPool(key).swapFeeTax`. A different level is a different policy.
39
+ * `max` is the manager's bound.
35
40
  */
36
- export async function cSwapFeeTax(c: LogswapClient): Promise<{ tax: bigint; max: bigint }> {
41
+ export async function cSwapFeeTax(c: LogswapClient, policy?: Address): Promise<{ tax: bigint; max: bigint }> {
42
+ const address = policy ?? c.addresses.publicPolicyC;
43
+ if (!address) throw new Error("logswap: this deployment carries no C sponsored policy (addresses.publicPolicyC); pass one");
37
44
  const [tax, max] = await Promise.all([
38
- c.public.readContract({ address: c.addresses.publicPolicy as Address, abi: publicPolicyAbi, functionName: "swapFeeTax" } as never) as Promise<bigint>,
39
- c.public.readContract({ address: c.addresses.cPoolManager, abi: cPoolManagerAbi, functionName: "SWAP_FEE_TAX_MAX" }),
45
+ c.public.readContract({ address, abi: sponsorPolicyCAbi, functionName: "swapFeeTax" } as never) as Promise<bigint>,
46
+ c.public.readContract({ address: managerC(c), abi: managerCAbi, functionName: "SWAP_FEE_TAX_MAX" }),
40
47
  ]);
41
48
  return { tax, max };
42
49
  }
@@ -46,14 +53,6 @@ export async function cMarketSwapFeeTax(c: LogswapClient, key: PoolKey): Promise
46
53
  return (await getPool(c, key)).swapFeeTax;
47
54
  }
48
55
 
49
- /**
50
- * `PublicPolicy.setSwapFeeTax`: the level a C market born after it is given (066), at most
51
- * `SWAP_FEE_TAX_MAX` (25%). The LOG Authority's. A live market keeps the level of its birth.
52
- */
53
- export async function setCSwapFeeTax(c: LogswapClient, taxWad: bigint): Promise<Hash> {
54
- return write(c, c.addresses.publicPolicy as Address, publicPolicyAbi, "setSwapFeeTax", [taxWad]);
55
- }
56
-
57
56
  // ─── the registry: the LOG Authority's (046, 066) ───────────────────────────
58
57
 
59
58
  const ZERO = "0x0000000000000000000000000000000000000000" as const;
@@ -65,7 +64,7 @@ const ZERO = "0x0000000000000000000000000000000000000000" as const;
65
64
  */
66
65
  export async function policyRegistryOf(c: LogswapClient): Promise<Address> {
67
66
  if (c.addresses.policyRegistry) return c.addresses.policyRegistry;
68
- return (await c.public.readContract({ address: c.addresses.fPoolManager as Address, abi: fPoolManagerAbi, functionName: "registry" } as never)) as Address;
67
+ return (await c.public.readContract({ address: c.addresses.managerF, abi: managerFAbi, functionName: "registry" } as never)) as Address;
69
68
  }
70
69
 
71
70
  /** Whether `policy` is approved now — listed and not yet sunset. True everywhere on a deployment with no registry. */
@@ -75,11 +74,12 @@ export async function policyApproved(c: LogswapClient, policy: Address): Promise
75
74
  return c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "isApproved", args: [policy] } as never) as Promise<boolean>;
76
75
  }
77
76
 
78
- /** One policy on the registry's list, with what it says it is. */
77
+ /** One policy on the registry's list, with what it is. */
79
78
  export interface RegistryEntry {
80
79
  policy: Address;
81
- /** The policy's own `kind()` tag — what a pool born under it is. */
82
- kind: FPoolKind;
80
+ /** The label the policy's terms spell ({@link fPolicyTermsOf}) — what a pool born under it is; `null` for a policy that answers no F terms (the C sponsored policy). */
81
+ kind: FPoolKind | null;
82
+ /** The name recorded at approval (`approve(policy, name)`). */
83
83
  name: string;
84
84
  /** The time (unix seconds) it closes to new pools from; 0 = open. A block number before F version 29. */
85
85
  until: bigint;
@@ -88,9 +88,9 @@ export interface RegistryEntry {
88
88
  }
89
89
 
90
90
  /**
91
- * Every policy listed, sunset ones included — one flat list, each with the kind
92
- * it says it is; `kind` narrows it to one, which is what a create form's dropdown reads. Empty
93
- * with no registry.
91
+ * Every policy listed, sunset ones included — one flat list, each with the kind its terms spell; `kind` narrows it to one,
92
+ * which is what a create form's dropdown reads. The registry is one list for both managers: a C policy is on it with `kind`
93
+ * `null`. Empty with no registry.
94
94
  */
95
95
  export async function registryPolicies(c: LogswapClient, kind?: FPoolKind): Promise<RegistryEntry[]> {
96
96
  const registry = await policyRegistryOf(c);
@@ -102,7 +102,7 @@ export async function registryPolicies(c: LogswapClient, kind?: FPoolKind): Prom
102
102
  list.map(async (policy) => {
103
103
  const [[listed, until, , name], tag] = await Promise.all([
104
104
  c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "entries", args: [policy] } as never) as Promise<[boolean, bigint, number, `0x${string}`]>,
105
- fPoolKindOfPolicy(c, policy),
105
+ fPoolKindOfPolicy(c, policy).catch(() => null), // a C policy answers no F terms
106
106
  ]);
107
107
  return { policy, kind: tag, name: bytes32ToText(name), until, approved: listed && (until === 0n || now < until) };
108
108
  }),
@@ -173,188 +173,79 @@ export const registryAcceptOwner = acceptLogAuthority;
173
173
  * {@link registryApprove} under the policy's own tag as its name, false is {@link registryRevoke}.
174
174
  */
175
175
  export async function setPolicyApproved(c: LogswapClient, policy: Address, approved: boolean): Promise<Hash> {
176
- return approved ? registryApprove(c, policy, await fPoolKindOfPolicy(c, policy)) : registryRevoke(c, policy);
176
+ return approved ? registryApprove(c, policy, await fPoolKindOfPolicy(c, policy).catch(() => "policy")) : registryRevoke(c, policy);
177
177
  }
178
178
 
179
179
  /**
180
- * Move a pool to another approved policy of the same kind: the LOG Authority's alone, a forced move
181
- * (adoption at regeneration by the pool authority's consent is specified, not built — logswap-docs
182
- * `specs/governance/policy-adoption.md`),
183
- * orchestrated on the registry — `migrate(manager, key, to)` since F version 20 (it took the
184
- * pool's id before). The registry checks the key against the manager (`NoPool`), checks the
185
- * manager is its own (`WrongManager`), and compares the two policies' tags recorded at approval
186
- * ({@link registryKindOf}). The new policy is brought the creator (the key's), the authority and
187
- * the name (read off the old policy defensively, the key's creator standing in when it cannot
188
- * answer); the operator and the lists void; no swap lands in the block.
189
- *
190
- * Pass the pool's `key` when in hand. Given only `poolId`, the key is rebuilt from the pool's
191
- * `PoolCreated` log ({@link fPoolKeyOfPool}) with `salt` (zero by default) and checked against
192
- * the id — the log does not carry the salt, so a salted pool needs it named.
180
+ * The name the registry recorded for `policy` at approval (`kindOf`, F version 20: `approve(policy, name)`'s word) — refreshed
181
+ * on re-approval and kept after a revoke. The LOG's own instances are approved as `public`, `private`, `pol`, `pad`; what a
182
+ * policy IS is its terms ({@link fPolicyTermsOf}). "" for a policy the registry never approved (or a deployment with no registry).
193
183
  */
194
- export async function fPoolMigrate(
195
- c: LogswapClient,
196
- a: { to: Address } & ({ key: FPoolKey } | { poolId: `0x${string}`; salt?: `0x${string}`; fromBlock?: bigint }),
197
- ): Promise<Hash> {
198
- const key = "key" in a ? a.key : await fPoolKeyOfPool(c, a.poolId, { salt: a.salt, fromBlock: a.fromBlock });
199
- return registryWrite(c, "migrate", [c.addresses.fPoolManager as Address, key, a.to]);
200
- }
201
-
202
- /**
203
- * The kind tag the registry recorded for `policy` at approval (`kindOf`, F version 20) — refreshed
204
- * on re-approval and kept after a revoke; what `migrate` compares, never the policy's live
205
- * answer. "" for a policy the registry never approved (or a deployment with no registry).
206
- */
207
- export async function registryKindOf(c: LogswapClient, policy: Address): Promise<FPoolKind | ""> {
184
+ export async function registryKindOf(c: LogswapClient, policy: Address): Promise<string> {
208
185
  const registry = await policyRegistryOf(c);
209
186
  if (registry === ZERO) return "";
210
187
  const word = (await c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "kindOf", args: [policy] } as never)) as `0x${string}`;
211
- return bytes32ToText(word) as FPoolKind | "";
212
- }
213
-
214
- // ─── the policies' numbers (the LOG Authority's; each bounded where it reaches the manager) ─────
215
-
216
- /**
217
- * `PadPolicy.setSchedule` (decisions 056, 067, 070, 073): the rung's growth and the RANGE inside which a creator chooses their cut of the income
218
- * at creation (its top ≤ the F manager's `PAYEE_CUT_MAX`). The rest of the income deepens the bid — nothing is bought or
219
- * burnt since F version 28, and the protocol takes no cut of the income since F version 33 (its revenue is the income tax,
220
- * {@link padSetIncomeTaxRate}). A change to the range applies to pads born after it; the growth moves every pad at its
221
- * next rung. The rung is the pool's generation. `T(0)` is per quote since decision 070: {@link padSetThresholdBase}.
222
- */
223
- export async function padSetSchedule(c: LogswapClient, policy: Address, s: PadSchedule): Promise<Hash> {
224
- if ("thresholdBase" in s) throw new Error("logswap: T(0) is per quote since decision 070 — padSetThresholdBase(c, policy, quote, base)");
225
- return write(c, policy, padPolicyAbi, "setSchedule", [s.thresholdGrowth, s.creatorShareMin, s.creatorShareMax]);
226
- }
227
-
228
- /**
229
- * `PadPolicy.setThresholdBase(quote, base)` (decision 070): `T(0)` for pads quoted in `quote`, in that quote's units. A pad is
230
- * born (or moved in) only on a quote that has one (`NoThreshold`). It moves every pad in that quote at its next rung. The LOG
231
- * Authority's.
232
- */
233
- export async function padSetThresholdBase(c: LogswapClient, policy: Address, quote: Address, base: bigint): Promise<Hash> {
234
- return write(c, policy, padPolicyAbi, "setThresholdBase", [quote, base]);
235
- }
236
-
237
- /** A pad policy's `T(0)` in one quote (decision 070): `set` false means no pad can be born on that quote. */
238
- export interface PadThresholdBase {
239
- quote: Address;
240
- set: boolean;
241
- /** In the quote's units; 0 when not set. */
242
- base: bigint;
243
- }
244
-
245
- /** `PadPolicy.thresholdSet(quote)` and `thresholdBaseOf(quote)` for each quote asked (decision 070). */
246
- export async function padThresholdBases(c: LogswapClient, policy: Address, quotes: readonly Address[]): Promise<PadThresholdBase[]> {
247
- const rd = <T>(functionName: string, quote: Address) =>
248
- c.public.readContract({ address: policy, abi: padPolicyAbi, functionName, args: [quote] } as never) as Promise<T>;
249
- return Promise.all(
250
- quotes.map(async (quote) => {
251
- const [set, base] = await Promise.all([rd<boolean>("thresholdSet", quote), rd<bigint>("thresholdBaseOf", quote)]);
252
- return { quote, set, base };
253
- }),
254
- );
255
- }
256
-
257
- /** `PadPolicy.thresholdOf(quote, rung)` (decision 070): the income a pad quoted in `quote` must bank to climb `rung` (0 reads `T(0)`). */
258
- export async function padThresholdOf(c: LogswapClient, policy: Address, quote: Address, rung: bigint | number = 0n): Promise<bigint> {
259
- return (await c.public.readContract({ address: policy, abi: padPolicyAbi, functionName: "thresholdOf", args: [quote, BigInt(rung)] } as never)) as bigint;
260
- }
261
-
262
- /** `PadPolicy.threshold(poolId, rung)` (decision 070): the income pad `poolId` must bank to climb `rung`, in its own quote. */
263
- export async function padThreshold(c: LogswapClient, policy: Address, poolId: Hex, rung: bigint | number): Promise<bigint> {
264
- return (await c.public.readContract({ address: policy, abi: padPolicyAbi, functionName: "threshold", args: [poolId, BigInt(rung)] } as never)) as bigint;
265
- }
266
-
267
- /** A pad policy's schedule (decision 070: without `T(0)`, which is per quote — {@link padThresholdBases}). WAD numbers. */
268
- export interface PadSchedule {
269
- thresholdGrowth: bigint;
270
- creatorShareMin: bigint;
271
- creatorShareMax: bigint;
272
- }
273
-
274
- /** Read {@link PadSchedule} off a pad policy. */
275
- export async function padScheduleOf(c: LogswapClient, policy: Address): Promise<PadSchedule> {
276
- const rd = (functionName: string) => c.public.readContract({ address: policy, abi: padPolicyAbi, functionName } as never) as Promise<bigint>;
277
- const [thresholdGrowth, creatorShareMin, creatorShareMax] = await Promise.all([rd("thresholdGrowth"), rd("creatorShareMin"), rd("creatorShareMax")]);
278
- return { thresholdGrowth, creatorShareMin, creatorShareMax };
279
- }
280
-
281
- /** `PolPolicy.setMinQuoteRatio` (decision 073): the reserve a harvest must leave in the bid (`may(Harvest)` refuses less) and a relaunch's seed must bring, a multiple of the pool's L in WAD (at most 100e18). The policy sponsor's. */
282
- export async function polSetMinQuoteRatio(c: LogswapClient, policy: Address, ratio: bigint): Promise<Hash> {
283
- return write(c, policy, polPolicyAbi, "setMinQuoteRatio", [ratio]);
284
- }
285
-
286
- /** `PadPolicy.setIncomeTaxRate` (decision 073): the share of its new income dividend the dead shares pay LOG Treasury as income tax, WAD, at most 50%. The policy sponsor's. */
287
- export async function padSetIncomeTaxRate(c: LogswapClient, policy: Address, rate: bigint): Promise<Hash> {
288
- return write(c, policy, padPolicyAbi, "setIncomeTaxRate", [rate]);
188
+ return bytes32ToText(word);
289
189
  }
290
190
 
291
- /** `PolPolicy.setIncomeTaxRate` (decision 073): the share of its new income dividend the pool's authority pays LOG Treasury, WAD, at most 50%. Paid on the authority's own shares only: an authority that holds through another address pays nothing. The policy sponsor's. */
292
- export async function polSetIncomeTaxRate(c: LogswapClient, policy: Address, rate: bigint): Promise<Hash> {
293
- return write(c, policy, polPolicyAbi, "setIncomeTaxRate", [rate]);
294
- }
295
-
296
- /** `setQuoteListed` on any protocol policy: a quote a pool of that kind may be born against while it curates quotes. The LOG Authority's. */
297
- export async function policySetQuoteListed(c: LogswapClient, policy: Address, quote: Address, listed: boolean): Promise<Hash> {
298
- return write(c, policy, fPolicyBaseAbi, "setQuoteListed", [quote, listed]);
299
- }
300
-
301
- /** `setQuoteCurated` on any protocol policy: on, a birth against an unlisted quote is refused. The LOG Authority's. */
302
- export async function policySetQuoteCurated(c: LogswapClient, policy: Address, curated: boolean): Promise<Hash> {
303
- return write(c, policy, fPolicyBaseAbi, "setQuoteCurated", [curated]);
304
- }
191
+ // ─── the F policy's lists: immutable, so read-only here (policy.md §4.1) ─────
192
+ // The quotes a pool may be born on, the bases it may hold and the fee entries it may use are constructor values of the
193
+ // policy the LOG deploys. The whole set of numbers is `fPolicyTermsOf`; these answer one candidate.
305
194
 
306
- /** Whether `quote` passes `policy`'s birth check now: listed, or the policy does not curate quotes. */
195
+ /** Whether `quote` passes an F `policy`'s birth check now: it curates quotes (`quoteCurated`, a non-empty list set in the constructor) and lists it, or it does not curate. */
307
196
  export async function policyQuoteAllowed(c: LogswapClient, policy: Address, quote: Address): Promise<{ curated: boolean; listed: boolean; allowed: boolean }> {
308
197
  const [curated, listed] = await Promise.all([
309
- c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "quoteCurated" } as never) as Promise<boolean>,
310
- c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "quoteListed", args: [quote] } as never) as Promise<boolean>,
198
+ c.public.readContract({ address: policy, abi: policyFAbi, functionName: "quoteCurated" } as never) as Promise<boolean>,
199
+ c.public.readContract({ address: policy, abi: policyFAbi, functionName: "quoteListed", args: [quote] } as never) as Promise<boolean>,
311
200
  ]);
312
201
  return { curated, listed, allowed: !curated || listed };
313
202
  }
314
203
 
315
- /**
316
- * `setFeeListed` on any protocol policy (decisions 059): a swap-fee tier a pool of that kind may be
317
- * born with while the policy curates fees. Within the family's domain (`FEE_MIN` ≤ fee ≤ `FEE_MAX`).
318
- * The LOG Authority's.
319
- */
320
- export async function policySetFeeListed(c: LogswapClient, policy: Address, fee: bigint, listed: boolean): Promise<Hash> {
321
- return write(c, policy, fPolicyBaseAbi, "setFeeListed", [fee, listed]);
322
- }
323
-
324
- /** `setFeeCurated` on any protocol policy: on, a birth with an unlisted swap fee is refused (`FeeNotListed`). The LOG Authority's. */
325
- export async function policySetFeeCurated(c: LogswapClient, policy: Address, curated: boolean): Promise<Hash> {
326
- return write(c, policy, fPolicyBaseAbi, "setFeeCurated", [curated]);
327
- }
328
-
329
- /** Whether `fee` passes `policy`'s birth check now: listed, or the policy does not curate fees (the desk's never does). */
330
- export async function policyFeeAllowed(c: LogswapClient, policy: Address, fee: bigint): Promise<{ curated: boolean; listed: boolean; allowed: boolean }> {
204
+ /** Whether `base` passes an F `policy`'s birth check now: it curates bases (`baseCurated`) and lists it, or it does not curate. */
205
+ export async function policyBaseAllowed(c: LogswapClient, policy: Address, base: Address): Promise<{ curated: boolean; listed: boolean; allowed: boolean }> {
331
206
  const [curated, listed] = await Promise.all([
332
- c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "feeCurated" } as never) as Promise<boolean>,
333
- c.public.readContract({ address: policy, abi: fPolicyBaseAbi, functionName: "feeListed", args: [fee] } as never) as Promise<boolean>,
207
+ c.public.readContract({ address: policy, abi: policyFAbi, functionName: "baseCurated" } as never) as Promise<boolean>,
208
+ c.public.readContract({ address: policy, abi: policyFAbi, functionName: "baseListed", args: [base] } as never) as Promise<boolean>,
334
209
  ]);
335
210
  return { curated, listed, allowed: !curated || listed };
336
211
  }
337
212
 
338
- /** `PolicyRegistry.CreationMode` (decision 073): who may create under a policy. Open = 0, Restricted = 1 (the initializer list), SponsorOnly = 2 (bound to a sponsor, permanent). */
339
- export type CreationMode = "open" | "restricted" | "sponsorOnly";
340
- const CREATION_MODES: readonly CreationMode[] = ["open", "restricted", "sponsorOnly"];
213
+ /**
214
+ * Whether the swap fee at `swapFeeIdx` of the F fee list passes `policy`'s birth check now (`feeMask`, policy.md §6). `curated` is true
215
+ * when the policy masks the list (a non-zero mask); with none, every entry is allowed. The mint fee follows the swap fee and is not asked.
216
+ */
217
+ export async function policyFeeAllowed(c: LogswapClient, policy: Address, swapFeeIdx: number): Promise<{ curated: boolean; listed: boolean; allowed: boolean }> {
218
+ const { feeMask } = await fPolicyTermsOf(c, policy);
219
+ const listed = fFeeListed(feeMask, swapFeeIdx);
220
+ return { curated: feeMask !== 0, listed, allowed: listed };
221
+ }
222
+
223
+ /** `PolicyRegistry.CreationMode` (decisions 073, 098): who may create under a policy. Open = 0, SponsorOnly = 1 (the policy's own immutable sponsor, who must also be the key's creator). `Restricted` and the initializer list are gone. */
224
+ export type CreationMode = "open" | "sponsorOnly";
225
+ const CREATION_MODES: readonly CreationMode[] = ["open", "sponsorOnly"];
341
226
 
342
- /** `PolicyRegistry.setCreationMode(policy, mode)` (the LOG Authority): replaces the per-policy creator lists (064). A sponsor-bound policy cannot leave `sponsorOnly`. */
227
+ /** `PolicyRegistry.setCreationMode(policy, mode)` (the LOG Authority). A sponsored policy is approved `sponsorOnly`. */
343
228
  export async function registrySetCreationMode(c: LogswapClient, policy: Address, mode: CreationMode): Promise<Hash> {
344
229
  return registryWrite(c, "setCreationMode", [policy, CREATION_MODES.indexOf(mode)]);
345
230
  }
346
231
 
347
- /** `PolicyRegistry.setInitializerListed(policy, who, allowed)` (the LOG Authority): who may create under a `restricted` policy, authenticated as the caller or a trusted forwarder's user. */
348
- export async function registrySetInitializerListed(c: LogswapClient, policy: Address, who: Address, allowed: boolean): Promise<Hash> {
349
- return registryWrite(c, "setInitializerListed", [policy, who, allowed]);
350
- }
351
-
352
232
  /** `PolicyRegistry.setForwarderTrusted` (the LOG Authority): a router whose `user()` names the creator. Moved off the public policy in F version 33. */
353
233
  export async function registrySetForwarderTrusted(c: LogswapClient, forwarder: Address, trusted: boolean): Promise<Hash> {
354
234
  return registryWrite(c, "setForwarderTrusted", [forwarder, trusted]);
355
235
  }
356
236
 
357
237
  /** `PolicyRegistry.creationMode(policy)`. */
238
+ /**
239
+ * `PolicyRegistry.userOf(caller)` (C 15, decision 097): the account a caller acts for — the user a trusted forwarder
240
+ * (a router) names, else the caller itself. The account the managers authenticate as a market's creator and as the
241
+ * first minter; what a create form compares to the key's `creator`.
242
+ */
243
+ export async function registryUserOf(c: LogswapClient, caller: Address): Promise<Address> {
244
+ const registry = await policyRegistryOf(c);
245
+ if (registry === ZERO) return caller;
246
+ return (await c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName: "userOf", args: [caller] } as never)) as Address;
247
+ }
248
+
358
249
  export async function registryCreationMode(c: LogswapClient, policy: Address): Promise<CreationMode> {
359
250
  const registry = await policyRegistryOf(c);
360
251
  if (registry === ZERO) return "open";
@@ -362,108 +253,111 @@ export async function registryCreationMode(c: LogswapClient, policy: Address): P
362
253
  return CREATION_MODES[Number(m)] ?? "open";
363
254
  }
364
255
 
365
- /** `PublicPolicy.setPairListed` (064): a C pair a market may be born on while pairs are curated. Directional (base, quote). */
366
- export async function gateSetPairListed(c: LogswapClient, policy: Address, base: Address, quote: Address, listed: boolean): Promise<Hash> {
367
- return write(c, policy, publicPolicyAbi, "setPairListed", [base, quote, listed]);
368
- }
369
-
370
- /** `PublicPolicy.setPairCurated` (064). */
371
- export async function gateSetPairCurated(c: LogswapClient, policy: Address, curated: boolean): Promise<Hash> {
372
- return write(c, policy, publicPolicyAbi, "setPairCurated", [curated]);
373
- }
374
-
375
- /** `PublicPolicy.setSpacingListed` (064): a C tick spacing, WAD (10 bp = 1e15, 100 bp = 1e16). Always consulted. */
376
- export async function gateSetSpacingListed(c: LogswapClient, policy: Address, tickSpacing: bigint, listed: boolean): Promise<Hash> {
377
- return write(c, policy, publicPolicyAbi, "setSpacingListed", [tickSpacing, listed]);
378
- }
379
-
380
- /**
381
- * @deprecated C version 8 fixes the gate at construction (066): there is no `setGate`. Open or close
382
- * C through the gate's lists (`registrySetCreationMode`, `gateSetPairCurated`, `gateSetSpacingListed`, …).
383
- */
384
- export async function setCGate(_c: LogswapClient, _gate: Address): Promise<Hash> {
385
- throw new Error("logswap: the C gate is fixed at construction since C version 8 (decision 066); change its lists instead");
256
+ /** Whether `policy` (a `SponsorPolicyC`) admits C tick spacing `tickSpacing`: it curates spacings (`spacingCurated`) and lists it, or it does not curate. */
257
+ export async function policySpacingAllowed(c: LogswapClient, policy: Address, tickSpacing: bigint): Promise<{ curated: boolean; listed: boolean; allowed: boolean }> {
258
+ const [curated, listed] = await Promise.all([
259
+ c.public.readContract({ address: policy, abi: sponsorPolicyCAbi, functionName: "spacingCurated" } as never) as Promise<boolean>,
260
+ c.public.readContract({ address: policy, abi: sponsorPolicyCAbi, functionName: "spacingListed", args: [tickSpacing] } as never) as Promise<boolean>,
261
+ ]);
262
+ return { curated, listed, allowed: !curated || listed };
386
263
  }
387
264
 
388
265
  export interface CGateRules {
389
- /** The registry admits `creator` to create under `key.policy` (creation mode, initializer list, sponsor binding; decision 073). */
266
+ /**
267
+ * The registry admits `creator` to create under `key.policy` (creation mode and sponsor binding; decisions 073, 097, 098):
268
+ * `admit(policy, creator, creator)` resolves to `creator`. Both managers then require the initializer to BE the key's creator (`NotCreator`).
269
+ */
390
270
  creatorOk: boolean;
271
+ /** The quote is on the policy's list, or the policy lists none (`quoteCurated`). */
391
272
  quoteOk: boolean;
392
- pairOk: boolean;
273
+ /** The swap fee is on the policy's swap tiers, or it lists none. */
393
274
  feeOk: boolean;
275
+ /** The mint fee is on the policy's mint tiers, or it lists none. */
276
+ mintFeeOk: boolean;
277
+ /** The tick spacing is on the policy's list, or it lists none (`spacingCurated`). */
394
278
  spacingOk: boolean;
395
- /** A market on (base, quote, fee) already exists, whatever its spacing: the policy refuses another (064 (b)). */
279
+ /** A canonical policy (the LOG's open instance) needs `salt` zero (`NotCanonical`); a desk's may run several markets of one shape. */
280
+ saltOk: boolean;
281
+ /** This exact market (the key's id) is already initialized: another is a different key. */
396
282
  exists: boolean;
397
283
  /** Whether `router` is a trusted forwarder on the registry — `createMarket` through it is then checked against `creator`. */
398
284
  routerTrusted: boolean;
399
- /** Every check passes: the policy would admit this market from this creator (the mint fee is a key field, checked by the manager). */
285
+ /** Every check passes: the policy would admit this market from this creator (the manager checks the fee domain, `BadParam`). */
400
286
  admitted: boolean;
401
287
  }
402
288
 
403
289
  /**
404
- * The public policy's C checks for one candidate market and creator, in one round of reads — what
405
- * the create form shows before a wallet is asked (064, 073). The policy is `key.policy`; the registry
406
- * is asked `admit(policy, caller, 0)`, with the caller being the router when it is a trusted forwarder
407
- * (it then names `creator` itself) and `creator` otherwise.
290
+ * A sponsored C policy's checks for one candidate market and creator, in one round of reads — what the create form shows before a wallet
291
+ * is asked (064, 073, 097, 098). The policy is `key.policy` (a `SponsorPolicyC`); the registry is asked `admit(policy, creator, creator)`: the
292
+ * account that starts a market is its creator, so the key's `creator` is the connected account (a router call resolves to it through the
293
+ * trusted forwarder's `user()`). The policy's pair list is gone (098).
408
294
  */
409
- export async function cGateRules(c: LogswapClient, a: { key: PoolKey; creator: Address; router?: Address; gate?: Address }): Promise<CGateRules> {
295
+ export async function cGateRules(c: LogswapClient, a: { key: PoolKey; creator?: Address; router?: Address; gate?: Address }): Promise<CGateRules> {
410
296
  const g = a.gate ?? (a.key.policy as Address);
411
297
  const rd = <T>(functionName: string, args: readonly unknown[] = []) =>
412
- c.public.readContract({ address: g, abi: publicPolicyAbi, functionName, args } as never) as Promise<T>;
298
+ c.public.readContract({ address: g, abi: sponsorPolicyCAbi, functionName, args } as never) as Promise<T>;
413
299
  const { key } = a;
300
+ const creator = a.creator ?? key.creator;
414
301
  const registry = await policyRegistryOf(c);
415
- const router = a.router ?? c.addresses.router;
302
+ const router = a.router ?? routerC(c);
416
303
  const registryRd = <T>(functionName: string, args: readonly unknown[]) =>
417
304
  c.public.readContract({ address: registry, abi: policyRegistryAbi, functionName, args } as never) as Promise<T>;
418
- const [quoteCurated, quoteListed, pairCurated, pairListed, feeCurated, feeListed, spacingListed, market, routerTrusted, creatorOk] =
305
+ const [quoteCurated, quoteListed, feeListed, mintFeeListed, spacingCurated, spacingListed, canonical, state, routerTrusted, creatorOk] =
419
306
  await Promise.all([
420
307
  rd<boolean>("quoteCurated"),
421
308
  rd<boolean>("quoteListed", [key.quote]),
422
- rd<boolean>("pairCurated"),
423
- rd<boolean>("pairListed", [key.base, key.quote]),
424
- rd<boolean>("feeCurated"),
425
- rd<boolean>("feeListed", [key.swapFee]),
309
+ rd<boolean>("swapFeeListed", [key.swapFee]),
310
+ rd<boolean>("mintFeeListed", [key.mintFee]),
311
+ rd<boolean>("spacingCurated"),
426
312
  rd<boolean>("spacingListed", [key.tickSpacing]),
427
- rd<Hex>("cMarketOf", [key.base, key.quote, key.swapFee]),
313
+ rd<boolean>("canonical"),
314
+ getPool(c, key),
428
315
  registry === ZERO ? Promise.resolve(false) : registryRd<boolean>("forwarderTrusted", [router]),
429
316
  registry === ZERO
430
317
  ? Promise.resolve(true)
431
- : registryRd<Address>("admit", [g, a.creator, ZERO]).then(() => true, () => false),
318
+ : registryRd<Address>("admit", [g, creator, creator]).then((who) => who.toLowerCase() === creator.toLowerCase(), () => false),
432
319
  ]);
433
320
  const r = {
434
321
  creatorOk,
435
322
  quoteOk: !quoteCurated || quoteListed,
436
- pairOk: !pairCurated || pairListed,
437
- feeOk: !feeCurated || feeListed,
438
- spacingOk: spacingListed,
439
- exists: BigInt(market) !== 0n,
323
+ feeOk: feeListed,
324
+ mintFeeOk: mintFeeListed,
325
+ spacingOk: !spacingCurated || spacingListed,
326
+ saltOk: !canonical || key.salt === "0x0000000000000000000000000000000000000000000000000000000000000000",
327
+ exists: state.initialized,
440
328
  routerTrusted,
441
329
  };
442
- return { ...r, admitted: r.creatorOk && r.quoteOk && r.pairOk && r.feeOk && r.spacingOk && !r.exists };
330
+ return { ...r, admitted: r.creatorOk && r.quoteOk && r.feeOk && r.mintFeeOk && r.spacingOk && r.saltOk && !r.exists };
443
331
  }
444
332
 
445
333
  /**
446
- * Every refusal a birth can meet at the gate or a policy (064, 065), for `decodeErrorResult` on a
447
- * failed simulation: the public policy's errors plus the pad's `PadExists` (one pad per base) and `NoThreshold` (no `T(0)`
448
- * in the pad's quote, decision 070).
334
+ * Every refusal a birth can meet at a policy or the registry (064, 065, 098; policy.md §4.4), for `decodeErrorResult` on a
335
+ * failed simulation: the sponsored C policy's errors, the F policy's (`Refused`, `NotCanonical`, `FeeNotListed`, `QuoteNotListed`,
336
+ * `BaseNotListed`, `TooManyLegs`, `AlreadyHeld`, …) and the registry's admission errors. One entry per distinct signature.
449
337
  */
450
- export const gateErrorAbi = [
451
- ...publicPolicyAbi.filter((x) => x.type === "error"),
452
- // creation admission moved to the registry in F 33 / C 10 (073): a refusal there surfaces through the manager's birth
453
- ...policyRegistryAbi.filter((x) => x.type === "error" && ["SponsorOnly", "InitializerNotListed", "InvalidForwardedUser", "NotListed"].includes(x.name)),
454
- ...padPolicyAbi.filter((x) => x.type === "error" && (x.name === "PadExists" || x.name === "NoThreshold")),
455
- ] as const;
338
+ type AbiError = { type: "error"; name: string; inputs: readonly { type: string; name?: string }[] };
339
+ const isAbiError = (x: { type: string }): x is AbiError => x.type === "error";
340
+ export const gateErrorAbi: readonly AbiError[] = (() => {
341
+ const seen = new Set<string>();
342
+ const sig = (x: AbiError) => `${x.name}(${x.inputs.map((i) => i.type).join(",")})`;
343
+ const all = (abi: readonly unknown[]) => (abi as readonly { type: string }[]).filter(isAbiError);
344
+ const errors: AbiError[] = [
345
+ ...all(sponsorPolicyCAbi),
346
+ ...all(policyFAbi),
347
+ // creation admission is the registry's (F 33 / C 10, 073): a refusal there surfaces through the manager's birth
348
+ ...all(policyRegistryAbi).filter((x) => ["SponsorOnly", "InvalidForwardedUser", "NotListed"].includes(x.name)),
349
+ ];
350
+ return errors.filter((x) => (seen.has(sig(x)) ? false : (seen.add(sig(x)), true)));
351
+ })();
456
352
 
457
353
  // ─── the LOG Treasury (066): receives, administers nothing ───────────────────
458
354
 
459
- function manager(c: LogswapClient, side: "C" | "F"): { address: Address; abi: readonly unknown[] } {
460
- return side === "C"
461
- ? { address: c.addresses.cPoolManager, abi: cPoolManagerAbi }
462
- : { address: c.addresses.fPoolManager as Address, abi: fPoolManagerAbi };
355
+ function manager(c: LogswapClient, side: Side): { address: Address; abi: readonly unknown[] } {
356
+ return side === "C" ? { address: managerC(c), abi: managerCAbi } : { address: c.addresses.managerF, abi: managerFAbi };
463
357
  }
464
358
 
465
359
  /** A manager's treasury — where its protocol revenue goes — and the proposed next one. */
466
- export async function logTreasury(c: LogswapClient, side: "C" | "F"): Promise<{ treasury: Address; pending: Address }> {
360
+ export async function logTreasury(c: LogswapClient, side: Side): Promise<{ treasury: Address; pending: Address }> {
467
361
  const m = manager(c, side);
468
362
  const [treasury, pending] = await Promise.all([
469
363
  c.public.readContract({ ...m, functionName: "treasury" } as never) as Promise<Address>,
@@ -476,12 +370,12 @@ export async function logTreasury(c: LogswapClient, side: "C" | "F"): Promise<{
476
370
  * Propose a manager's next treasury: the LOG Authority's call, never the treasury's own, so a
477
371
  * treasury that can no longer act is replaced without it. Nothing the old treasury holds moves.
478
372
  */
479
- export async function proposeTreasury(c: LogswapClient, side: "C" | "F", next: Address): Promise<Hash> {
373
+ export async function proposeTreasury(c: LogswapClient, side: Side, next: Address): Promise<Hash> {
480
374
  const m = manager(c, side);
481
375
  return write(c, m.address, m.abi, "proposeTreasury", [next]);
482
376
  }
483
377
  /** The proposed treasury takes the role, sending from its own address. */
484
- export async function acceptTreasury(c: LogswapClient, side: "C" | "F"): Promise<Hash> {
378
+ export async function acceptTreasury(c: LogswapClient, side: Side): Promise<Hash> {
485
379
  const m = manager(c, side);
486
380
  return write(c, m.address, m.abi, "acceptTreasury", []);
487
381
  }
@@ -491,9 +385,9 @@ export const proposeCollector = proposeTreasury;
491
385
  export const acceptCollector = acceptTreasury;
492
386
 
493
387
  /**
494
- * `CPoolManager.collectProtocolFees(key)`: pay one market's `protocolOwed` (mint fees and swap-fee
388
+ * `ManagerC.collectProtocolFees(poolId)`: pay one market's `protocolOwed` (mint fees and swap-fee
495
389
  * tax) to the treasury. Anyone may send it (066); the destination is fixed.
496
390
  */
497
391
  export async function collectCProtocolFees(c: LogswapClient, key: PoolKey): Promise<Hash> {
498
- return write(c, c.addresses.cPoolManager, cPoolManagerAbi, "collectProtocolFees", [key]);
392
+ return write(c, managerC(c), managerCAbi, "collectProtocolFees", [keyId(key)]);
499
393
  }