@nuluvium/mcp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env node
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 Nuluvium relayer.
4
+ //
5
+ // Environment:
6
+ // NULUVIUM_MNEMONIC required. The agent's secret (BIP-39). Never printed or returned.
7
+ // NULUVIUM_NETWORK default "robinhood-testnet"
8
+ // NULUVIUM_RPC_URL optional own RPC (may hold an API key; never printed)
9
+ // NULUVIUM_LOG_CHUNK blocks per log query with NULUVIUM_RPC_URL (default 10000, Alchemy limit)
10
+ // NULUVIUM_HOME default ~/.nuluvium (order schedule; local only)
11
+ // NULUVIUM_ARTIFACTS circuit files folder. Default: testnet/artifacts when run from the source
12
+ // tree with the files there, else ~/.nuluvium/artifacts (downloaded once)
13
+ import { existsSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
18
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
19
+ import { formatUnits } from "viem";
20
+ import { z } from "zod";
21
+ import { depositAccount, depositUsdg, erc20Abi, keysFromMnemonic, planPieces, walletClientFor } from "../../sdk/src/index.js";
22
+ import { noteApproval, pickNote } from "./approval.js";
23
+ import { ensureArtifacts, missingArtifacts } from "./artifacts.js";
24
+ import { depositProblem } from "./deposit.js";
25
+ import { Engine } from "./engine.js";
26
+ import { NETWORKS } from "./networks.js";
27
+ import { OrderStore, orderStatus } from "./store.js";
28
+ // stdout carries the MCP protocol; anything a library prints must go to stderr.
29
+ console.log = console.error;
30
+ console.info = console.error;
31
+ const USDG = 1000000n;
32
+ const MIN_PIECE = 1n * USDG;
33
+ const START_DELAY_SECONDS = 30;
34
+ const networkName = process.env.NULUVIUM_NETWORK ?? "robinhood-testnet";
35
+ const baseNetwork = NETWORKS[networkName];
36
+ if (!baseNetwork)
37
+ throw new Error(`unknown NULUVIUM_NETWORK ${networkName}`);
38
+ // Own RPC (e.g. Alchemy): needed where the public *.robinhood.com RPC is unreachable (some ISPs
39
+ // block the domain) or rate-limited. Alchemy accepts at most 10,000 blocks per log query.
40
+ const rpcOverride = process.env.NULUVIUM_RPC_URL;
41
+ const network = rpcOverride
42
+ ? {
43
+ ...baseNetwork,
44
+ config: {
45
+ ...baseNetwork.config,
46
+ rpcUrl: rpcOverride,
47
+ logChunk: BigInt(process.env.NULUVIUM_LOG_CHUNK ?? 10_000),
48
+ },
49
+ }
50
+ : baseNetwork;
51
+ delete process.env.NULUVIUM_RPC_URL; // may contain an API key
52
+ const home = process.env.NULUVIUM_HOME ?? join(homedir(), ".nuluvium");
53
+ const sourceArtifacts = fileURLToPath(new URL("../../testnet/artifacts", import.meta.url));
54
+ const artifacts = process.env.NULUVIUM_ARTIFACTS ??
55
+ (existsSync(sourceArtifacts) && missingArtifacts(sourceArtifacts).length === 0 ? sourceArtifacts : join(home, "artifacts"));
56
+ // `npx -y @nuluvium/mcp --prepare`: one-time setup before adding the server to an MCP client. The
57
+ // first npx run installs the package (over a minute, longer than many clients wait for a server to
58
+ // start) and the circuit files are 23 MB; doing both here makes later starts take seconds.
59
+ // Needs no secret.
60
+ if (process.argv.includes("--prepare")) {
61
+ await ensureArtifacts(artifacts, network.artifactsUrl, (message) => console.error(`[nuluvium] ${message}`));
62
+ console.error(`[nuluvium] ready: package installed, circuit files in ${artifacts}. Add the server to your MCP client now.`);
63
+ process.exit(0);
64
+ }
65
+ const mnemonic = process.env.NULUVIUM_MNEMONIC;
66
+ if (!mnemonic)
67
+ throw new Error("NULUVIUM_MNEMONIC is not set");
68
+ const keys = keysFromMnemonic(mnemonic);
69
+ delete process.env.NULUVIUM_MNEMONIC; // keep it out of anything that dumps the environment
70
+ // The agent's own wallet: pays for deposits (public, so this is the address linked to the agent).
71
+ const depositWallet = depositAccount(keys);
72
+ // One download at a time; a failed one is tried again before the next piece.
73
+ let artifactsReady = null;
74
+ const prepareProver = () => {
75
+ artifactsReady ??= ensureArtifacts(artifacts, network.artifactsUrl, (message) => console.error(`[nuluvium] ${message}`)).catch((error) => {
76
+ artifactsReady = null;
77
+ throw error;
78
+ });
79
+ return artifactsReady;
80
+ };
81
+ const store = new OrderStore(home, networkName);
82
+ const engine = new Engine(network, keys, store, artifacts, prepareProver);
83
+ const usdg = (units) => `${formatUnits(BigInt(units), 6)} USDG`;
84
+ const clock = (unix) => new Date(unix * 1000).toISOString().replace(".000Z", "Z");
85
+ const reply = (body) => ({ content: [{ type: "text", text: JSON.stringify(body, null, 2) }] });
86
+ const failure = (message) => ({ content: [{ type: "text", text: message }], isError: true });
87
+ /**
88
+ * Wraps a tool so errors reach the agent as a short message only. viem error messages include the
89
+ * RPC URL, which can hold an API key, so the full message is never returned.
90
+ */
91
+ function safe(handler) {
92
+ return async (...args) => {
93
+ try {
94
+ return await handler(...args);
95
+ }
96
+ catch (error) {
97
+ const short = error.shortMessage;
98
+ const details = error.details;
99
+ const message = short ? `${short}${details ? ` (${details})` : ""}` : error instanceof Error ? error.message : String(error);
100
+ return failure(`Nuluvium error: ${message.replace(/https?:\/\/\S+/g, "<rpc>")}`);
101
+ }
102
+ };
103
+ }
104
+ function describe(order) {
105
+ const done = order.pieces.filter((piece) => piece.status === "done");
106
+ return {
107
+ orderId: order.id,
108
+ status: orderStatus(order),
109
+ token: order.token,
110
+ amount: usdg(order.amount),
111
+ pieces: order.pieces.map((piece) => ({
112
+ piece: piece.number,
113
+ amount: usdg(piece.amount),
114
+ scheduledFor: clock(piece.at),
115
+ status: piece.status,
116
+ ...(piece.error ? { error: piece.error } : {}),
117
+ })),
118
+ routed: usdg(done.reduce((sum, piece) => sum + BigInt(piece.amount), 0n)),
119
+ createdAt: clock(order.createdAt),
120
+ };
121
+ }
122
+ /** USDG and ETH in the deposit wallet. */
123
+ async function walletFunds() {
124
+ const client = engine.ctx.client;
125
+ const [usdgBalance, eth] = await Promise.all([
126
+ client.readContract({ address: network.config.usdg, abi: erc20Abi, functionName: "balanceOf", args: [depositWallet.address] }),
127
+ client.getBalance({ address: depositWallet.address }),
128
+ ]);
129
+ return { usdg: usdgBalance, eth };
130
+ }
131
+ const server = new McpServer({ name: "nuluvium", version: "0.1.0" });
132
+ server.registerTool("get_balance", {
133
+ title: "Shielded balance",
134
+ description: "Shows the agent's shielded USDG balance on Nuluvium, per note, and the deposit wallet that funds new deposits. One order is paid from one note, so the largest note is the largest order you can route right now.",
135
+ }, safe(async () => {
136
+ const [notes, funds, set] = await Promise.all([engine.notes(), walletFunds(), engine.approvedSet()]);
137
+ const busy = new Set(store.all().filter((order) => ["scheduled", "routing"].includes(orderStatus(order))).map((order) => order.depositIndex));
138
+ // No approved set read yet (the ASP is mid-update): statuses are unknown, the balance still shows.
139
+ const rows = notes.map((note) => ({ note, ...(set ? noteApproval(note, set) : { approval: "unknown", reason: undefined }) }));
140
+ return reply({
141
+ network: network.name,
142
+ ...(set ? {} : { statusNote: "The clean-funds list is updating; note statuses are unknown for now. Try again in about a minute." }),
143
+ total: usdg(notes.reduce((sum, note) => sum + note.value, 0n)),
144
+ approvedTotal: usdg(rows.filter((row) => row.approval === "approved").reduce((sum, row) => sum + row.note.value, 0n)),
145
+ notes: rows.map(({ note, approval, reason }) => ({
146
+ note: Number(note.depositIndex),
147
+ balance: usdg(note.value),
148
+ status: approval,
149
+ ...(reason ? { reason } : {}),
150
+ inUseByAnOrder: busy.has(note.depositIndex.toString()),
151
+ })),
152
+ depositWallet: { address: depositWallet.address, usdg: usdg(funds.usdg), eth: formatUnits(funds.eth, 18) },
153
+ tradableTokens: Object.values(network.tokens).map((token) => ({ symbol: token.symbol, note: token.note })),
154
+ });
155
+ }));
156
+ server.registerTool("deposit", {
157
+ title: "Deposit USDG into the shielded balance",
158
+ description: "Moves USDG from the agent's deposit wallet (see get_balance) into its shielded balance as a new note. The deposit itself is public: anyone can see this wallet deposited this amount; what the note pays for later is not linked to it. Sends two transactions (approve, deposit) and waits for them. The new note can pay for orders once the clean-funds check approves it, usually within a minute. Up to 1,000 USDG per deposit until the audit.",
159
+ inputSchema: {
160
+ usdgAmount: z.number().positive().describe("USDG to deposit (1 to 1,000)"),
161
+ },
162
+ }, safe(async ({ usdgAmount }) => {
163
+ const amount = BigInt(Math.round(usdgAmount * 1e6));
164
+ const problem = depositProblem(amount, await walletFunds(), depositWallet.address, network.faucet);
165
+ if (problem)
166
+ return failure(problem);
167
+ const wallet = walletClientFor(network.config, depositWallet);
168
+ const { note, tx } = await depositUsdg(engine.ctx.client, wallet, network.config, keys, amount);
169
+ return reply({
170
+ deposited: usdg(note.value),
171
+ note: Number(note.depositIndex),
172
+ from: depositWallet.address,
173
+ transaction: `${network.explorer}/tx/${tx}`,
174
+ next: "Wait about a minute for the clean-funds check, then route_order can pay from this note.",
175
+ });
176
+ }));
177
+ server.registerTool("route_order", {
178
+ title: "Route a private buy order",
179
+ description: "Buys a stock token with shielded USDG, split into pieces of random size sent at random times inside the window. Each piece goes to its own fresh address, so the trades do not trace back to the agent's wallet. Returns at once; pieces are sent in the background (check with get_orders / get_fills). Privacy is from other readers of the chain, not from Robinhood.",
180
+ inputSchema: {
181
+ token: z.string().describe("Symbol of an allowlisted stock token, e.g. MSTK on testnet"),
182
+ usdgAmount: z.number().positive().describe("Total USDG to spend"),
183
+ pieces: z.number().int().min(1).max(20).default(5).describe("How many pieces (1 to 20)"),
184
+ 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"),
186
+ },
187
+ }, safe(async ({ token, usdgAmount, pieces, windowMinutes, maxSlippagePercent }) => {
188
+ const target = network.tokens[token.toUpperCase()];
189
+ if (!target)
190
+ return failure(`${token} is not tradable here. Tradable: ${Object.keys(network.tokens).join(", ")}`);
191
+ const amount = BigInt(Math.round(usdgAmount * 1e6));
192
+ if (amount < MIN_PIECE * BigInt(pieces))
193
+ return failure(`Each piece must be at least ${usdg(MIN_PIECE)}; lower the piece count or raise the amount.`);
194
+ // Pay from the smallest approved, free note that covers the order.
195
+ const busy = new Set(store.all().filter((order) => ["scheduled", "routing"].includes(orderStatus(order))).map((order) => order.depositIndex));
196
+ const [notes, set] = await Promise.all([engine.notes(), engine.approvedSet()]);
197
+ if (!set)
198
+ return failure("The clean-funds list is updating, so it is not clear yet which notes may pay. Try again in about a minute.");
199
+ const picked = pickNote(notes, set, busy, amount);
200
+ if ("problem" in picked)
201
+ return failure(picked.problem);
202
+ const { note } = picked;
203
+ const start = Math.floor(Date.now() / 1000) + START_DELAY_SECONDS;
204
+ const windowSeconds = Math.round(windowMinutes * 60);
205
+ const minGapSeconds = Math.min(30, Math.floor(windowSeconds / Math.max(1, pieces - 1)));
206
+ const plan = planPieces({ amount, pieces, windowSeconds, start, minPiece: MIN_PIECE, minGapSeconds });
207
+ const order = {
208
+ id: `ord_${crypto.randomUUID().slice(0, 8)}`,
209
+ network: networkName,
210
+ token: target.symbol,
211
+ amount: amount.toString(),
212
+ depositIndex: note.depositIndex.toString(),
213
+ slippageBps: Math.round(maxSlippagePercent * 100),
214
+ createdAt: Math.floor(Date.now() / 1000),
215
+ pieces: plan.map((piece) => ({ number: piece.number, amount: piece.amount.toString(), at: piece.at, status: "scheduled" })),
216
+ };
217
+ store.add(order);
218
+ for (const piece of order.pieces)
219
+ engine.arm(order, piece.number);
220
+ return reply({ ...describe(order), paidFromNote: Number(note.depositIndex), noteBalanceAfter: usdg(note.value - amount) });
221
+ }));
222
+ server.registerTool("cancel_order", {
223
+ title: "Cancel an order",
224
+ description: "Cancels the pieces of an order that have not been sent yet. A piece already being sent may still complete.",
225
+ inputSchema: { orderId: z.string().describe("Order id from route_order or get_orders") },
226
+ }, safe(async ({ orderId }) => {
227
+ const order = store.get(orderId);
228
+ if (!order)
229
+ return failure(`No order ${orderId}`);
230
+ const cancelled = engine.cancel(order);
231
+ return reply({ ...describe(order), cancelledPieces: cancelled });
232
+ }));
233
+ server.registerTool("get_orders", {
234
+ title: "List orders",
235
+ description: "Lists this agent's orders with the status of every piece (scheduled, sending, done, failed, cancelled).",
236
+ inputSchema: { onlyOpen: z.boolean().default(false).describe("Only orders still scheduled or routing") },
237
+ }, safe(async ({ onlyOpen }) => {
238
+ const orders = store.all().filter((order) => !onlyOpen || ["scheduled", "routing"].includes(orderStatus(order)));
239
+ return reply({ network: network.name, orders: orders.map(describe) });
240
+ }));
241
+ server.registerTool("get_fills", {
242
+ title: "Executed pieces",
243
+ description: "Shows executed pieces: USDG spent, tokens received, the fresh address holding them, and the transaction link.",
244
+ inputSchema: { orderId: z.string().optional().describe("Limit to one order") },
245
+ }, safe(async ({ orderId }) => {
246
+ const orders = orderId ? [store.get(orderId)].filter((order) => Boolean(order)) : store.all();
247
+ if (orderId && orders.length === 0)
248
+ return failure(`No order ${orderId}`);
249
+ const fills = orders.flatMap((order) => order.pieces
250
+ .filter((piece) => piece.status === "done")
251
+ .map((piece) => {
252
+ const token = network.tokens[order.token];
253
+ return {
254
+ orderId: order.id,
255
+ piece: piece.number,
256
+ spent: usdg(piece.amount),
257
+ relayerFee: usdg(piece.fee ?? "0"),
258
+ received: `${formatUnits(BigInt(piece.received ?? "0"), token.decimals)} ${token.symbol}`,
259
+ freshAddress: piece.fresh,
260
+ transaction: `${network.explorer}/tx/${piece.tx}`,
261
+ at: piece.sentAt ? clock(piece.sentAt) : undefined,
262
+ };
263
+ }));
264
+ return reply({ fills });
265
+ }));
266
+ engine.resumeAll();
267
+ await server.connect(new StdioServerTransport());
268
+ // Start the circuit download now (in the background) so the first piece does not wait for it.
269
+ prepareProver().catch((error) => console.error(`[nuluvium] ${error instanceof Error ? error.message : String(error)}; will retry before the first piece`));
270
+ console.error(`[nuluvium] MCP server ready on ${network.name}; orders in ${store.file}`);
@@ -0,0 +1,48 @@
1
+ // Orders on the agent's own machine. No secrets in here, but the file links the fresh addresses of
2
+ // one order, so it must stay local (never sent to a server).
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync, existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ export function orderStatus(order) {
6
+ const statuses = order.pieces.map((piece) => piece.status);
7
+ if (statuses.some((status) => status === "failed"))
8
+ return "failed";
9
+ if (statuses.every((status) => status === "done"))
10
+ return "done";
11
+ if (statuses.every((status) => status === "done" || status === "cancelled"))
12
+ return "cancelled";
13
+ if (statuses.some((status) => status === "done" || status === "sending"))
14
+ return "routing";
15
+ return "scheduled";
16
+ }
17
+ export class OrderStore {
18
+ file;
19
+ orders;
20
+ constructor(home, network) {
21
+ mkdirSync(home, { recursive: true });
22
+ this.file = join(home, `orders-${network}.json`);
23
+ this.orders = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : [];
24
+ }
25
+ all() {
26
+ return this.orders;
27
+ }
28
+ get(id) {
29
+ return this.orders.find((order) => order.id === id);
30
+ }
31
+ add(order) {
32
+ this.orders.push(order);
33
+ this.save();
34
+ }
35
+ /** Changes one piece and writes the file at once (atomic rename), so a crash loses nothing. */
36
+ updatePiece(id, number, change) {
37
+ const piece = this.get(id)?.pieces.find((item) => item.number === number);
38
+ if (!piece)
39
+ throw new Error(`no piece ${number} in order ${id}`);
40
+ Object.assign(piece, change);
41
+ this.save();
42
+ }
43
+ save() {
44
+ const temporary = `${this.file}.tmp`;
45
+ writeFileSync(temporary, JSON.stringify(this.orders, null, 2));
46
+ renameSync(temporary, this.file);
47
+ }
48
+ }
@@ -0,0 +1,91 @@
1
+ // The approved set a withdrawal must prove membership of, read from the ASP and checked twice:
2
+ // the document against its CID (SHA-256), and its root against the root posted on chain.
3
+ import { generateMerkleProof } from "@0xbow/privacy-pools-core-sdk";
4
+ import { entrypointAbi } from "./chain.js";
5
+ const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
6
+ /** SHA-256 digest inside a raw CIDv1 ("b" + base32 of 0x01 0x55 0x12 0x20 digest). */
7
+ export function cidDigestHex(cid) {
8
+ if (!/^b[a-z2-7]{58}$/.test(cid))
9
+ throw new Error(`not a raw CIDv1: ${cid}`);
10
+ let bits = 0;
11
+ let buffer = 0;
12
+ const bytes = [];
13
+ for (const char of cid.slice(1)) {
14
+ buffer = ((buffer << 5) | BASE32.indexOf(char)) & 0xffff;
15
+ bits += 5;
16
+ if (bits >= 8) {
17
+ bytes.push((buffer >>> (bits - 8)) & 255);
18
+ bits -= 8;
19
+ }
20
+ }
21
+ if (bytes[0] !== 0x01 || bytes[1] !== 0x55 || bytes[2] !== 0x12 || bytes[3] !== 0x20)
22
+ throw new Error("unexpected CID prefix");
23
+ return bytes.slice(4).map((byte) => byte.toString(16).padStart(2, "0")).join("");
24
+ }
25
+ async function sha256Hex(bytes) {
26
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
27
+ return [...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("");
28
+ }
29
+ /** Root of a lean Merkle tree of labels (a single leaf is its own root). */
30
+ export function rootOf(labels) {
31
+ if (labels.length === 0)
32
+ return 0n;
33
+ if (labels.length === 1)
34
+ return labels[0];
35
+ return generateMerkleProof(labels, labels[0]).root;
36
+ }
37
+ /** The set document stored under `cid`, checked against the CID and against its own root. */
38
+ async function fetchSetDocument(config, cid) {
39
+ const bytes = new Uint8Array(await (await fetch(`${config.aspUrl}/sets/${cid}`)).arrayBuffer());
40
+ if ((await sha256Hex(bytes)) !== cidDigestHex(cid))
41
+ throw new Error(`ASP set does not match its CID ${cid}`);
42
+ const document = JSON.parse(new TextDecoder().decode(bytes));
43
+ const labels = document.approvedLabels.map(BigInt);
44
+ if (rootOf(labels) !== BigInt(document.root))
45
+ throw new Error(`ASP set ${cid} does not hash to its root`);
46
+ return { root: BigInt(document.root), labels, rejected: document.rejected };
47
+ }
48
+ /** Blocks searched back for the RootUpdated event when the ASP's status lags (a few minutes here). */
49
+ const ROOT_EVENT_LOOKBACK = 10000n;
50
+ /**
51
+ * The CID posted on chain with `root` (RootUpdated event), searched in the recent blocks. The
52
+ * Entrypoint keeps the CID in storage too, but has no getter for the latest index.
53
+ */
54
+ async function cidOnChain(client, config, root) {
55
+ const latest = await client.getBlockNumber();
56
+ const span = config.logChunk < ROOT_EVENT_LOOKBACK ? config.logChunk : ROOT_EVENT_LOOKBACK;
57
+ const logs = await client.getContractEvents({
58
+ address: config.entrypoint,
59
+ abi: entrypointAbi,
60
+ eventName: "RootUpdated",
61
+ fromBlock: latest - span + 1n,
62
+ toBlock: latest,
63
+ });
64
+ const match = logs.reverse().find((log) => log.args._root === root);
65
+ return match?.args._ipfsCID ?? null;
66
+ }
67
+ /**
68
+ * The approved set for the root currently on chain. The ASP's status (GET /) names the latest set,
69
+ * but after a new root it can point at the previous one for up to about a minute (Cloudflare KV
70
+ * spreads writes slowly). Then the CID is taken from the chain's RootUpdated event instead. Either
71
+ * way the document is checked against its CID and its root against the chain.
72
+ */
73
+ export async function fetchApprovedSet(client, config) {
74
+ const [status, onchainRoot] = await Promise.all([
75
+ fetch(`${config.aspUrl}/`).then((response) => response.json()),
76
+ client.readContract({ address: config.entrypoint, abi: entrypointAbi, functionName: "latestRoot" }),
77
+ ]);
78
+ const statusCid = status.latest?.cid;
79
+ if (statusCid) {
80
+ const document = await fetchSetDocument(config, statusCid);
81
+ if (document.root === onchainRoot)
82
+ return { cid: statusCid, ...document, root: onchainRoot };
83
+ }
84
+ const cid = await cidOnChain(client, config, onchainRoot);
85
+ if (!cid)
86
+ throw new Error("ASP set root does not match the root on chain, and no recent RootUpdated event names it");
87
+ const document = await fetchSetDocument(config, cid);
88
+ if (document.root !== onchainRoot)
89
+ throw new Error(`ASP set ${cid} does not match the root on chain`);
90
+ return { cid, ...document, root: onchainRoot };
91
+ }
@@ -0,0 +1,63 @@
1
+ import { createPublicClient, createWalletClient, defineChain, http, parseAbi } from "viem";
2
+ export const poolAbi = parseAbi([
3
+ "event Deposited(address indexed _depositor, uint256 _commitment, uint256 _label, uint256 _value, uint256 _precommitmentHash)",
4
+ "event Withdrawn(address indexed _processooor, uint256 _value, uint256 _spentNullifier, uint256 _newCommitment)",
5
+ "event Ragequit(address indexed _ragequitter, uint256 _commitment, uint256 _label, uint256 _value)",
6
+ "event LeafInserted(uint256 _index, uint256 _leaf, uint256 _root)",
7
+ "function currentRoot() view returns (uint256)",
8
+ ]);
9
+ export const entrypointAbi = parseAbi([
10
+ "function deposit(address asset, uint256 value, uint256 precommitment) returns (uint256)",
11
+ "function latestRoot() view returns (uint256)",
12
+ "event RootUpdated(uint256 _root, string _ipfsCID, uint256 _timestamp)",
13
+ ]);
14
+ export const erc20Abi = parseAbi([
15
+ "function balanceOf(address owner) view returns (uint256)",
16
+ "function approve(address spender, uint256 amount) returns (bool)",
17
+ "function nonces(address owner) view returns (uint256)",
18
+ "function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)",
19
+ ]);
20
+ export function chainFor(config) {
21
+ return defineChain({
22
+ id: config.chainId,
23
+ name: "Robinhood Chain",
24
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
25
+ rpcUrls: { default: { http: [config.rpcUrl] } },
26
+ });
27
+ }
28
+ export function publicClientFor(config) {
29
+ return createPublicClient({ chain: chainFor(config), transport: http(config.rpcUrl, { timeout: 30_000, retryCount: 2 }) });
30
+ }
31
+ /** A wallet client that signs locally with `account` and sends through the network's RPC. */
32
+ export function walletClientFor(config, account) {
33
+ return createWalletClient({ account, chain: chainFor(config), transport: http(config.rpcUrl, { timeout: 30_000, retryCount: 2 }) });
34
+ }
35
+ /** Parallel requests per scan: fast enough in a browser, gentle on the RPC. */
36
+ const SCAN_CONCURRENCY = 4;
37
+ /**
38
+ * Logs of the given pool events since the deployment, in chain order. The block range is cut into
39
+ * chunks the RPC accepts; chunks are fetched a few at a time, all event types in one request each.
40
+ */
41
+ export async function poolLogs(client, config, eventNames) {
42
+ const events = poolAbi.filter((item) => item.type === "event" && eventNames.includes(item.name));
43
+ const latest = await client.getBlockNumber();
44
+ const ranges = [];
45
+ for (let from = config.deployBlock; from <= latest; from += config.logChunk) {
46
+ ranges.push([from, from + config.logChunk - 1n < latest ? from + config.logChunk - 1n : latest]);
47
+ }
48
+ const chunks = new Array(ranges.length);
49
+ let next = 0;
50
+ const worker = async () => {
51
+ while (next < ranges.length) {
52
+ const index = next++;
53
+ const [fromBlock, toBlock] = ranges[index];
54
+ chunks[index] = (await client.getLogs({ address: config.pool, events, fromBlock, toBlock, strict: true }));
55
+ }
56
+ };
57
+ await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, ranges.length) }, worker));
58
+ return chunks.flat().sort((a, b) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1));
59
+ }
60
+ /** All logs of one pool event since the deployment, in chain order. */
61
+ export function poolEvents(client, config, eventName) {
62
+ return poolLogs(client, config, [eventName]);
63
+ }
@@ -0,0 +1,14 @@
1
+ /** Robinhood Chain testnet deployment (docs/testnet.md). */
2
+ export const ROBINHOOD_TESTNET = {
3
+ chainId: 46_630,
4
+ rpcUrl: "https://rpc.testnet.chain.robinhood.com",
5
+ logChunk: 5000000n,
6
+ entrypoint: "0x1C7Bd821a61A90BA06e21aac4e03640E3D065536",
7
+ pool: "0x2B38bF53acc21a51603E68f5BC3bC8943B01fD4a",
8
+ usdg: "0xd26d58F86cf82c702b558D6E7F159939E97F0Bfa",
9
+ scope: 20883339666151915200592145183006062909365231028523521475069391119255857699183n,
10
+ deployBlock: 153603397n,
11
+ router: "0x3287C2947f137c20c8BfeB628f800D23b8e5D155",
12
+ relayerUrl: "https://relayer.nuluvium.com",
13
+ aspUrl: "https://asp.nuluvium.com",
14
+ };
@@ -0,0 +1,47 @@
1
+ // Deposits USDG into the shielded pool under the next unused deposit index of these keys.
2
+ import { hashPrecommitment } from "@0xbow/privacy-pools-core-sdk";
3
+ import { parseEventLogs } from "viem";
4
+ import { entrypointAbi, erc20Abi, poolAbi } from "./chain.js";
5
+ import { depositSecrets, recoverNotes } from "./notes.js";
6
+ export async function depositUsdg(client, wallet, config, keys, amount) {
7
+ const account = wallet.account;
8
+ if (!account)
9
+ throw new Error("wallet client needs an account");
10
+ const { spendable, spent } = await recoverNotes(client, config, keys);
11
+ const used = [...spendable, ...spent].map((note) => note.depositIndex);
12
+ const index = used.length === 0 ? 0n : used.reduce((max, value) => (value > max ? value : max)) + 1n;
13
+ const secrets = depositSecrets(keys, config.scope, index);
14
+ const send = async (request) => {
15
+ const hash = await wallet.writeContract(request);
16
+ const receipt = await client.waitForTransactionReceipt({ hash });
17
+ if (receipt.status !== "success")
18
+ throw new Error(`transaction reverted: ${hash}`);
19
+ return receipt;
20
+ };
21
+ await send({ account, chain: wallet.chain, address: config.usdg, abi: erc20Abi, functionName: "approve", args: [config.entrypoint, amount] });
22
+ const receipt = await send({
23
+ account,
24
+ chain: wallet.chain,
25
+ address: config.entrypoint,
26
+ abi: entrypointAbi,
27
+ functionName: "deposit",
28
+ args: [config.usdg, amount, hashPrecommitment(secrets.nullifier, secrets.secret)],
29
+ });
30
+ const [event] = parseEventLogs({ abi: poolAbi, eventName: "Deposited", logs: receipt.logs });
31
+ if (!event)
32
+ throw new Error("no Deposited event in the receipt");
33
+ return {
34
+ tx: receipt.transactionHash,
35
+ note: {
36
+ depositIndex: index,
37
+ label: event.args._label,
38
+ value: event.args._value,
39
+ nullifier: secrets.nullifier,
40
+ secret: secrets.secret,
41
+ commitment: event.args._commitment,
42
+ withdrawals: 0,
43
+ depositTx: receipt.transactionHash,
44
+ depositor: account.address,
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,99 @@
1
+ // Ways out.
2
+ // ragequit the depositing wallet takes a note's USDG back from the pool. Public: it links that
3
+ // deposit to the wallet, so it is the exit for deposits that are not approved, or for
4
+ // anyone who wants their USDG back as it was.
5
+ // sell a fresh address sells stock tokens for USDG through the Router, gasless: it signs an
6
+ // order and a permit, the relayer sends Router.swap and takes its fee from the USDG.
7
+ import { parseAbi } from "viem";
8
+ import { getQuote, sendSell, signOrder, signPermit } from "./relayer.js";
9
+ import { randomNonce } from "./routing.js";
10
+ // JSON form: abitype cannot type the nested fixed array (uint256[2][2]) from the human-readable form.
11
+ export const ragequitAbi = [
12
+ {
13
+ type: "function",
14
+ name: "ragequit",
15
+ stateMutability: "nonpayable",
16
+ inputs: [
17
+ {
18
+ name: "_proof",
19
+ type: "tuple",
20
+ components: [
21
+ { name: "pA", type: "uint256[2]" },
22
+ { name: "pB", type: "uint256[2][2]" },
23
+ { name: "pC", type: "uint256[2]" },
24
+ { name: "pubSignals", type: "uint256[4]" },
25
+ ],
26
+ },
27
+ ],
28
+ outputs: [],
29
+ },
30
+ ...parseAbi(["error OnlyOriginalDepositor()", "error InvalidProof()", "error InvalidCommitment()", "error NullifierAlreadySpent()"]),
31
+ ];
32
+ /** Proves the note's commitment (the "commitment" circuit) in the pool's argument format. */
33
+ export async function proveRagequit(prover, note) {
34
+ const { proof, publicSignals } = await prover.proveCommitment(note.value, note.label, note.nullifier, note.secret);
35
+ const big = (value) => BigInt(String(value));
36
+ if (publicSignals.length !== 4)
37
+ throw new Error("unexpected commitment proof shape");
38
+ return {
39
+ pA: [big(proof.pi_a[0]), big(proof.pi_a[1])],
40
+ // pB coordinates swapped, as the Groth16 verifier expects (same as formatProof).
41
+ pB: [
42
+ [big(proof.pi_b[0][1]), big(proof.pi_b[0][0])],
43
+ [big(proof.pi_b[1][1]), big(proof.pi_b[1][0])],
44
+ ],
45
+ pC: [big(proof.pi_c[0]), big(proof.pi_c[1])],
46
+ pubSignals: [big(publicSignals[0]), big(publicSignals[1]), big(publicSignals[2]), big(publicSignals[3])],
47
+ };
48
+ }
49
+ /**
50
+ * Takes the whole note back to the wallet that deposited it. The wallet sends the transaction and
51
+ * pays the gas; the pool refuses any other sender.
52
+ */
53
+ export async function ragequitNote(client, wallet, config, prover, note) {
54
+ const account = wallet.account;
55
+ if (!account)
56
+ throw new Error("wallet client needs an account");
57
+ if (account.address.toLowerCase() !== note.depositor.toLowerCase()) {
58
+ throw new Error("only the wallet that made this deposit can take it back");
59
+ }
60
+ if (note.value === 0n || note.ragequitTx)
61
+ throw new Error("this deposit has nothing left to take back");
62
+ const proof = await proveRagequit(prover, note);
63
+ // Simulate first, so a bad proof or a spent note fails before the wallet is asked to sign.
64
+ // Typed through ContractFunctionArgs: viem's `const args` inference fails on an interface value.
65
+ const args = [proof];
66
+ const { request } = await client.simulateContract({ account, address: config.pool, abi: ragequitAbi, functionName: "ragequit", args });
67
+ const tx = await wallet.writeContract(request);
68
+ const receipt = await client.waitForTransactionReceipt({ hash: tx });
69
+ if (receipt.status !== "success")
70
+ throw new Error(`ragequit reverted: ${tx}`);
71
+ return { tx, value: note.value };
72
+ }
73
+ const SELL_DEADLINE_SECONDS = 15 * 60;
74
+ /**
75
+ * 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 fee
77
+ */
78
+ export async function sellFromFresh(client, config, fresh, token, amountIn, minUsdgOut) {
79
+ if (amountIn <= 0n)
80
+ throw new Error("nothing to sell");
81
+ const quote = await getQuote(config);
82
+ const deadline = BigInt(Math.floor(Date.now() / 1000) + SELL_DEADLINE_SECONDS);
83
+ const order = {
84
+ owner: fresh.address,
85
+ tokenIn: token,
86
+ tokenOut: config.usdg,
87
+ amountIn,
88
+ minAmountOut: minUsdgOut,
89
+ maxFee: quote.fee * 2n, // room for the quote to move before the relayer sends
90
+ nonce: randomNonce(),
91
+ deadline,
92
+ };
93
+ const [orderSignature, permit] = await Promise.all([
94
+ signOrder(fresh, config, order),
95
+ signPermit(fresh, client, config, token, config.router, amountIn, deadline),
96
+ ]);
97
+ const sent = await sendSell(config, { order, orderSignature, permit, fee: quote.fee });
98
+ return { tx: sent.tx, fee: quote.fee };
99
+ }
@@ -0,0 +1,20 @@
1
+ // @nuluvium/sdk: private routing on Robinhood Chain.
2
+ // keys one user secret → note keys and a fresh address per piece
3
+ // notes spendable notes rebuilt from the chain (nothing secret is stored)
4
+ // planner random piece sizes and times inside a window
5
+ // proof withdrawal proofs (Privacy Pools v1 circuits); Node folder prover in ./node.ts
6
+ // asp the approved set, checked against its CID and the on-chain root
7
+ // relayer quote, order and permit signatures, piece submission
8
+ // routing one piece end to end, or a whole plan on schedule
9
+ // exit ragequit a deposit back to its wallet; sell a fresh address's tokens for USDG
10
+ export { ROBINHOOD_TESTNET } from "./config.js";
11
+ export { KEY_MESSAGE_VERSION, depositAccount, freshAccount, isValidMnemonic, keyMessage, keysFromMnemonic, keysFromSignature, newMnemonic } from "./keys.js";
12
+ export { changeSecrets, depositSecrets, noteAfterWithdrawal, nullifierHash, recoverNotes } from "./notes.js";
13
+ export { planPieces, secureRandom } from "./planner.js";
14
+ export { createUrlProver, formatProof, proveWithdrawal } from "./proof.js";
15
+ export { cidDigestHex, fetchApprovedSet, rootOf } from "./asp.js";
16
+ export { RelayerError, getQuote, sendPiece, sendSell, signOrder, signPermit } from "./relayer.js";
17
+ export { executePiece, randomNonce, runPlan } from "./routing.js";
18
+ export { depositUsdg } from "./deposit.js";
19
+ export { proveRagequit, ragequitAbi, ragequitNote, sellFromFresh } from "./exit.js";
20
+ export { chainFor, erc20Abi, publicClientFor, walletClientFor } from "./chain.js";