@priors/mcp 0.13.0 → 0.14.0
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/CHANGELOG.md +42 -0
- package/README.md +74 -7
- package/deployments/stock-zap.4663.json +520 -0
- package/package.json +1 -1
- package/src/pt-usdg.mjs +22 -17
- package/src/server.mjs +75 -8
- package/src/stock-tools.mjs +182 -0
- package/src/stock-trade.mjs +361 -0
- package/src/stock-zap.mjs +299 -0
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// Stock tokens bought with USDG, in one sponsored operation (Go mode's stock buy, web/account-zap.js; the gas gate's
|
|
2
|
+
// STOCK_ZAP rule, gas-worker/gate.mjs; docs/STOCK-ZAP-SPEC.md): the record (deployments/stock-zap.4663.json) checked and
|
|
3
|
+
// frozen, the two calls Priors builds, the gate's check of the swap, and a quote for node and the rigs.
|
|
4
|
+
//
|
|
5
|
+
// A buy is exactly two calls: USDG approved to the swap's spender for exactly the amount swapped, then the swap, the
|
|
6
|
+
// tokens paid to the account itself.
|
|
7
|
+
// - a v4 pool (its key: the lower of USDG and the token, the higher, a static fee, its tick spacing, no hooks): Priors'
|
|
8
|
+
// V4SwapOnce.swapExactIn(key, zeroForOne, amountIn, minOut, limit, to, deadline), zeroForOne = (currency0 == USDG),
|
|
9
|
+
// the price limit at v4's extreme for that direction (it fills in full or reverts on minOut);
|
|
10
|
+
// - a v3 pool: Uniswap's SwapRouter02.multicall(deadline, [exactInputSingle({ tokenIn: USDG, tokenOut: token, fee,
|
|
11
|
+
// recipient: account, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0 })]) (multicall's deadline form:
|
|
12
|
+
// exactInputSingle has none of its own).
|
|
13
|
+
// web/zap-core.js encodes the same calls without viem for the page; scripts/test-stock-zap.mjs holds the two byte for byte.
|
|
14
|
+
// A sale is the same two calls the other way, on the same pinned pools (docs/STOCK-ZAP-SPEC.md 15, "Selling"): the
|
|
15
|
+
// stock token approved to the swap's spender for exactly the amount sold, then the exact-input swap to USDG, paid to the
|
|
16
|
+
// account itself (v4: zeroForOne = (currency0 == the token), its own extreme limit; v3: tokenIn the token, tokenOut
|
|
17
|
+
// USDG). The gas gate sponsors buys only (checkZapCall): a sale is sent from the agent's own key (sdk/stock-trade.mjs).
|
|
18
|
+
//
|
|
19
|
+
// ZAP the record, checked (zapConfig)
|
|
20
|
+
// zapConfig(raw) a record checked and frozen, or throws with the reason
|
|
21
|
+
// v4Key, v4Id a v4 pool's key (USDG, the token, fee, tick spacing; no hooks) and its id (keccak256 of the key)
|
|
22
|
+
// buildBuy(o) the two calls of a buy: [{ to, data } approve, { to, data } swap]
|
|
23
|
+
// buildSell(o) the two calls of a sale: [{ to, data } approve of the token, { to, data } swap to USDG]
|
|
24
|
+
// checkZapCall the gate's check of a stock swap call for `sender`: { kind, symbol, usdgIn, minOut, spender }, or
|
|
25
|
+
// throws with the reason ("stock buy: …")
|
|
26
|
+
// swapKeyId(data) the pool id a V4SwapOnce.swapExactIn names, or null (the gate routes by it)
|
|
27
|
+
// quoteZap the pinned pools' quotes for a buy, read at one block (node and the rigs)
|
|
28
|
+
import { decodeFunctionData, encodeAbiParameters, encodeFunctionData, getAddress, keccak256, parseAbi } from "viem";
|
|
29
|
+
import RECORD from "../deployments/stock-zap.4663.json" with { type: "json" };
|
|
30
|
+
import ASSETS from "../deployments/stock-assets.4663.json" with { type: "json" };
|
|
31
|
+
|
|
32
|
+
export const ZAP_RECORD_PATH = "deployments/stock-zap.4663.json";
|
|
33
|
+
const ZERO = "0x0000000000000000000000000000000000000000";
|
|
34
|
+
const KEY_T = "(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)";
|
|
35
|
+
const EIS_T = "(address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96)";
|
|
36
|
+
export const ERC20_ABI = parseAbi(["function approve(address spender, uint256 amount) returns (bool)", "function balanceOf(address) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)"]);
|
|
37
|
+
export const SWAPPER_ABI = parseAbi([
|
|
38
|
+
`function swapExactIn(${KEY_T} key, bool zeroForOne, uint128 amountIn, uint256 minOut, uint160 sqrtPriceLimitX96, address to, uint256 deadline) returns (uint256 paid, uint256 out)`,
|
|
39
|
+
"error TooLittleOut(uint256 out, uint256 minOut)", "error Expired()",
|
|
40
|
+
]);
|
|
41
|
+
// SwapRouter02's deadline form of multicall, and the one call allowed inside it
|
|
42
|
+
export const ROUTER_ABI = parseAbi(["function multicall(uint256 deadline, bytes[] data) payable returns (bytes[] results)"]);
|
|
43
|
+
export const EXACT_INPUT_ABI = parseAbi([`function exactInputSingle(${EIS_T} params) payable returns (uint256 amountOut)`]);
|
|
44
|
+
export const V4_QUOTER_ABI = parseAbi([`function quoteExactInputSingle((${KEY_T} poolKey, bool zeroForOne, uint128 exactAmount, bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)`]);
|
|
45
|
+
export const V3_QUOTER_ABI = parseAbi(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)"]);
|
|
46
|
+
export const READS_ABI = parseAbi([
|
|
47
|
+
"function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)",
|
|
48
|
+
"function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)",
|
|
49
|
+
"function tokenPaused() view returns (bool)", "function paused() view returns (bool)", "function isBlocked(address) view returns (bool)",
|
|
50
|
+
"function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)",
|
|
51
|
+
]);
|
|
52
|
+
/** v4's TickMath.MIN_SQRT_PRICE + 1 and MAX_SQRT_PRICE - 1: the extreme limits of a USDG-in swap, by direction. No price
|
|
53
|
+
* stops it early: it fills in full or reverts on its minimum out. */
|
|
54
|
+
export const MIN_SQRT_PRICE_LIMIT = 4295128740n;
|
|
55
|
+
export const MAX_SQRT_PRICE_LIMIT = 1461446703485210103287273052203988822378723970341n;
|
|
56
|
+
export const limitFor = (zeroForOne) => (zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT);
|
|
57
|
+
const V3_FEES = new Set([100, 500, 3000, 10000]);
|
|
58
|
+
const DYNAMIC_FEE = 0x800000;
|
|
59
|
+
|
|
60
|
+
const same = (x, y) => { try { return !!x && !!y && getAddress(x) === getAddress(y); } catch (_) { return false; } };
|
|
61
|
+
const lowerFirst = (a, b) => (BigInt(a) < BigInt(b) ? [getAddress(a), getAddress(b)] : [getAddress(b), getAddress(a)]);
|
|
62
|
+
|
|
63
|
+
/** A v4 pool's key: the lower of USDG and the token as currency0, the higher as currency1, the fee and tick spacing, no
|
|
64
|
+
* hooks. */
|
|
65
|
+
export function v4Key(usdg, token, fee, tickSpacing) {
|
|
66
|
+
const [currency0, currency1] = lowerFirst(usdg, token);
|
|
67
|
+
return { currency0, currency1, fee: Number(fee), tickSpacing: Number(tickSpacing), hooks: ZERO };
|
|
68
|
+
}
|
|
69
|
+
/** A v4 pool's id: keccak256(abi.encode(key)), lower case. */
|
|
70
|
+
export const v4Id = (k) => keccak256(encodeAbiParameters([{ type: "address" }, { type: "address" }, { type: "uint24" }, { type: "int24" }, { type: "address" }], [getAddress(k.currency0), getAddress(k.currency1), Number(k.fee), Number(k.tickSpacing), getAddress(k.hooks)])).toLowerCase();
|
|
71
|
+
|
|
72
|
+
/** A record of deployments/stock-zap.4663.json's shape, checked and frozen; throws with the reason for one that is not:
|
|
73
|
+
* every address an address; every token one of stock-assets' (deployments/stock-assets.4663.json) at the same address,
|
|
74
|
+
* listed once; 1 to 3 pools a token and none for a token not offered; each v4 pool hookless with a static fee and its
|
|
75
|
+
* id its key's hash; each v3 fee a Uniswap tier; 0 < min ≤ max; the default slippage ≤ the max ≤ 500 bps; the
|
|
76
|
+
* deadline under its bound; the price impact's warning under its stop. */
|
|
77
|
+
export function zapConfig(raw, assets = ASSETS.assets) {
|
|
78
|
+
const no = (why) => { throw new Error(`stock zap record: ${why}`); };
|
|
79
|
+
const addr = (v, what) => { let a; try { a = getAddress(v); } catch (_) { no(`${what} is not an address`); } if (a === ZERO) no(`${what} is the zero address`); return a; };
|
|
80
|
+
if (!raw || typeof raw !== "object") no("not an object");
|
|
81
|
+
const usdg = addr(raw.usdg, "usdg"), registry = addr(raw.registry, "registry");
|
|
82
|
+
const v4 = Object.freeze({ poolManager: addr(raw.v4 && raw.v4.poolManager, "v4.poolManager"), swapper: addr(raw.v4 && raw.v4.swapper, "v4.swapper"), quoter: addr(raw.v4 && raw.v4.quoter, "v4.quoter"), stateView: addr(raw.v4 && raw.v4.stateView, "v4.stateView") });
|
|
83
|
+
const v3 = Object.freeze({ router: addr(raw.v3 && raw.v3.router, "v3.router"), quoter: addr(raw.v3 && raw.v3.quoter, "v3.quoter"), factory: addr(raw.v3 && raw.v3.factory, "v3.factory") });
|
|
84
|
+
let min, max;
|
|
85
|
+
try { min = BigInt(raw.minUsdgPerOp); max = BigInt(raw.maxUsdgPerOp); } catch (_) { no("minUsdgPerOp and maxUsdgPerOp must be whole numbers"); }
|
|
86
|
+
if (!(min > 0n && min <= max)) no("the bounds must be 0 < minUsdgPerOp ≤ maxUsdgPerOp");
|
|
87
|
+
const slips = Array.isArray(raw.slippageBps) ? raw.slippageBps.map(Number) : [];
|
|
88
|
+
const def = Number(raw.defaultSlippageBps), maxSlip = Number(raw.maxSlippageBps);
|
|
89
|
+
if (!(Number.isInteger(maxSlip) && maxSlip > 0 && maxSlip <= 500)) no("maxSlippageBps must be 1 to 500");
|
|
90
|
+
if (!(Number.isInteger(def) && def > 0 && def <= maxSlip)) no("defaultSlippageBps must be above 0 and at most maxSlippageBps");
|
|
91
|
+
if (!slips.length || !slips.every((s) => Number.isInteger(s) && s > 0 && s <= maxSlip) || !slips.includes(def)) no("slippageBps must be choices up to maxSlippageBps, the default among them");
|
|
92
|
+
const deadlineS = Number(raw.deadlineS), maxDeadlineS = Number(raw.maxDeadlineS);
|
|
93
|
+
if (!(Number.isInteger(deadlineS) && deadlineS > 0 && deadlineS < maxDeadlineS)) no("deadlineS must be above 0 and under maxDeadlineS");
|
|
94
|
+
const warn = Number(raw.impactWarnBps), stop = Number(raw.impactStopBps);
|
|
95
|
+
if (!(Number.isInteger(warn) && Number.isInteger(stop) && warn > 0 && warn < stop && stop < 10_000)) no("impactWarnBps must be under impactStopBps");
|
|
96
|
+
const bySym = new Map(assets.map((a) => [a.symbol, a]));
|
|
97
|
+
const notOffered = raw.notOffered && typeof raw.notOffered === "object" ? raw.notOffered : {};
|
|
98
|
+
for (const s of Object.keys(notOffered)) if (!bySym.has(s)) no(`${s} (not offered) is not a listed stock token`);
|
|
99
|
+
if (!Array.isArray(raw.tokens) || !raw.tokens.length) no("no tokens");
|
|
100
|
+
const seen = new Set(), v4ById = new Map(), v3ByPair = new Map(), v3ByPool = new Map();
|
|
101
|
+
const tokens = raw.tokens.map((t) => {
|
|
102
|
+
const a = t && bySym.get(t.symbol);
|
|
103
|
+
if (!a) no(`${t && t.symbol} is not one of the listed stock tokens`);
|
|
104
|
+
if (seen.has(t.symbol)) no(`${t.symbol} is listed twice`);
|
|
105
|
+
seen.add(t.symbol);
|
|
106
|
+
if (Object.prototype.hasOwnProperty.call(notOffered, t.symbol)) no(`${t.symbol} is not offered, yet has pools`);
|
|
107
|
+
const token = addr(t.token, `${t.symbol}'s token`);
|
|
108
|
+
if (token !== getAddress(a.token)) no(`${t.symbol}'s token is not stock-assets' ${a.token}`);
|
|
109
|
+
if (!Array.isArray(t.pools) || t.pools.length < 1 || t.pools.length > 3) no(`${t.symbol} must have 1 to 3 pools`);
|
|
110
|
+
const pools = t.pools.map((p) => {
|
|
111
|
+
if (p.v === 4) {
|
|
112
|
+
if (p.hooks !== undefined && !same(p.hooks, ZERO)) no(`${t.symbol}: a v4 pool with hooks`);
|
|
113
|
+
const fee = Number(p.fee), ts = Number(p.tickSpacing);
|
|
114
|
+
if (!(Number.isInteger(fee) && fee >= 0 && fee < DYNAMIC_FEE)) no(`${t.symbol}: a v4 pool's fee must be static (under 0x800000)`);
|
|
115
|
+
if (!(Number.isInteger(ts) && ts >= 1 && ts <= 32767)) no(`${t.symbol}: a v4 pool's tick spacing must be 1 to 32767`);
|
|
116
|
+
const key = Object.freeze(v4Key(usdg, token, fee, ts)), id = v4Id(key);
|
|
117
|
+
if (String(p.id).toLowerCase() !== id) no(`${t.symbol}: a v4 pool's id is not its key's hash`);
|
|
118
|
+
if (v4ById.has(id)) no(`${t.symbol}: a v4 pool listed twice`);
|
|
119
|
+
const pool = Object.freeze({ v: 4, symbol: t.symbol, token, fee, tickSpacing: ts, id, key, zeroForOne: same(key.currency0, usdg) });
|
|
120
|
+
v4ById.set(id, pool);
|
|
121
|
+
return pool;
|
|
122
|
+
}
|
|
123
|
+
if (p.v === 3) {
|
|
124
|
+
const fee = Number(p.fee);
|
|
125
|
+
if (!V3_FEES.has(fee)) no(`${t.symbol}: a v3 fee must be 100, 500, 3000 or 10000`);
|
|
126
|
+
const pool = Object.freeze({ v: 3, symbol: t.symbol, token, fee, pool: addr(p.pool, `${t.symbol}'s v3 pool`), zeroForOne: BigInt(usdg) < BigInt(token) });
|
|
127
|
+
const pair = `${token.toLowerCase()}:${fee}`;
|
|
128
|
+
if (v3ByPair.has(pair)) no(`${t.symbol}: a v3 pool listed twice`);
|
|
129
|
+
v3ByPair.set(pair, pool); v3ByPool.set(pool.pool.toLowerCase(), pool);
|
|
130
|
+
return pool;
|
|
131
|
+
}
|
|
132
|
+
return no(`${t.symbol}: a pool must be v 3 or 4`);
|
|
133
|
+
});
|
|
134
|
+
return Object.freeze({ symbol: t.symbol, name: a.name, token, decimals: Number(a.decimals), feed: getAddress(a.feed), feedDecimals: Number(a.feedDecimals), pools: Object.freeze(pools) });
|
|
135
|
+
});
|
|
136
|
+
return Object.freeze({
|
|
137
|
+
chainId: Number(raw.chainId) || 4663, usdg, registry, v4, v3, minUsdgPerOp: min, maxUsdgPerOp: max,
|
|
138
|
+
slippageBps: Object.freeze(slips), defaultSlippageBps: def, maxSlippageBps: maxSlip, deadlineS, maxDeadlineS, impactWarnBps: warn, impactStopBps: stop,
|
|
139
|
+
tokens: Object.freeze(tokens), bySymbol: new Map(tokens.map((t) => [t.symbol, t])), v4ById, v3ByPair, v3ByPool, notOffered: Object.freeze({ ...notOffered }),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export const ZAP = zapConfig(RECORD);
|
|
144
|
+
|
|
145
|
+
/** minOut: `out` less `slippageBps`, rounded down; a slippage above the record's cap is refused. */
|
|
146
|
+
export function minOutOf(out, slippageBps, conf = ZAP) {
|
|
147
|
+
const s = Number(slippageBps);
|
|
148
|
+
if (!(Number.isInteger(s) && s > 0 && s <= conf.maxSlippageBps)) throw new Error(`stock buy: slippage is at most ${conf.maxSlippageBps / 100}%`);
|
|
149
|
+
return (BigInt(out) * BigInt(10_000 - s)) / 10_000n;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The two calls of a buy of `symbol` on `pool` (one of its record pools: the object, its id or its address): USDG
|
|
153
|
+
* approved to that pool's spender for exactly `usdgIn`, then the swap for at least `minOut`, paid to `account`, by
|
|
154
|
+
* `deadline` (unix seconds). [{ to, data }, { to, data }]. */
|
|
155
|
+
/** One of token `t`'s record pools: the object, its v4 id or its v3 address; or undefined. */
|
|
156
|
+
export const pinnedPool = (t, pool) => t.pools.find((x) => x === pool || (x.v === 4 && String(pool).toLowerCase() === x.id) || (x.v === 3 && same(pool, x.pool)));
|
|
157
|
+
|
|
158
|
+
export function buildBuy({ account, symbol, pool, usdgIn, minOut, deadline }, conf = ZAP) {
|
|
159
|
+
const t = conf.bySymbol.get(symbol);
|
|
160
|
+
if (!t) throw new Error(`stock buy: ${symbol} is not offered`);
|
|
161
|
+
const p = pinnedPool(t, pool);
|
|
162
|
+
if (!p) throw new Error(`stock buy: not a pool of ${symbol} in the record`);
|
|
163
|
+
usdgIn = BigInt(usdgIn); minOut = BigInt(minOut);
|
|
164
|
+
if (usdgIn < conf.minUsdgPerOp || usdgIn > conf.maxUsdgPerOp) throw new Error("stock buy: the amount is out of bounds");
|
|
165
|
+
if (!(minOut > 0n)) throw new Error("stock buy: a minimum out is required");
|
|
166
|
+
const to = getAddress(account), dl = BigInt(deadline);
|
|
167
|
+
const spender = p.v === 4 ? conf.v4.swapper : conf.v3.router;
|
|
168
|
+
const approve = { to: conf.usdg, data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [spender, usdgIn] }) };
|
|
169
|
+
if (p.v === 4) return [approve, { to: spender, data: encodeFunctionData({ abi: SWAPPER_ABI, functionName: "swapExactIn", args: [p.key, p.zeroForOne, usdgIn, minOut, limitFor(p.zeroForOne), to, dl] }) }];
|
|
170
|
+
const inner = encodeFunctionData({ abi: EXACT_INPUT_ABI, functionName: "exactInputSingle", args: [{ tokenIn: conf.usdg, tokenOut: t.token, fee: p.fee, recipient: to, amountIn: usdgIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n }] });
|
|
171
|
+
return [approve, { to: spender, data: encodeFunctionData({ abi: ROUTER_ABI, functionName: "multicall", args: [dl, [inner]] }) }];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The two calls of a sale of `amountIn` (the token's base units) of `symbol` on `pool` (one of its record pools: the
|
|
175
|
+
* object, its id or its address): the token approved to that pool's spender for exactly `amountIn`, then the swap for
|
|
176
|
+
* at least `minOut` USDG, paid to `account`, by `deadline` (unix seconds). [{ to, data }, { to, data }]. The size of a
|
|
177
|
+
* sale in USDG is the planner's to bound (sdk/stock-trade.mjs): only the quote knows it. */
|
|
178
|
+
export function buildSell({ account, symbol, pool, amountIn, minOut, deadline }, conf = ZAP) {
|
|
179
|
+
const t = conf.bySymbol.get(symbol);
|
|
180
|
+
if (!t) throw new Error(`stock sell: ${symbol} is not offered`);
|
|
181
|
+
const p = pinnedPool(t, pool);
|
|
182
|
+
if (!p) throw new Error(`stock sell: not a pool of ${symbol} in the record`);
|
|
183
|
+
amountIn = BigInt(amountIn); minOut = BigInt(minOut);
|
|
184
|
+
if (!(amountIn > 0n && amountIn < 2n ** 128n)) throw new Error("stock sell: the amount is out of bounds");
|
|
185
|
+
if (!(minOut > 0n)) throw new Error("stock sell: a minimum out is required");
|
|
186
|
+
const to = getAddress(account), dl = BigInt(deadline);
|
|
187
|
+
const spender = p.v === 4 ? conf.v4.swapper : conf.v3.router;
|
|
188
|
+
const approve = { to: t.token, data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [spender, amountIn] }) };
|
|
189
|
+
// the token in: on v4, zeroForOne exactly when the token is currency0, at that direction's extreme limit
|
|
190
|
+
if (p.v === 4) { const z = !p.zeroForOne; return [approve, { to: spender, data: encodeFunctionData({ abi: SWAPPER_ABI, functionName: "swapExactIn", args: [p.key, z, amountIn, minOut, limitFor(z), to, dl] }) }]; }
|
|
191
|
+
const inner = encodeFunctionData({ abi: EXACT_INPUT_ABI, functionName: "exactInputSingle", args: [{ tokenIn: t.token, tokenOut: conf.usdg, fee: p.fee, recipient: to, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n }] });
|
|
192
|
+
return [approve, { to: spender, data: encodeFunctionData({ abi: ROUTER_ABI, functionName: "multicall", args: [dl, [inner]] }) }];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The pool id a V4SwapOnce.swapExactIn call names (lower case), or null when `data` is not one. */
|
|
196
|
+
export function swapKeyId(data) {
|
|
197
|
+
try { const d = decodeFunctionData({ abi: SWAPPER_ABI, data }); return d.functionName === "swapExactIn" ? v4Id(d.args[0]) : null; } catch (_) { return null; }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The gate's check of a stock swap call to `to` (V4SwapOnce or SwapRouter02) for `sender`: the one function, exactly
|
|
201
|
+
* re-encoded, a record pool, USDG in, the account itself paid, a minimum out above 0, no price limit short of a full
|
|
202
|
+
* fill, 0 < amountIn ≤ maxUsdgPerOp, now < deadline ≤ now + maxDeadlineS. Returns { kind ("v4" | "v3"), symbol, usdgIn,
|
|
203
|
+
* minOut, spender }; throws with the reason. */
|
|
204
|
+
export function checkZapCall(to, data, sender, { now = Math.floor(Date.now() / 1000), conf = ZAP } = {}) {
|
|
205
|
+
const bounds = (amountIn, deadline) => {
|
|
206
|
+
if (!(amountIn > 0n)) throw new Error("stock buy: no USDG in");
|
|
207
|
+
if (amountIn > conf.maxUsdgPerOp) throw new Error(`stock buy: at most ${conf.maxUsdgPerOp / 1_000_000n} USDG a buy`);
|
|
208
|
+
if (deadline <= BigInt(now) || deadline > BigInt(now + conf.maxDeadlineS)) throw new Error(`stock buy: the deadline must be ahead, at most ${conf.maxDeadlineS} s`);
|
|
209
|
+
};
|
|
210
|
+
const exact = (abi, d, raw) => { if (encodeFunctionData({ abi, functionName: d.functionName, args: d.args }).toLowerCase() !== String(raw).toLowerCase()) throw new Error("stock buy: malformed call"); };
|
|
211
|
+
if (same(to, conf.v4.swapper)) {
|
|
212
|
+
let d;
|
|
213
|
+
try { d = decodeFunctionData({ abi: SWAPPER_ABI, data }); } catch (_) { throw new Error("stock buy: only V4SwapOnce's swapExactIn"); }
|
|
214
|
+
if (d.functionName !== "swapExactIn") throw new Error("stock buy: only V4SwapOnce's swapExactIn");
|
|
215
|
+
exact(SWAPPER_ABI, d, data);
|
|
216
|
+
const [key, zeroForOne, amountIn, minOut, limit, recipient, deadline] = d.args;
|
|
217
|
+
const p = conf.v4ById.get(v4Id(key));
|
|
218
|
+
if (!p) throw new Error("stock buy: only the record's pools");
|
|
219
|
+
if (zeroForOne !== p.zeroForOne) throw new Error("stock buy: USDG in, the stock token out only");
|
|
220
|
+
if (!same(recipient, sender)) throw new Error("stock buy: the account itself must receive the tokens");
|
|
221
|
+
if (!(minOut > 0n)) throw new Error("stock buy: a minimum out is required");
|
|
222
|
+
if (limit !== limitFor(p.zeroForOne)) throw new Error("stock buy: the swap must fill in full (no price limit)");
|
|
223
|
+
bounds(amountIn, deadline);
|
|
224
|
+
return { kind: "v4", symbol: p.symbol, usdgIn: amountIn, minOut, spender: conf.v4.swapper };
|
|
225
|
+
}
|
|
226
|
+
if (same(to, conf.v3.router)) {
|
|
227
|
+
let d, e;
|
|
228
|
+
try { d = decodeFunctionData({ abi: ROUTER_ABI, data }); } catch (_) { throw new Error("stock buy: only SwapRouter02's multicall(deadline, [exactInputSingle])"); }
|
|
229
|
+
exact(ROUTER_ABI, d, data);
|
|
230
|
+
const [deadline, calls] = d.args;
|
|
231
|
+
if (calls.length !== 1) throw new Error("stock buy: one exactInputSingle in the multicall");
|
|
232
|
+
try { e = decodeFunctionData({ abi: EXACT_INPUT_ABI, data: calls[0] }); } catch (_) { throw new Error("stock buy: only exactInputSingle inside the multicall"); }
|
|
233
|
+
exact(EXACT_INPUT_ABI, e, calls[0]);
|
|
234
|
+
const x = e.args[0];
|
|
235
|
+
if (!same(x.tokenIn, conf.usdg)) throw new Error("stock buy: USDG in, the stock token out only");
|
|
236
|
+
const p = conf.v3ByPair.get(`${String(x.tokenOut).toLowerCase()}:${Number(x.fee)}`);
|
|
237
|
+
if (!p) throw new Error("stock buy: only the record's pools");
|
|
238
|
+
if (!same(x.recipient, sender)) throw new Error("stock buy: the account itself must receive the tokens");
|
|
239
|
+
if (!(x.amountOutMinimum > 0n)) throw new Error("stock buy: a minimum out is required");
|
|
240
|
+
if (x.sqrtPriceLimitX96 !== 0n) throw new Error("stock buy: the swap must fill in full (no price limit)");
|
|
241
|
+
bounds(x.amountIn, deadline);
|
|
242
|
+
return { kind: "v3", symbol: p.symbol, usdgIn: x.amountIn, minOut: x.amountOutMinimum, spender: conf.v3.router };
|
|
243
|
+
}
|
|
244
|
+
throw new Error("stock buy: not a stock buy's contract");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const Q96 = 2n ** 96n;
|
|
248
|
+
/** Price impact in bps (floored at 0): 1 − out / ideal, where ideal is usdgIn less the pool's fee at the pool's price
|
|
249
|
+
* now (sqrtPriceX96: token1 per token0 in raw units), in bigints. */
|
|
250
|
+
export function impactBps({ usdgIn, out, sqrtPriceX96, fee, usdgIsToken0 }) {
|
|
251
|
+
const s2 = BigInt(sqrtPriceX96) ** 2n, net = BigInt(usdgIn) * (1_000_000n - BigInt(fee));
|
|
252
|
+
if (s2 === 0n || net <= 0n) return 0;
|
|
253
|
+
// ideal = num / den
|
|
254
|
+
const [num, den] = usdgIsToken0 ? [net * s2, 1_000_000n * Q96 * Q96] : [net * Q96 * Q96, 1_000_000n * s2];
|
|
255
|
+
const gap = num - BigInt(out) * den;
|
|
256
|
+
return gap <= 0n ? 0 : Number((gap * 10_000n) / num);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The pinned pools' quotes for a buy of `usdgIn` USDG of `symbol`, read at one block (the latest when asked):
|
|
260
|
+
* { block, at, best: { pool, out, minOut, impactBps } | null, quotes: [{ pool, out | null }], answer, updatedAt,
|
|
261
|
+
* paused, allPaused, blocked, usdg, held }. `client` is a viem public client. A token not in the record is refused
|
|
262
|
+
* before any read. */
|
|
263
|
+
export async function quoteZap(client, { symbol, usdgIn, account = null, slippageBps = null }, conf = ZAP) {
|
|
264
|
+
const t = conf.bySymbol.get(symbol);
|
|
265
|
+
if (!t) throw new Error(`stock buy: ${symbol} is not offered`);
|
|
266
|
+
usdgIn = BigInt(usdgIn);
|
|
267
|
+
const b = await client.getBlock();
|
|
268
|
+
const blockNumber = b.number;
|
|
269
|
+
const who = account ? getAddress(account) : ZERO;
|
|
270
|
+
const contracts = [
|
|
271
|
+
{ address: conf.usdg, abi: ERC20_ABI, functionName: "balanceOf", args: [who] },
|
|
272
|
+
{ address: t.token, abi: ERC20_ABI, functionName: "balanceOf", args: [who] },
|
|
273
|
+
{ address: t.token, abi: READS_ABI, functionName: "tokenPaused" },
|
|
274
|
+
{ address: conf.registry, abi: READS_ABI, functionName: "paused" },
|
|
275
|
+
{ address: conf.registry, abi: READS_ABI, functionName: "isBlocked", args: [who] },
|
|
276
|
+
{ address: t.feed, abi: READS_ABI, functionName: "latestRoundData" },
|
|
277
|
+
...t.pools.map((p) => (p.v === 4 ? { address: conf.v4.stateView, abi: READS_ABI, functionName: "getSlot0", args: [p.id] } : { address: p.pool, abi: READS_ABI, functionName: "slot0" })),
|
|
278
|
+
];
|
|
279
|
+
const r = await client.multicall({ contracts, allowFailure: true, blockNumber });
|
|
280
|
+
const v = (i) => (r[i] && r[i].status === "success" ? r[i].result : null);
|
|
281
|
+
const quotes = await Promise.all(t.pools.map(async (p, i) => {
|
|
282
|
+
try {
|
|
283
|
+
const out = p.v === 4
|
|
284
|
+
? (await client.simulateContract({ address: conf.v4.quoter, abi: V4_QUOTER_ABI, functionName: "quoteExactInputSingle", args: [{ poolKey: p.key, zeroForOne: p.zeroForOne, exactAmount: usdgIn, hookData: "0x" }], blockNumber })).result[0]
|
|
285
|
+
: (await client.simulateContract({ address: conf.v3.quoter, abi: V3_QUOTER_ABI, functionName: "quoteExactInputSingle", args: [{ tokenIn: conf.usdg, tokenOut: t.token, amountIn: usdgIn, fee: p.fee, sqrtPriceLimitX96: 0n }], blockNumber })).result[0];
|
|
286
|
+
const s0 = v(6 + i);
|
|
287
|
+
return { pool: p, out, impactBps: s0 ? impactBps({ usdgIn, out, sqrtPriceX96: s0[0], fee: p.fee, usdgIsToken0: p.zeroForOne }) : null };
|
|
288
|
+
} catch (_) { return { pool: p, out: null, impactBps: null }; }
|
|
289
|
+
}));
|
|
290
|
+
const ok = quotes.filter((q) => q.out !== null && q.out > 0n);
|
|
291
|
+
const best = ok.length ? ok.reduce((a, q) => (q.out > a.out ? q : a)) : null;
|
|
292
|
+
const round = v(5);
|
|
293
|
+
return {
|
|
294
|
+
block: blockNumber, at: Number(b.timestamp), symbol, usdgIn, quotes,
|
|
295
|
+
best: best ? { ...best, minOut: minOutOf(best.out, slippageBps ?? conf.defaultSlippageBps, conf) } : null,
|
|
296
|
+
answer: round ? round[1] : null, updatedAt: round ? Number(round[3]) : null,
|
|
297
|
+
paused: v(2), allPaused: v(3), blocked: account ? v(4) : null, usdg: account ? v(0) : null, held: account ? v(1) : null,
|
|
298
|
+
};
|
|
299
|
+
}
|