@nuluvium/mcp 0.0.0-stage → 0.1.1

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,76 @@
1
+ // Everything secret derives from one user secret, so nothing secret is ever stored:
2
+ // - note keys (Privacy Pools master nullifier and master secret)
3
+ // - one fresh address per piece, at m/44'/60'/1'/<deposit index>/<piece number>
4
+ // In v1 the secret is a BIP-39 mnemonic; the web app (1.8) derives it from a wallet signature.
5
+ import { generateMasterKeys } from "@0xbow/privacy-pools-core-sdk";
6
+ import { entropyToMnemonic, generateMnemonic, validateMnemonic } from "@scure/bip39";
7
+ import { wordlist as english } from "@scure/bip39/wordlists/english";
8
+ import { hexToBytes, keccak256 } from "viem";
9
+ import { mnemonicToAccount } from "viem/accounts";
10
+ /** HD account index reserved for fresh addresses (account 0 stays the user's normal wallet path). */
11
+ const FRESH_ACCOUNT_INDEX = 1;
12
+ /** Bump only with a migration: a new message gives every user new keys (and an empty balance). */
13
+ export const KEY_MESSAGE_VERSION = 1;
14
+ /**
15
+ * The message a person signs with their wallet to unlock Nuluvium. The signature is the secret,
16
+ * so it must never leave the browser. Fixed text per address and network: the same wallet always
17
+ * gets the same keys.
18
+ */
19
+ export function keyMessage(address, chainId) {
20
+ return [
21
+ "Nuluvium key",
22
+ "",
23
+ "Sign to unlock your shielded balance on Nuluvium. This is not a transaction and costs nothing.",
24
+ "The signature stays in your browser; anyone who has it can spend your shielded balance.",
25
+ "",
26
+ `Address: ${address.toLowerCase()}`,
27
+ `Chain: ${chainId}`,
28
+ `Version: ${KEY_MESSAGE_VERSION}`,
29
+ ].join("\n");
30
+ }
31
+ /**
32
+ * Keys from a wallet signature of `keyMessage`: keccak256(signature) → 128 bits of entropy → a
33
+ * BIP-39 mnemonic → the usual note keys and fresh addresses. Only safe with wallets that sign
34
+ * deterministically (RFC 6979); the app checks that by asking for the signature twice once.
35
+ */
36
+ export function keysFromSignature(signature) {
37
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature))
38
+ throw new Error("expected a 65-byte signature");
39
+ const entropy = hexToBytes(keccak256(signature)).slice(0, 16);
40
+ return keysFromMnemonic(entropyToMnemonic(entropy, english));
41
+ }
42
+ /** A new random 12-word recovery phrase (128 bits), for people who log in without a wallet. */
43
+ export function newMnemonic() {
44
+ return generateMnemonic(english, 128);
45
+ }
46
+ /** True for a 12 or 24 word BIP-39 phrase with a valid checksum (catches typos when restoring). */
47
+ export function isValidMnemonic(mnemonic) {
48
+ const words = mnemonic.trim().toLowerCase().split(/\s+/);
49
+ return (words.length === 12 || words.length === 24) && validateMnemonic(words.join(" "), english);
50
+ }
51
+ export function keysFromMnemonic(mnemonic) {
52
+ const words = mnemonic.trim().split(/\s+/);
53
+ if (words.length !== 12 && words.length !== 24)
54
+ throw new Error("mnemonic must have 12 or 24 words");
55
+ return { mnemonic: words.join(" "), masterKeys: generateMasterKeys(words.join(" ")) };
56
+ }
57
+ /**
58
+ * The secret's normal wallet (m/44'/60'/0'/0/0). An agent holding a mnemonic funds its deposits
59
+ * from here: deposits are public, so this address is the one the world links to the agent.
60
+ */
61
+ export function depositAccount(keys) {
62
+ return mnemonicToAccount(keys.mnemonic);
63
+ }
64
+ /**
65
+ * Fresh account for piece `pieceNumber` of the note that came from deposit `depositIndex`.
66
+ * Deterministic, so the user can always find and recover every fresh address.
67
+ */
68
+ export function freshAccount(keys, depositIndex, pieceNumber) {
69
+ if (depositIndex > 0x7fffffffn || pieceNumber < 0 || pieceNumber > 0x7fffffff)
70
+ throw new Error("index out of range");
71
+ return mnemonicToAccount(keys.mnemonic, {
72
+ accountIndex: FRESH_ACCOUNT_INDEX,
73
+ changeIndex: Number(depositIndex),
74
+ addressIndex: pieceNumber,
75
+ });
76
+ }
@@ -0,0 +1,22 @@
1
+ // Node-only parts of @nuluvium/sdk (import from "@nuluvium/sdk/node").
2
+ import { readFile } from "node:fs/promises";
3
+ import { basename, join } from "node:path";
4
+ import { Circuits, PrivacyPoolSDK } from "@0xbow/privacy-pools-core-sdk";
5
+ /**
6
+ * Circuits loader reading wasm/zkey/vkey from a folder (see testnet/setup-artifacts.mjs).
7
+ * The SDK still checks every file against its pinned SHA-256 hashes.
8
+ */
9
+ class FolderCircuits extends Circuits {
10
+ folder;
11
+ constructor(folder) {
12
+ super({ browser: false });
13
+ this.folder = folder;
14
+ }
15
+ async _fetchVersionedArtifact(artifactPath) {
16
+ return new Uint8Array(await readFile(join(this.folder, basename(artifactPath))));
17
+ }
18
+ }
19
+ /** Prover reading the circuit files from a local folder. */
20
+ export function createFolderProver(artifactFolder) {
21
+ return new PrivacyPoolSDK(new FolderCircuits(artifactFolder));
22
+ }
@@ -0,0 +1,89 @@
1
+ // Spendable notes, rebuilt from the chain and the user's keys alone (nothing secret is stored).
2
+ //
3
+ // Deposit i uses secrets derived from (scope, i); its precommitment hash appears in the Deposited
4
+ // event, which is how our deposits are found. Each private withdrawal spends a note and creates a
5
+ // "change" note with secrets derived from (label, k) for the k-th withdrawal of that deposit. The
6
+ // Withdrawn event names the spent nullifier hash and the amount, so the chain can be followed.
7
+ import { generateDepositSecrets, generateWithdrawalSecrets, getCommitment, hashPrecommitment, } from "@0xbow/privacy-pools-core-sdk";
8
+ import { poseidon1 } from "poseidon-lite";
9
+ import { poolLogs } from "./chain.js";
10
+ /** Hash the pool records when a note is spent (Poseidon of the nullifier, as in the circuit). */
11
+ export const nullifierHash = (nullifier) => poseidon1([nullifier]);
12
+ /** Secrets of deposit number `index` for this pool. */
13
+ export function depositSecrets(keys, scope, index) {
14
+ return generateDepositSecrets(keys.masterKeys, scope, index);
15
+ }
16
+ /** Secrets of the change note created by withdrawal number `k` from deposit `label`. */
17
+ export function changeSecrets(keys, label, k) {
18
+ return generateWithdrawalSecrets(keys.masterKeys, label, BigInt(k));
19
+ }
20
+ /** The note left after withdrawing `amount` from `note` (the next change note). */
21
+ export function noteAfterWithdrawal(keys, note, amount) {
22
+ if (amount <= 0n || amount > note.value)
23
+ throw new Error("withdrawal amount out of range");
24
+ const next = changeSecrets(keys, note.label, note.withdrawals);
25
+ const value = note.value - amount;
26
+ return {
27
+ ...note,
28
+ value,
29
+ nullifier: next.nullifier,
30
+ secret: next.secret,
31
+ commitment: getCommitment(value, note.label, next.nullifier, next.secret).hash,
32
+ withdrawals: note.withdrawals + 1,
33
+ };
34
+ }
35
+ /**
36
+ * Finds every deposit made with these keys and follows its withdrawals to the current note.
37
+ * @param gapLimit how many unused deposit indexes in a row end the search
38
+ */
39
+ export async function recoverNotes(client, config, keys, { gapLimit = 10 } = {}) {
40
+ // One scan for all three event types.
41
+ const logs = await poolLogs(client, config, ["Deposited", "Withdrawn", "Ragequit"]);
42
+ const deposits = logs.filter((log) => log.eventName === "Deposited");
43
+ const withdrawals = logs.filter((log) => log.eventName === "Withdrawn");
44
+ const ragequits = logs.filter((log) => log.eventName === "Ragequit");
45
+ const depositByPrecommitment = new Map(deposits.map((log) => [log.args._precommitmentHash, log]));
46
+ const withdrawalBySpentNullifier = new Map(withdrawals.map((log) => [log.args._spentNullifier, log]));
47
+ const ragequitByCommitment = new Map(ragequits.map((log) => [log.args._commitment, log]));
48
+ const spendable = [];
49
+ const spent = [];
50
+ let misses = 0;
51
+ for (let index = 0n; misses < gapLimit; index++) {
52
+ const secrets = depositSecrets(keys, config.scope, index);
53
+ const log = depositByPrecommitment.get(hashPrecommitment(secrets.nullifier, secrets.secret));
54
+ if (!log) {
55
+ misses += 1;
56
+ continue;
57
+ }
58
+ misses = 0;
59
+ let note = {
60
+ depositIndex: index,
61
+ label: log.args._label,
62
+ value: log.args._value,
63
+ nullifier: secrets.nullifier,
64
+ secret: secrets.secret,
65
+ commitment: log.args._commitment,
66
+ withdrawals: 0,
67
+ depositTx: log.transactionHash,
68
+ depositor: log.args._depositor,
69
+ };
70
+ // Follow the chain of withdrawals: each one spends the current note and creates the change.
71
+ for (;;) {
72
+ const withdrawal = withdrawalBySpentNullifier.get(nullifierHash(note.nullifier));
73
+ if (!withdrawal)
74
+ break;
75
+ const next = noteAfterWithdrawal(keys, note, withdrawal.args._value);
76
+ if (next.commitment !== withdrawal.args._newCommitment) {
77
+ throw new Error(`Note chain of deposit ${index} does not match the chain (withdrawal ${note.withdrawals})`);
78
+ }
79
+ note = next;
80
+ }
81
+ // A ragequit spends the current note (the deposit itself or a change note left after private
82
+ // withdrawals) and ends the chain: the pool names the commitment it took back.
83
+ const ragequit = ragequitByCommitment.get(note.commitment);
84
+ if (ragequit)
85
+ note = { ...note, ragequitTx: ragequit.transactionHash };
86
+ (note.value > 0n && !ragequit ? spendable : spent).push(note);
87
+ }
88
+ return { spendable, spent };
89
+ }
@@ -0,0 +1,49 @@
1
+ // Splits one order into pieces of random size at random times inside a window.
2
+ // Pure: randomness is injected, so plans are reproducible in tests.
3
+ /** Cryptographically random float in [0, 1). */
4
+ export function secureRandom() {
5
+ const word = new Uint32Array(1);
6
+ crypto.getRandomValues(word);
7
+ return word[0] / 2 ** 32;
8
+ }
9
+ /**
10
+ * Piece sizes: each piece gets the minimum, and the rest is shared out by random weights in
11
+ * [0.5, 1.5), so sizes vary by up to about 3x but none is tiny. Rounded to whole cents; the last
12
+ * piece takes the rounding remainder so the total is exact.
13
+ * Times: random points in the window, sorted, then pushed apart to respect the minimum gap.
14
+ */
15
+ export function planPieces(input) {
16
+ const { amount, pieces, windowSeconds, start, minPiece, minGapSeconds } = input;
17
+ const random = input.random ?? secureRandom;
18
+ if (!Number.isInteger(pieces) || pieces < 1)
19
+ throw new Error("pieces must be a positive integer");
20
+ if (amount < minPiece * BigInt(pieces))
21
+ throw new Error("amount too small for that many pieces");
22
+ if (minGapSeconds * (pieces - 1) > windowSeconds)
23
+ throw new Error("window too short for the minimum gap");
24
+ const CENT = 10000n; // 0.01 USDG in 6-decimal units
25
+ const spare = amount - minPiece * BigInt(pieces);
26
+ const weights = Array.from({ length: pieces }, () => 0.5 + random());
27
+ const weightTotal = weights.reduce((sum, weight) => sum + weight, 0);
28
+ const amounts = [];
29
+ let assigned = 0n;
30
+ for (let i = 0; i < pieces - 1; i++) {
31
+ const share = (spare * BigInt(Math.floor((weights[i] / weightTotal) * 1e9))) / 1000000000n;
32
+ const rounded = (share / CENT) * CENT;
33
+ amounts.push(minPiece + rounded);
34
+ assigned += rounded;
35
+ }
36
+ amounts.push(minPiece + spare - assigned);
37
+ // Times: sort random offsets, then enforce the gap; if pushing runs past the window, pull back.
38
+ const offsets = Array.from({ length: pieces }, () => Math.floor(random() * (windowSeconds + 1))).sort((a, b) => a - b);
39
+ for (let i = 1; i < pieces; i++)
40
+ offsets[i] = Math.max(offsets[i], offsets[i - 1] + minGapSeconds);
41
+ const overflow = offsets[pieces - 1] - windowSeconds;
42
+ if (overflow > 0) {
43
+ for (let i = pieces - 1; i >= 0; i--) {
44
+ const latest = i === pieces - 1 ? windowSeconds : offsets[i + 1] - minGapSeconds;
45
+ offsets[i] = Math.min(offsets[i], latest);
46
+ }
47
+ }
48
+ return amounts.map((pieceAmount, i) => ({ number: i, amount: pieceAmount, at: start + offsets[i] }));
49
+ }
@@ -0,0 +1,55 @@
1
+ // Withdrawal proofs with the Privacy Pools SDK. Browser-safe: the folder-based prover for Node
2
+ // lives in node.ts (`@nuluvium/sdk/node`).
3
+ import { Circuits, PrivacyPoolSDK, calculateContext, generateMerkleProof, getCommitment, } from "@0xbow/privacy-pools-core-sdk";
4
+ import { encodeAbiParameters } from "viem";
5
+ import { changeSecrets } from "./notes.js";
6
+ /**
7
+ * Prover that downloads the circuit files from `<baseUrl>/artifacts/` (browser or Node with fetch).
8
+ * The SDK checks every file against its pinned SHA-256 hashes.
9
+ */
10
+ export function createUrlProver(baseUrl) {
11
+ return new PrivacyPoolSDK(new Circuits({ baseUrl, browser: true }));
12
+ }
13
+ export function formatProof(proof) {
14
+ const p = proof.proof;
15
+ return {
16
+ pA: [String(p.pi_a[0]), String(p.pi_a[1])],
17
+ pB: [
18
+ [String(p.pi_b[0][1]), String(p.pi_b[0][0])],
19
+ [String(p.pi_b[1][1]), String(p.pi_b[1][0])],
20
+ ],
21
+ pC: [String(p.pi_c[0]), String(p.pi_c[1])],
22
+ pubSignals: proof.publicSignals.map(String),
23
+ };
24
+ }
25
+ const leanTreeDepth = (size) => (size <= 1 ? 0n : BigInt(Math.ceil(Math.log2(size))));
26
+ /**
27
+ * Proves a withdrawal of `amount` from `note` under `terms`, against the given state leaves and
28
+ * approved labels. Throws "Leaf not found" if the deposit is not in the approved set.
29
+ */
30
+ export async function proveWithdrawal(prover, config, keys, note, amount, terms, stateLeaves, approvedLabels) {
31
+ const stateProof = generateMerkleProof(stateLeaves, note.commitment);
32
+ const aspProof = generateMerkleProof(approvedLabels, note.label);
33
+ const withdrawal = {
34
+ processooor: config.entrypoint,
35
+ data: encodeAbiParameters([{ type: "tuple", components: [{ type: "address" }, { type: "address" }, { type: "uint256" }] }], [[terms.recipient, terms.feeRecipient, terms.relayFeeBps]]),
36
+ };
37
+ const change = changeSecrets(keys, note.label, note.withdrawals);
38
+ const started = Date.now();
39
+ const commitment = getCommitment(note.value, note.label, note.nullifier, note.secret);
40
+ const proof = await prover.proveWithdrawal(commitment, {
41
+ context: BigInt(calculateContext(withdrawal, config.scope)),
42
+ withdrawalAmount: amount,
43
+ stateMerkleProof: stateProof,
44
+ aspMerkleProof: aspProof,
45
+ stateRoot: stateProof.root,
46
+ stateTreeDepth: leanTreeDepth(stateLeaves.length),
47
+ aspRoot: aspProof.root,
48
+ aspTreeDepth: leanTreeDepth(approvedLabels.length),
49
+ newSecret: change.secret,
50
+ newNullifier: change.nullifier,
51
+ });
52
+ if (!(await prover.verifyWithdrawal(proof)))
53
+ throw new Error("withdrawal proof failed local verification");
54
+ return { withdrawal, proof, seconds: (Date.now() - started) / 1000 };
55
+ }
@@ -0,0 +1,97 @@
1
+ // Talks to the Nuluvium relayer and signs what the fresh address must sign (order + permit).
2
+ import { parseSignature } from "viem";
3
+ import { erc20Abi } from "./chain.js";
4
+ export class RelayerError extends Error {
5
+ status;
6
+ constructor(status, message) {
7
+ super(message);
8
+ this.status = status;
9
+ }
10
+ }
11
+ export async function getQuote(config) {
12
+ const response = await fetch(`${config.relayerUrl}/quote`);
13
+ if (!response.ok)
14
+ throw new RelayerError(response.status, "quote failed");
15
+ const body = (await response.json());
16
+ if (body.router.toLowerCase() !== config.router.toLowerCase())
17
+ throw new Error("relayer uses a different Router");
18
+ return { router: body.router, relayer: body.relayer, fee: BigInt(body.fee), gasCost: BigInt(body.gasCost) };
19
+ }
20
+ export function signOrder(account, config, order) {
21
+ return account.signTypedData({
22
+ domain: { name: "Nuluvium Router", version: "1", chainId: config.chainId, verifyingContract: config.router },
23
+ types: {
24
+ Order: [
25
+ { name: "owner", type: "address" },
26
+ { name: "tokenIn", type: "address" },
27
+ { name: "tokenOut", type: "address" },
28
+ { name: "amountIn", type: "uint256" },
29
+ { name: "minAmountOut", type: "uint256" },
30
+ { name: "maxFee", type: "uint256" },
31
+ { name: "nonce", type: "uint256" },
32
+ { name: "deadline", type: "uint256" },
33
+ ],
34
+ },
35
+ primaryType: "Order",
36
+ message: order,
37
+ });
38
+ }
39
+ /** EIP-2612 permit for `value` of `token` to `spender`, using the token's own EIP-712 domain. */
40
+ export async function signPermit(account, client, config, token, spender, value, deadline) {
41
+ const [, name, version] = await client.readContract({ address: token, abi: erc20Abi, functionName: "eip712Domain" });
42
+ const nonce = await client.readContract({ address: token, abi: erc20Abi, functionName: "nonces", args: [account.address] });
43
+ const signature = parseSignature(await account.signTypedData({
44
+ domain: { name, version, chainId: config.chainId, verifyingContract: token },
45
+ types: {
46
+ Permit: [
47
+ { name: "owner", type: "address" },
48
+ { name: "spender", type: "address" },
49
+ { name: "value", type: "uint256" },
50
+ { name: "nonce", type: "uint256" },
51
+ { name: "deadline", type: "uint256" },
52
+ ],
53
+ },
54
+ primaryType: "Permit",
55
+ message: { owner: account.address, spender, value, nonce, deadline },
56
+ }));
57
+ const v = signature.v ?? BigInt((signature.yParity ?? 0) + 27);
58
+ return { deadline: deadline.toString(), v: v.toString(), r: signature.r, s: signature.s };
59
+ }
60
+ export async function sendPiece(config, piece) {
61
+ const body = {
62
+ withdrawal: piece.withdrawal,
63
+ proof: piece.proof,
64
+ scope: config.scope.toString(),
65
+ order: Object.fromEntries(Object.entries(piece.order).map(([key, value]) => [key, String(value)])),
66
+ orderSignature: piece.orderSignature,
67
+ permit: piece.permit,
68
+ fee: piece.fee.toString(),
69
+ };
70
+ const response = await fetch(`${config.relayerUrl}/piece`, {
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 ?? "" };
79
+ }
80
+ /** Sends a signed sell (stock token → USDG on the same fresh address) through Router.swap. */
81
+ export async function sendSell(config, sell) {
82
+ const body = {
83
+ order: Object.fromEntries(Object.entries(sell.order).map(([key, value]) => [key, String(value)])),
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 ?? "" };
97
+ }
@@ -0,0 +1,86 @@
1
+ // Sends pieces: each one is a private withdrawal of the piece amount to its own fresh address and
2
+ // a buy, relayed in one transaction (Router.relayAndSwap). Pieces from one note run in order,
3
+ // because each spends the change note the previous one created.
4
+ import { fetchApprovedSet } from "./asp.js";
5
+ import { poolEvents } from "./chain.js";
6
+ import { freshAccount } from "./keys.js";
7
+ import { noteAfterWithdrawal } from "./notes.js";
8
+ import { formatProof, proveWithdrawal } from "./proof.js";
9
+ import { getQuote, sendPiece, signOrder, signPermit } from "./relayer.js";
10
+ const ORDER_DEADLINE_SECONDS = 15 * 60;
11
+ /** Random 64-bit order nonce (the Router only checks it was not used before by this owner). */
12
+ export function randomNonce() {
13
+ const words = new Uint32Array(2);
14
+ crypto.getRandomValues(words);
15
+ return (BigInt(words[0]) << 32n) | BigInt(words[1]);
16
+ }
17
+ /** One piece, end to end. Returns the result and the note left afterwards. */
18
+ export async function executePiece(ctx, note, pieceNumber, amount, target) {
19
+ const { config, keys, client, prover } = ctx;
20
+ const quote = await getQuote(config);
21
+ if (amount <= quote.fee)
22
+ throw new Error("piece smaller than the relayer fee");
23
+ const fresh = freshAccount(keys, note.depositIndex, note.withdrawals);
24
+ const [approved, leafLogs] = await Promise.all([fetchApprovedSet(client, config), poolEvents(client, config, "LeafInserted")]);
25
+ const leaves = leafLogs.sort((a, b) => Number(a.args._index - b.args._index)).map((log) => log.args._leaf);
26
+ // Relay fee 0 in the withdrawal: the relayer is paid once, through the Router, in USDG.
27
+ const { withdrawal, proof, seconds } = await proveWithdrawal(prover, config, keys, note, amount, { recipient: fresh.address, feeRecipient: quote.relayer, relayFeeBps: 0n }, leaves, approved.labels);
28
+ const deadline = BigInt(Math.floor(Date.now() / 1000) + ORDER_DEADLINE_SECONDS);
29
+ const order = {
30
+ owner: fresh.address,
31
+ tokenIn: config.usdg,
32
+ tokenOut: target.tokenOut,
33
+ amountIn: amount,
34
+ minAmountOut: await target.minAmountOut(amount - quote.fee),
35
+ maxFee: quote.fee * 2n, // room for the quote to move before the relayer sends
36
+ nonce: randomNonce(),
37
+ deadline,
38
+ };
39
+ const [orderSignature, permit] = await Promise.all([
40
+ signOrder(fresh, config, order),
41
+ signPermit(fresh, client, config, config.usdg, config.router, amount, deadline),
42
+ ]);
43
+ const sent = await sendPiece(config, { withdrawal, proof: formatProof(proof), order, orderSignature, permit, fee: quote.fee });
44
+ return {
45
+ result: { amount, tx: sent.tx, fresh: fresh.address, fee: quote.fee, proofSeconds: seconds, gasUsed: sent.gasUsed },
46
+ next: noteAfterWithdrawal(keys, note, amount),
47
+ };
48
+ }
49
+ /**
50
+ * Sends every piece of `plan` from `note` at its time. A failed piece is rebuilt and retried (the
51
+ * ASP root or the state tree may have moved since the proof was made). Returns the results and the
52
+ * note that stays shielded.
53
+ */
54
+ export async function runPlan(ctx, startNote, plan, target, { onEvent = () => { }, maxAttempts = 3, retryDelayMs = 20_000, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), } = {}) {
55
+ const total = plan.reduce((sum, piece) => sum + piece.amount, 0n);
56
+ if (total > startNote.value)
57
+ throw new Error("plan is larger than the note");
58
+ let note = startNote;
59
+ const results = [];
60
+ for (const piece of plan) {
61
+ const wait = piece.at * 1000 - Date.now();
62
+ if (wait > 0) {
63
+ onEvent({ type: "waiting", piece, seconds: Math.round(wait / 1000) });
64
+ await sleep(wait);
65
+ }
66
+ for (let attempt = 1;; attempt++) {
67
+ onEvent({ type: "sending", piece, attempt });
68
+ try {
69
+ const { result, next } = await executePiece(ctx, note, piece.number, piece.amount, target);
70
+ const full = { ...result, number: piece.number, attempts: attempt, sentAt: Math.floor(Date.now() / 1000) };
71
+ results.push(full);
72
+ onEvent({ type: "sent", result: full });
73
+ note = next;
74
+ break;
75
+ }
76
+ catch (error) {
77
+ const reason = error instanceof Error ? error.message : String(error);
78
+ if (attempt >= maxAttempts)
79
+ throw new Error(`piece ${piece.number} failed after ${attempt} attempts: ${reason}`);
80
+ onEvent({ type: "retry", piece, attempt, reason });
81
+ await sleep(retryDelayMs);
82
+ }
83
+ }
84
+ }
85
+ return { results, remaining: note };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@nuluvium/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "mcpName": "com.nuluvium/mcp",
4
+ "version": "0.1.1",
5
+ "type": "module",
6
+ "description": "Nuluvium MCP server: lets an AI agent trade Robinhood Chain stock tokens privately, from its own machine",
7
+ "license": "Apache-2.0",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/nuluviumhq/nuluvium.git",
11
+ "directory": "mcp"
12
+ },
13
+ "homepage": "https://github.com/nuluviumhq/nuluvium/blob/main/docs/mcp.md",
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "ai-agent",
18
+ "privacy",
19
+ "robinhood-chain",
20
+ "privacy-pools"
21
+ ],
22
+ "bin": {
23
+ "nuluvium-mcp": "./dist/mcp/src/server.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.18"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "start": "node src/server.ts",
38
+ "test": "node --test \"test/**/*.test.ts\"",
39
+ "typecheck": "tsc --noEmit",
40
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
41
+ "prepack": "npm run build && node -e \"require('fs').copyFileSync('../LICENSE','LICENSE')\""
42
+ },
43
+ "dependencies": {
44
+ "@0xbow/privacy-pools-core-sdk": "1.5.0",
45
+ "@modelcontextprotocol/sdk": "1.32.2",
46
+ "@scure/bip39": "1.5.4",
47
+ "poseidon-lite": "0.3.0",
48
+ "viem": "2.57.8",
49
+ "zod": "3.25.76"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "22.19.1",
53
+ "typescript": "5.9.3"
54
+ },
55
+ "overrides": {
56
+ "@0xbow/privacy-pools-core-sdk": {
57
+ "viem": "2.57.8"
58
+ }
59
+ }
60
+ }