@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.
- package/LICENSE +201 -0
- package/README.md +70 -2
- package/dist/mcp/src/approval.js +24 -0
- package/dist/mcp/src/artifacts.js +40 -0
- package/dist/mcp/src/deposit.js +29 -0
- package/dist/mcp/src/engine.js +137 -0
- package/dist/mcp/src/networks.js +21 -0
- package/dist/mcp/src/server.js +270 -0
- package/dist/mcp/src/store.js +48 -0
- package/dist/sdk/src/asp.js +91 -0
- package/dist/sdk/src/chain.js +63 -0
- package/dist/sdk/src/config.js +14 -0
- package/dist/sdk/src/deposit.js +47 -0
- package/dist/sdk/src/exit.js +99 -0
- package/dist/sdk/src/index.js +20 -0
- package/dist/sdk/src/keys.js +76 -0
- package/dist/sdk/src/node.js +22 -0
- package/dist/sdk/src/notes.js +89 -0
- package/dist/sdk/src/planner.js +49 -0
- package/dist/sdk/src/proof.js +55 -0
- package/dist/sdk/src/relayer.js +97 -0
- package/dist/sdk/src/routing.js +86 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Nuluvium
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nuluvium/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP server that lets an AI agent trade stock tokens on Robinhood Chain without its trades tracing
|
|
4
|
+
back to it. The agent keeps a shielded USDG balance; each order is split into pieces of random size,
|
|
5
|
+
sent at random times, each bought from a fresh address through the Nuluvium relayer.
|
|
6
|
+
|
|
7
|
+
It runs **on the agent's own machine**: the secret, the notes and the order schedule never leave it.
|
|
8
|
+
Privacy is from other readers of the chain, not from Robinhood.
|
|
9
|
+
|
|
10
|
+
**Testnet only for now** (Robinhood Chain testnet, test tokens). Deposits are capped at 1,000 USDG
|
|
11
|
+
each until the audit.
|
|
12
|
+
|
|
13
|
+
## Setup
|
|
14
|
+
|
|
15
|
+
Node.js 22.18 or newer. First, once:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx -y @nuluvium/mcp --prepare
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
This installs the package and downloads the circuit files (about 23 MB) into
|
|
22
|
+
`~/.nuluvium/artifacts`, then exits. It needs no secret. Without it the first start takes over a
|
|
23
|
+
minute, longer than many MCP clients wait. The Privacy Pools SDK checks every circuit file against
|
|
24
|
+
its pinned SHA-256 hash before proving.
|
|
25
|
+
|
|
26
|
+
Then add this to your MCP client config (Claude Code `.mcp.json`, Claude Desktop
|
|
27
|
+
`claude_desktop_config.json`, Cursor, Codex…):
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"mcpServers": {
|
|
32
|
+
"nuluvium": {
|
|
33
|
+
"command": "npx",
|
|
34
|
+
"args": ["-y", "@nuluvium/mcp"],
|
|
35
|
+
"env": {
|
|
36
|
+
"NULUVIUM_MNEMONIC": "${NULUVIUM_MNEMONIC}",
|
|
37
|
+
"NULUVIUM_NETWORK": "robinhood-testnet"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Set `NULUVIUM_MNEMONIC` in the agent's environment: twelve words that only this machine knows. Use a
|
|
45
|
+
new testnet mnemonic, never a real wallet's.
|
|
46
|
+
|
|
47
|
+
| Variable | |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `NULUVIUM_MNEMONIC` | required. The agent's secret. Removed from the process environment after reading; never returned |
|
|
50
|
+
| `NULUVIUM_NETWORK` | default `robinhood-testnet` |
|
|
51
|
+
| `NULUVIUM_RPC_URL` | optional own RPC (for networks that block `*.robinhood.com`) |
|
|
52
|
+
| `NULUVIUM_HOME` | default `~/.nuluvium` (order schedule and circuit files; local only) |
|
|
53
|
+
| `NULUVIUM_ARTIFACTS` | optional folder with the circuit files |
|
|
54
|
+
|
|
55
|
+
## Tools
|
|
56
|
+
|
|
57
|
+
| Tool | Does |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `get_balance` | Shielded USDG per note with its status (approved, waiting, rejected), the deposit wallet, tradable tokens |
|
|
60
|
+
| `deposit` | Moves USDG from the deposit wallet into the shielded balance (1 to 1,000 USDG) |
|
|
61
|
+
| `route_order` | Buys a stock token in pieces over a time window; returns at once, pieces go out in the background |
|
|
62
|
+
| `cancel_order` | Cancels pieces not sent yet |
|
|
63
|
+
| `get_orders` | Orders and the status of every piece |
|
|
64
|
+
| `get_fills` | Executed pieces: USDG spent, fee, tokens received, fresh address, transaction |
|
|
65
|
+
|
|
66
|
+
The deposit wallet is the mnemonic's first address (`m/44'/60'/0'/0/0`): send it USDG and a little
|
|
67
|
+
ETH for gas, then call `deposit`. A deposit is public; what the note pays for later is not linked to
|
|
68
|
+
it. Orders run while the server runs.
|
|
69
|
+
|
|
70
|
+
Docs: [github.com/nuluviumhq/nuluvium](https://github.com/nuluviumhq/nuluvium/blob/main/docs/mcp.md).
|
|
71
|
+
License: Apache-2.0.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Which notes can pay for an order. A note pays only once the approved-set provider (ASP) has put
|
|
2
|
+
// its deposit label in the approved set: before that, the withdrawal proof for a piece is refused.
|
|
3
|
+
// Right after `deposit` the new note is "waiting" for about a minute.
|
|
4
|
+
export function noteApproval(note, set) {
|
|
5
|
+
if (set.labels.includes(note.label))
|
|
6
|
+
return { approval: "approved" };
|
|
7
|
+
const rejected = set.rejected.find((item) => BigInt(item.label) === note.label);
|
|
8
|
+
return rejected ? { approval: "rejected", reason: rejected.reason } : { approval: "waiting" };
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The note an order of `amount` pays from: the smallest approved, free note that covers it (bigger
|
|
12
|
+
* notes stay for bigger orders). Otherwise a message telling the agent why none fits.
|
|
13
|
+
*/
|
|
14
|
+
export function pickNote(notes, set, busy, amount) {
|
|
15
|
+
const covering = notes.filter((note) => note.value >= amount && !busy.has(note.depositIndex.toString()));
|
|
16
|
+
const approved = covering.filter((note) => noteApproval(note, set).approval === "approved");
|
|
17
|
+
const note = approved.sort((a, b) => (a.value < b.value ? -1 : a.value > b.value ? 1 : 0))[0];
|
|
18
|
+
if (note)
|
|
19
|
+
return { note };
|
|
20
|
+
if (covering.some((item) => noteApproval(item, set).approval === "waiting")) {
|
|
21
|
+
return { problem: "The note that covers this order is still waiting for the clean-funds check (usually about a minute after the deposit). Try again shortly; get_balance shows each note's status." };
|
|
22
|
+
}
|
|
23
|
+
return { problem: "No free, approved note covers this amount. Use get_balance to see the notes; one order is paid from one note." };
|
|
24
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Circuit files (wasm, zkey, vkey for the commitment and withdraw circuits, about 23 MB) that the
|
|
2
|
+
// prover needs. Run from source they come from testnet/setup-artifacts.mjs; installed from npm they
|
|
3
|
+
// are downloaded once from the Nuluvium site into ~/.nuluvium/artifacts. Where they come from does
|
|
4
|
+
// not matter for safety: the Privacy Pools SDK checks every file against its pinned SHA-256 hashes
|
|
5
|
+
// before proving, so a changed file is refused.
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
export const ARTIFACT_FILES = ["commitment.wasm", "commitment.zkey", "commitment.vkey", "withdraw.wasm", "withdraw.zkey", "withdraw.vkey"];
|
|
10
|
+
/** The files still missing from `folder`. */
|
|
11
|
+
export function missingArtifacts(folder) {
|
|
12
|
+
return ARTIFACT_FILES.filter((name) => !existsSync(join(folder, name)));
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Downloads the missing files from `baseUrl` (e.g. https://…/artifacts) into `folder`. Each file is
|
|
16
|
+
* written to a temporary name first and renamed when complete, so an interrupted download is
|
|
17
|
+
* fetched again next time instead of being used half-written.
|
|
18
|
+
*/
|
|
19
|
+
export async function ensureArtifacts(folder, baseUrl, log = () => { }) {
|
|
20
|
+
const missing = missingArtifacts(folder);
|
|
21
|
+
if (missing.length === 0)
|
|
22
|
+
return;
|
|
23
|
+
await mkdir(folder, { recursive: true });
|
|
24
|
+
log(`downloading ${missing.length} circuit files (about 23 MB, once) into ${folder}`);
|
|
25
|
+
for (const name of missing) {
|
|
26
|
+
const response = await fetch(`${baseUrl}/${name}`, { signal: AbortSignal.timeout(180_000) });
|
|
27
|
+
if (!response.ok)
|
|
28
|
+
throw new Error(`could not download circuit file ${name} (HTTP ${response.status})`);
|
|
29
|
+
const partial = join(folder, `${name}.partial`);
|
|
30
|
+
try {
|
|
31
|
+
await writeFile(partial, new Uint8Array(await response.arrayBuffer()));
|
|
32
|
+
await rename(partial, join(folder, name));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
await rm(partial, { force: true });
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
log("circuit files ready");
|
|
40
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The deposit tool's rules, kept apart from the server so they can be tested without a chain.
|
|
2
|
+
// A deposit is paid from the agent's own wallet (the mnemonic's account 0, see sdk depositAccount):
|
|
3
|
+
// it needs the USDG and a little ETH for two transactions (approve, then deposit).
|
|
4
|
+
/** Beta cap per deposit, the same as the approved-set provider applies (asp/src/screen.js). */
|
|
5
|
+
export const DEPOSIT_CAP = 1000n * 1000000n;
|
|
6
|
+
/** Smallest deposit: one piece of the smallest order (1 USDG). */
|
|
7
|
+
export const MIN_DEPOSIT = 1000000n;
|
|
8
|
+
/** Gas reserve for approve + deposit on Robinhood Chain (an L2: well above the real cost). */
|
|
9
|
+
export const MIN_GAS_WEI = 10n ** 13n; // 0.00001 ETH
|
|
10
|
+
/** Why this deposit cannot go ahead, or null when it can. Messages are written for the agent. */
|
|
11
|
+
export function depositProblem(amount, funds, wallet, faucet) {
|
|
12
|
+
if (amount < MIN_DEPOSIT)
|
|
13
|
+
return "The smallest deposit is 1 USDG.";
|
|
14
|
+
if (amount > DEPOSIT_CAP)
|
|
15
|
+
return "Deposits are capped at 1,000 USDG each until the audit; a larger one would not be approved.";
|
|
16
|
+
if (funds.usdg < amount) {
|
|
17
|
+
return `The deposit wallet ${wallet} holds ${formatUsdg(funds.usdg)} USDG, less than ${formatUsdg(amount)}. Send USDG to it first.`;
|
|
18
|
+
}
|
|
19
|
+
if (funds.eth < MIN_GAS_WEI) {
|
|
20
|
+
return `The deposit wallet ${wallet} has no ETH for gas. Send it a little ETH first${faucet ? ` (testnet faucet: ${faucet})` : ""}.`;
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
/** USDG units (6 decimals) as a plain number string, trailing zeros dropped. */
|
|
25
|
+
export function formatUsdg(units) {
|
|
26
|
+
const whole = units / 1000000n;
|
|
27
|
+
const fraction = (units % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
28
|
+
return fraction ? `${whole}.${fraction}` : whole.toString();
|
|
29
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Runs orders in the background: each piece at its time, pieces of one order one after another.
|
|
2
|
+
// Before every piece the note is rebuilt from the chain, so restarts and partial runs are safe.
|
|
3
|
+
import { parseAbi } from "viem";
|
|
4
|
+
import { executePiece, fetchApprovedSet, publicClientFor, recoverNotes, } from "../../sdk/src/index.js";
|
|
5
|
+
import { createFolderProver } from "../../sdk/src/node.js";
|
|
6
|
+
const balanceAbi = parseAbi(["function balanceOf(address) view returns (uint256)"]);
|
|
7
|
+
const MAX_ATTEMPTS = 3;
|
|
8
|
+
const RETRY_DELAY_MS = 20_000;
|
|
9
|
+
export class Engine {
|
|
10
|
+
ctx;
|
|
11
|
+
network;
|
|
12
|
+
store;
|
|
13
|
+
timers = new Map();
|
|
14
|
+
/** One promise chain per note (deposit index): pieces spending the same note never overlap. */
|
|
15
|
+
lanes = new Map();
|
|
16
|
+
/** Resolves once the circuit files are on disk; called before every proof (retries a failed download). */
|
|
17
|
+
prepareProver;
|
|
18
|
+
constructor(network, keys, store, artifactFolder, prepareProver) {
|
|
19
|
+
this.network = network;
|
|
20
|
+
this.store = store;
|
|
21
|
+
this.prepareProver = prepareProver;
|
|
22
|
+
const client = publicClientFor(network.config);
|
|
23
|
+
this.ctx = { config: network.config, keys, client, prover: createFolderProver(artifactFolder) };
|
|
24
|
+
}
|
|
25
|
+
async notes() {
|
|
26
|
+
return (await recoverNotes(this.ctx.client, this.ctx.config, this.ctx.keys)).spendable;
|
|
27
|
+
}
|
|
28
|
+
/** The last approved set that matched the root on chain. */
|
|
29
|
+
lastApprovedSet = null;
|
|
30
|
+
/**
|
|
31
|
+
* The ASP's approved set, checked against its CID and the root on chain. After the ASP posts a
|
|
32
|
+
* new root, its status can point at the previous set for up to about a minute (Cloudflare KV
|
|
33
|
+
* spreads writes slowly), so a fresh read may not match. Then the last matching set is used: it
|
|
34
|
+
* can only miss the newest approvals, which then show as waiting. Null when no set has matched
|
|
35
|
+
* yet in this run.
|
|
36
|
+
*/
|
|
37
|
+
async approvedSet() {
|
|
38
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
39
|
+
try {
|
|
40
|
+
this.lastApprovedSet = await fetchApprovedSet(this.ctx.client, this.ctx.config);
|
|
41
|
+
return this.lastApprovedSet;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
if (attempt === 0)
|
|
45
|
+
await new Promise((resolve) => setTimeout(resolve, 3_000));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return this.lastApprovedSet;
|
|
49
|
+
}
|
|
50
|
+
/** Arms timers for every piece still scheduled (new orders and orders left from a restart). */
|
|
51
|
+
resumeAll() {
|
|
52
|
+
for (const order of this.store.all()) {
|
|
53
|
+
for (const piece of order.pieces) {
|
|
54
|
+
// A piece caught mid-send by a restart is checked again: the note rebuild shows if it landed.
|
|
55
|
+
if (piece.status === "scheduled" || piece.status === "sending")
|
|
56
|
+
this.arm(order, piece.number);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
arm(order, number) {
|
|
61
|
+
const piece = order.pieces.find((item) => item.number === number);
|
|
62
|
+
const key = `${order.id}:${number}`;
|
|
63
|
+
if (this.timers.has(key))
|
|
64
|
+
return;
|
|
65
|
+
const delay = Math.max(0, piece.at * 1000 - Date.now());
|
|
66
|
+
this.timers.set(key, setTimeout(() => {
|
|
67
|
+
this.timers.delete(key);
|
|
68
|
+
const lane = this.lanes.get(order.depositIndex) ?? Promise.resolve();
|
|
69
|
+
const next = lane.then(() => this.runPiece(order.id, number));
|
|
70
|
+
this.lanes.set(order.depositIndex, next.catch(() => { }));
|
|
71
|
+
}, delay));
|
|
72
|
+
}
|
|
73
|
+
/** Stops pieces not sent yet. Returns how many were cancelled. */
|
|
74
|
+
cancel(order) {
|
|
75
|
+
let cancelled = 0;
|
|
76
|
+
for (const piece of order.pieces) {
|
|
77
|
+
if (piece.status !== "scheduled")
|
|
78
|
+
continue;
|
|
79
|
+
const key = `${order.id}:${piece.number}`;
|
|
80
|
+
clearTimeout(this.timers.get(key));
|
|
81
|
+
this.timers.delete(key);
|
|
82
|
+
this.store.updatePiece(order.id, piece.number, { status: "cancelled" });
|
|
83
|
+
cancelled += 1;
|
|
84
|
+
}
|
|
85
|
+
return cancelled;
|
|
86
|
+
}
|
|
87
|
+
async runPiece(orderId, number) {
|
|
88
|
+
const order = this.store.get(orderId);
|
|
89
|
+
const piece = order?.pieces.find((item) => item.number === number);
|
|
90
|
+
if (!order || !piece || piece.status === "cancelled" || piece.status === "done")
|
|
91
|
+
return;
|
|
92
|
+
const token = this.network.tokens[order.token];
|
|
93
|
+
for (let attempt = 1;; attempt++) {
|
|
94
|
+
this.store.updatePiece(orderId, number, { status: "sending" });
|
|
95
|
+
try {
|
|
96
|
+
await this.prepareProver();
|
|
97
|
+
const note = (await this.notes()).find((item) => item.depositIndex === BigInt(order.depositIndex));
|
|
98
|
+
if (!note)
|
|
99
|
+
throw new Error("the note for this order is gone (spent elsewhere?)");
|
|
100
|
+
const amount = BigInt(piece.amount);
|
|
101
|
+
if (amount > note.value)
|
|
102
|
+
throw new Error(`note holds ${note.value}, piece needs ${amount}`);
|
|
103
|
+
const { result } = await executePiece(this.ctx, note, number, amount, {
|
|
104
|
+
tokenOut: token.address,
|
|
105
|
+
minAmountOut: (usdgIn) => (token.expectedOut(usdgIn) * BigInt(10_000 - order.slippageBps)) / 10000n,
|
|
106
|
+
});
|
|
107
|
+
const receipt = await this.ctx.client.waitForTransactionReceipt({ hash: result.tx });
|
|
108
|
+
const received = await this.ctx.client.readContract({
|
|
109
|
+
address: token.address,
|
|
110
|
+
abi: balanceAbi,
|
|
111
|
+
functionName: "balanceOf",
|
|
112
|
+
args: [result.fresh],
|
|
113
|
+
blockNumber: receipt.blockNumber,
|
|
114
|
+
});
|
|
115
|
+
this.store.updatePiece(orderId, number, {
|
|
116
|
+
status: "done",
|
|
117
|
+
tx: result.tx,
|
|
118
|
+
fresh: result.fresh,
|
|
119
|
+
fee: result.fee.toString(),
|
|
120
|
+
received: received.toString(),
|
|
121
|
+
sentAt: Math.floor(Date.now() / 1000),
|
|
122
|
+
error: undefined,
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
const reason = error.shortMessage ?? (error instanceof Error ? error.message : String(error));
|
|
128
|
+
if (attempt >= MAX_ATTEMPTS) {
|
|
129
|
+
this.store.updatePiece(orderId, number, { status: "failed", error: reason });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
console.error(`[nuluvium] piece ${orderId}:${number} attempt ${attempt} failed: ${reason}; retrying`);
|
|
133
|
+
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Networks and tradable tokens. Only allowlisted tokens can be routed.
|
|
2
|
+
import { ROBINHOOD_TESTNET } from "../../sdk/src/index.js";
|
|
3
|
+
const MOCK_USDG_PER_STOCK = 180000000n; // contracts/deployments/46630-router.json
|
|
4
|
+
export const NETWORKS = {
|
|
5
|
+
"robinhood-testnet": {
|
|
6
|
+
name: "Robinhood Chain testnet",
|
|
7
|
+
config: ROBINHOOD_TESTNET,
|
|
8
|
+
explorer: "https://explorer.testnet.chain.robinhood.com",
|
|
9
|
+
faucet: "https://faucet.testnet.chain.robinhood.com",
|
|
10
|
+
artifactsUrl: "https://nuluvium.com/artifacts",
|
|
11
|
+
tokens: {
|
|
12
|
+
MSTK: {
|
|
13
|
+
symbol: "MSTK",
|
|
14
|
+
address: "0xf2a0289ec25994dC7d22461Afd1dF3B818A0E088",
|
|
15
|
+
decimals: 18,
|
|
16
|
+
expectedOut: (usdgIn) => (usdgIn * 10n ** 18n) / MOCK_USDG_PER_STOCK,
|
|
17
|
+
note: "Testnet mock stock at a fixed price of 180 tUSDG (no official Uniswap on testnet).",
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
};
|