@nuluvium/mcp 0.1.1 → 0.2.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/dist/mcp/src/engine.js +4 -5
- package/dist/mcp/src/networks.js +3 -3
- package/dist/mcp/src/server.js +12 -2
- package/dist/sdk/src/config.js +6 -2
- package/dist/sdk/src/exit.js +20 -4
- package/dist/sdk/src/index.js +5 -3
- package/dist/sdk/src/quote.js +49 -0
- package/dist/sdk/src/relayer.js +173 -37
- package/dist/sdk/src/routing.js +9 -7
- package/package.json +3 -3
package/dist/mcp/src/engine.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Runs orders in the background: each piece at its time, pieces of one order one after another.
|
|
2
2
|
// Before every piece the note is rebuilt from the chain, so restarts and partial runs are safe.
|
|
3
3
|
import { parseAbi } from "viem";
|
|
4
|
-
import { executePiece, fetchApprovedSet, publicClientFor, recoverNotes, } from "../../sdk/src/index.js";
|
|
4
|
+
import { executePiece, fetchApprovedSet, publicClientFor, quotedBuy, recoverNotes, } from "../../sdk/src/index.js";
|
|
5
5
|
import { createFolderProver } from "../../sdk/src/node.js";
|
|
6
6
|
const balanceAbi = parseAbi(["function balanceOf(address) view returns (uint256)"]);
|
|
7
7
|
const MAX_ATTEMPTS = 3;
|
|
@@ -100,10 +100,8 @@ export class Engine {
|
|
|
100
100
|
const amount = BigInt(piece.amount);
|
|
101
101
|
if (amount > note.value)
|
|
102
102
|
throw new Error(`note holds ${note.value}, piece needs ${amount}`);
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
minAmountOut: (usdgIn) => (token.expectedOut(usdgIn) * BigInt(10_000 - order.slippageBps)) / 10000n,
|
|
106
|
-
});
|
|
103
|
+
const target = quotedBuy(this.ctx.client, this.ctx.config, token.address, order.slippageBps);
|
|
104
|
+
const { result } = await executePiece(this.ctx, note, number, amount, target);
|
|
107
105
|
const receipt = await this.ctx.client.waitForTransactionReceipt({ hash: result.tx });
|
|
108
106
|
const received = await this.ctx.client.readContract({
|
|
109
107
|
address: token.address,
|
|
@@ -117,6 +115,7 @@ export class Engine {
|
|
|
117
115
|
tx: result.tx,
|
|
118
116
|
fresh: result.fresh,
|
|
119
117
|
fee: result.fee.toString(),
|
|
118
|
+
protocolFee: result.protocolFee.toString(),
|
|
120
119
|
received: received.toString(),
|
|
121
120
|
sentAt: Math.floor(Date.now() / 1000),
|
|
122
121
|
error: undefined,
|
package/dist/mcp/src/networks.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
// Networks and tradable tokens. Only allowlisted tokens can be routed.
|
|
1
|
+
// Networks and tradable tokens. Only allowlisted tokens can be routed. Minimum outputs come from a
|
|
2
|
+
// QuoterV2 quote at the Router's fee tier for every piece (SDK quotedBuy); on testnet the quoter is
|
|
3
|
+
// a stand-in for the fixed-price mock router.
|
|
2
4
|
import { ROBINHOOD_TESTNET } from "../../sdk/src/index.js";
|
|
3
|
-
const MOCK_USDG_PER_STOCK = 180000000n; // contracts/deployments/46630-router.json
|
|
4
5
|
export const NETWORKS = {
|
|
5
6
|
"robinhood-testnet": {
|
|
6
7
|
name: "Robinhood Chain testnet",
|
|
@@ -13,7 +14,6 @@ export const NETWORKS = {
|
|
|
13
14
|
symbol: "MSTK",
|
|
14
15
|
address: "0xf2a0289ec25994dC7d22461Afd1dF3B818A0E088",
|
|
15
16
|
decimals: 18,
|
|
16
|
-
expectedOut: (usdgIn) => (usdgIn * 10n ** 18n) / MOCK_USDG_PER_STOCK,
|
|
17
17
|
note: "Testnet mock stock at a fixed price of 180 tUSDG (no official Uniswap on testnet).",
|
|
18
18
|
},
|
|
19
19
|
},
|
package/dist/mcp/src/server.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Nuluvium MCP server (stdio). Runs on the agent's own machine: the secret, the notes and the
|
|
3
|
-
// order schedule never leave it. Pieces are sent through the
|
|
3
|
+
// order schedule never leave it. Pieces are sent through the relayers active in the RelayerRegistry
|
|
4
|
+
// (another one when one is down or refuses) to Router v2, which takes the relayer gas fee and a 0.1%
|
|
5
|
+
// protocol fee from the USDG of each piece. The agent never holds or pays NLV.
|
|
4
6
|
//
|
|
5
7
|
// Environment:
|
|
6
8
|
// NULUVIUM_MNEMONIC required. The agent's secret (BIP-39). Never printed or returned.
|
|
7
9
|
// NULUVIUM_NETWORK default "robinhood-testnet"
|
|
8
10
|
// NULUVIUM_RPC_URL optional own RPC (may hold an API key; never printed)
|
|
9
11
|
// NULUVIUM_LOG_CHUNK blocks per log query with NULUVIUM_RPC_URL (default 10000, Alchemy limit)
|
|
12
|
+
// NULUVIUM_RELAYERS optional comma-separated relayer URLs instead of the registry's list (each
|
|
13
|
+
// must still be active in the RelayerRegistry, or Router v2 refuses its pieces)
|
|
10
14
|
// NULUVIUM_HOME default ~/.nuluvium (order schedule; local only)
|
|
11
15
|
// NULUVIUM_ARTIFACTS circuit files folder. Default: testnet/artifacts when run from the source
|
|
12
16
|
// tree with the files there, else ~/.nuluvium/artifacts (downloaded once)
|
|
@@ -49,6 +53,10 @@ const network = rpcOverride
|
|
|
49
53
|
}
|
|
50
54
|
: baseNetwork;
|
|
51
55
|
delete process.env.NULUVIUM_RPC_URL; // may contain an API key
|
|
56
|
+
// Own relayer list (e.g. a relayer the agent runs itself); failover works across all of them.
|
|
57
|
+
const relayerOverride = process.env.NULUVIUM_RELAYERS?.split(",").map((url) => url.trim().replace(/\/$/, "")).filter(Boolean);
|
|
58
|
+
if (relayerOverride?.length)
|
|
59
|
+
network.config = { ...network.config, relayerUrls: relayerOverride, registry: undefined };
|
|
52
60
|
const home = process.env.NULUVIUM_HOME ?? join(homedir(), ".nuluvium");
|
|
53
61
|
const sourceArtifacts = fileURLToPath(new URL("../../testnet/artifacts", import.meta.url));
|
|
54
62
|
const artifacts = process.env.NULUVIUM_ARTIFACTS ??
|
|
@@ -182,7 +190,7 @@ server.registerTool("route_order", {
|
|
|
182
190
|
usdgAmount: z.number().positive().describe("Total USDG to spend"),
|
|
183
191
|
pieces: z.number().int().min(1).max(20).default(5).describe("How many pieces (1 to 20)"),
|
|
184
192
|
windowMinutes: z.number().min(1).max(1440).default(10).describe("Spread the pieces over this many minutes"),
|
|
185
|
-
maxSlippagePercent: z.number().min(0.1).max(5).default(1).describe("Worst price accepted per piece, in percent"),
|
|
193
|
+
maxSlippagePercent: z.number().min(0.1).max(5).default(1).describe("Worst price accepted per piece, in percent below a fresh Uniswap quote (the relayer refuses more than 5)"),
|
|
186
194
|
},
|
|
187
195
|
}, safe(async ({ token, usdgAmount, pieces, windowMinutes, maxSlippagePercent }) => {
|
|
188
196
|
const target = network.tokens[token.toUpperCase()];
|
|
@@ -255,6 +263,8 @@ server.registerTool("get_fills", {
|
|
|
255
263
|
piece: piece.number,
|
|
256
264
|
spent: usdg(piece.amount),
|
|
257
265
|
relayerFee: usdg(piece.fee ?? "0"),
|
|
266
|
+
// 0.1% of the piece (Router v2); absent on pieces sent before it
|
|
267
|
+
protocolFee: piece.protocolFee === undefined ? undefined : usdg(piece.protocolFee),
|
|
258
268
|
received: `${formatUnits(BigInt(piece.received ?? "0"), token.decimals)} ${token.symbol}`,
|
|
259
269
|
freshAddress: piece.fresh,
|
|
260
270
|
transaction: `${network.explorer}/tx/${piece.tx}`,
|
package/dist/sdk/src/config.js
CHANGED
|
@@ -8,7 +8,11 @@ export const ROBINHOOD_TESTNET = {
|
|
|
8
8
|
usdg: "0xd26d58F86cf82c702b558D6E7F159939E97F0Bfa",
|
|
9
9
|
scope: 20883339666151915200592145183006062909365231028523521475069391119255857699183n,
|
|
10
10
|
deployBlock: 153603397n,
|
|
11
|
-
router: "
|
|
12
|
-
|
|
11
|
+
router: "0x2A97D783811ADa610223CeBD56d77d72306F0B9e",
|
|
12
|
+
previousRouters: ["0x3287C2947f137c20c8BfeB628f800D23b8e5D155"],
|
|
13
|
+
registry: "0xcF69fE69E3B273f66F589c5f912f347144316bB0",
|
|
14
|
+
protocolFeeBps: 10n,
|
|
15
|
+
quoter: "0x42093B3DAb22760EF67849984A81084E564f728e",
|
|
16
|
+
relayerUrls: ["https://relayer.nuluvium.com", "https://relayer2.nuluvium.com"],
|
|
13
17
|
aspUrl: "https://asp.nuluvium.com",
|
|
14
18
|
};
|
package/dist/sdk/src/exit.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// sell a fresh address sells stock tokens for USDG through the Router, gasless: it signs an
|
|
6
6
|
// order and a permit, the relayer sends Router.swap and takes its fee from the USDG.
|
|
7
7
|
import { parseAbi } from "viem";
|
|
8
|
+
import { quotedSellMinimum } from "./quote.js";
|
|
8
9
|
import { getQuote, sendSell, signOrder, signPermit } from "./relayer.js";
|
|
9
10
|
import { randomNonce } from "./routing.js";
|
|
10
11
|
// JSON form: abitype cannot type the nested fixed array (uint256[2][2]) from the human-readable form.
|
|
@@ -73,12 +74,27 @@ export async function ragequitNote(client, wallet, config, prover, note) {
|
|
|
73
74
|
const SELL_DEADLINE_SECONDS = 15 * 60;
|
|
74
75
|
/**
|
|
75
76
|
* Sells `amountIn` of `token` held by a fresh address for USDG, which stays on that address.
|
|
76
|
-
* @param minUsdgOut smallest USDG the owner accepts after the relayer
|
|
77
|
+
* @param minUsdgOut smallest USDG the owner accepts after the relayer and protocol fees
|
|
77
78
|
*/
|
|
78
79
|
export async function sellFromFresh(client, config, fresh, token, amountIn, minUsdgOut) {
|
|
79
80
|
if (amountIn <= 0n)
|
|
80
81
|
throw new Error("nothing to sell");
|
|
81
|
-
|
|
82
|
+
return signAndSendSell(client, config, fresh, token, amountIn, minUsdgOut, await getQuote(config, client));
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Sells `amountIn` of `token` at a fresh Uniswap quote less `slippageBps` (and less room for the
|
|
86
|
+
* relayer and protocol fees). Refuses when the holding is worth less than those fees.
|
|
87
|
+
*/
|
|
88
|
+
export async function sellAtQuote(client, config, fresh, token, amountIn, slippageBps) {
|
|
89
|
+
if (amountIn <= 0n)
|
|
90
|
+
throw new Error("nothing to sell");
|
|
91
|
+
const quote = await getQuote(config, client);
|
|
92
|
+
const { quoted, minimum } = await quotedSellMinimum(client, config, token, amountIn, quote.fee, slippageBps);
|
|
93
|
+
if (minimum <= 0n)
|
|
94
|
+
throw new Error("holding is worth less than the relayer and protocol fees");
|
|
95
|
+
return { ...(await signAndSendSell(client, config, fresh, token, amountIn, minimum, quote)), quoted };
|
|
96
|
+
}
|
|
97
|
+
async function signAndSendSell(client, config, fresh, token, amountIn, minUsdgOut, quote) {
|
|
82
98
|
const deadline = BigInt(Math.floor(Date.now() / 1000) + SELL_DEADLINE_SECONDS);
|
|
83
99
|
const order = {
|
|
84
100
|
owner: fresh.address,
|
|
@@ -94,6 +110,6 @@ export async function sellFromFresh(client, config, fresh, token, amountIn, minU
|
|
|
94
110
|
signOrder(fresh, config, order),
|
|
95
111
|
signPermit(fresh, client, config, token, config.router, amountIn, deadline),
|
|
96
112
|
]);
|
|
97
|
-
const sent = await sendSell(config, { order, orderSignature, permit
|
|
98
|
-
return { tx: sent.tx, fee:
|
|
113
|
+
const sent = await sendSell(config, quote, { order, orderSignature, permit });
|
|
114
|
+
return { tx: sent.tx, fee: sent.fee };
|
|
99
115
|
}
|
package/dist/sdk/src/index.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// planner random piece sizes and times inside a window
|
|
5
5
|
// proof withdrawal proofs (Privacy Pools v1 circuits); Node folder prover in ./node.ts
|
|
6
6
|
// asp the approved set, checked against its CID and the on-chain root
|
|
7
|
-
// relayer quote, order and permit signatures, piece submission
|
|
7
|
+
// relayer relayers from the registry, quote, order and permit signatures, piece submission (fails over)
|
|
8
|
+
// quote minimum outputs from a Uniswap v3 quote (QuoterV2) at the Router's fee tier
|
|
8
9
|
// routing one piece end to end, or a whole plan on schedule
|
|
9
10
|
// exit ragequit a deposit back to its wallet; sell a fresh address's tokens for USDG
|
|
10
11
|
export { ROBINHOOD_TESTNET } from "./config.js";
|
|
@@ -13,8 +14,9 @@ export { changeSecrets, depositSecrets, noteAfterWithdrawal, nullifierHash, reco
|
|
|
13
14
|
export { planPieces, secureRandom } from "./planner.js";
|
|
14
15
|
export { createUrlProver, formatProof, proveWithdrawal } from "./proof.js";
|
|
15
16
|
export { cidDigestHex, fetchApprovedSet, rootOf } from "./asp.js";
|
|
16
|
-
export { RelayerError, getQuote, sendPiece, sendSell, signOrder, signPermit } from "./relayer.js";
|
|
17
|
+
export { RelayerError, clearRelayerCache, getQuote, listRelayers, markRelayerFailed, markRelayerOk, protocolFeeFor, quoteFrom, registryEntries, relayerOrder, sendPiece, sendSell, signOrder, signPermit, } from "./relayer.js";
|
|
18
|
+
export { quoteSwap, quotedBuy, quotedSellMinimum, quoterAbi, withSlippage } from "./quote.js";
|
|
17
19
|
export { executePiece, randomNonce, runPlan } from "./routing.js";
|
|
18
20
|
export { depositUsdg } from "./deposit.js";
|
|
19
|
-
export { proveRagequit, ragequitAbi, ragequitNote, sellFromFresh } from "./exit.js";
|
|
21
|
+
export { proveRagequit, ragequitAbi, ragequitNote, sellAtQuote, sellFromFresh } from "./exit.js";
|
|
20
22
|
export { chainFor, erc20Abi, publicClientFor, walletClientFor } from "./chain.js";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Minimum outputs from a Uniswap v3 quote (QuoterV2.quoteExactInputSingle) at the fee tier the
|
|
2
|
+
// Router will swap on. The quote is an eth_call; nothing is sent. The relayer runs the same quote
|
|
3
|
+
// and refuses a piece whose minimum is far below it (relayer/src/bound.js).
|
|
4
|
+
import { parseAbi } from "viem";
|
|
5
|
+
export const quoterAbi = parseAbi([
|
|
6
|
+
"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; uint24 fee; uint160 sqrtPriceLimitX96; }",
|
|
7
|
+
"function quoteExactInputSingle(QuoteExactInputSingleParams params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)",
|
|
8
|
+
]);
|
|
9
|
+
const routerPoolFeeAbi = parseAbi(["function poolFee(address token) view returns (uint24)"]);
|
|
10
|
+
/** Basis points in one whole. */
|
|
11
|
+
const BPS = 10000n;
|
|
12
|
+
/** `amount` less `slippageBps` (rounded down). */
|
|
13
|
+
export function withSlippage(amount, slippageBps) {
|
|
14
|
+
if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps >= 10_000)
|
|
15
|
+
throw new Error("slippage must be 0 to 9,999 basis points");
|
|
16
|
+
return (amount * (BPS - BigInt(slippageBps))) / BPS;
|
|
17
|
+
}
|
|
18
|
+
/** Output of swapping `amountIn` of `tokenIn` for `tokenOut` on the Router's pool, quoted now. */
|
|
19
|
+
export async function quoteSwap(client, config, tokenIn, tokenOut, amountIn) {
|
|
20
|
+
const stock = tokenIn.toLowerCase() === config.usdg.toLowerCase() ? tokenOut : tokenIn;
|
|
21
|
+
const fee = await client.readContract({ address: config.router, abi: routerPoolFeeAbi, functionName: "poolFee", args: [stock] });
|
|
22
|
+
if (fee === 0)
|
|
23
|
+
throw new Error("token is not listed on the Router");
|
|
24
|
+
const { result } = await client.simulateContract({
|
|
25
|
+
address: config.quoter,
|
|
26
|
+
abi: quoterAbi,
|
|
27
|
+
functionName: "quoteExactInputSingle",
|
|
28
|
+
args: [{ tokenIn, tokenOut, amountIn, fee, sqrtPriceLimitX96: 0n }],
|
|
29
|
+
});
|
|
30
|
+
return result[0];
|
|
31
|
+
}
|
|
32
|
+
/** Buy target whose minimum is a fresh quote for each piece, less `slippageBps`. */
|
|
33
|
+
export function quotedBuy(client, config, tokenOut, slippageBps) {
|
|
34
|
+
return {
|
|
35
|
+
tokenOut,
|
|
36
|
+
minAmountOut: async (usdgIn) => withSlippage(await quoteSwap(client, config, config.usdg, tokenOut, usdgIn), slippageBps),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Smallest USDG a sell of `amountIn` accepts after the fees: the quote less slippage, less twice the
|
|
41
|
+
* quoted relayer fee (the order lets that fee rise up to it before the relayer sends) and less the
|
|
42
|
+
* protocol fee on the quote (Router v2 takes it from the USDG the swap brings).
|
|
43
|
+
* Returns 0 or less when the holding is worth less than the fees.
|
|
44
|
+
*/
|
|
45
|
+
export async function quotedSellMinimum(client, config, token, amountIn, quotedFee, slippageBps) {
|
|
46
|
+
const quoted = await quoteSwap(client, config, token, config.usdg, amountIn);
|
|
47
|
+
const protocolFee = (quoted * config.protocolFeeBps) / BPS;
|
|
48
|
+
return { quoted, minimum: withSlippage(quoted, slippageBps) - quotedFee * 2n - protocolFee };
|
|
49
|
+
}
|
package/dist/sdk/src/relayer.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
// Talks to the Nuluvium
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
// Talks to the Nuluvium relayers and signs what the fresh address must sign (order + permit).
|
|
2
|
+
// Relayers come from the RelayerRegistry (bonded with NLV; tNLV on testnet); orders go to Router v2,
|
|
3
|
+
// which pays the sending relayer its gas fee plus half of the 0.1% protocol fee (the rest to the
|
|
4
|
+
// treasury Safe). Traders never hold or pay NLV: both fees come out of the USDG side of the piece.
|
|
5
|
+
import { parseAbi, parseSignature } from "viem";
|
|
6
|
+
import { erc20Abi, publicClientFor } from "./chain.js";
|
|
7
|
+
/** Protocol fee the Router takes from `usdgAmount` (Router v2 protocolFeeFor: rounded down). */
|
|
8
|
+
export function protocolFeeFor(config, usdgAmount) {
|
|
9
|
+
return (usdgAmount * config.protocolFeeBps) / 10000n;
|
|
10
|
+
}
|
|
4
11
|
export class RelayerError extends Error {
|
|
5
12
|
status;
|
|
6
13
|
constructor(status, message) {
|
|
@@ -8,18 +15,168 @@ export class RelayerError extends Error {
|
|
|
8
15
|
this.status = status;
|
|
9
16
|
}
|
|
10
17
|
}
|
|
11
|
-
|
|
12
|
-
|
|
18
|
+
/* ------------------------------------------------------------------ relayer registry */
|
|
19
|
+
const registryAbi = parseAbi([
|
|
20
|
+
"struct ListedRelayer { address relayer; string url; uint256 bond; }",
|
|
21
|
+
"function activeRelayers() view returns (ListedRelayer[])",
|
|
22
|
+
]);
|
|
23
|
+
/** How long a registry read is reused (per process or per tab). */
|
|
24
|
+
const REGISTRY_CACHE_MS = 5 * 60_000;
|
|
25
|
+
let registryCache = null;
|
|
26
|
+
/** Registry rows as relayer entries: https URLs only, no trailing slash, one entry per URL. */
|
|
27
|
+
export function registryEntries(rows) {
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
const entries = [];
|
|
30
|
+
for (const row of rows) {
|
|
31
|
+
const url = row.url.trim().replace(/\/+$/, "");
|
|
32
|
+
if (!/^https:\/\/[^\s/?#]+(\/[^\s?#]*)?$/.test(url) || seen.has(url))
|
|
33
|
+
continue;
|
|
34
|
+
seen.add(url);
|
|
35
|
+
entries.push({ url, address: row.relayer });
|
|
36
|
+
}
|
|
37
|
+
return entries;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The relayers to try: the active ones in the RelayerRegistry, or `config.relayerUrls` when the
|
|
41
|
+
* registry is unset, cannot be read or lists none (so a registry outage does not stop pieces).
|
|
42
|
+
*/
|
|
43
|
+
export async function listRelayers(config, client, now = Date.now()) {
|
|
44
|
+
const fallback = config.relayerUrls.map((url) => ({ url }));
|
|
45
|
+
if (!config.registry)
|
|
46
|
+
return fallback;
|
|
47
|
+
const key = `${config.chainId}:${config.registry}:${config.rpcUrl}`;
|
|
48
|
+
if (registryCache?.key === key && now - registryCache.at < REGISTRY_CACHE_MS)
|
|
49
|
+
return registryCache.entries;
|
|
50
|
+
try {
|
|
51
|
+
const rows = await (client ?? publicClientFor(config)).readContract({ address: config.registry, abi: registryAbi, functionName: "activeRelayers" });
|
|
52
|
+
const entries = registryEntries(rows);
|
|
53
|
+
if (entries.length === 0)
|
|
54
|
+
return fallback;
|
|
55
|
+
registryCache = { key, at: now, entries };
|
|
56
|
+
return entries;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return fallback;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Forgets the cached registry read (tests, or after a relayer was removed). */
|
|
63
|
+
export function clearRelayerCache() {
|
|
64
|
+
registryCache = null;
|
|
65
|
+
}
|
|
66
|
+
/* ------------------------------------------------------------------ several relayers */
|
|
67
|
+
/** How long a relayer that failed is tried last (it is still tried if all others fail too). */
|
|
68
|
+
const SKIP_AFTER_FAILURE_MS = 2 * 60_000;
|
|
69
|
+
const QUOTE_TIMEOUT_MS = 8_000;
|
|
70
|
+
/** A piece waits for its receipt on the relayer (up to 60 s), so the request gets longer. */
|
|
71
|
+
const SEND_TIMEOUT_MS = 90_000;
|
|
72
|
+
/** Relayer URL → time it last failed. Per process (MCP server) or per tab (web app). */
|
|
73
|
+
const failedAt = new Map();
|
|
74
|
+
export function markRelayerFailed(url, now = Date.now()) {
|
|
75
|
+
failedAt.set(url, now);
|
|
76
|
+
}
|
|
77
|
+
export function markRelayerOk(url) {
|
|
78
|
+
failedAt.delete(url);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The order to try the relayers in: random (so no single relayer sees every piece of an order),
|
|
82
|
+
* with relayers that failed in the last two minutes moved to the end.
|
|
83
|
+
*/
|
|
84
|
+
export function relayerOrder(urls, { now = Date.now(), random = Math.random } = {}) {
|
|
85
|
+
const shuffled = [...urls];
|
|
86
|
+
for (let i = shuffled.length - 1; i > 0; i--) {
|
|
87
|
+
const j = Math.floor(random() * (i + 1));
|
|
88
|
+
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
|
89
|
+
}
|
|
90
|
+
const recentlyFailed = (url) => now - (failedAt.get(url) ?? Number.NEGATIVE_INFINITY) < SKIP_AFTER_FAILURE_MS;
|
|
91
|
+
return [...shuffled.filter((url) => !recentlyFailed(url)), ...shuffled.filter(recentlyFailed)];
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Fee quote from one relayer. Checks it sends to the same Router as `config` and, for a relayer
|
|
95
|
+
* from the registry, that it signs with the address that bonded (the Router refuses any other).
|
|
96
|
+
*/
|
|
97
|
+
export async function quoteFrom(config, url, expectedRelayer) {
|
|
98
|
+
let response;
|
|
99
|
+
try {
|
|
100
|
+
response = await fetch(`${url}/quote`, { signal: AbortSignal.timeout(QUOTE_TIMEOUT_MS) });
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw new RelayerError(0, `relayer ${url} did not answer`);
|
|
104
|
+
}
|
|
13
105
|
if (!response.ok)
|
|
14
|
-
throw new RelayerError(response.status,
|
|
106
|
+
throw new RelayerError(response.status, `relayer ${url} quote failed`);
|
|
15
107
|
const body = (await response.json());
|
|
16
108
|
if (body.router.toLowerCase() !== config.router.toLowerCase())
|
|
17
|
-
throw new
|
|
18
|
-
|
|
109
|
+
throw new RelayerError(0, `relayer ${url} uses a different Router`);
|
|
110
|
+
if (expectedRelayer && body.relayer.toLowerCase() !== expectedRelayer.toLowerCase()) {
|
|
111
|
+
throw new RelayerError(0, `relayer ${url} is not the address registered for it`);
|
|
112
|
+
}
|
|
113
|
+
if (body.active === false)
|
|
114
|
+
throw new RelayerError(0, `relayer ${url} is not active in the registry`);
|
|
115
|
+
return { url, router: body.router, relayer: body.relayer, fee: BigInt(body.fee), gasCost: BigInt(body.gasCost) };
|
|
19
116
|
}
|
|
117
|
+
/** A quote from the first relayer that answers, in `relayerOrder`. */
|
|
118
|
+
export async function getQuote(config, client) {
|
|
119
|
+
const reasons = [];
|
|
120
|
+
const entries = await listRelayers(config, client);
|
|
121
|
+
const addressOf = new Map(entries.map((entry) => [entry.url, entry.address]));
|
|
122
|
+
for (const url of relayerOrder(entries.map((entry) => entry.url))) {
|
|
123
|
+
try {
|
|
124
|
+
const quote = await quoteFrom(config, url, addressOf.get(url));
|
|
125
|
+
markRelayerOk(url);
|
|
126
|
+
return quote;
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
markRelayerFailed(url);
|
|
130
|
+
reasons.push(error instanceof Error ? error.message : String(error));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
throw new RelayerError(0, `no relayer answered (${reasons.join("; ")})`);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Posts a signed piece or sell to `quote`'s relayer; if that one is down or refuses, to the others.
|
|
137
|
+
* The same signatures and proof work with any relayer: the withdrawal's relay fee is 0, and the
|
|
138
|
+
* Router pays its fee to whoever sends the transaction (it must be active in the registry). Another
|
|
139
|
+
* relayer is asked for its own quote first (same Router, fee within the signed maxFee).
|
|
140
|
+
*/
|
|
141
|
+
async function postWithFailover(config, path, body, quote, maxFee) {
|
|
142
|
+
const reasons = [];
|
|
143
|
+
const entries = await listRelayers(config);
|
|
144
|
+
const addressOf = new Map(entries.map((entry) => [entry.url, entry.address]));
|
|
145
|
+
const others = relayerOrder(entries.map((entry) => entry.url).filter((url) => url !== quote.url));
|
|
146
|
+
for (const url of [quote.url, ...others]) {
|
|
147
|
+
try {
|
|
148
|
+
const fee = url === quote.url ? quote.fee : (await quoteFrom(config, url, addressOf.get(url))).fee;
|
|
149
|
+
if (fee > maxFee)
|
|
150
|
+
throw new RelayerError(0, `relayer ${url} fee is above the signed maximum`);
|
|
151
|
+
let response;
|
|
152
|
+
try {
|
|
153
|
+
response = await fetch(`${url}${path}`, {
|
|
154
|
+
method: "POST",
|
|
155
|
+
headers: { "content-type": "application/json" },
|
|
156
|
+
body: JSON.stringify({ ...body, fee: fee.toString() }),
|
|
157
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
throw new RelayerError(0, `relayer ${url} did not answer`);
|
|
162
|
+
}
|
|
163
|
+
const result = (await response.json().catch(() => ({})));
|
|
164
|
+
if (!response.ok || !result.tx)
|
|
165
|
+
throw new RelayerError(response.status, result.error ?? `relayer ${url} refused`);
|
|
166
|
+
markRelayerOk(url);
|
|
167
|
+
return { tx: result.tx, gasUsed: result.gasUsed ?? "", fee, relayerUrl: url };
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
markRelayerFailed(url);
|
|
171
|
+
reasons.push(error instanceof Error ? error.message : String(error));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
throw new RelayerError(0, reasons.join("; "));
|
|
175
|
+
}
|
|
176
|
+
const stringFields = (order) => Object.fromEntries(Object.entries(order).map(([key, value]) => [key, String(value)]));
|
|
20
177
|
export function signOrder(account, config, order) {
|
|
21
178
|
return account.signTypedData({
|
|
22
|
-
domain: { name: "Nuluvium Router", version: "
|
|
179
|
+
domain: { name: "Nuluvium Router", version: "2", chainId: config.chainId, verifyingContract: config.router },
|
|
23
180
|
types: {
|
|
24
181
|
Order: [
|
|
25
182
|
{ name: "owner", type: "address" },
|
|
@@ -57,41 +214,20 @@ export async function signPermit(account, client, config, token, spender, value,
|
|
|
57
214
|
const v = signature.v ?? BigInt((signature.yParity ?? 0) + 27);
|
|
58
215
|
return { deadline: deadline.toString(), v: v.toString(), r: signature.r, s: signature.s };
|
|
59
216
|
}
|
|
60
|
-
|
|
217
|
+
/** Sends a signed piece (Router.relayAndSwap), failing over to another relayer if needed. */
|
|
218
|
+
export function sendPiece(config, quote, piece) {
|
|
61
219
|
const body = {
|
|
62
220
|
withdrawal: piece.withdrawal,
|
|
63
221
|
proof: piece.proof,
|
|
64
222
|
scope: config.scope.toString(),
|
|
65
|
-
order:
|
|
223
|
+
order: stringFields(piece.order),
|
|
66
224
|
orderSignature: piece.orderSignature,
|
|
67
225
|
permit: piece.permit,
|
|
68
|
-
fee: piece.fee.toString(),
|
|
69
226
|
};
|
|
70
|
-
|
|
71
|
-
method: "POST",
|
|
72
|
-
headers: { "content-type": "application/json" },
|
|
73
|
-
body: JSON.stringify(body),
|
|
74
|
-
});
|
|
75
|
-
const result = (await response.json());
|
|
76
|
-
if (!response.ok || !result.tx)
|
|
77
|
-
throw new RelayerError(response.status, result.error ?? "relayer refused the piece");
|
|
78
|
-
return { tx: result.tx, gasUsed: result.gasUsed ?? "" };
|
|
227
|
+
return postWithFailover(config, "/piece", body, quote, piece.order.maxFee);
|
|
79
228
|
}
|
|
80
229
|
/** Sends a signed sell (stock token → USDG on the same fresh address) through Router.swap. */
|
|
81
|
-
export
|
|
82
|
-
const body = {
|
|
83
|
-
|
|
84
|
-
orderSignature: sell.orderSignature,
|
|
85
|
-
permit: sell.permit,
|
|
86
|
-
fee: sell.fee.toString(),
|
|
87
|
-
};
|
|
88
|
-
const response = await fetch(`${config.relayerUrl}/sell`, {
|
|
89
|
-
method: "POST",
|
|
90
|
-
headers: { "content-type": "application/json" },
|
|
91
|
-
body: JSON.stringify(body),
|
|
92
|
-
});
|
|
93
|
-
const result = (await response.json());
|
|
94
|
-
if (!response.ok || !result.tx)
|
|
95
|
-
throw new RelayerError(response.status, result.error ?? "relayer refused the sell");
|
|
96
|
-
return { tx: result.tx, gasUsed: result.gasUsed ?? "" };
|
|
230
|
+
export function sendSell(config, quote, sell) {
|
|
231
|
+
const body = { order: stringFields(sell.order), orderSignature: sell.orderSignature, permit: sell.permit };
|
|
232
|
+
return postWithFailover(config, "/sell", body, quote, sell.order.maxFee);
|
|
97
233
|
}
|
package/dist/sdk/src/routing.js
CHANGED
|
@@ -6,7 +6,7 @@ import { poolEvents } from "./chain.js";
|
|
|
6
6
|
import { freshAccount } from "./keys.js";
|
|
7
7
|
import { noteAfterWithdrawal } from "./notes.js";
|
|
8
8
|
import { formatProof, proveWithdrawal } from "./proof.js";
|
|
9
|
-
import { getQuote, sendPiece, signOrder, signPermit } from "./relayer.js";
|
|
9
|
+
import { getQuote, protocolFeeFor, sendPiece, signOrder, signPermit } from "./relayer.js";
|
|
10
10
|
const ORDER_DEADLINE_SECONDS = 15 * 60;
|
|
11
11
|
/** Random 64-bit order nonce (the Router only checks it was not used before by this owner). */
|
|
12
12
|
export function randomNonce() {
|
|
@@ -17,9 +17,11 @@ export function randomNonce() {
|
|
|
17
17
|
/** One piece, end to end. Returns the result and the note left afterwards. */
|
|
18
18
|
export async function executePiece(ctx, note, pieceNumber, amount, target) {
|
|
19
19
|
const { config, keys, client, prover } = ctx;
|
|
20
|
-
const quote = await getQuote(config);
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
const quote = await getQuote(config, client);
|
|
21
|
+
// Router v2 swaps what is left after the relayer gas fee and the protocol fee (0.1% of the piece).
|
|
22
|
+
const protocolFee = protocolFeeFor(config, amount);
|
|
23
|
+
if (amount <= quote.fee + protocolFee)
|
|
24
|
+
throw new Error("piece smaller than the relayer and protocol fees");
|
|
23
25
|
const fresh = freshAccount(keys, note.depositIndex, note.withdrawals);
|
|
24
26
|
const [approved, leafLogs] = await Promise.all([fetchApprovedSet(client, config), poolEvents(client, config, "LeafInserted")]);
|
|
25
27
|
const leaves = leafLogs.sort((a, b) => Number(a.args._index - b.args._index)).map((log) => log.args._leaf);
|
|
@@ -31,7 +33,7 @@ export async function executePiece(ctx, note, pieceNumber, amount, target) {
|
|
|
31
33
|
tokenIn: config.usdg,
|
|
32
34
|
tokenOut: target.tokenOut,
|
|
33
35
|
amountIn: amount,
|
|
34
|
-
minAmountOut: await target.minAmountOut(amount - quote.fee),
|
|
36
|
+
minAmountOut: await target.minAmountOut(amount - quote.fee - protocolFee),
|
|
35
37
|
maxFee: quote.fee * 2n, // room for the quote to move before the relayer sends
|
|
36
38
|
nonce: randomNonce(),
|
|
37
39
|
deadline,
|
|
@@ -40,9 +42,9 @@ export async function executePiece(ctx, note, pieceNumber, amount, target) {
|
|
|
40
42
|
signOrder(fresh, config, order),
|
|
41
43
|
signPermit(fresh, client, config, config.usdg, config.router, amount, deadline),
|
|
42
44
|
]);
|
|
43
|
-
const sent = await sendPiece(config, { withdrawal, proof: formatProof(proof), order, orderSignature, permit
|
|
45
|
+
const sent = await sendPiece(config, quote, { withdrawal, proof: formatProof(proof), order, orderSignature, permit });
|
|
44
46
|
return {
|
|
45
|
-
result: { amount, tx: sent.tx, fresh: fresh.address, fee:
|
|
47
|
+
result: { amount, tx: sent.tx, fresh: fresh.address, fee: sent.fee, protocolFee, proofSeconds: seconds, gasUsed: sent.gasUsed, relayerUrl: sent.relayerUrl },
|
|
46
48
|
next: noteAfterWithdrawal(keys, note, amount),
|
|
47
49
|
};
|
|
48
50
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nuluvium/mcp",
|
|
3
3
|
"mcpName": "com.nuluvium/mcp",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Nuluvium MCP server: lets an AI agent trade Robinhood Chain stock tokens privately, from its own machine",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
46
46
|
"@scure/bip39": "1.5.4",
|
|
47
47
|
"poseidon-lite": "0.3.0",
|
|
48
|
-
"viem": "2.57.
|
|
48
|
+
"viem": "2.57.17",
|
|
49
49
|
"zod": "3.25.76"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
},
|
|
55
55
|
"overrides": {
|
|
56
56
|
"@0xbow/privacy-pools-core-sdk": {
|
|
57
|
-
"viem": "2.57.
|
|
57
|
+
"viem": "2.57.17"
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
}
|