@logswap/sdk 0.5.102 → 0.5.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +14 -418
  2. package/dist/actions.d.ts +0 -39
  3. package/dist/actions.js +0 -39
  4. package/dist/admin.d.ts +0 -106
  5. package/dist/admin.js +1 -96
  6. package/dist/chains.d.ts +0 -49
  7. package/dist/chains.js +0 -30
  8. package/dist/claims.d.ts +0 -32
  9. package/dist/claims.js +0 -30
  10. package/dist/client.d.ts +0 -116
  11. package/dist/client.js +1 -231
  12. package/dist/fees.d.ts +1 -45
  13. package/dist/fees.js +0 -44
  14. package/dist/fpool.d.ts +4 -612
  15. package/dist/fpool.js +14 -490
  16. package/dist/generated.js +0 -30
  17. package/dist/history.d.ts +0 -61
  18. package/dist/history.js +5 -74
  19. package/dist/ids.d.ts +0 -30
  20. package/dist/ids.js +0 -31
  21. package/dist/index.d.ts +0 -7
  22. package/dist/index.js +0 -7
  23. package/dist/indexer.d.ts +0 -68
  24. package/dist/indexer.js +1 -77
  25. package/dist/keys.d.ts +0 -50
  26. package/dist/keys.js +0 -35
  27. package/dist/liquidity.d.ts +0 -128
  28. package/dist/liquidity.js +1 -107
  29. package/dist/onboard.d.ts +0 -52
  30. package/dist/onboard.js +1 -59
  31. package/dist/pools.d.ts +3 -157
  32. package/dist/pools.js +1 -164
  33. package/dist/positions.d.ts +0 -102
  34. package/dist/positions.js +1 -90
  35. package/dist/quote.d.ts +0 -14
  36. package/dist/quote.js +0 -14
  37. package/dist/swap.d.ts +0 -31
  38. package/dist/swap.js +5 -37
  39. package/dist/tokencache.d.ts +0 -48
  40. package/dist/tokencache.js +1 -73
  41. package/dist/write.d.ts +1 -87
  42. package/dist/write.js +1 -87
  43. package/package.json +3 -8
  44. package/src/actions.ts +0 -208
  45. package/src/admin.ts +0 -350
  46. package/src/chains.ts +0 -278
  47. package/src/claims.ts +0 -111
  48. package/src/client.ts +0 -436
  49. package/src/fees.ts +0 -138
  50. package/src/fpool.ts +0 -2049
  51. package/src/generated.ts +0 -4345
  52. package/src/history.ts +0 -383
  53. package/src/ids.ts +0 -78
  54. package/src/index.ts +0 -26
  55. package/src/indexer.ts +0 -264
  56. package/src/keys.ts +0 -138
  57. package/src/liquidity.ts +0 -456
  58. package/src/onboard.ts +0 -253
  59. package/src/pools.ts +0 -465
  60. package/src/positions.ts +0 -297
  61. package/src/quote.ts +0 -36
  62. package/src/swap.ts +0 -181
  63. package/src/tokencache.ts +0 -178
  64. package/src/write.ts +0 -236
package/dist/write.js CHANGED
@@ -1,46 +1,10 @@
1
- /**
2
- * write.ts — shared plumbing for every mutating call.
3
- *
4
- * Two conventions every write helper inherits, so no caller has to remember them:
5
- *
6
- * **Deadlines are mandatory on-chain and defaulted here.** Every mutating router entry carries
7
- * `checkDeadline`. Passing `type(uint256).max` disables it, which is what most SDKs do implicitly
8
- * and is a real hazard for a user whose transaction sits in the mempool through a price move. The
9
- * default is a bounded window; pass `deadline: NEVER` only deliberately.
10
- *
11
- * **Slippage is expressed as a bound, never as a percentage of a stale quote.** Helpers take the
12
- * raw `minOut`/`maxIn` the contract wants. `withSlippage()` derives one from a quote when that is
13
- * what you have — but the bound is what ships.
14
- */
15
1
  import { routerOf } from "./client.js";
16
2
  import { managerCAbi, managerFAbi, policyFAbi } from "./generated.js";
