@logswap/sdk 0.5.99 → 0.5.101
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/README.md +104 -36
- package/dist/actions.d.ts +8 -8
- package/dist/actions.js +8 -8
- package/dist/admin.d.ts +16 -36
- package/dist/admin.js +26 -57
- package/dist/chains.d.ts +1 -1
- package/dist/client.d.ts +5 -5
- package/dist/client.js +19 -3
- package/dist/fees.js +2 -24
- package/dist/fpool.d.ts +10 -6
- package/dist/fpool.js +15 -25
- package/dist/generated.d.ts +1611 -2189
- package/dist/generated.js +947 -1224
- package/dist/history.d.ts +1 -1
- package/dist/history.js +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -2
- package/dist/indexer.d.ts +1 -1
- package/dist/indexer.js +5 -12
- package/dist/keys.d.ts +39 -52
- package/dist/keys.js +59 -38
- package/dist/liquidity.d.ts +2 -24
- package/dist/liquidity.js +7 -33
- package/dist/pools.d.ts +23 -14
- package/dist/pools.js +36 -28
- package/dist/positions.d.ts +2 -7
- package/dist/positions.js +6 -25
- package/package.json +1 -1
- package/src/actions.ts +12 -12
- package/src/admin.ts +42 -85
- package/src/chains.ts +1 -1
- package/src/client.ts +21 -5
- package/src/fees.ts +2 -22
- package/src/fpool.ts +19 -26
- package/src/generated.ts +951 -1228
- package/src/history.ts +2 -2
- package/src/index.ts +1 -2
- package/src/indexer.ts +6 -13
- package/src/keys.ts +80 -74
- package/src/liquidity.ts +7 -47
- package/src/pools.ts +45 -33
- package/src/positions.ts +7 -27
- package/dist/views.d.ts +0 -281
- package/dist/views.js +0 -188
- package/src/views.ts +0 -480
package/src/history.ts
CHANGED
|
@@ -55,7 +55,7 @@ export interface EventLogsQuery {
|
|
|
55
55
|
* On the chain path the node is asked for the last {@link LATEST_SCAN_BLOCKS} blocks only.
|
|
56
56
|
*/
|
|
57
57
|
latest?: number;
|
|
58
|
-
/** Only events from these transactions — e.g. the
|
|
58
|
+
/** Only events from these transactions — e.g. the other events of a page of swaps. */
|
|
59
59
|
transactionHashes?: Hex[];
|
|
60
60
|
signal?: AbortSignal;
|
|
61
61
|
}
|
|
@@ -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
|
|
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,6 +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
|
|
26
|
-
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";
|
|
27
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` (
|
|
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;
|
|
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
|
|
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
|
-
|
|
193
|
-
|
|
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
|
-
*
|
|
18
|
-
*
|
|
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
|
-
/**
|
|
36
|
-
|
|
37
|
-
|
|
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
|
|
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
|
-
|
|
53
|
-
|
|
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 (
|
|
56
|
-
*
|
|
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
|
-
*
|
|
62
|
-
* (`
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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: "
|
|
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
|
|
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
|
|
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
|
/**
|
|
@@ -390,7 +349,8 @@ export async function floor(c: LogswapClient, a: EditArgs & { rungs: bigint }):
|
|
|
390
349
|
*
|
|
391
350
|
* ΔQ = L (ξ' − ξ), ΔR = 0
|
|
392
351
|
*
|
|
393
|
-
* because $R = Le^{-x}$ depends on neither the floor nor the withdrawal. No base moves
|
|
352
|
+
* because $R = Le^{-x}$ depends on neither the floor nor the withdrawal. No base moves beyond one
|
|
353
|
+
* wei (the edit's mint half rounds what it pays in up; the preview returns it), the price
|
|
394
354
|
* does not move, and depth is unchanged. **The cost, which a UI must show:** the position stops
|
|
395
355
|
* bidding below ξ'. `settleIn: "base"` swaps the proceeds into base in the same batch.
|
|
396
356
|
*/
|
|
@@ -414,7 +374,7 @@ export async function deepen(c: LogswapClient, a: EditArgs & { rungs?: bigint })
|
|
|
414
374
|
export async function cap(c: LogswapClient, a: EditArgs & { rungs: bigint }): Promise<Hash> {
|
|
415
375
|
const k = await classOf(c, a.key, a.fromId, a.shares);
|
|
416
376
|
if (!k.capped) throw new Error("logswap: cap() needs a capped class — an uncapped one has no cap to move");
|
|
417
|
-
const toCap = k.cap + a.rungs * a.key
|
|
377
|
+
const toCap = k.cap + a.rungs * tickSpacingOf(a.key);
|
|
418
378
|
if (toCap <= k.floor) throw new Error("logswap: the cap cannot sit at or below the floor");
|
|
419
379
|
return edit(c, { ...a, toFloor: k.floor, toCap, newL: k.L });
|
|
420
380
|
}
|
|
@@ -422,7 +382,7 @@ export async function cap(c: LogswapClient, a: EditArgs & { rungs: bigint }): Pr
|
|
|
422
382
|
/** Translate the class by `rungs` (signed): floor and cap together, width and L pinned. */
|
|
423
383
|
export async function shift(c: LogswapClient, a: EditArgs & { rungs: bigint }): Promise<Hash> {
|
|
424
384
|
const k = await classOf(c, a.key, a.fromId, a.shares);
|
|
425
|
-
const d = a.rungs * a.key
|
|
385
|
+
const d = a.rungs * tickSpacingOf(a.key);
|
|
426
386
|
return edit(c, { ...a, toFloor: k.floor + d, toCap: k.capped ? k.cap + d : undefined, newL: k.L });
|
|
427
387
|
}
|
|
428
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,
|
|
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
|
|
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
|
|
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
|
-
//
|
|
175
|
-
// C
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
434
|
-
*
|
|
435
|
-
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
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,14 +10,13 @@ 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 {
|
|
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;
|
|
17
17
|
const U128 = (1n << 128n) - 1n;
|
|
18
18
|
import { isPosition, NO_CAP, positionId, unpackFloorCap } from "./ids.js";
|
|
19
19
|
import { getEventLogs } from "./history.js";
|
|
20
|
-
import { poolHolders } from "./views.js";
|
|
21
20
|
|
|
22
21
|
/** A class's aggregate state — the whole class, not one holder's slice. */
|
|
23
22
|
export interface PositionClass {
|
|
@@ -99,7 +98,7 @@ export async function getHolderPosition(
|
|
|
99
98
|
floor: bigint,
|
|
100
99
|
cap: bigint = NO_CAP,
|
|
101
100
|
): Promise<HolderPosition> {
|
|
102
|
-
const id = positionId(poolId(key), key
|
|
101
|
+
const id = positionId(poolId(key), tickSpacingOf(key), floor, cap);
|
|
103
102
|
const [cls, shares, claimableFees] = await Promise.all([
|
|
104
103
|
getPositionClass(c, id),
|
|
105
104
|
balanceOf(c, owner, id),
|
|
@@ -198,20 +197,11 @@ export function positionQuote(
|
|
|
198
197
|
return (p.L * (upper - p.floor)) / 10n ** 18n;
|
|
199
198
|
}
|
|
200
199
|
|
|
201
|
-
/**
|
|
202
|
-
* The mint fee a create form presets: the least the managers accept, twice the swap fee (C 12 / F 38, decision
|
|
203
|
-
* 078: `2 * swapFee <= mintFee <= {@link MINT_FEE_MAX}`). The creator selects it in the key; there is no menu.
|
|
204
|
-
*/
|
|
205
|
-
export function presetMintFee(swapFee: bigint): bigint {
|
|
206
|
-
const m = 2n * swapFee;
|
|
207
|
-
return m > MINT_FEE_MAX ? MINT_FEE_MAX : m;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
200
|
/**
|
|
211
201
|
* The one-time mint fee at log-price `x`, in quote units — the amount `_mintCore` pulls ON TOP of
|
|
212
202
|
* the position's own legs, so a mint's total quote pull is `positionQuote(p, x) + mintFee(p, x, rate)`.
|
|
213
|
-
* `rate` is the MARKET's mint fee
|
|
214
|
-
* 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`.
|
|
215
205
|
*
|
|
216
206
|
* Mirrors the manager's exemption cases: a DORMANT mint pays nothing — floor above spot, or a
|
|
217
207
|
* capped class spot has already passed (`cap <= x`). Anything earning pays `rate · L`, all of it
|
|
@@ -261,17 +251,7 @@ export async function positionsOf(c: LogswapClient, key: PoolKey, owner: Address
|
|
|
261
251
|
return rows.map((r) => ({ id: r.id, floor: r.floor, cap: NO_CAP, capped: false, shares: r.shares, L: r.L, fees: r.fees }));
|
|
262
252
|
}
|
|
263
253
|
|
|
264
|
-
const ID_REGISTERED = parseAbiItem("event ClassRegistered(
|
|
265
|
-
|
|
266
|
-
/** The class ids `owner` holds in `pool`, from the indexer's `pool_holder` view; null when the indexer cannot answer. */
|
|
267
|
-
async function heldIdsFromView(c: LogswapClient, indexer: string, pool: Hex, owner: Address): Promise<bigint[] | null> {
|
|
268
|
-
try {
|
|
269
|
-
const rows = await poolHolders(indexer, { condition: { side: "C", poolId: pool.toLowerCase(), holder: owner.toLowerCase(), manager: managerC(c).toLowerCase() } });
|
|
270
|
-
return rows.filter((r) => r.balance > 0n && !r.isBackstop).map((r) => r.id);
|
|
271
|
-
} catch {
|
|
272
|
-
return null; // the view is a cache: the ClassRegistered replay below answers the same
|
|
273
|
-
}
|
|
274
|
-
}
|
|
254
|
+
const ID_REGISTERED = parseAbiItem("event ClassRegistered(bytes32 indexed poolId, uint256 indexed id, int256 floor, int256 cap, bool capped)") // C 17: poolId first;
|
|
275
255
|
|
|
276
256
|
/** Every class id ever registered in `pool` (`ClassRegistered`), from the indexer's table or the node. */
|
|
277
257
|
async function registeredIds(c: LogswapClient, pool: Hex, fromBlock?: bigint, indexer?: string): Promise<bigint[]> {
|
|
@@ -289,10 +269,10 @@ async function registeredIds(c: LogswapClient, pool: Hex, fromBlock?: bigint, in
|
|
|
289
269
|
* holder's slice is L · shares_owner / shares_class, and fees from the lens. One log query plus
|
|
290
270
|
* a read per registered class; fine for a pool's lifetime of classes.
|
|
291
271
|
*/
|
|
292
|
-
export async function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock?: bigint, opts: { /** The rindexer GraphQL endpoint: the
|
|
272
|
+
export async function holdingsOf(c: LogswapClient, key: PoolKey, owner: Address, fromBlock?: bigint, opts: { /** The rindexer GraphQL endpoint: the class registry from its tables, the node otherwise. Defaults to the client's. */ indexer?: string } = {}): Promise<HeldPositionRow[]> {
|
|
293
273
|
const pool = poolId(key);
|
|
294
274
|
const indexer = opts.indexer ?? c.indexerUrl;
|
|
295
|
-
const ids =
|
|
275
|
+
const ids = await registeredIds(c, pool, fromBlock, indexer);
|
|
296
276
|
if (ids.length === 0) return [];
|
|
297
277
|
// one lens call: balance, class L, fees, floor and cap for every id the owner holds
|
|
298
278
|
const rows = (await c.public.readContract({
|