@gvnrdao/dh-mcp 0.0.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.
Files changed (43) hide show
  1. package/.env.example +22 -0
  2. package/README.md +39 -0
  3. package/dist/index.js +1575 -0
  4. package/package.json +26 -0
  5. package/src/actions/index.ts +13 -0
  6. package/src/actions/loan-create.action.ts +28 -0
  7. package/src/actions/loan-extend.action.ts +17 -0
  8. package/src/actions/loan-mint.action.ts +17 -0
  9. package/src/actions/loan-pay.action.ts +17 -0
  10. package/src/actions/loan-withdraw.action.ts +17 -0
  11. package/src/actions/types.ts +33 -0
  12. package/src/config.ts +43 -0
  13. package/src/context.ts +87 -0
  14. package/src/index.ts +23 -0
  15. package/src/resources/position.ts +39 -0
  16. package/src/resources/protocol.ts +57 -0
  17. package/src/server.ts +58 -0
  18. package/src/signer/eoa-dh.ts +35 -0
  19. package/src/signer/index.ts +12 -0
  20. package/src/signer/safe-module-signer-adapter.ts +61 -0
  21. package/src/signer/safe-module.ts +110 -0
  22. package/src/signer/types.ts +12 -0
  23. package/src/tools/_helpers.ts +47 -0
  24. package/src/tools/btc.ts +38 -0
  25. package/src/tools/loan.ts +197 -0
  26. package/src/tools/position.ts +93 -0
  27. package/src/tools/protocol.ts +35 -0
  28. package/src/util/btc-address.ts +58 -0
  29. package/src/util/eip712-login.ts +65 -0
  30. package/src/util/errors.ts +24 -0
  31. package/src/util/extend-fee-bound.ts +51 -0
  32. package/src/util/format.ts +9 -0
  33. package/src/util/network.ts +34 -0
  34. package/src/util/server-fetch.ts +27 -0
  35. package/src/util/server-mint.ts +108 -0
  36. package/src/util/server-renew.ts +107 -0
  37. package/src/util/server-repay.ts +118 -0
  38. package/src/util/server-session.ts +108 -0
  39. package/src/util/server-withdraw.ts +34 -0
  40. package/src/util/tx-validator.ts +231 -0
  41. package/src/util/validate.ts +41 -0
  42. package/tsconfig.json +20 -0
  43. package/tsup.config.ts +11 -0