17
- /** Disables the deadline check. Deliberate opt-out, never a default. */
18
3
  export const NEVER = (1n << 256n) - 1n;
19
- /** Default deadline window: 20 minutes, the same order as every major DEX front end. */
20
4
  export const DEFAULT_DEADLINE_SECONDS = 20n * 60n;
21
5
  export function resolveDeadline(o, now = Date.now()) {
22
6
  return o?.deadline ?? BigInt(Math.floor(now / 1000)) + DEFAULT_DEADLINE_SECONDS;
23
7
  }
24
- /**
25
- * The wallet's account, as the ACCOUNT OBJECT rather than its address.
26
- *
27
- * This distinction decides how the transaction is signed, and getting it wrong fails in only half
28
- * the cases — which is how it survived a long time here. viem treats a bare `0x…` address as a
29
- * *JSON-RPC account* and calls `eth_sendTransaction`, asking the NODE to sign. That is right for an
30
- * injected wallet and wrong for a local account, which must sign in-process and send
31
- * `eth_sendRawTransaction`.
32
- *
33
- * A dev node holds the keys for its own accounts, so passing an address appears to work right up
34
- * until someone uses a key the node does not have — a bot, a script, CI, or a real user's wallet.
35
- * Passing the object lets viem pick the correct path for both kinds.
36
- */
37
- /**
38
- * The wallet's account OBJECT for a write the caller named by address — see {@link requireWallet}
39
- * for why the object and never the address. The F helpers take `account: Address` in their
40
- * arguments; passed straight to viem it became a JSON-RPC account and the NODE was asked to sign,
41
- * which works only on a dev node holding the key (every agent on the devnet did exactly that).
42
- * A named account that is not the wallet's is refused: nothing else could sign for it.
43
- */
44
8
  export function signerFor(c, address) {
45
9
  const { account } = requireWallet(c);
46
10
  if (account.address.toLowerCase() !== address.toLowerCase()) {
@@ -58,21 +22,12 @@ export function requireWallet(c) {
58
22
  export function resolveRecipient(c, o) {
59
23
  return o?.recipient ?? requireWallet(c).address;
60
24
  }
61
- /**
62
- * Turn a quoted amount into a slippage bound.
63
- *
64
- * `bps` is basis points of tolerance. Direction matters: an output bound floors, an input bound
65
- * ceilings. Getting that backwards produces a bound that can never bind, which is worse than no
66
- * bound at all because it looks protective.
67
- */
68
25
  export function withSlippage(quoted, bps, side) {
69
26
  if (bps < 0 || bps > 10_000)
70
27
  throw new Error(`logswap: slippage bps out of range: ${bps}`);
71
28
  const b = BigInt(Math.round(bps));
72
- // an input bound rounds UP: flooring it would put a wei-exact quote at bps = 0 one wei short
73
29
  return side === "output" ? (quoted * (10000n - b)) / 10000n : (quoted * (10000n + b) + 9999n) / 10000n;
74
30
  }
75
- /** Permit2's pull errors — Uniswap's and the devnet mock's — which a router write can revert with. */
76
31
  const permit2Errors = [
77
32
  { type: "error", name: "AllowanceExpired", inputs: [{ type: "uint256" }] },
78
33
  { type: "error", name: "InsufficientAllowance", inputs: [{ type: "uint256" }] },
@@ -80,13 +35,6 @@ const permit2Errors = [
80
35
  { type: "error", name: "NotAllowed", inputs: [] },
81
36
  ];
82
37
  const errorKey = (e) => `${e.name}(${e.inputs.map((i) => i.type).join(",")})`;
83
- /**
84
- * Every custom error a router call can revert with that the router's own ABI does not declare: the
85
- * C and F managers' (a mint, a swap or a settlement bubbles them up unchanged), the pad policy's
86
- * (a launch's `NoThreshold`, `PadExists`, `OutOfRange`; a graduation's `NotGraduated`) and Permit2's.
87
- * Without them viem can name only the router's errors, and anything raised in the manager comes
88
- * back as a bare selector.
89
- */
90
38
  export const routerRevertErrors = (() => {
91
39
  const seen = new Set();
92
40
  const out = [];
@@ -101,17 +49,10 @@ export const routerRevertErrors = (() => {
101
49
  }
102
50
  return out;
103
51
  })();
104
- /** `abi` plus every error in {@link routerRevertErrors} it does not already declare. */
105
52
  export function withRevertErrors(abi) {
106
53
  const have = new Set(abi.filter((x) => x.type === "error").map((x) => errorKey(x)));
107
54
  return [...abi, ...routerRevertErrors.filter((e) => !have.has(errorKey(e)))];
108
55
  }
109
- /**
110
- * The decoded revert of a contract call, e.g. `SlippageIn()` or `AllowanceExpired(1700000000)`,
111
- * found however deep viem nested it; the raw selector when the error is not in the ABI; undefined
112
- * when the failure was not a revert. viem's `message` puts the name on its second line, so a UI
113
- * that shows only the first line ("The contract function … reverted.") loses it.
114
- */
115
56
  export function revertName(e) {
116
57
  const seen = new Set();
117
58
  for (let x = e; x && typeof x === "object" && !seen.has(x); x = x.cause) {
@@ -126,17 +67,7 @@ export function revertName(e) {
126
67
  }
127
68
  return undefined;
128
69
  }
129
- /**
130
- * Send a router write with a gas buffer over an explicit estimate.
131
- *
132
- * A swap's gas is path-dependent: how many ticks it crosses depends on the price when it LANDS, not
133
- * when it was estimated, and the variance kernel does more work when a block boundary has passed
134
- * since the last touch. An exact `eth_estimateGas` can therefore OutOfGas one block later. Every
135
- * write goes through here.
136
- */
137
- export async function sendRouterWrite(c,
138
- /** `side` picks the router (decision 096: one per manager, each its own Permit2 spender). */
139
- args) {
70
+ export async function sendRouterWrite(c, args) {
140
71
  const { account } = requireWallet(c);
141
72
  const params = {
142
73
  address: routerOf(c, args.side),
@@ -150,10 +81,6 @@ args) {
150
81
  const gas = (estimate * (100n + (args.bufferPct ?? 30n))) / 100n;
151
82
  return c.wallet.writeContract({ ...params, gas });
152
83
  }
153
- /**
154
- * Whether an error is the user saying no in their wallet (EIP-1193 code 4001, viem's
155
- * `UserRejectedRequestError`), however deep viem nested it.
156
- */
157
84
  export function isUserRejection(e) {
158
85
  const seen = new Set();
159
86
  for (let x = e; x && typeof x === "object" && !seen.has(x); x = x.cause) {
@@ -164,18 +91,11 @@ export function isUserRejection(e) {
164
91
  }
165
92
  return false;
166
93
  }
167
- /**
168
- * The permit signatures are an optimisation: when they cannot be produced (a wallet without
169
- * `signTypedData`, a read that failed) the write goes out plain and relies on a standing
170
- * allowance. A REJECTED signature is not that — it was swallowed too, and the user who had just
171
- * said no was shown a transaction prompt, which then reverted with a Permit2 error that hid why.
172
- */
173
94
  export function fallBackUnlessRejected(e) {
174
95
  if (isUserRejection(e))
175
96
  throw e;
176
97
  return [];
177
98
  }
178
- /** Simulate a router write and return its decoded result, without sending. */
179
99
  export async function simulateRouterWrite(c, args) {
180
100
  const account = args.account ?? c.wallet?.account?.address;
181
101
  const { result } = await c.public.simulateContract({
@@ -187,12 +107,6 @@ export async function simulateRouterWrite(c, args) {
187
107
  });
188
108
  return result;
189
109
  }
190
- /**
191
- * A router write that carries its own Permit2 permissions: missing allowances for `pullTokens`
192
- * are SIGNED (no gas, no extra transaction) and submitted as `applyPermit2` calls in one
193
- * multicall with the action. The 3-transaction mint becomes 1. Falls through to a plain write
194
- * when nothing is missing or Permit2 is not wired.
195
- */
196
110
  export async function sendRouterWriteWithPermits(c, args, pullTokens) {
197
111
  const { permit2SigCalls } = await import("./onboard.js");
198
112
  const sigCalls = await permit2SigCalls(c, args.side, pullTokens).catch(fallBackUnlessRejected);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@logswap/sdk",
3
- "version": "0.5.102",
4
- "description": "TypeScript SDK for Logswap, the liquidity primitive introducing the logarithmic invariant — typed wrappers over the ManagerF / ManagerC, RouterF / RouterC and LensF / LensC surface.",
3
+ "version": "0.5.103",
4
+ "description": "TypeScript SDK for log(swap).",
5
5
  "license": "GPL-2.0-or-later",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -14,8 +14,7 @@
14
14
  }
15
15
  },
16
16
  "files": [
17
- "dist",
18
- "src"
17
+ "dist"
19
18
  ],
20
19
  "scripts": {
21
20
  "contracts:sync": "bash scripts/sync-contracts.sh",
@@ -42,9 +41,5 @@
42
41
  "publishConfig": {
43
42
  "access": "public"
44
43
  },
45
- "repository": {
46
- "type": "git",
47
- "url": "git+https://github.com/logswap/logswap-sdk.git"
48
- },
49
44
  "homepage": "https://logswap.org"
50
45
  }
package/src/actions.ts DELETED
@@ -1,208 +0,0 @@
1
- /**
2
- * actions.ts — the router's transaction: a BATCH.
3
- *
4
- * `execute(actions, settle)` runs a list of actions — mint, burn, update, claim, swap, path, in any
5
- * order, across any C markets — under ONE manager lock. Each action accrues deltas on the router
6
- * and settles nothing; the batch settles once per token in `settle.tokens`, pulling at most
7
- * `maxIn[i]` from the caller and taking at least `minOut[i]` to `settle.to`. A touched token
8
- * left off the list fails the manager's own close (`TokensNotSettled`), so the list is also the
9
- * caller's statement of which tokens may move.
10
- *
11
- * `OPEN_DELTA` as a swap amount means "the router's open delta of that token": what earlier
12
- * actions left it holding (exact-in, path) or owing (exact-out). It is what lets action i+1
13
- * consume action i's proceeds — a harvest funds a buy, a burn exits to one asset, a deepen is paid
14
- * in base — each moving ONE token.
15
- *
16
- * Payloads are `abi.encode` of the router's `*Act` structs. Their tuple types are read from the
17
- * generated ABI (the router's pure `encode*` helpers exist for exactly this), so nothing here is
18
- * hand-written and a struct change is a `tsc`/vector failure, not a runtime surprise.
19
- */
20
-
21
- import { encodeAbiParameters, type Address, type Hash, type Hex } from "viem";
22
- import { routerCAbi, routerActionsAbi } from "./generated.js";
23
- import type { LogswapClient } from "./client.js";
24
- import { poolId as keyId, type PoolKey } from "./keys.js";
25
- import { NO_CAP } from "./ids.js";
26
- import type { Hop } from "./swap.js";
27
- import { resolveDeadline, resolveRecipient, sendRouterWriteWithPermits, simulateRouterWrite, type WriteOptions } from "./write.js";
28
-
29
- /** "The router's open delta of that token" — the swap-amount sentinel. `type(uint256).max`. */
30
- export const OPEN_DELTA = (1n << 256n) - 1n;
31
- /** No bound. The same word as the sentinel, kept apart because it means something else. */
32
- export const UNBOUNDED = (1n << 256n) - 1n;
33
-
34
- /** The router's op tags — `OpType` in `RouterOps.sol`, C actions only (the F ops have their own lock). */
35
- export enum Op {
36
- MintBlended = 0,
37
- Burn = 1,
38
- SwapExactIn = 2,
39
- SwapExactOut = 3,
40
- Claim = 4,
41
- Update = 5,
42
- Path = 6,
43
- }
44
-
45
- export interface Action {
46
- op: Op;
47
- data: Hex;
48
- }
49
-
50
- export interface Settle {
51
- tokens: readonly Address[];
52
- maxIn: readonly bigint[];
53
- minOut: readonly bigint[];
54
- /** Receives whatever is taken, and the shares the actions mint (`Settle.to`; `recipient` before C 17). */
55
- to: Address;
56
- }
57
-
58
- /* payload encoding ========================================================== */
59
-
60
- function payloadType(encoder: string) {
61
- const f = (routerActionsAbi as readonly { type: string; name?: string; inputs?: readonly unknown[] }[]).find(
62
- (x) => x.type === "function" && x.name === encoder,
63
- );
64
- if (!f?.inputs) throw new Error(`logswap: RouterActions has no ${encoder} — SDK and contracts disagree`);
65
- return f.inputs;
66
- }
67
-
68
- const enc = (encoder: string, value: unknown): Hex => encodeAbiParameters(payloadType(encoder) as never, [value] as never);
69
-
70
- /** Mint exposure `L` at `targetFloor` (off-grid blends the two adjacent rungs), `cap` optional. */
71
- export function mintAction(a: { key: PoolKey; targetFloor: bigint; cap?: bigint; L: bigint }): Action {
72
- return { op: Op.MintBlended, data: enc("encodeMint", { poolId: keyId(a.key), targetFloor: a.targetFloor, cap: a.cap ?? NO_CAP, L: a.L }) };
73
- }
74
-
75
- /** Burn `shares[i]` of `ids[i]`; accrued fees are swept into the same batch. Needs the operator grant. */
76
- export function burnAction(a: { key: PoolKey; ids: readonly bigint[]; shares: readonly bigint[] }): Action {
77
- if (a.ids.length !== a.shares.length) throw new Error("logswap: ids and shares length mismatch");
78
- return { op: Op.Burn, data: enc("encodeBurn", { poolId: keyId(a.key), ids: a.ids, shares: a.shares }) };
79
- }
80
-
81
- /** Exact-in swap. `amountIn` may be `OPEN_DELTA`: the input an earlier action left the router holding. */
82
- export function swapExactInAction(a: { key: PoolKey; baseIn: boolean; amountIn: bigint; minOut?: bigint }): Action {
83
- return { op: Op.SwapExactIn, data: enc("encodeSwap", { poolId: keyId(a.key), baseSide: a.baseIn, amount: a.amountIn, limit: a.minOut ?? 0n }) };
84
- }
85
-
86
- /** Exact-out swap. `amountOut` may be `OPEN_DELTA`: the output an earlier action left the router owing. */
87
- export function swapExactOutAction(a: { key: PoolKey; baseOut: boolean; amountOut: bigint; maxIn?: bigint }): Action {
88
- return {
89
- op: Op.SwapExactOut,
90
- data: enc("encodeSwap", { poolId: keyId(a.key), baseSide: a.baseOut, amount: a.amountOut, limit: a.maxIn ?? UNBOUNDED }),
91
- };
92
- }
93
-
94
- /** Collect the caller's fees on `ids`; positions untouched. */
95
- export function claimAction(a: { key: PoolKey; ids: readonly bigint[] }): Action {
96
- return { op: Op.Claim, data: enc("encodeClaim", { poolId: keyId(a.key), ids: a.ids }) };
97
- }
98
-
99
- /** The general edit — set `shares` of `fromId` to (`toFloor`, `toCap`, `newL`); `newL = 0` exits. */
100
- export function updateAction(a: {
101
- key: PoolKey;
102
- fromId: bigint;
103
- shares: bigint;
104
- toFloor: bigint;
105
- toCap?: bigint;
106
- newL: bigint;
107
- }): Action {
108
- return {
109
- op: Op.Update,
110
- data: enc("encodeUpdate", {
111
- poolId: keyId(a.key),
112
- fromId: a.fromId,
113
- shares: a.shares,
114
- toFloor: a.toFloor,
115
- toCap: a.toCap ?? NO_CAP,
116
- newL: a.newL,
117
- }),
118
- };
119
- }
120
-
121
- /** Multi-hop exact-in route; `amountIn` may be `OPEN_DELTA`. Intermediate tokens never move. */
122
- export function pathAction(a: { hops: readonly Hop[]; amountIn: bigint; minOut?: bigint }): Action {
123
- if (a.hops.length === 0) throw new Error("logswap: empty path");
124
- return { op: Op.Path, data: enc("encodePath", { hops: a.hops.map((h) => ({ poolId: keyId(h.key), baseIn: h.baseIn })), amountIn: a.amountIn, minOut: a.minOut ?? 0n }) };
125
- }
126
-
127
- /* settlement builders ======================================================= */
128
-
129
- /** A settlement over explicit tokens; missing bounds default to unbounded in, zero out. */
130
- export function settlement(a: {
131
- tokens: readonly Address[];
132
- maxIn?: readonly bigint[];
133
- minOut?: readonly bigint[];
134
- to: Address;
135
- }): Settle {
136
- const n = a.tokens.length;
137
- const maxIn = a.maxIn ?? a.tokens.map(() => UNBOUNDED);
138
- const minOut = a.minOut ?? a.tokens.map(() => 0n);
139
- if (maxIn.length !== n || minOut.length !== n) throw new Error("logswap: settlement bounds length mismatch");
140
- return { tokens: a.tokens, maxIn, minOut, to: a.to };
141
- }
142
-
143
- export interface PairBounds {
144
- maxBaseIn?: bigint;
145
- maxQuoteIn?: bigint;
146
- minBaseOut?: bigint;
147
- minQuoteOut?: bigint;
148
- }
149
-
150
- /** Settle both of a market's tokens, in kind. */
151
- export function settleInKind(key: PoolKey, to: Address, b: PairBounds = {}): Settle {
152
- return settlement({
153
- tokens: [key.base, key.quote],
154
- maxIn: [b.maxBaseIn ?? UNBOUNDED, b.maxQuoteIn ?? UNBOUNDED],
155
- minOut: [b.minBaseOut ?? 0n, b.minQuoteOut ?? 0n],
156
- to,
157
- });
158
- }
159
-
160
- /**
161
- * Settle in ONE of a market's tokens: the other is bound to zero both ways, so the batch must have
162
- * netted it — which is what a trailing `OPEN_DELTA` swap does.
163
- */
164
- export function settleOnly(key: PoolKey, to: Address, side: "base" | "quote", b: { maxIn?: bigint; minOut?: bigint } = {}): Settle {
165
- const base = side === "base";
166
- return settlement({
167
- tokens: [key.base, key.quote],
168
- maxIn: [base ? (b.maxIn ?? UNBOUNDED) : 0n, base ? 0n : (b.maxIn ?? UNBOUNDED)],
169
- minOut: [base ? (b.minOut ?? 0n) : 0n, base ? 0n : (b.minOut ?? 0n)],
170
- to,
171
- });
172
- }
173
-
174
- /* the batch ================================================================= */
175
-
176
- export interface ExecuteArgs extends WriteOptions {
177
- actions: readonly Action[];
178
- settle: Omit<Settle, "to"> & { to?: Address };
179
- /** Tokens the batch may pull, for the Permit2 signatures. Defaults to every token with `maxIn > 0`. */
180
- pullTokens?: readonly Address[];
181
- }
182
-
183
- /** Run a batch: one lock, one settlement per token, one transaction (Permit2 signatures ride inside). */
184
- export async function execute(c: LogswapClient, a: ExecuteArgs): Promise<Hash> {
185
- const settle: Settle = { ...a.settle, to: a.settle.to ?? resolveRecipient(c, a) };
186
- const pull = a.pullTokens ?? settle.tokens.filter((_, i) => settle.maxIn[i]! > 0n);
187
- return sendRouterWriteWithPermits(
188
- c,
189
- { side: "C", abi: routerCAbi, functionName: "execute", args: [a.actions, settle, resolveDeadline(a)] },
190
- [...pull],
191
- );
192
- }
193
-
194
- /** Simulate a batch: the per-action returns and the signed flows (+ = paid in), without sending. */
195
- export async function simulateExecute(
196
- c: LogswapClient,
197
- a: ExecuteArgs & { account?: Address },
198
- ): Promise<{ results: readonly Hex[]; flows: readonly bigint[] }> {
199
- const settle: Settle = { ...a.settle, to: a.settle.to ?? a.account ?? resolveRecipient(c, a) };
200
- const [results, flows] = await simulateRouterWrite<readonly [readonly Hex[], readonly bigint[]]>(c, {
201
- side: "C",
202
- abi: routerCAbi,
203
- functionName: "execute",
204
- args: [a.actions, settle, resolveDeadline(a)],
205
- account: a.account,
206
- });
207
- return { results, flows };
208
- }