@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/dist/history.js CHANGED
@@ -64,7 +64,7 @@ function contractName(c, address, event) {
64
64
  * 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.
65
65
  */
66
66
  export function indexedContractOf(kind, event) {
67
- 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
67
+ void kind; // one contract serves every F kind (F 41) and `PolicyC` emits the same set (C 18): every policy event is unshared
68
68
  return "Policy";
69
69
  }
70
70
  /** Events whose name two indexed contracts share: postgraphile prefixes their tables. */
package/dist/index.d.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/dist/index.js 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/dist/indexer.d.ts CHANGED
@@ -82,7 +82,7 @@ export declare function indexerHealthy(url: string, signal?: AbortSignal): Promi
82
82
  * the more durable path and should be preferred wherever an indexer is configured, with the log
83
83
  * scan as the fallback for when it is not.
84
84
  *
85
- * `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
85
+ * `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
86
86
  * recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
87
87
  * everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
88
88
  */
package/dist/indexer.js CHANGED
@@ -134,26 +134,19 @@ export async function indexerHealthy(url, signal) {
134
134
  * the more durable path and should be preferred wherever an indexer is configured, with the log
135
135
  * scan as the fallback for when it is not.
136
136
  *
137
- * `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
137
+ * `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
138
138
  * recomputed locally rather than trusted from the row — the same offline derivation the SDK uses
139
139
  * everywhere else, so a wrong id fails loudly instead of addressing the wrong pool.
140
140
  */
141
141
  export async function discoverMarketsIndexed(url, signal) {
142
- const nodes = await gqlAll(url, "allCPoolManagerPoolCreateds", "poolId base quote creator salt tickSpacing swapFee mintFee policy initialLogPrice blockNumber txHash contractAddress", { signal });
142
+ const nodes = await gqlAll(url, "allCPoolManagerPoolCreateds", "poolId base quote creator salt swapFeeIdx spacingIdx policy initialLogPrice blockNumber txHash contractAddress", { signal });
143
143
  return nodes.map((n) => {
144
- const key = {
145
- base: n.base,
146
- quote: n.quote,
147
- tickSpacing: BigInt(n.tickSpacing),
148
- policy: n.policy,
149
- creator: n.creator, // a key field since C 15 (097): the event carries it, and the salt
150
- salt: n.salt,
151
- swapFee: BigInt(n.swapFee), // rindexer names the column after the event's field: `swapFee` since C version 6 (logswap-be #40)
152
- mintFee: BigInt(n.mintFee), // a key field since C 12 (078): the event carries it
153
- };
144
+ // rindexer names a column after the event's field: `swapFeeIdx` / `spacingIdx` since C 18 (decision 099)
145
+ const key = { quote: n.quote, base: n.base, swapFeeIdx: Number(n.swapFeeIdx), spacingIdx: Number(n.spacingIdx), policy: n.policy, salt: n.salt };
154
146
  return {
155
147
  key,
156
148
  poolId: poolId(key),
149
+ creator: n.creator,
157
150
  initialLogPrice: BigInt(n.initialLogPrice),
158
151
  blockNumber: BigInt(n.blockNumber),
159
152
  transactionHash: n.txHash,
package/dist/keys.d.ts CHANGED
@@ -12,75 +12,62 @@
12
12
  */
13
13
  import { type Address, type Hex } from "viem";
14
14
  /**
15
- * The fee domain of the family, `FeeParams.FEE_MIN` / `FEE_MAX` (decisions 043): one bound for a
16
- * C market's φ and an F pool's alike, WAD. 1 bp and 1% — plus 0, which since C version 7 / F
17
- * version 26 is a fee-free market or pool, admitted only if the policy lists it (decisions 065).
18
- * The mint fee lives in the same domain. The F manager no longer answers
19
- * `FEE_MIN()` / `FEE_MAX()` (F version 21 cut the getters for bytecode); every F policy still
20
- * checks φ against these at `onInitialize`, and the C side re-exposes them through the lens's
21
- * `params()` (`LensC`, decision 096). Constants here, so a create form bounds φ with no read.
15
+ * `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
16
+ * (decisions 099, 102). A key carries the index; the list is the whole fee domain, with no fee-free entry.
22
17
  */
18
+ export declare const FEE_LIST_BP: readonly [1, 2, 5, 10, 20, 50, 100, 200];
19
+ /** {@link FEE_LIST_BP} in WAD. */
20
+ export declare const FEE_LIST: readonly bigint[];
21
+ /** The least and the most swap fee of the family, WAD: the ends of {@link FEE_LIST} (1 bp, 200 bp). */
23
22
  export declare const FEE_MIN: bigint;
24
23
  export declare const FEE_MAX: bigint;
24
+ /** The most a mint fee is, WAD (2%): the top of {@link FEE_LIST}, which a 200 bp swap fee mints at. */
25
+ export declare const MINT_FEE_MAX: bigint;
25
26
  /**
26
- * The most a pool's creator-selected mint fee may be, WAD (2%): `2 * swapFee <= mintFee <= MINT_FEE_MAX`
27
- * (C 12 / F 38, decision 078). Both managers check it at `initialize` and revert `BadParam`; the mint fee is a
28
- * key field, fixed for the life of the pool.
27
+ * `MarketParams.SPACING_LIST` (decision 099): the log-tick spacings a C market may be born on, WAD steps of log-price
28
+ * (0.1%, about 1% and about 10.5%). A key names one by `spacingIdx`.
29
29
  */
30
- export declare const MINT_FEE_MAX: bigint;
31
- /** The least a pool's mint fee may be for this swap fee: twice it. */
32
- export declare function minMintFee(swapFee: bigint): bigint;
33
- /** Is `mintFee` inside the domain for this `swapFee`? Pure; the managers enforce the same bound. */
34
- export declare function isValidMintFee(swapFee: bigint, mintFee: bigint): boolean;
30
+ export declare const SPACING_LIST: readonly bigint[];
35
31
  /**
36
- * 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,
37
- * so it must match `src/types/PoolKeyC.sol` exactly.
32
+ * The tuple that IS the market (`PoolKeyC`, C 18, decision 099: quote, base, swapFeeIdx, spacingIdx, policy, salt). Field
33
+ * order is load-bearing: it is the ABI encoding order, so it must match `src/types/PoolKeyC.sol` exactly. The resolved
34
+ * swap fee, mint fee and tick spacing are no key fields: {@link swapFeeOfKey}, {@link mintFeeOfKey}, {@link tickSpacingOf}.
38
35
  */
39
36
  export interface PoolKey {
40
- base: Address;
41
37
  quote: Address;
42
- /** Log-tick spacing, WAD. The LP-boundary ladder — position floors and caps. */
43
- tickSpacing: bigint;
38
+ base: Address;
39
+ /** 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). */
40
+ swapFeeIdx: number;
41
+ /** The log-tick spacing (the LP-boundary ladder: position floors and caps), as its index into {@link SPACING_LIST}. */
42
+ spacingIdx: number;
44
43
  /**
45
- * The C policy that admits this market (C version 10, decision 073): `PoolKey.policy`, a registry-approved
46
- * policy, fixed for the market's life. Part of the id: the same pair under two policies is two markets.
47
- * `address(0)` is a bare deployment with no registry.
44
+ * The C policy that admits this market (`PolicyC`, decision 100): registry-approved, fixed for the market's life. Part
45
+ * of the id: the same pair under two policies is two markets.
48
46
  */
49
47
  policy: Address;
50
48
  /**
51
- * Who started the market (C 15, decision 097): the caller of `initialize`, checked by the manager and the registry
52
- * (`NotCreator`). It prices the market at birth and is the only account that may make the FIRST mint, which seeds
53
- * the backstop; after that, minting is open. Part of the id: two creators' markets of one shape are two markets.
54
- * On a router-routed call the creator is the trusted forwarder's user (the connected account), not the router.
55
- */
56
- creator: Address;
57
- /**
58
- * A creator's way to open a second market of the same shape (C 15, decision 097). Part of the id. Zero on the
59
- * public policy, which refuses any other value (`NotCanonical`): a public market is canonical per exact key.
49
+ * A second market of one shape under a closed policy. Part of the id. Zero on an open policy, which refuses any other
50
+ * value (`NotCanonical`): a public market is canonical per exact key.
60
51
  */
61
52
  salt: Hex;
62
- /**
63
- * The swap fee, WAD, fixed for the life of the market: {@link FEE_MIN} (1 bp) ≤ φ ≤ {@link FEE_MAX} (1%),
64
- * or `0n`, which since C version 7 is NO fee (decisions 065; `DEFAULT_FEE` is gone). The gate
65
- * admits only its listed tiers (064: 2, 5, 10, 25, 50, 100 bp). Four fields since C version 4
66
- *: `kappa` and `alpha` left with the variance kernel, and `phiMin` — a floor with
67
- * nothing above it — became `phi`, named `swapFee` since C version 6 (decisions 059). The name
68
- * is not part of the encoding: no pool id changed with it.
69
- */
70
- swapFee: bigint;
71
- /**
72
- * The mint fee, WAD, selected by the creator and fixed for the life of the market (C version 12, decision
73
- * 078): `2 * swapFee <= mintFee <= {@link MINT_FEE_MAX}`. The fee on newly earning `L`; part of the id, so the
74
- * same pair and swap fee at two mint fees is two markets. `initialize` takes no separate mint-fee argument.
75
- */
76
- mintFee: bigint;
77
53
  }
54
+ /** The swap fee at `idx` of {@link FEE_LIST}, WAD. Throws off the list. */
55
+ export declare function feeOfIdx(idx: number): bigint;
56
+ /** 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. */
57
+ export declare function mintFeeIdxOf(swapFeeIdx: number): number;
58
+ /** The index of `fee` (WAD) in {@link FEE_LIST}. Throws for a fee off the list. */
59
+ export declare function feeIdxOf(fee: bigint): number;
60
+ /** The index of `tickSpacing` (WAD) in {@link SPACING_LIST}. Throws for a spacing off the list. */
61
+ export declare function spacingIdxOf(tickSpacing: bigint): number;
62
+ /** A market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]`, what the manager resolves at `initialize`. */
63
+ export declare function swapFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint;
64
+ /** A market's mint fee, WAD of newly earning L: the list's next entry after the swap fee (the same at the top). */
65
+ export declare function mintFeeOfKey(key: Pick<PoolKey, "swapFeeIdx">): bigint;
66
+ /** A market's log-tick spacing, WAD: `SPACING_LIST[key.spacingIdx]`. */
67
+ export declare function tickSpacingOf(key: Pick<PoolKey, "spacingIdx">): bigint;
78
68
  /**
79
- * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model.
80
- *
81
- * A key's `swapFee` is the market's fee as written — `0n` is a fee-free market since C version 7
82
- * (decisions 065), not the 2 bp default it selected before. Always address a market by the key it
83
- * was initialized with.
69
+ * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model. Always address a market by the key
70
+ * it was initialized with. Throws for an index off its list: the manager refuses such a key (`BadParam`).
84
71
  */
85
72
  export declare function poolId(key: PoolKey): Hex;
86
73
  /** Structural equality of two keys — i.e. "the same market". */
package/dist/keys.js CHANGED
@@ -12,64 +12,85 @@
12
12
  */
13
13
  import { encodeAbiParameters, keccak256 } from "viem";
14
14
  /**
15
- * The fee domain of the family, `FeeParams.FEE_MIN` / `FEE_MAX` (decisions 043): one bound for a
16
- * C market's φ and an F pool's alike, WAD. 1 bp and 1% — plus 0, which since C version 7 / F
17
- * version 26 is a fee-free market or pool, admitted only if the policy lists it (decisions 065).
18
- * The mint fee lives in the same domain. The F manager no longer answers
19
- * `FEE_MIN()` / `FEE_MAX()` (F version 21 cut the getters for bytecode); every F policy still
20
- * checks φ against these at `onInitialize`, and the C side re-exposes them through the lens's
21
- * `params()` (`LensC`, decision 096). Constants here, so a create form bounds φ with no read.
15
+ * `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
16
+ * (decisions 099, 102). A key carries the index; the list is the whole fee domain, with no fee-free entry.
22
17
  */
18
+ export const FEE_LIST_BP = [1, 2, 5, 10, 20, 50, 100, 200];
19
+ /** {@link FEE_LIST_BP} in WAD. */
20
+ export const FEE_LIST = FEE_LIST_BP.map((bp) => BigInt(bp) * 10n ** 14n);
21
+ /** The least and the most swap fee of the family, WAD: the ends of {@link FEE_LIST} (1 bp, 200 bp). */
23
22
  export const FEE_MIN = 10n ** 14n;
24
- export const FEE_MAX = 10n ** 16n;
23
+ export const FEE_MAX = 2n * 10n ** 16n;
24
+ /** The most a mint fee is, WAD (2%): the top of {@link FEE_LIST}, which a 200 bp swap fee mints at. */
25
+ export const MINT_FEE_MAX = 2n * 10n ** 16n;
25
26
  /**
26
- * The most a pool's creator-selected mint fee may be, WAD (2%): `2 * swapFee <= mintFee <= MINT_FEE_MAX`
27
- * (C 12 / F 38, decision 078). Both managers check it at `initialize` and revert `BadParam`; the mint fee is a
28
- * key field, fixed for the life of the pool.
27
+ * `MarketParams.SPACING_LIST` (decision 099): the log-tick spacings a C market may be born on, WAD steps of log-price
28
+ * (0.1%, about 1% and about 10.5%). A key names one by `spacingIdx`.
29
29
  */
30
- export const MINT_FEE_MAX = 2n * 10n ** 16n;
31
- /** The least a pool's mint fee may be for this swap fee: twice it. */
32
- export function minMintFee(swapFee) {
33
- return 2n * swapFee;
30
+ export const SPACING_LIST = [10n ** 15n, 10n ** 16n, 10n ** 17n];
31
+ function listed(list, idx, what) {
32
+ const v = Number.isInteger(idx) ? list[idx] : undefined;
33
+ if (v === undefined)
34
+ throw new Error(`logswap: ${what} index ${idx} is off the list (0..${list.length - 1})`);
35
+ return v;
36
+ }
37
+ /** The swap fee at `idx` of {@link FEE_LIST}, WAD. Throws off the list. */
38
+ export function feeOfIdx(idx) {
39
+ return listed(FEE_LIST, idx, "swap fee");
40
+ }
41
+ /** 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. */
42
+ export function mintFeeIdxOf(swapFeeIdx) {
43
+ feeOfIdx(swapFeeIdx);
44
+ return Math.min(swapFeeIdx + 1, FEE_LIST.length - 1);
45
+ }
46
+ /** The index of `fee` (WAD) in {@link FEE_LIST}. Throws for a fee off the list. */
47
+ export function feeIdxOf(fee) {
48
+ const idx = FEE_LIST.indexOf(fee);
49
+ if (idx < 0)
50
+ throw new Error(`logswap: swap fee ${fee} is not on the fee list (${FEE_LIST_BP.join(", ")} bp)`);
51
+ return idx;
52
+ }
53
+ /** The index of `tickSpacing` (WAD) in {@link SPACING_LIST}. Throws for a spacing off the list. */
54
+ export function spacingIdxOf(tickSpacing) {
55
+ const idx = SPACING_LIST.indexOf(tickSpacing);
56
+ if (idx < 0)
57
+ throw new Error(`logswap: tick spacing ${tickSpacing} is not on the spacing list (${SPACING_LIST.join(", ")})`);
58
+ return idx;
34
59
  }
35
- /** Is `mintFee` inside the domain for this `swapFee`? Pure; the managers enforce the same bound. */
36
- export function isValidMintFee(swapFee, mintFee) {
37
- return mintFee <= MINT_FEE_MAX && swapFee <= mintFee / 2n;
60
+ /** A market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]`, what the manager resolves at `initialize`. */
61
+ export function swapFeeOfKey(key) {
62
+ return feeOfIdx(key.swapFeeIdx);
63
+ }
64
+ /** A market's mint fee, WAD of newly earning L: the list's next entry after the swap fee (the same at the top). */
65
+ export function mintFeeOfKey(key) {
66
+ return feeOfIdx(mintFeeIdxOf(key.swapFeeIdx));
67
+ }
68
+ /** A market's log-tick spacing, WAD: `SPACING_LIST[key.spacingIdx]`. */
69
+ export function tickSpacingOf(key) {
70
+ return listed(SPACING_LIST, key.spacingIdx, "spacing");
38
71
  }
39
72
  const POOL_KEY_ABI = [
40
73
  {
41
74
  type: "tuple",
42
75
  components: [
43
- { name: "base", type: "address" },
44
76
  { name: "quote", type: "address" },
45
- { name: "tickSpacing", type: "int256" },
77
+ { name: "base", type: "address" },
78
+ { name: "swapFeeIdx", type: "uint8" },
79
+ { name: "spacingIdx", type: "uint8" },
46
80
  { name: "policy", type: "address" },
47
- { name: "creator", type: "address" },
48
81
  { name: "salt", type: "bytes32" },
49
- { name: "swapFee", type: "uint256" },
50
- { name: "mintFee", type: "uint256" },
51
82
  ],
52
83
  },
53
84
  ];
54
85
  /**
55
- * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model.
56
- *
57
- * A key's `swapFee` is the market's fee as written — `0n` is a fee-free market since C version 7
58
- * (decisions 065), not the 2 bp default it selected before. Always address a market by the key it
59
- * was initialized with.
86
+ * `poolId = keccak256(abi.encode(key))` — the primary key of the entire read model. Always address a market by the key
87
+ * it was initialized with. Throws for an index off its list: the manager refuses such a key (`BadParam`).
60
88
  */
61
89
  export function poolId(key) {
90
+ swapFeeOfKey(key);
91
+ tickSpacingOf(key);
62
92
  return keccak256(encodeAbiParameters(POOL_KEY_ABI, [
63
- {
64
- base: key.base,
65
- quote: key.quote,
66
- tickSpacing: key.tickSpacing,
67
- policy: key.policy,
68
- creator: key.creator,
69
- salt: key.salt,
70
- swapFee: key.swapFee,
71
- mintFee: key.mintFee,
72
- },
93
+ { quote: key.quote, base: key.base, swapFeeIdx: key.swapFeeIdx, spacingIdx: key.spacingIdx, policy: key.policy, salt: key.salt },
73
94
  ]));
74
95
  }
75
96
  /** Structural equality of two keys — i.e. "the same market". */
@@ -53,29 +53,6 @@ export interface MintArgs extends WriteOptions {
53
53
  * costs zero quote too — that is what makes single-asset entry possible in both directions.
54
54
  */
55
55
  export declare function mint(c: LogswapClient, a: MintArgs): Promise<Hash>;
56
- export interface CreateMarketArgs extends WriteOptions {
57
- key: PoolKey;
58
- /** Launch log-price. Bounded by the manager to ±46 (the price domain). */
59
- initialLogPrice: bigint;
60
- /** The backstop's floor — the first mint's rung, permanent for the pool's life. */
61
- targetFloor: bigint;
62
- /** The founding exposure; must exceed the manager's `minBackstopL` lock. */
63
- L: bigint;
64
- /** 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. */
65
- maxBaseIn: bigint;
66
- maxQuoteIn: bigint;
67
- }
68
- /**
69
- * Create a market ATOMICALLY: `initialize` at `initialLogPrice` plus the backstop-establishing first mint in
70
- * one transaction — the canonical creation path. Under the C gate (064) the router is a trusted
71
- * forwarder: the gate checks the router's `user()` — the wallet sending this — against the
72
- * creator list, so a listed creator opens and funds a market in this one call. The
73
- * two-step path let an attacker seat the PERMANENT backstop at a hostile rung between an honest
74
- * `initialize` and its first mint; here either both land or neither, and a front-run of the whole
75
- * call reverts it without moving a wei. No cap: the first mint IS the backstop and must be
76
- * uncapped.
77
- */
78
- export declare function createMarket(c: LogswapClient, a: CreateMarketArgs): Promise<Hash>;
79
56
  export interface ZapArgs extends WriteOptions {
80
57
  key: PoolKey;
81
58
  /** Fund entirely from base (true) or entirely from quote (false). */
package/dist/liquidity.js CHANGED
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { lensCAbi, routerCAbi } from "./generated.js";
25
25
  import { lensC } from "./client.js";
26
- import { poolId as keyId } from "./keys.js";
26
+ import { poolId as keyId, tickSpacingOf } from "./keys.js";
27
27
  import { NO_CAP } from "./ids.js";
28
28
  import { describeId, getPositionClass } from "./positions.js";
29
29
  import { execute, OPEN_DELTA, settleInKind, settleOnly, swapExactInAction, swapExactOutAction, updateAction, } from "./actions.js";
@@ -58,33 +58,6 @@ export async function mint(c, a) {
58
58
  ],
59
59
  }, [a.key.base, a.key.quote]);
60
60
  }
61
- /**
62
- * Create a market ATOMICALLY: `initialize` at `initialLogPrice` plus the backstop-establishing first mint in
63
- * one transaction — the canonical creation path. Under the C gate (064) the router is a trusted
64
- * forwarder: the gate checks the router's `user()` — the wallet sending this — against the
65
- * creator list, so a listed creator opens and funds a market in this one call. The
66
- * two-step path let an attacker seat the PERMANENT backstop at a hostile rung between an honest
67
- * `initialize` and its first mint; here either both land or neither, and a front-run of the whole
68
- * call reverts it without moving a wei. No cap: the first mint IS the backstop and must be
69
- * uncapped.
70
- */
71
- export async function createMarket(c, a) {
72
- return sendRouterWriteWithPermits(c, {
73
- side: "C",
74
- abi: routerCAbi,
75
- functionName: "createMarket",
76
- args: [
77
- a.key,
78
- a.initialLogPrice,
79
- a.targetFloor,
80
- a.L,
81
- a.maxBaseIn,
82
- a.maxQuoteIn,
83
- resolveRecipient(c, a),
84
- resolveDeadline(a),
85
- ],
86
- }, [a.key.base, a.key.quote]);
87
- }
88
61
  /**
89
62
  * Fund a mint from a single asset: the router swaps the imbalanced part through the curve, then
90
63
  * mints, all inside one lock — the two-action batch `[swapExactIn, mint]`.
@@ -235,7 +208,7 @@ function defined(b) {
235
208
  }
236
209
  /** The class behind `shares` of `id`: its floor, cap, and the exposure those shares carry. */
237
210
  async function classOf(c, key, id, shares) {
238
- const [d, cls] = await Promise.all([describeId(c, id, key.tickSpacing), getPositionClass(c, id)]);
211
+ const [d, cls] = await Promise.all([describeId(c, id, tickSpacingOf(key)), getPositionClass(c, id)]);
239
212
  if (d.poolId === `0x${"0".repeat(64)}`)
240
213
  throw new Error(`logswap: id ${id} was never minted`);
241
214
  const L = cls.shares === 0n ? 0n : (cls.L * shares) / cls.shares;
@@ -244,7 +217,7 @@ async function classOf(c, key, id, shares) {
244
217
  /** Move the floor by `rungs` (signed), cap and L pinned. Positive = harvest, negative = deepen. */
245
218
  export async function floor(c, a) {
246
219
  const k = await classOf(c, a.key, a.fromId, a.shares);
247
- return edit(c, { ...a, toFloor: k.floor + a.rungs * a.key.tickSpacing, toCap: k.capped ? k.cap : undefined, newL: k.L });
220
+ return edit(c, { ...a, toFloor: k.floor + a.rungs * tickSpacingOf(a.key), toCap: k.capped ? k.cap : undefined, newL: k.L });
248
221
  }
249
222
  /**
250
223
  * Raise the floor by `rungs` (default 1) and withdraw PURE QUOTE — the base leg untouched.
@@ -280,7 +253,7 @@ export async function cap(c, a) {
280
253
  const k = await classOf(c, a.key, a.fromId, a.shares);
281
254
  if (!k.capped)
282
255
  throw new Error("logswap: cap() needs a capped class — an uncapped one has no cap to move");
283
- const toCap = k.cap + a.rungs * a.key.tickSpacing;
256
+ const toCap = k.cap + a.rungs * tickSpacingOf(a.key);
284
257
  if (toCap <= k.floor)
285
258
  throw new Error("logswap: the cap cannot sit at or below the floor");
286
259
  return edit(c, { ...a, toFloor: k.floor, toCap, newL: k.L });
@@ -288,7 +261,7 @@ export async function cap(c, a) {
288
261
  /** Translate the class by `rungs` (signed): floor and cap together, width and L pinned. */
289
262
  export async function shift(c, a) {
290
263
  const k = await classOf(c, a.key, a.fromId, a.shares);
291
- const d = a.rungs * a.key.tickSpacing;
264
+ const d = a.rungs * tickSpacingOf(a.key);
292
265
  return edit(c, { ...a, toFloor: k.floor + d, toCap: k.capped ? k.cap + d : undefined, newL: k.L });
293
266
  }
294
267
  /** Set the exposure to `newL`, floor and cap pinned; both legs pro rata. The mint fee bites on an increase only. */
package/dist/pools.d.ts CHANGED
@@ -15,12 +15,12 @@ import { type Address, type Hex } from "viem";
15
15
  import { type LogswapClient } from "./client.js";
16
16
  import { type PoolKey } from "./keys.js";
17
17
  /**
18
- * A market's scalar state, field-for-field with `CPoolState.PoolView` — what the manager's `getPool`
19
- * returned before C version 7 moved it behind `extsload` (decisions 065); read through the lens.
18
+ * A market's scalar state, as `PoolStateC.PoolView` names it — what the manager's `getPool`
19
+ * returned before C version 7 moved it behind `extsload` (decisions 065); read through the lens. No `backstopSeeded`
20
+ * since C 18 (decision 099): `initialize` mints the backstop, so an initialized market has one.
20
21
  */
21
22
  export interface PoolState {
22
23
  initialized: boolean;
23
- backstopSeeded: boolean;
24
24
  /** $x = \log p$, WAD — the stored state (`logPrice`; `x` before C 13). */
25
25
  logPrice: bigint;
26
26
  /** Exposure currently earning. Steps only when a floor or cap is crossed. */
@@ -41,10 +41,9 @@ export interface PoolState {
41
41
  /** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
42
42
  export declare function getPool(c: LogswapClient, key: PoolKey): Promise<PoolState>;
43
43
  /**
44
- * The market's swap fee — the key's own `swapFee` since C version 7: a fee of 0 is no fee, and
45
- * `DEFAULT_FEE` / the manager's `swapFeeOf` are gone (decisions 065). Constant for the market's
44
+ * The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
46
45
  * life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
47
- * drop a stale indexer's rows. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
46
+ * drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
48
47
  */
49
48
  export declare function marketSwapFee(c: LogswapClient, key: PoolKey): Promise<bigint>;
50
49
  /**
@@ -105,6 +104,8 @@ export interface DiscoveredMarket {
105
104
  initialLogPrice: bigint;
106
105
  blockNumber: bigint;
107
106
  transactionHash: Hex;
107
+ /** The account that opened the market (`PoolCreated.creator`): it paid the backstop and holds no role by it. Not a key field (C 18). */
108
+ creator?: Address;
108
109
  /** The manager that emitted the `PoolCreated` — set when the row came from the indexer. */
109
110
  manager?: Address;
110
111
  }
@@ -119,7 +120,9 @@ export declare function discoverMarkets(c: LogswapClient, opts?: {
119
120
  fromBlock?: bigint;
120
121
  toBlock?: bigint;
121
122
  base?: Address;
122
- quote?: Address; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */
123
+ quote?: Address; /** Only markets under this policy (an indexed topic, C 19). */
124
+ policy?: Address; /** Only markets this account opened (data since C 20: filtered after decoding). */
125
+ creator?: Address; /** The rindexer GraphQL endpoint: `PoolCreated` from there, the node otherwise. */
123
126
  indexer?: string;
124
127
  }): Promise<DiscoveredMarket[]>;
125
128
  /**
@@ -209,16 +212,22 @@ export declare function annualise(perUnitL: bigint, elapsedSeconds: bigint): num
209
212
  /** When a market was created, as a unix timestamp — the denominator for {@link annualise}. */
210
213
  export declare function marketOpenedAt(c: LogswapClient, m: DiscoveredMarket): Promise<bigint>;
211
214
  /**
212
- * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and no funds move. The
213
- * caller must BE the key's `creator` (C 15, decision 097: `NotCreator`; the registry resolves a routed caller to its user), and only
214
- * the creator may make the first mint, which seeds the backstop. The
215
- * creator-selected mint fee is part of the key (C 12, decision 078: `2 * swapFee <= mintFee <= MINT_FEE_MAX`,
216
- * preset at twice the swap fee by {@link presetMintFee}); there is no separate argument. Under a curated gate the
217
- * CALLER must be a listed creator; the canonical path is the router's {@link createMarket}, which forwards its
218
- * user to the gate and mints the backstop in the same transaction (064).
215
+ * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and the one creation path
216
+ * (C 18, decisions 099, 100: `RouterC.createMarket` is gone). The call mints the permanent backstop (`minBackstopL` of uncapped
217
+ * liquidity to 0xdead on the rung under the opening price), so the market is born live and `account` pays dust of BOTH tokens,
218
+ * and the mint fee on it, by plain ERC-20 allowance to the MANAGER: {@link approveTokenForCManager} for each first. Whoever opens
219
+ * a market holds nothing of it. The policy answers who may create (`PolicyC.mayInit`): anyone at salt zero on an open policy,
220
+ * the policy's authority on a closed one; {@link cGateRules} reads the same checks before a wallet is asked.
219
221
  */
220
222
  export declare function initializeMarket(c: LogswapClient, a: {
221
223
  key: PoolKey;
222
224
  initialLogPrice: bigint;
223
225
  account: Address;
224
226
  }): Promise<`0x${string}`>;
227
+ /**
228
+ * Plain ERC-20 approval to the C manager — the allowance {@link initializeMarket} pulls the backstop against (C 18). Every
229
+ * other C write goes through the router and Permit2 (`onboardToken`). `amount` defaults to the maximum; the backstop is dust.
230
+ */
231
+ export declare function approveTokenForCManager(c: LogswapClient, token: Address, account: Address, amount?: bigint): Promise<Hex>;
232
+ /** Does `owner` have enough allowance on `token` for the C MANAGER to pull `need`? */
233
+ export declare function cManagerAllowanceOk(c: LogswapClient, token: Address, owner: Address, need: bigint): Promise<boolean>;
package/dist/pools.js CHANGED
@@ -16,7 +16,7 @@ import { lensCAbi, managerCAbi } from "./generated.js";
16
16
  import { lensC, managerC, clientChainId } from "./client.js";
17
17
  import { signerFor } from "./write.js";
18
18
  import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
19
- import { poolId } from "./keys.js";
19
+ import { poolId, swapFeeOfKey } from "./keys.js";
20
20
  import { getEventLogs } from "./history.js";
21
21
  /** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
22
22
  export async function getPool(c, key) {
@@ -29,16 +29,15 @@ export async function getPool(c, key) {
29
29
  return v[0];
30
30
  }
31
31
  /**
32
- * The market's swap fee — the key's own `swapFee` since C version 7: a fee of 0 is no fee, and
33
- * `DEFAULT_FEE` / the manager's `swapFeeOf` are gone (decisions 065). Constant for the market's
32
+ * The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
34
33
  * life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
35
- * drop a stale indexer's rows. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
34
+ * drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
36
35
  */
37
36
  export async function marketSwapFee(c, key) {
38
37
  const s = await getPool(c, key);
39
38
  if (!s.initialized)
40
39
  throw new Error(`logswap: market ${poolId(key)} is not initialized`);
41
- return key.swapFee;
40
+ return swapFeeOfKey(key);
42
41
  }
43
42
  /**
44
43
  * Price from the stored log-price. **Lossy** — `x` is exact and this is a float, so use it for
@@ -113,10 +112,13 @@ export async function discoverMarkets(c, opts = {}) {
113
112
  if (!ev)
114
113
  throw new Error("logswap: PoolCreated event missing from the generated ABI");
115
114
  const args = {};
116
- // `quote` is an indexed topic (C 13: `PoolCreated(poolId, quote, creator, base, …)`); `base` no longer is, so it filters below.
117
- // 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.
115
+ // C 20: the topics are `poolId`, `quote`, `policy`; `base` and `creator` are data and filter below.
116
+ // C 18 (decision 099): the event carries the six key fields, so the whole key is rebuilt from the log; `creator` is the account
117
+ // that opened the market and no key field.
118
118
  if (opts.quote)
119
119
  args.quote = opts.quote;
120
+ if (opts.policy)
121
+ args.policy = opts.policy;
120
122
  const { logs } = await getEventLogs(c, {
121
123
  indexer: opts.indexer,
122
124
  address: managerC(c),
@@ -126,21 +128,16 @@ export async function discoverMarkets(c, opts = {}) {
126
128
  toBlock: opts.toBlock,
127
129
  });
128
130
  const wantBase = opts.base?.toLowerCase();
129
- return logs.filter((l) => wantBase === undefined || l.args.base.toLowerCase() === wantBase).map((l) => {
131
+ const wantCreator = opts.creator?.toLowerCase();
132
+ return logs
133
+ .filter((l) => (wantBase === undefined || l.args.base.toLowerCase() === wantBase) && (wantCreator === undefined || l.args.creator.toLowerCase() === wantCreator))
134
+ .map((l) => {
130
135
  const a = l.args;
131
- const key = {
132
- base: a.base,
133
- quote: a.quote,
134
- tickSpacing: a.tickSpacing,
135
- policy: a.policy,
136
- creator: a.creator,
137
- salt: a.salt,
138
- swapFee: a.swapFee,
139
- mintFee: a.mintFee,
140
- };
136
+ const key = { quote: a.quote, base: a.base, swapFeeIdx: Number(a.swapFeeIdx), spacingIdx: Number(a.spacingIdx), policy: a.policy, salt: a.salt };
141
137
  return {
142
138
  key,
143
139
  poolId: poolId(key),
140
+ creator: a.creator,
144
141
  initialLogPrice: a.initialLogPrice,
145
142
  blockNumber: l.blockNumber,
146
143
  transactionHash: l.transactionHash,
@@ -343,18 +340,14 @@ export async function marketOpenedAt(c, m) {
343
340
  return b.timestamp;
344
341
  }
345
342
  /**
346
- * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and no funds move. The
347
- * caller must BE the key's `creator` (C 15, decision 097: `NotCreator`; the registry resolves a routed caller to its user), and only
348
- * the creator may make the first mint, which seeds the backstop. The
349
- * creator-selected mint fee is part of the key (C 12, decision 078: `2 * swapFee <= mintFee <= MINT_FEE_MAX`,
350
- * preset at twice the swap fee by {@link presetMintFee}); there is no separate argument. Under a curated gate the
351
- * CALLER must be a listed creator; the canonical path is the router's {@link createMarket}, which forwards its
352
- * user to the gate and mints the backstop in the same transaction (064).
343
+ * Create a C market: `initialize(key, initialLogPrice)` on the manager — a call, not a deployment, and the one creation path
344
+ * (C 18, decisions 099, 100: `RouterC.createMarket` is gone). The call mints the permanent backstop (`minBackstopL` of uncapped
345
+ * liquidity to 0xdead on the rung under the opening price), so the market is born live and `account` pays dust of BOTH tokens,
346
+ * and the mint fee on it, by plain ERC-20 allowance to the MANAGER: {@link approveTokenForCManager} for each first. Whoever opens
347
+ * a market holds nothing of it. The policy answers who may create (`PolicyC.mayInit`): anyone at salt zero on an open policy,
348
+ * the policy's authority on a closed one; {@link cGateRules} reads the same checks before a wallet is asked.
353
349
  */
354
350
  export async function initializeMarket(c, a) {
355
- if (a.account.toLowerCase() !== a.key.creator.toLowerCase()) {
356
- throw new Error(`logswap: the key's creator ${a.key.creator} must be the account that initializes it (${a.account}) — NotCreator`);
357
- }
358
351
  const { request } = await c.public.simulateContract({
359
352
  address: managerC(c),
360
353
  abi: managerCAbi,
@@ -364,3 +357,18 @@ export async function initializeMarket(c, a) {
364
357
  });
365
358
  return c.wallet.writeContract(request);
366
359
  }
360
+ const ERC20_APPROVE = [{ type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "s", type: "address" }, { name: "a", type: "uint256" }], outputs: [{ type: "bool" }] }];
361
+ const ERC20_ALLOWANCE = [{ type: "function", name: "allowance", stateMutability: "view", inputs: [{ name: "o", type: "address" }, { name: "s", type: "address" }], outputs: [{ type: "uint256" }] }];
362
+ /**
363
+ * Plain ERC-20 approval to the C manager — the allowance {@link initializeMarket} pulls the backstop against (C 18). Every
364
+ * other C write goes through the router and Permit2 (`onboardToken`). `amount` defaults to the maximum; the backstop is dust.
365
+ */
366
+ export async function approveTokenForCManager(c, token, account, amount = (1n << 256n) - 1n) {
367
+ const { request } = await c.public.simulateContract({ address: token, abi: ERC20_APPROVE, functionName: "approve", args: [managerC(c), amount], account: signerFor(c, account) });
368
+ return c.wallet.writeContract(request);
369
+ }
370
+ /** Does `owner` have enough allowance on `token` for the C MANAGER to pull `need`? */
371
+ export async function cManagerAllowanceOk(c, token, owner, need) {
372
+ const allowance = (await c.public.readContract({ address: token, abi: ERC20_ALLOWANCE, functionName: "allowance", args: [owner, managerC(c)] }));
373
+ return allowance >= need;
374
+ }