@logswap/sdk 0.5.102 → 0.5.104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -418
- package/dist/actions.d.ts +0 -39
- package/dist/actions.js +0 -39
- package/dist/admin.d.ts +0 -106
- package/dist/admin.js +1 -96
- package/dist/chains.d.ts +0 -49
- package/dist/chains.js +0 -30
- package/dist/claims.d.ts +0 -32
- package/dist/claims.js +0 -30
- package/dist/client.d.ts +0 -116
- package/dist/client.js +1 -231
- package/dist/fees.d.ts +1 -45
- package/dist/fees.js +0 -44
- package/dist/fpool.d.ts +4 -612
- package/dist/fpool.js +14 -490
- package/dist/generated.js +0 -30
- package/dist/history.d.ts +0 -61
- package/dist/history.js +5 -74
- package/dist/ids.d.ts +0 -30
- package/dist/ids.js +0 -31
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -7
- package/dist/indexer.d.ts +0 -68
- package/dist/indexer.js +1 -77
- package/dist/keys.d.ts +0 -50
- package/dist/keys.js +0 -35
- package/dist/liquidity.d.ts +0 -128
- package/dist/liquidity.js +1 -107
- package/dist/onboard.d.ts +0 -52
- package/dist/onboard.js +1 -59
- package/dist/pools.d.ts +3 -157
- package/dist/pools.js +1 -164
- package/dist/positions.d.ts +0 -102
- package/dist/positions.js +1 -90
- package/dist/quote.d.ts +0 -14
- package/dist/quote.js +0 -14
- package/dist/swap.d.ts +0 -31
- package/dist/swap.js +5 -37
- package/dist/tokencache.d.ts +0 -48
- package/dist/tokencache.js +1 -73
- package/dist/write.d.ts +1 -87
- package/dist/write.js +1 -87
- package/package.json +3 -8
- package/src/actions.ts +0 -208
- package/src/admin.ts +0 -350
- package/src/chains.ts +0 -278
- package/src/claims.ts +0 -111
- package/src/client.ts +0 -436
- package/src/fees.ts +0 -138
- package/src/fpool.ts +0 -2049
- package/src/generated.ts +0 -4345
- package/src/history.ts +0 -383
- package/src/ids.ts +0 -78
- package/src/index.ts +0 -26
- package/src/indexer.ts +0 -264
- package/src/keys.ts +0 -138
- package/src/liquidity.ts +0 -456
- package/src/onboard.ts +0 -253
- package/src/pools.ts +0 -465
- package/src/positions.ts +0 -297
- package/src/quote.ts +0 -36
- package/src/swap.ts +0 -181
- package/src/tokencache.ts +0 -178
- package/src/write.ts +0 -236
package/src/pools.ts
DELETED
|
@@ -1,465 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* pools.ts — market state and discovery.
|
|
3
|
-
*
|
|
4
|
-
* Two things worth knowing before reading further.
|
|
5
|
-
*
|
|
6
|
-
* **Markets are discovered from logs, not configuration.** `MarketCreated` carries the ENTIRE
|
|
7
|
-
* `PoolKey` in the clear, so a client can reconstruct any market's key — and therefore call any
|
|
8
|
-
* keyed function — having never been told the market exists. There is no registry to maintain.
|
|
9
|
-
*
|
|
10
|
-
* **`x` is the state, price is derived.** The contract stores $x = \log p$ and materialises the
|
|
11
|
-
* price only where unavoidable; `priceOf` below mirrors that, and is lossy in the way any float
|
|
12
|
-
* conversion is. Prefer comparing in log space when precision matters.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { formatUnits, type Address, type Hex } from "viem";
|
|
16
|
-
import { lensCAbi, managerCAbi } from "./generated.js";
|
|
17
|
-
import { lensC, managerC, clientChainId, type LogswapClient } from "./client.js";
|
|
18
|
-
import { signerFor } from "./write.js";
|
|
19
|
-
import { readCachedToken, registerCacheClear, writeCachedToken } from "./tokencache.js";
|
|
20
|
-
import { poolId, swapFeeOfKey, type PoolKey } from "./keys.js";
|
|
21
|
-
import { getEventLogs } from "./history.js";
|
|
22
|
-
|
|
23
|
-
/**
|
|
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.
|
|
27
|
-
*/
|
|
28
|
-
export interface PoolState {
|
|
29
|
-
initialized: boolean;
|
|
30
|
-
/** $x = \log p$, WAD — the stored state (`logPrice`; `x` before C 13). */
|
|
31
|
-
logPrice: bigint;
|
|
32
|
-
/** Exposure currently earning. Steps only when a floor or cap is crossed. */
|
|
33
|
-
lActive: bigint;
|
|
34
|
-
reserveBase: bigint;
|
|
35
|
-
reserveQuote: bigint;
|
|
36
|
-
/** Fee-per-unit-L accumulator $F = \phi \cdot \mathrm{TV}(\log p)$ (`feeGrowth`; `F` before C 13). */
|
|
37
|
-
feeGrowth: bigint;
|
|
38
|
-
/** Quadratic variation of log-price, $\Sigma = \sum_{\text{swaps}} (\Delta x_{\text{swap}})^2$ — one term per swap. */
|
|
39
|
-
realizedVariance: bigint;
|
|
40
|
-
currentK: bigint;
|
|
41
|
-
protocolOwed: bigint;
|
|
42
|
-
minBackstopL: bigint;
|
|
43
|
-
backstopFloor: bigint;
|
|
44
|
-
/** The market's swap-fee tax, WAD of every fee paid out: the gate's answer at birth, fixed for life (066). */
|
|
45
|
-
swapFeeTax: bigint;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** Read a market's full state by key, through the lens (`getPools`; C version 7). All zero, `initialized` false, for a market nobody opened. */
|
|
49
|
-
export async function getPool(c: LogswapClient, key: PoolKey): Promise<PoolState> {
|
|
50
|
-
const v = (await c.public.readContract({
|
|
51
|
-
address: lensC(c),
|
|
52
|
-
abi: lensCAbi,
|
|
53
|
-
functionName: "getPools",
|
|
54
|
-
args: [[poolId(key)]],
|
|
55
|
-
})) as readonly unknown[];
|
|
56
|
-
return v[0] as PoolState;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* The market's swap fee, WAD: `FEE_LIST[key.swapFeeIdx]` (C 18, decision 099), constant for the market's
|
|
61
|
-
* life. Still a read: it refuses a key nobody initialized, which `discoverMarkets` relies on to
|
|
62
|
-
* drop a stale indexer's rows. Offline: {@link swapFeeOfKey}. (`swapFeeOf` in `fees.ts` is the fee one swap paid.)
|
|
63
|
-
*/
|
|
64
|
-
export async function marketSwapFee(c: LogswapClient, key: PoolKey): Promise<bigint> {
|
|
65
|
-
const s = await getPool(c, key);
|
|
66
|
-
if (!s.initialized) throw new Error(`logswap: market ${poolId(key)} is not initialized`);
|
|
67
|
-
return swapFeeOfKey(key);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Price from the stored log-price. **Lossy** — `x` is exact and this is a float, so use it for
|
|
72
|
-
* display and never for arithmetic you intend to send back on-chain.
|
|
73
|
-
*/
|
|
74
|
-
export function priceOf(state: Pick<PoolState, "logPrice">, scale = 1): number {
|
|
75
|
-
return Math.exp(Number(state.logPrice) / 1e18) * scale;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* The factor between the chain's price and the human one. The chain's log-price is of the WEI
|
|
80
|
-
* ratio, so with a 6-dec USDC quote and an 18-dec base the human price is `e^x · 10^12`. Pass
|
|
81
|
-
* this as `scale` to {@link priceOf}, {@link floorPrice} and `fPoolPriceOf` — with 18/18 tokens
|
|
82
|
-
* it is 1 and nothing changes.
|
|
83
|
-
*/
|
|
84
|
-
export function priceScale(baseDecimals: number, quoteDecimals: number): number {
|
|
85
|
-
return 10 ** (baseDecimals - quoteDecimals);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** The C manager's log-price wall: |x| ≤ 46 on the WEI ratio (`MAX_ABS_FLOOR`). */
|
|
89
|
-
export const C_MAX_ABS_X = 46;
|
|
90
|
-
|
|
91
|
-
/** The least derived base reserve a C book keeps, in base wei (`MIN_RESERVE`, decisions 023). */
|
|
92
|
-
export const C_MIN_RESERVE = 10n ** 6n;
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* The prices a C market can hold, in human units — quote per whole base token (decisions 054).
|
|
96
|
-
*
|
|
97
|
-
* - `listMin`, `listMax`: the wall, `10^(base − quote) · e^{∓46}`. A market cannot be initialized,
|
|
98
|
-
* and no floor or cap placed, outside it. An 18-dec token against 6-dec USDC cannot list under
|
|
99
|
-
* 1.05e-8; against an 18-dec quote the same token lists down to 1.05e-20.
|
|
100
|
-
* - `ceiling`: the highest price the book can trade to with `lActive` of active exposure (quote
|
|
101
|
-
* wei): the derived reserve `lActive / p` must stay at or above `C_MIN_RESERVE` base wei, so
|
|
102
|
-
* `ceiling = lActive · 10^(base − quote) / 1e6`, capped by `listMax`. In whole units that is
|
|
103
|
-
* `L · 10^(base − 6)`: the quote's decimals cancel and the base's set it — harmless on an
|
|
104
|
-
* 18-dec base, but a WBTC book of 1,000 USDC of depth stops at 100,000. Omit `lActive` for the
|
|
105
|
-
* wall alone.
|
|
106
|
-
*
|
|
107
|
-
* Floats, for display and warnings; the chain is the authority.
|
|
108
|
-
*/
|
|
109
|
-
export function cPriceRange(
|
|
110
|
-
baseDecimals: number,
|
|
111
|
-
quoteDecimals: number,
|
|
112
|
-
lActive?: bigint,
|
|
113
|
-
): { listMin: number; listMax: number; ceiling: number } {
|
|
114
|
-
const scale = priceScale(baseDecimals, quoteDecimals);
|
|
115
|
-
const listMin = Math.exp(-C_MAX_ABS_X) * scale;
|
|
116
|
-
const listMax = Math.exp(C_MAX_ABS_X) * scale;
|
|
117
|
-
const ceiling =
|
|
118
|
-
lActive === undefined || lActive === 0n ? listMax : Math.min(listMax, (Number(lActive) / Number(C_MIN_RESERVE)) * scale);
|
|
119
|
-
return { listMin, listMax, ceiling };
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** Whether a C market can be initialized at `price` (human units) for this pair's decimals. */
|
|
123
|
-
export function cListable(price: number, baseDecimals: number, quoteDecimals: number): boolean {
|
|
124
|
-
const { listMin, listMax } = cPriceRange(baseDecimals, quoteDecimals);
|
|
125
|
-
return price >= listMin && price <= listMax;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* The model-free LP edge, $F - \tfrac12\Sigma$ — the protocol's headline metric, in quote per unit
|
|
130
|
-
* of exposure.
|
|
131
|
-
*
|
|
132
|
-
* $F$ is fee income per unit active $L$; $\Sigma$ is the realised quadratic variation, whose half
|
|
133
|
-
* is the LVR a log pool pays. The difference is what an LP actually earns, with no model of the
|
|
134
|
-
* price process assumed. Both ride on every `Swap` event, so this is reconstructible from logs
|
|
135
|
-
* alone (docs/app.md) — no state read needed if you are already indexing.
|
|
136
|
-
*
|
|
137
|
-
* Signed: negative means variation has outrun fee income over the pool's life.
|
|
138
|
-
*/
|
|
139
|
-
export function lpEdge(state: Pick<PoolState, "feeGrowth" | "realizedVariance">): bigint {
|
|
140
|
-
return state.feeGrowth - state.realizedVariance / 2n;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** A market discovered from a `PoolCreated` log — the full key, plus where it was created. */
|
|
144
|
-
export interface DiscoveredMarket {
|
|
145
|
-
key: PoolKey;
|
|
146
|
-
poolId: Hex;
|
|
147
|
-
/** The market's opening log-price (`x0` before C 13). */
|
|
148
|
-
initialLogPrice: bigint;
|
|
149
|
-
blockNumber: bigint;
|
|
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;
|
|
153
|
-
/** The manager that emitted the `PoolCreated` — set when the row came from the indexer. */
|
|
154
|
-
manager?: Address;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Enumerate markets from the C manager's `PoolCreated` logs.
|
|
159
|
-
*
|
|
160
|
-
* This is the whole market registry: the event carries every key field rather than just the id,
|
|
161
|
-
* deliberately, so nothing downstream needs a configured list. The scan starts at the client's
|
|
162
|
-
* `deployBlock` unless `fromBlock` says otherwise.
|
|
163
|
-
*/
|
|
164
|
-
export async function discoverMarkets(
|
|
165
|
-
c: LogswapClient,
|
|
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 } = {},
|
|
167
|
-
): Promise<DiscoveredMarket[]> {
|
|
168
|
-
// Narrow the const ABI to the PoolCreated entry while KEEPING its literal type, so viem can infer
|
|
169
|
-
// the log shape. `as never` would compile but collapse every arg to `never` at the call site.
|
|
170
|
-
type Ev = Extract<(typeof managerCAbi)[number], { type: "event"; name: "PoolCreated" }>;
|
|
171
|
-
const ev = managerCAbi.find((x): x is Ev => x.type === "event" && x.name === "PoolCreated");
|
|
172
|
-
if (!ev) throw new Error("logswap: PoolCreated event missing from the generated ABI");
|
|
173
|
-
|
|
174
|
-
const args: Record<string, unknown> = {};
|
|
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.
|
|
178
|
-
if (opts.quote) args.quote = opts.quote;
|
|
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, {
|
|
181
|
-
indexer: opts.indexer,
|
|
182
|
-
address: managerC(c),
|
|
183
|
-
event: ev,
|
|
184
|
-
args,
|
|
185
|
-
fromBlock: opts.fromBlock, // the client's deployBlock when absent
|
|
186
|
-
toBlock: opts.toBlock,
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
const wantBase = opts.base?.toLowerCase();
|
|
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) => {
|
|
194
|
-
const a = l.args;
|
|
195
|
-
const key: PoolKey = { quote: a.quote, base: a.base, swapFeeIdx: Number(a.swapFeeIdx), spacingIdx: Number(a.spacingIdx), policy: a.policy, salt: a.salt };
|
|
196
|
-
return {
|
|
197
|
-
key,
|
|
198
|
-
poolId: poolId(key),
|
|
199
|
-
creator: a.creator,
|
|
200
|
-
initialLogPrice: a.initialLogPrice,
|
|
201
|
-
blockNumber: l.blockNumber,
|
|
202
|
-
transactionHash: l.transactionHash,
|
|
203
|
-
};
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Ladder shape: the live FLOORS, in log-price WAD — **not** tick indices.
|
|
209
|
-
*
|
|
210
|
-
* Named `liveFloors` deliberately. The lens function it wraps is called `liveTicks`, which reads as
|
|
211
|
-
* if it returns `k`; it returns `k * tickSpacing`. Multiplying by the spacing again yields an
|
|
212
|
-
* off-grid value and an `OffGrid` revert at the next call, which is a confusing place to discover
|
|
213
|
-
* the mistake.
|
|
214
|
-
*/
|
|
215
|
-
export async function liveFloors(c: LogswapClient, key: PoolKey): Promise<readonly bigint[]> {
|
|
216
|
-
return c.public.readContract({
|
|
217
|
-
address: lensC(c),
|
|
218
|
-
abi: lensCAbi,
|
|
219
|
-
functionName: "liveTicks",
|
|
220
|
-
args: [poolId(key)],
|
|
221
|
-
}) as Promise<readonly bigint[]>;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/** Is this floor on the market's grid, and inside `MAX_ABS_FLOOR`? Pure — no RPC on the manager. */
|
|
225
|
-
export async function isValidFloor(c: LogswapClient, key: PoolKey, floor: bigint): Promise<boolean> {
|
|
226
|
-
return c.public.readContract({
|
|
227
|
-
address: lensC(c),
|
|
228
|
-
abi: lensCAbi,
|
|
229
|
-
functionName: "isValidFloor",
|
|
230
|
-
args: [poolId(key), floor],
|
|
231
|
-
}) as Promise<boolean>;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* A market's token decimals, read from the tokens themselves.
|
|
236
|
-
*
|
|
237
|
-
* **Never assume these.** A market's two tokens routinely differ (USDC 6 against WETH 18), the
|
|
238
|
-
* manager itself probes `decimals()` to scale `minBackstopL`, and a token that does not implement
|
|
239
|
-
* it falls back to 18. Hardcoding a guess makes every parse and every display wrong by orders of
|
|
240
|
-
* magnitude while the contract behaves perfectly — which reads as "the app is broken".
|
|
241
|
-
*/
|
|
242
|
-
export async function marketDecimals(
|
|
243
|
-
c: LogswapClient,
|
|
244
|
-
key: PoolKey,
|
|
245
|
-
): Promise<{ base: number; quote: number }> {
|
|
246
|
-
// It used to fall back to 18 on ANY failure, a dropped request included — a 6-decimal quote read
|
|
247
|
-
// as 18 is every amount 10^12 off. `marketTokens` retries and then refuses; so does this.
|
|
248
|
-
const { base, quote } = await marketTokens(c, key);
|
|
249
|
-
return { base: base.decimals, quote: quote.decimals };
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** A token as a UI needs it: address, symbol and decimals, all read from the chain. */
|
|
253
|
-
export interface TokenInfo {
|
|
254
|
-
address: Address;
|
|
255
|
-
symbol: string;
|
|
256
|
-
decimals: number;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/**
|
|
260
|
-
* Both sides of a market, for labelling and scaling.
|
|
261
|
-
*
|
|
262
|
-
* **Decimals are read from the token and never guessed.** They used to fall back to 18 on any
|
|
263
|
-
* failure, which quietly reintroduced the worst bug this stack has had: an 18 assumed for a
|
|
264
|
-
* 6-decimal token is a 10^12 error in a number that goes on to `parseUnits` and becomes a transfer
|
|
265
|
-
* amount. A wrong scale is indistinguishable from a working app until somebody moves funds, so a
|
|
266
|
-
* read that will not resolve must fail loudly instead.
|
|
267
|
-
*
|
|
268
|
-
* `symbol` keeps a fallback because it is a label: a market shown as `0x5FbD…` is ugly, not wrong.
|
|
269
|
-
*
|
|
270
|
-
* Retries first, because a blip on the transport is not the same as a token that has no `decimals`,
|
|
271
|
-
* and killing a market over one dropped packet is its own kind of wrong.
|
|
272
|
-
*
|
|
273
|
-
* **Cached** per (chain, address) — see `tokencache.ts` for why only successes are stored and why
|
|
274
|
-
* the chain id is part of the key. Concurrent calls for the same token share one read, which
|
|
275
|
-
* matters because the quote asset is usually the same across every market in a deployment.
|
|
276
|
-
*/
|
|
277
|
-
export async function marketTokens(
|
|
278
|
-
c: LogswapClient,
|
|
279
|
-
key: PoolKey,
|
|
280
|
-
): Promise<{ base: TokenInfo; quote: TokenInfo }> {
|
|
281
|
-
const abi = [
|
|
282
|
-
{ type: "function", name: "decimals", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
|
|
283
|
-
{ type: "function", name: "symbol", stateMutability: "view", inputs: [], outputs: [{ type: "string" }] },
|
|
284
|
-
] as const;
|
|
285
|
-
|
|
286
|
-
const chainId = await clientChainId(c);
|
|
287
|
-
|
|
288
|
-
const readDecimals = async (address: Address): Promise<number> => {
|
|
289
|
-
let last: unknown;
|
|
290
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
291
|
-
try {
|
|
292
|
-
const d = Number(await c.public.readContract({ address, abi, functionName: "decimals" }));
|
|
293
|
-
if (!Number.isInteger(d) || d < 0 || d > 36) {
|
|
294
|
-
throw new Error(`returned ${d}, which is not a plausible decimals value`);
|
|
295
|
-
}
|
|
296
|
-
return d;
|
|
297
|
-
} catch (e) {
|
|
298
|
-
last = e;
|
|
299
|
-
if (attempt < 2) await new Promise((r) => setTimeout(r, 150 * (attempt + 1)));
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
throw new Error(
|
|
303
|
-
`logswap: could not read decimals() from ${address}. Refusing to assume — every amount for ` +
|
|
304
|
-
`this token would be scaled wrongly. Cause: ${last instanceof Error ? last.message.split("\n")[0] : String(last)}`,
|
|
305
|
-
);
|
|
306
|
-
};
|
|
307
|
-
|
|
308
|
-
const read = async (address: Address): Promise<TokenInfo> => {
|
|
309
|
-
const hit = readCachedToken(chainId, address);
|
|
310
|
-
if (hit) return { address, ...hit };
|
|
311
|
-
|
|
312
|
-
const inflight = pending.get(`${chainId}:${address.toLowerCase()}`);
|
|
313
|
-
if (inflight) return inflight;
|
|
314
|
-
|
|
315
|
-
const k = `${chainId}:${address.toLowerCase()}`;
|
|
316
|
-
// Deregistration happens INSIDE the job, so it completes before the promise settles. Cleaning
|
|
317
|
-
// up in a `.finally()` on the outside runs a microtask later — late enough that a caller
|
|
318
|
-
// arriving right after an `await` could still attach to a job that has already failed and
|
|
319
|
-
// inherit a failure a fresh read would not have hit. Sharing an in-flight read is an
|
|
320
|
-
// optimisation for concurrent callers; it must never make a later, separate call fail.
|
|
321
|
-
// `| undefined` because the assignment below is what tsc cannot see happening first; the
|
|
322
|
-
// finally only runs after an await, so by then it is set.
|
|
323
|
-
let self: Promise<TokenInfo> | undefined;
|
|
324
|
-
const job = (async (): Promise<TokenInfo> => {
|
|
325
|
-
try {
|
|
326
|
-
// `symbol` is allowed to fail; `decimals` is not. Caught separately so a missing symbol
|
|
327
|
-
// does not discard a decimals read that succeeded.
|
|
328
|
-
const [decimals, symbolResult] = await Promise.all([
|
|
329
|
-
readDecimals(address),
|
|
330
|
-
c.public
|
|
331
|
-
.readContract({ address, abi, functionName: "symbol" })
|
|
332
|
-
.then((v) => ({ ok: true as const, value: String(v) }))
|
|
333
|
-
.catch(() => ({ ok: false as const, value: address.slice(0, 6) })),
|
|
334
|
-
]);
|
|
335
|
-
// Only a real symbol is cached. Persisting the 0x… fallback would let one blip name the
|
|
336
|
-
// token that for as long as the store lives.
|
|
337
|
-
if (symbolResult.ok) writeCachedToken(chainId, address, { symbol: symbolResult.value, decimals });
|
|
338
|
-
return { address, symbol: symbolResult.value, decimals };
|
|
339
|
-
} finally {
|
|
340
|
-
if (pending.get(k) === self) pending.delete(k);
|
|
341
|
-
}
|
|
342
|
-
})();
|
|
343
|
-
self = job;
|
|
344
|
-
pending.set(k, job);
|
|
345
|
-
return job;
|
|
346
|
-
};
|
|
347
|
-
const [base, quote] = await Promise.all([read(key.base), read(key.quote)]);
|
|
348
|
-
return { base, quote };
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/** In-flight reads, so simultaneous callers for one token share a single round trip. */
|
|
352
|
-
const pending = new Map<string, Promise<TokenInfo>>();
|
|
353
|
-
registerCacheClear(() => pending.clear());
|
|
354
|
-
|
|
355
|
-
/** Format a quote-denominated amount for display, given the quote's decimals. */
|
|
356
|
-
export function formatQuote(amount: bigint, quoteDecimals: number): string {
|
|
357
|
-
return formatUnits(amount, quoteDecimals);
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// ---------------------------------------------------------------------------------------------
|
|
361
|
-
// Denominated readouts
|
|
362
|
-
//
|
|
363
|
-
// `F` and `lpEdge` are per unit of active L — dimensionless WAD fractions, not amounts. A
|
|
364
|
-
// dashboard wants amounts, and multiplying by L is the whole conversion. Keeping these here rather
|
|
365
|
-
// than in the app means one definition of "fees in quote" instead of one per screen.
|
|
366
|
-
// ---------------------------------------------------------------------------------------------
|
|
367
|
-
|
|
368
|
-
const WAD = 10n ** 18n;
|
|
369
|
-
const YEAR_SECONDS = 31_536_000n;
|
|
370
|
-
|
|
371
|
-
/** Fees the pool has accrued over its life, in QUOTE units: $F \cdot L$. */
|
|
372
|
-
export function feesQuote(state: Pick<PoolState, "feeGrowth" | "lActive">): bigint {
|
|
373
|
-
return (state.feeGrowth * state.lActive) / WAD;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
/** The LP edge in QUOTE units: $(F - \tfrac12\Sigma) \cdot L$. Signed. */
|
|
377
|
-
export function edgeQuote(state: Pick<PoolState, "feeGrowth" | "realizedVariance" | "lActive">): bigint {
|
|
378
|
-
return (lpEdge(state) * state.lActive) / WAD;
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/** The pool floor as a price. **Lossy** — display only, like {@link priceOf}. */
|
|
382
|
-
export function floorPrice(state: Pick<PoolState, "backstopFloor">, scale = 1): number {
|
|
383
|
-
return Math.exp(Number(state.backstopFloor) / 1e18) * scale;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/** $\log(p / p_{\text{floor}}) = x - \xi$ — how far spot sits above the floor, in log units (WAD). */
|
|
387
|
-
export function floorDistance(state: Pick<PoolState, "logPrice" | "backstopFloor">): bigint {
|
|
388
|
-
return state.logPrice - state.backstopFloor;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
/**
|
|
392
|
-
* $-\log(p/p_{\text{floor}})$ as a fraction: the log-drawdown from spot down to the floor.
|
|
393
|
-
*
|
|
394
|
-
* **Negative** while price is above the floor — it is how far price has to fall, so a UI can print
|
|
395
|
-
* it with its sign and mean it. Zero at the floor.
|
|
396
|
-
*
|
|
397
|
-
* This is the LOG measure, not the arithmetic one: the actual price drawdown is
|
|
398
|
-
* $e^{-\Delta} - 1$, which differs materially once the distance is large (a log distance of 0.7
|
|
399
|
-
* is a 50% price fall, not 70%).
|
|
400
|
-
*/
|
|
401
|
-
export function floorDrawdown(state: Pick<PoolState, "logPrice" | "backstopFloor">): number {
|
|
402
|
-
return -Number(floorDistance(state)) / 1e18;
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/** The arithmetic price drawdown to the floor, $p_{\text{floor}}/p - 1$. Negative above the floor. */
|
|
406
|
-
export function floorDrawdownPrice(state: Pick<PoolState, "logPrice" | "backstopFloor">): number {
|
|
407
|
-
return Math.exp(-Number(floorDistance(state)) / 1e18) - 1;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Annualise a per-unit-L WAD rate over the window it accrued in.
|
|
412
|
-
*
|
|
413
|
-
* `F` is cumulative fee income per unit of exposure since the pool opened, so dividing by the
|
|
414
|
-
* elapsed time and scaling to a year gives a rate directly — no price process assumed. Returns a
|
|
415
|
-
* fraction: 0.12 is 12%.
|
|
416
|
-
*
|
|
417
|
-
* Treat it as what it is: a *realised* rate over one short devnet window, not a forecast.
|
|
418
|
-
*/
|
|
419
|
-
export function annualise(perUnitL: bigint, elapsedSeconds: bigint): number {
|
|
420
|
-
if (elapsedSeconds <= 0n) return 0;
|
|
421
|
-
return (Number(perUnitL) / 1e18) * (Number(YEAR_SECONDS) / Number(elapsedSeconds));
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/** When a market was created, as a unix timestamp — the denominator for {@link annualise}. */
|
|
425
|
-
export async function marketOpenedAt(c: LogswapClient, m: DiscoveredMarket): Promise<bigint> {
|
|
426
|
-
const b = await c.public.getBlock({ blockNumber: m.blockNumber });
|
|
427
|
-
return b.timestamp;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/**
|
|
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.
|
|
437
|
-
*/
|
|
438
|
-
export async function initializeMarket(c: LogswapClient, a: { key: PoolKey; initialLogPrice: bigint; account: Address }) {
|
|
439
|
-
const { request } = await c.public.simulateContract({
|
|
440
|
-
address: managerC(c),
|
|
441
|
-
abi: managerCAbi,
|
|
442
|
-
functionName: "initialize",
|
|
443
|
-
args: [a.key, a.initialLogPrice],
|
|
444
|
-
account: signerFor(c, a.account),
|
|
445
|
-
} as never);
|
|
446
|
-
return c.wallet!.writeContract(request as never);
|
|
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
|
-
}
|