@logswap/sdk 0.5.76 → 0.5.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/chains.ts ADDED
@@ -0,0 +1,259 @@
1
+ /**
2
+ * chains.ts — the chains log(swap) runs on, and their deployments.
3
+ *
4
+ * The release chains carry the contracts at ONE address each (CREATE3 through CreateX, contracts
5
+ * decision 069): the same `LogswapAddresses` on every chain. What differs per chain is the deploy
6
+ * block, the quote tokens, the explorer and the indexer. An address therefore names a contract only
7
+ * together with a chain id; every cache and every indexer URL in this SDK is per chain.
8
+ */
9
+
10
+ import { defineChain, getAddress, isAddress, type Address, type Chain } from "viem";
11
+ import { arbitrum, base, foundry, mainnet, robinhood, robinhoodTestnet } from "viem/chains";
12
+ import type { LogswapAddresses } from "./client.js";
13
+
14
+ /** A quote token a chain's policies list at deployment (`deployments/config/<chainId>.json`). */
15
+ export interface LogswapQuote {
16
+ symbol: string;
17
+ address: Address;
18
+ decimals: number;
19
+ }
20
+
21
+ export interface LogswapChain {
22
+ chainId: number;
23
+ /** The deployment artifact's `network` (`deployments/<chainId>.json`). */
24
+ network: string;
25
+ name: string;
26
+ /** The viem chain, for `createPublicClient({ chain })`. */
27
+ chain: Chain;
28
+ nativeCurrency: Chain["nativeCurrency"];
29
+ /** Block explorer root URL. */
30
+ explorer?: string;
31
+ /** A public JSON-RPC endpoint: rate-limited, for reads at low volume; production reads bring their own. */
32
+ publicRpc?: string;
33
+ /** A development chain: wiped and redeployed at the same addresses, so nothing keyed on its addresses persists. */
34
+ devnet: boolean;
35
+ testnet: boolean;
36
+ /** The quotes the deploy config lists, verified on chain (symbol, decimals). Empty where none is configured. */
37
+ quotes: readonly LogswapQuote[];
38
+ /** The quote pads launch against on this chain. */
39
+ padQuote?: Address;
40
+ /** Block span of one `eth_getLogs` call on this chain; the client's default {@link LogswapClient.maxLogRange}. */
41
+ maxLogRange: bigint;
42
+ }
43
+
44
+ /** The logswap devnet (anvil, persisted with `--state`). No public RPC. */
45
+ export const logswapDevnet = defineChain({
46
+ id: 31339,
47
+ name: "log(swap) devnet",
48
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
49
+ rpcUrls: { default: { http: [] } },
50
+ testnet: true,
51
+ });
52
+
53
+ /** Default block span per `eth_getLogs` call: public endpoints refuse wider ranges (or cap the result). */
54
+ export const DEFAULT_MAX_LOG_RANGE = 2_000n;
55
+ /** A local node answers any range. */
56
+ const LOCAL_MAX_LOG_RANGE = 1_000_000n;
57
+
58
+ const USDC = (address: Address): LogswapQuote => ({ symbol: "USDC", address, decimals: 6 });
59
+ const WETH = (address: Address): LogswapQuote => ({ symbol: "WETH", address, decimals: 18 });
60
+
61
+ function entry(chain: Chain, e: Omit<LogswapChain, "chainId" | "name" | "chain" | "nativeCurrency" | "testnet" | "maxLogRange"> & { maxLogRange?: bigint }): LogswapChain {
62
+ return {
63
+ chainId: chain.id,
64
+ name: chain.name,
65
+ chain,
66
+ nativeCurrency: chain.nativeCurrency,
67
+ testnet: chain.testnet ?? false,
68
+ maxLogRange: DEFAULT_MAX_LOG_RANGE,
69
+ ...e,
70
+ };
71
+ }
72
+
73
+ /** Every chain this SDK knows, by chain id. */
74
+ export const LOGSWAP_CHAINS: Readonly<Record<number, LogswapChain>> = Object.freeze({
75
+ 1: entry(mainnet, {
76
+ network: "mainnet",
77
+ explorer: "https://etherscan.io",
78
+ publicRpc: "https://ethereum-rpc.publicnode.com",
79
+ devnet: false,
80
+ quotes: [USDC("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), WETH("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")],
81
+ padQuote: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
82
+ }),
83
+ 8453: entry(base, {
84
+ network: "base",
85
+ explorer: "https://basescan.org",
86
+ publicRpc: "https://mainnet.base.org",
87
+ devnet: false,
88
+ quotes: [USDC("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"), WETH("0x4200000000000000000000000000000000000006")],
89
+ padQuote: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
90
+ }),
91
+ 42161: entry(arbitrum, {
92
+ network: "arbitrum",
93
+ explorer: "https://arbiscan.io",
94
+ publicRpc: "https://arb1.arbitrum.io/rpc",
95
+ devnet: false,
96
+ quotes: [USDC("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), WETH("0x82aF49447D8a07e3bd95BD0d56f35241523fBab1")],
97
+ padQuote: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
98
+ }),
99
+ // no native USDC: USDG is the dollar quote
100
+ 4663: entry(robinhood, {
101
+ network: "robinhood",
102
+ explorer: "https://robinhoodchain.blockscout.com",
103
+ publicRpc: "https://rpc.mainnet.chain.robinhood.com",
104
+ devnet: false,
105
+ quotes: [{ symbol: "USDG", address: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", decimals: 6 }, WETH("0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73")],
106
+ padQuote: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
107
+ }),
108
+ 46630: entry(robinhoodTestnet, {
109
+ network: "robinhood-testnet",
110
+ explorer: robinhoodTestnet.blockExplorers.default.url,
111
+ publicRpc: robinhoodTestnet.rpcUrls.default.http[0],
112
+ devnet: false,
113
+ quotes: [],
114
+ }),
115
+ 31337: entry(foundry, { network: "local", publicRpc: "http://127.0.0.1:8545", devnet: true, quotes: [], maxLogRange: LOCAL_MAX_LOG_RANGE }),
116
+ 31339: entry(logswapDevnet, { network: "devnet", devnet: true, quotes: [], maxLogRange: LOCAL_MAX_LOG_RANGE }),
117
+ });
118
+
119
+ /** The production chains, in release order. */
120
+ export const RELEASE_CHAIN_IDS = [1, 8453, 42161, 4663] as const;
121
+
122
+ /** The registry entry for `chainId`, or undefined for a chain this SDK does not list. */
123
+ export function logswapChain(chainId: number): LogswapChain | undefined {
124
+ return LOGSWAP_CHAINS[chainId];
125
+ }
126
+
127
+ /** A quote of `chainId` by symbol (case-insensitive), or undefined. */
128
+ export function quoteOf(chainId: number, symbol: string): LogswapQuote | undefined {
129
+ const s = symbol.toLowerCase();
130
+ return LOGSWAP_CHAINS[chainId]?.quotes.find((q) => q.symbol.toLowerCase() === s);
131
+ }
132
+
133
+ // ─── deployments ──────────────────────────────────────────────────────────────
134
+
135
+ /**
136
+ * A deployment artifact: `deployments/<chainId>.json` as the contracts' `DeployChain.s.sol` writes
137
+ * it. `DeployLocal`'s artifact carries the same fields (without `deployTag` and `createX`) plus its
138
+ * devnet extras, of which `tokenFactory` is kept.
139
+ */
140
+ export interface LogswapDeployment {
141
+ chainId: number;
142
+ network: string;
143
+ /** The first block of the deployment: where every log scan starts. */
144
+ deployBlock: bigint;
145
+ cVersion: bigint;
146
+ fVersion: bigint;
147
+ /** The CREATE3 salt namespace (`logswap.v1`); absent on a local deployment. */
148
+ deployTag?: string;
149
+ deployer: Address;
150
+ createX?: Address;
151
+ logAuthority: Address;
152
+ logTreasury: Address;
153
+ permit2: Address;
154
+ multicall3: Address;
155
+ policyRegistry: Address;
156
+ fPoolManager: Address;
157
+ cPoolManager: Address;
158
+ publicPolicy: Address;
159
+ privatePolicy: Address;
160
+ polPolicy: Address;
161
+ padPolicy: Address;
162
+ router: Address;
163
+ lens: Address;
164
+ /** The devnet's token factory; local deployments only. */
165
+ tokenFactory?: Address;
166
+ }
167
+
168
+ /**
169
+ * The published deployments, by chain id. Empty until the release chains are deployed; a
170
+ * deployment is added here from its artifact in the release that ships it.
171
+ */
172
+ export const LOGSWAP_DEPLOYMENTS: Readonly<Record<number, LogswapDeployment>> = Object.freeze({});
173
+
174
+ /** The published deployment on `chainId`, or undefined. */
175
+ export function deploymentFor(chainId: number): LogswapDeployment | undefined {
176
+ return LOGSWAP_DEPLOYMENTS[chainId];
177
+ }
178
+
179
+ const REQUIRED_ADDRESSES = [
180
+ "deployer",
181
+ "logAuthority",
182
+ "logTreasury",
183
+ "permit2",
184
+ "multicall3",
185
+ "policyRegistry",
186
+ "fPoolManager",
187
+ "cPoolManager",
188
+ "publicPolicy",
189
+ "privatePolicy",
190
+ "polPolicy",
191
+ "padPolicy",
192
+ "router",
193
+ "lens",
194
+ ] as const;
195
+ const OPTIONAL_ADDRESSES = ["createX", "tokenFactory"] as const;
196
+
197
+ function uint(o: Record<string, unknown>, k: string): bigint {
198
+ const v = o[k];
199
+ if (typeof v === "bigint" && v >= 0n) return v;
200
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
201
+ if (typeof v === "string" && /^(0x[0-9a-fA-F]+|\d+)$/.test(v)) return BigInt(v);
202
+ throw new Error(`logswap: deployment artifact: "${k}" is ${JSON.stringify(v)}, expected a non-negative integer`);
203
+ }
204
+
205
+ function address(o: Record<string, unknown>, k: string): Address {
206
+ const v = o[k];
207
+ if (typeof v !== "string" || !isAddress(v, { strict: false })) {
208
+ throw new Error(`logswap: deployment artifact: "${k}" is ${JSON.stringify(v)}, expected an address`);
209
+ }
210
+ return getAddress(v);
211
+ }
212
+
213
+ /**
214
+ * Validate a deployment artifact (parsed JSON) and return it typed. Throws on a missing or
215
+ * malformed field, and on a `chainId` other than `opts.chainId` when given: one address set is valid
216
+ * on every release chain, so an artifact read for the wrong chain would otherwise load cleanly and
217
+ * scan from the wrong `deployBlock`.
218
+ */
219
+ export function deploymentFromArtifact(json: unknown, opts: { chainId?: number } = {}): LogswapDeployment {
220
+ if (typeof json !== "object" || json === null || Array.isArray(json)) throw new Error("logswap: deployment artifact is not a JSON object");
221
+ const o = json as Record<string, unknown>;
222
+ const chainId = Number(uint(o, "chainId"));
223
+ if (opts.chainId !== undefined && chainId !== opts.chainId) {
224
+ throw new Error(`logswap: deployment artifact is for chain ${chainId}, expected chain ${opts.chainId}`);
225
+ }
226
+ const network = o.network;
227
+ if (typeof network !== "string" || network === "") throw new Error(`logswap: deployment artifact: "network" is ${JSON.stringify(network)}`);
228
+ const d: Record<string, unknown> = {
229
+ chainId,
230
+ network,
231
+ deployBlock: uint(o, "deployBlock"),
232
+ cVersion: uint(o, "cVersion"),
233
+ fVersion: uint(o, "fVersion"),
234
+ };
235
+ if (o.deployTag !== undefined) {
236
+ if (typeof o.deployTag !== "string") throw new Error(`logswap: deployment artifact: "deployTag" is ${JSON.stringify(o.deployTag)}`);
237
+ d.deployTag = o.deployTag;
238
+ }
239
+ for (const k of REQUIRED_ADDRESSES) d[k] = address(o, k);
240
+ for (const k of OPTIONAL_ADDRESSES) if (o[k] !== undefined) d[k] = address(o, k);
241
+ return d as unknown as LogswapDeployment;
242
+ }
243
+
244
+ /** The client's address set from a deployment. */
245
+ export function addressesOfDeployment(d: LogswapDeployment): LogswapAddresses {
246
+ return {
247
+ cPoolManager: d.cPoolManager,
248
+ router: d.router,
249
+ lens: d.lens,
250
+ fPoolManager: d.fPoolManager,
251
+ publicPolicy: d.publicPolicy,
252
+ privatePolicy: d.privatePolicy,
253
+ polPolicy: d.polPolicy,
254
+ padPolicy: d.padPolicy,
255
+ policyRegistry: d.policyRegistry,
256
+ permit2: d.permit2,
257
+ ...(d.tokenFactory ? { tokenFactory: d.tokenFactory } : {}),
258
+ };
259
+ }
package/src/client.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { Address, PublicClient, WalletClient } from "viem";
12
+ import { addressesOfDeployment, DEFAULT_MAX_LOG_RANGE, logswapChain, type LogswapChain, type LogswapDeployment } from "./chains.js";
12
13
 
13
14
  export interface LogswapAddresses {
14
15
  /** The C singleton — a floor per position, on a tick ladder. ERC-6909 positions and token
@@ -47,14 +48,60 @@ export interface LogswapClient {
47
48
  public: PublicClient;
48
49
  wallet?: WalletClient;
49
50
  addresses: LogswapAddresses;
51
+ /** The chain the client reads: the deployment's, else the public client's. Unset when neither says. */
52
+ chainId?: number;
53
+ /** The deployment's first block: the default `fromBlock` of every log scan. */
54
+ deployBlock?: bigint;
55
+ /** Block span of one `eth_getLogs` call on the chain path; wider scans are split. {@link DEFAULT_MAX_LOG_RANGE} when unset. */
56
+ maxLogRange?: bigint;
57
+ /**
58
+ * The rindexer GraphQL endpoint of THIS chain's indexer: the default `indexer` of every history
59
+ * read. The contracts sit at one address on every release chain, so an indexer's rows carry no
60
+ * chain a reader could filter on: one URL per chain.
61
+ */
62
+ indexerUrl?: string;
50
63
  }
51
64
 
52
- export function createLogswapClient(args: {
65
+ export interface CreateLogswapClientArgs {
53
66
  public: PublicClient;
54
67
  wallet?: WalletClient;
55
- addresses: LogswapAddresses;
56
- }): LogswapClient {
57
- return { public: args.public, wallet: args.wallet && guardChain(args.wallet, args.public), addresses: args.addresses };
68
+ /** The addresses; derived from `deployment` when absent. One of the two is required. */
69
+ addresses?: LogswapAddresses;
70
+ /** A deployment ({@link deploymentFromArtifact}, {@link deploymentFor}): addresses, chain and deploy block. */
71
+ deployment?: LogswapDeployment;
72
+ /** Overrides the deployment's. */
73
+ deployBlock?: bigint;
74
+ /** Overrides the chain's default ({@link LogswapChain.maxLogRange}, else {@link DEFAULT_MAX_LOG_RANGE}). */
75
+ maxLogRange?: bigint;
76
+ indexerUrl?: string;
77
+ }
78
+
79
+ export function createLogswapClient(args: CreateLogswapClientArgs): LogswapClient {
80
+ const d = args.deployment;
81
+ const addresses = args.addresses ?? (d && addressesOfDeployment(d));
82
+ if (!addresses) throw new Error("logswap: createLogswapClient needs `addresses` or `deployment`");
83
+ const readChain = args.public.chain?.id;
84
+ if (d && readChain !== undefined && readChain !== d.chainId) {
85
+ throw new Error(`logswap: the deployment is on chain ${d.chainId} but the public client reads chain ${readChain}`);
86
+ }
87
+ const chainId = d?.chainId ?? readChain;
88
+ const maxLogRange = args.maxLogRange ?? (chainId !== undefined ? logswapChain(chainId)?.maxLogRange : undefined) ?? DEFAULT_MAX_LOG_RANGE;
89
+ if (maxLogRange <= 0n) throw new Error("logswap: maxLogRange must be positive");
90
+ const deployBlock = args.deployBlock ?? d?.deployBlock;
91
+ return {
92
+ public: args.public,
93
+ wallet: args.wallet && guardChain(args.wallet, args.public),
94
+ addresses,
95
+ maxLogRange,
96
+ ...(chainId !== undefined ? { chainId } : {}),
97
+ ...(deployBlock !== undefined ? { deployBlock } : {}),
98
+ ...(args.indexerUrl ? { indexerUrl: args.indexerUrl } : {}),
99
+ };
100
+ }
101
+
102
+ /** The chain id the client reads: set at construction when known, else asked of the node. */
103
+ export async function clientChainId(c: LogswapClient): Promise<number> {
104
+ return c.chainId ?? c.public.chain?.id ?? (await c.public.getChainId());
58
105
  }
59
106
 
60
107
  /**
@@ -122,8 +169,15 @@ function guardChain(wallet: WalletClient, pub: PublicClient): WalletClient {
122
169
  * fee (`swapFeeOf` and `DEFAULT_FEE` are gone); the mint fee is the market's, proposed at
123
170
  * `initialize` / `createMarket` and answered by the gate; the gate (`gate`, `setGate`) is the
124
171
  * public policy, set at construction. No pool id moved.
172
+ *
173
+ * **8** since 2026-10-13 (logswap-contract decision 066): the collector is split into two roles —
174
+ * `feeCollector` / `proposeCollector` / `acceptCollector` are `treasury` / `proposeTreasury` (the
175
+ * LOG Authority's) / `acceptTreasury`; `setSwapFeeTax` and `setGate` leave the manager: the tax is
176
+ * each market's, answered by the gate (`PublicPolicy.swapFeeTax`, the LOG Authority's) at birth and
177
+ * read as `getPool(key).swapFeeTax`; the gate is fixed at construction; `collectProtocolFees(key)` is
178
+ * permissionless and pays the treasury. No pool id moved.
125
179
  */
126
- export const EXPECTED_VERSION = 7n;
180
+ export const EXPECTED_VERSION = 8n;
127
181
  /**
128
182
  * The F manager's own tag (5 — the key's salt, pool names, the sponsor registry;
129
183
  * 4 was the income-only harvest cut).
@@ -195,16 +249,25 @@ export const EXPECTED_VERSION = 7n;
195
249
  // `harvestCut`, `setHarvestCut` are gone; a pad's split (creator's cut, token burn) rides in the key's salt.
196
250
  // 24 (logswap-contract#58): the pot splits in quote — `Terms.burn` is quote spent on a buy-and-burn, the
197
251
  // rest deepens the bid, no buy-in, `Regenerated` is (pot, payee, toPayee, cut, burnt, deepened), a pad's
198
- // salt carries `burnShare` of the pot (057); the mint fee all to the collector (058); `phi` → `swapFee`,
252
+ // salt carries `burnShare` of the pot (057); the mint fee all to the treasury (058, 066); `phi` → `swapFee`,
199
253
  // `MINT_FEE()` → `mintFee()`, the policies' fee tiers, a canonical public pool (059).
200
254
  // 25 (logswap-contract#59): the views moved behind `extsload` (062) — this SDK reads them through the
201
- // lens (`fPool`, `getFPools`, `fBundleOf`, `fDividendOf`, `fLienOf`); the capped F pool, `FPoolKey.cap`
255
+ // lens (`fPool`, `getFPools`, `fBundleOf`, `fDividendOf`, `fLienOf`); the capped F pool, `FPoolKey.cap` (`lnCapOverFloor` since 27)
202
256
  // appended so every pool id moved (061); the lien, `lock` / `unlock` (063); θ is `logFloor`, θ₀ `refLogFloor`.
203
257
  // 26 (logswap-contract#60): the mint fee is per pool, proposed at `initialize(key, mintFee)` and answered
204
258
  // by the policy's `onInitialize` from its menu (065); `MINT_FEE` is gone; a fee of 0 is no fee; the
205
259
  // policies curate creators, a public pool is uncapped, one pad per base (064). No pool id moved.
260
+ // 27 (decision 066): `FPoolKey.cap` → `lnCapOverFloor` (a name: no id moved); `feeCollector` → `treasury` (proposed by the LOG Authority, accepted by itself);
261
+ // the registry's `owner` → `logAuthority`, administering every policy's lists and numbers; a public pool
262
+ // is born to the LOG Authority. No pool id moved.
263
+ // 28 (decision 067): no buy-and-burn — `Terms` is four words, `Regenerated` loses `burnt`; on a pad the manager caps the
264
+ // payee at `PAYEE_CUT_MAX` and carries only the dead shares, and refuses `retire`; `PadPolicy.pack(creatorShare, nonce)`,
265
+ // `setSchedule` without a burn range, `splitOf` → (creatorShare, protocolShare). No pool id moved.
266
+ // 29 (decision 068): the restructure guard and the registry's sunset read `block.timestamp` —
267
+ // `Pool.restructureBlock` is `restructureTime` (unix seconds, same slot), `PolicyRegistry.sunset(policy, untilTime)`.
268
+ // Names only: no pool id moved.
206
269
  // A breaking bump: raised in the same change.
207
- export const EXPECTED_F_VERSION = 26n;
270
+ export const EXPECTED_F_VERSION = 29n;
208
271
 
209
272
  export async function assertVersion(c: LogswapClient, expected = EXPECTED_VERSION): Promise<void> {
210
273
  const { cPoolManagerAbi, fPoolManagerAbi } = await import("./generated.js");
package/src/fees.ts CHANGED
@@ -131,11 +131,12 @@ export async function swapFees(
131
131
  // the indexer's swap_flow view carries the same figure per swap (`feeQuote`, C)
132
132
  let fees = 0n;
133
133
  let swaps = 0;
134
- const viewed = fromBlock > toBlock || !opts.indexer ? null : await windowFromView(c, opts.indexer, m.poolId, fromBlock, toBlock);
134
+ const indexer = opts.indexer ?? c.indexerUrl;
135
+ const viewed = fromBlock > toBlock || !indexer ? null : await windowFromView(c, indexer, m.poolId, fromBlock, toBlock);
135
136
  if (viewed) {
136
137
  ({ fees, swaps } = viewed);
137
138
  } else if (fromBlock <= toBlock) {
138
- const { logs } = await getEventLogs<{ fee: bigint }>(c, { indexer: opts.indexer, address: c.addresses.cPoolManager, event: ev, args: { poolId: m.poolId }, fromBlock, toBlock });
139
+ const { logs } = await getEventLogs<{ fee: bigint }>(c, { indexer, address: c.addresses.cPoolManager, event: ev, args: { poolId: m.poolId }, fromBlock, toBlock });
139
140
  for (const l of logs) fees += l.args.fee;
140
141
  swaps = logs.length;
141
142
  }