@@ -0,0 +1,231 @@
1
+ import { ethers } from "ethers";
2
+ import { getContractsByNetwork } from "@gvnrdao/dh-sdk";
3
+ import type { DeploymentContracts } from "@gvnrdao/dh-sdk";
4
+
5
+ const SIGNABLE_FUNCTIONS = [
6
+ "function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)",
7
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
8
+ "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)",
9
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
10
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
11
+ "function withdrawBTC((bytes32 positionId, bytes32 actionHash, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractBundleHash, string withdrawalAddress, uint256 totalDeduction, uint256 newCollateral, uint256 quantumTimestamp, uint256 btcPrice, string utxoTxid, uint32 utxoVout) params, bytes withdrawalValidatorSignature, bytes btcSpendAuthSignature) external returns (bool)",
12
+ "function approve(address spender, uint256 amount) external returns (bool)",
13
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external",
14
+ ] as const;
15
+
16
+ const IFACE = new ethers.Interface(SIGNABLE_FUNCTIONS as unknown as string[]);
17
+
18
+ export type ExpectedAction =
19
+ | { kind: "mint"; positionId: string; amountWei: string; mintFeeWei: string }
20
+ | { kind: "repay"; positionId: string; amountWei: string }
21
+ | { kind: "extend"; positionId: string; selectedTerm: number; upperBoundProRataFeeWei?: string }
22
+ | {
23
+ kind: "withdraw-btc";
24
+ positionId: string;
25
+ btcAddress: string;
26
+ /**
27
+ * Audit M-9: optional upper bound on the on-chain `totalDeduction`
28
+ * (withdrawBTC params index 6 — the collateral debited from the vault).
29
+ * The validator refuses to sign if the server-returned value exceeds it,
30
+ * so a compromised server/validator cannot inflate the deduction beyond
31
+ * what the user approved. Compute from the user-approved amount + fee.
32
+ *
33
+ * NOT YET WIRED: the MCP/CLI withdraw flow is server-delegated
34
+ * (`sdk.withdrawBTCAndExecute`) and does not construct a `withdraw-btc`
35
+ * ExpectedAction, and `upperBoundTotalDeduction` is not plumbed through the
36
+ * SDK → server → LIT Action. End-to-end enforcement requires that plumbing
37
+ * (incl. a btc-withdrawal LIT Action change); until then this guard is inert.
38
+ */
39
+ upperBoundTotalDeduction?: string;
40
+ }
41
+ | { kind: "ucd-approve"; spenderCandidates: string[]; minAmountWei: string }
42
+ | { kind: "set-position-delegate"; positionId: string; delegate: string; registryAddress: string };
43
+
44
+ export interface ValidationContext {
45
+ chainId: number;
46
+ network: string;
47
+ contracts: DeploymentContracts;
48
+ }
49
+
50
+ export class TxValidationError extends Error {
51
+ constructor(msg: string) {
52
+ super(`Refusing to sign server-returned transaction: ${msg}`);
53
+ this.name = "TxValidationError";
54
+ }
55
+ }
56
+
57
+ export function buildValidationContext(network: string, chainId: number): ValidationContext {
58
+ const sdkKey =
59
+ chainId === 31337 ? "localhost" :
60
+ chainId === 11155111 ? "sepolia" :
61
+ network.toLowerCase();
62
+ const contracts = getContractsByNetwork(sdkKey);
63
+ if (!contracts) {
64
+ throw new TxValidationError(
65
+ `no SDK contract registry for network='${network}' chainId=${chainId} (sdkKey='${sdkKey}')`,
66
+ );
67
+ }
68
+ return { chainId, network, contracts };
69
+ }
70
+
71
+ function eqAddr(a?: string, b?: string): boolean {
72
+ if (!a || !b) return false;
73
+ try { return ethers.getAddress(a) === ethers.getAddress(b); } catch { return false; }
74
+ }
75
+
76
+ function readToAddress(tx: Record<string, unknown>): string {
77
+ const to = tx["to"];
78
+ if (typeof to !== "string") throw new TxValidationError(`unsignedTx.to is missing or not a string`);
79
+ return to;
80
+ }
81
+
82
+ function readData(tx: Record<string, unknown>): string {
83
+ const data = tx["data"];
84
+ if (typeof data !== "string" || !data.startsWith("0x")) throw new TxValidationError(`unsignedTx.data missing or malformed`);
85
+ return data;
86
+ }
87
+
88
+ function readChainId(tx: Record<string, unknown>): number | null {
89
+ const c = tx["chainId"];
90
+ if (c == null) return null;
91
+ if (typeof c === "number") return c;
92
+ if (typeof c === "string") return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
93
+ if (typeof c === "bigint") return Number(c);
94
+ return null;
95
+ }
96
+
97
+ function readValue(tx: Record<string, unknown>): bigint {
98
+ const v = tx["value"];
99
+ if (v == null) return 0n;
100
+ if (typeof v === "string") return BigInt(v.startsWith("0x") ? v : v);
101
+ if (typeof v === "number") return BigInt(v);
102
+ if (typeof v === "bigint") return v;
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ if (typeof (v as any)?.toBigInt === "function") return (v as any).toBigInt();
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
+ if (typeof (v as any)?.toString === "function") return BigInt((v as any).toString());
107
+ throw new TxValidationError(`unsignedTx.value has unrecognized type`);
108
+ }
109
+
110
+ function decode(data: string): { name: string; args: ethers.Result } {
111
+ try {
112
+ const parsed = IFACE.parseTransaction({ data });
113
+ if (!parsed) throw new TxValidationError(`unsignedTx.data does not decode against the signable-function whitelist`);
114
+ return { name: parsed.name, args: parsed.args };
115
+ } catch (e) {
116
+ if (e instanceof TxValidationError) throw e;
117
+ throw new TxValidationError(
118
+ `unsignedTx.data does not decode against the signable-function whitelist: ${(e as Error).message}`,
119
+ );
120
+ }
121
+ }
122
+
123
+ function normalizePositionId(id: string): string {
124
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
125
+ return ethers.zeroPadValue(hex, 32).toLowerCase();
126
+ }
127
+
128
+ export function validateUnsignedTx(
129
+ unsignedTx: Record<string, unknown>,
130
+ expected: ExpectedAction,
131
+ vctx: ValidationContext,
132
+ ): void {
133
+ const txChainId = readChainId(unsignedTx);
134
+ if (txChainId != null && txChainId !== vctx.chainId) {
135
+ throw new TxValidationError(`chainId mismatch — tx says ${txChainId}, expected ${vctx.chainId}`);
136
+ }
137
+ const value = readValue(unsignedTx);
138
+ if (value !== 0n) throw new TxValidationError(`unsignedTx.value is non-zero (${value})`);
139
+
140
+ const to = readToAddress(unsignedTx);
141
+ const data = readData(unsignedTx);
142
+ const { name, args } = decode(data);
143
+ const pm = vctx.contracts.PositionManager;
144
+
145
+ switch (expected.kind) {
146
+ case "mint": {
147
+ if (name !== "mintUCD") throw new TxValidationError(`expected mintUCD, server returned ${name}`);
148
+ if (!eqAddr(to, pm)) throw new TxValidationError(`mintUCD must target PositionManager (${pm}), got ${to}`);
149
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
150
+ throw new TxValidationError(`positionId mismatch`);
151
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
152
+ throw new TxValidationError(`mintAmount mismatch`);
153
+ if (BigInt(String(args[2])).toString() !== expected.mintFeeWei)
154
+ throw new TxValidationError(`mintFee mismatch`);
155
+ break;
156
+ }
157
+ case "repay": {
158
+ if (name !== "makePayment" && name !== "repayPosition")
159
+ throw new TxValidationError(`expected makePayment/repayPosition, server returned ${name}`);
160
+ if (!eqAddr(to, pm)) throw new TxValidationError(`${name} must target PositionManager`);
161
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
162
+ throw new TxValidationError(`positionId mismatch`);
163
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
164
+ throw new TxValidationError(`paymentAmount mismatch`);
165
+ break;
166
+ }
167
+ case "extend": {
168
+ if (name !== "extendPosition") throw new TxValidationError(`expected extendPosition, server returned ${name}`);
169
+ if (!eqAddr(to, pm)) throw new TxValidationError(`extendPosition must target PositionManager`);
170
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
171
+ throw new TxValidationError(`positionId mismatch`);
172
+ if (Number(args[1]) !== expected.selectedTerm) throw new TxValidationError(`selectedTerm mismatch`);
173
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
174
+ const txFee = BigInt(String(args[5]));
175
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
176
+ if (txFee > upper) throw new TxValidationError(`proRataRenewalFee=${txFee} exceeds upper bound=${upper}`);
177
+ }
178
+ break;
179
+ }
180
+ case "withdraw-btc": {
181
+ if (name !== "withdrawBTC") throw new TxValidationError(`expected withdrawBTC, server returned ${name}`);
182
+ if (!eqAddr(to, pm)) throw new TxValidationError(`withdrawBTC must target PositionManager`);
183
+ const paramsTuple = args[0] as unknown as ethers.Result;
184
+ if (String(paramsTuple[0]).toLowerCase() !== normalizePositionId(expected.positionId))
185
+ throw new TxValidationError(`positionId mismatch`);
186
+ if (String(paramsTuple[5]) !== expected.btcAddress) throw new TxValidationError(`btcAddress mismatch`);
187
+ // Audit M-9: cap totalDeduction (params index 6) at the user-approved upper bound.
188
+ if (expected.upperBoundTotalDeduction != null) {
189
+ const txDeduction = BigInt(String(paramsTuple[6]));
190
+ const upper = BigInt(expected.upperBoundTotalDeduction);
191
+ if (txDeduction > upper)
192
+ throw new TxValidationError(
193
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}`,
194
+ );
195
+ }
196
+ break;
197
+ }
198
+ case "ucd-approve": {
199
+ if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
200
+ const ucd = vctx.contracts.UCDToken;
201
+ if (!eqAddr(to, ucd)) throw new TxValidationError(`approve must target UCDToken`);
202
+ if (!expected.spenderCandidates.some((s) => eqAddr(String(args[0]), s)))
203
+ throw new TxValidationError(`approve spender not in expected set`);
204
+ const amt = BigInt(String(args[1]));
205
+ const min = BigInt(expected.minAmountWei);
206
+ if (amt < min) throw new TxValidationError(`approve amount ${amt} is less than required ${min}`);
207
+ if (amt > min * 1000n) throw new TxValidationError(`approve amount ${amt} exceeds sanity cap`);
208
+ break;
209
+ }
210
+ case "set-position-delegate": {
211
+ if (name !== "setPositionDelegate") throw new TxValidationError(`expected setPositionDelegate`);
212
+ if (!eqAddr(to, expected.registryAddress)) throw new TxValidationError(`setPositionDelegate wrong target`);
213
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
214
+ throw new TxValidationError(`positionId mismatch`);
215
+ if (!eqAddr(String(args[1]), expected.delegate)) throw new TxValidationError(`delegate mismatch`);
216
+ break;
217
+ }
218
+ }
219
+ }
220
+
221
+ export function describeUnsignedTx(unsignedTx: Record<string, unknown>): { to: string; fn: string; chainId: number | null } {
222
+ const to = readToAddress(unsignedTx);
223
+ const data = readData(unsignedTx);
224
+ const chainId = readChainId(unsignedTx);
225
+ let fn = "<unparseable>";
226
+ try {
227
+ const parsed = IFACE.parseTransaction({ data });
228
+ if (parsed) fn = parsed.name;
229
+ } catch { /* leave as <unparseable> */ }
230
+ return { to, fn, chainId };
231
+ }
@@ -0,0 +1,41 @@
1
+ import { fatal } from "./errors.js";
2
+
3
+ const POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
4
+ const SATS_SANITY_CAP = 1e10;
5
+ const UCD_SANITY_CAP = 1e9;
6
+
7
+ export function assertPositionIdHex(id: string, label = "Position ID"): void {
8
+ if (!POSITION_ID_RE.test(id)) {
9
+ fatal(`${label} must be 0x-prefixed 32-byte hex (got '${id}').`);
10
+ }
11
+ }
12
+
13
+ export function assertUcdAmount(amount: number, label = "Amount"): void {
14
+ if (!Number.isFinite(amount) || amount <= 0) {
15
+ fatal(`${label} must be a positive finite number (got ${amount}).`);
16
+ }
17
+ if (amount > UCD_SANITY_CAP) {
18
+ fatal(`${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`);
19
+ }
20
+ if (amount > 0 && amount < 1e-6) {
21
+ fatal(`${label} ${amount} has more than 6 decimals of precision — likely a typo.`);
22
+ }
23
+ }
24
+
25
+ export function assertSatsAmount(sats: number, label = "Amount"): void {
26
+ if (!Number.isInteger(sats) || sats <= 0) {
27
+ fatal(`${label} must be a positive integer (satoshis), got ${sats}.`);
28
+ }
29
+ if (sats > SATS_SANITY_CAP) {
30
+ fatal(`${label} ${sats} sats exceeds the 100 BTC sanity cap.`);
31
+ }
32
+ }
33
+
34
+ export function assertSelectedTerm(months: number, label = "Term"): void {
35
+ if (!Number.isInteger(months) || months <= 0) {
36
+ fatal(`${label} must be a positive integer (months), got ${months}.`);
37
+ }
38
+ if (months > 120) {
39
+ fatal(`${label} ${months} months exceeds the 10-year sanity cap.`);
40
+ }
41
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2022"],
7
+ "outDir": "dist",
8
+ "rootDir": "src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true,
13
+ "declaration": true,
14
+ "declarationMap": true,
15
+ "sourceMap": true,
16
+ "allowImportingTsExtensions": false
17
+ },
18
+ "include": ["src/**/*"],
19
+ "exclude": ["node_modules", "dist"]
20
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: { index: "src/index.ts" },
5
+ outDir: "dist",
6
+ format: ["cjs"],
7
+ target: "node18",
8
+ clean: true,
9
+ banner: { js: "#!/usr/bin/env node" },
10
+ outExtension: () => ({ js: ".js" }),
11
+ });