@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,51 @@
1
+ import { ethers } from "ethers";
2
+ import type { McpConfig } from "../config.js";
3
+ import type { DeploymentContracts } from "@gvnrdao/dh-sdk";
4
+
5
+ const POSITION_DETAILS_ABI = [
6
+ "function getPositionDetails(bytes32) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm))",
7
+ ];
8
+
9
+ const TERM_MANAGER_ABI = [
10
+ "function getExtensionFeeRateBps(uint16 termMonths) view returns (uint256)",
11
+ ];
12
+
13
+ export interface ExtendFeeBound {
14
+ ucdDebt: bigint;
15
+ extensionFeeRateBps: bigint;
16
+ upperBoundFeeWei: bigint;
17
+ }
18
+
19
+ export async function computeExtendFeeUpperBound(
20
+ config: McpConfig,
21
+ contracts: DeploymentContracts,
22
+ positionId: string,
23
+ selectedTerm: number,
24
+ ): Promise<ExtendFeeBound | null> {
25
+ const corePm = contracts.PositionManagerCoreModule;
26
+ const termMgr = contracts.TermManagerModule;
27
+ if (!corePm || !termMgr) return null;
28
+ if (!config.rpcUrl) return null;
29
+ let provider: ethers.JsonRpcProvider;
30
+ try {
31
+ provider = new ethers.JsonRpcProvider(config.rpcUrl);
32
+ } catch {
33
+ return null;
34
+ }
35
+ const positionIdBytes32 = ethers.zeroPadValue(
36
+ positionId.startsWith("0x") ? positionId : `0x${positionId}`,
37
+ 32,
38
+ );
39
+ try {
40
+ const pm = new ethers.Contract(corePm, POSITION_DETAILS_ABI, provider);
41
+ const details = await pm["getPositionDetails"](positionIdBytes32);
42
+ const ucdDebt = BigInt(details.ucdDebt?.toString?.() ?? "0");
43
+ const tm = new ethers.Contract(termMgr, TERM_MANAGER_ABI, provider);
44
+ const bps = await tm["getExtensionFeeRateBps"](selectedTerm);
45
+ const extensionFeeRateBps = BigInt(bps.toString());
46
+ const upperBoundFeeWei = (ucdDebt * extensionFeeRateBps) / 10000n;
47
+ return { ucdDebt, extensionFeeRateBps, upperBoundFeeWei };
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
@@ -0,0 +1,9 @@
1
+ /** JSON replacer that serializes bigint as string (SDK branded types). */
2
+ export function bigintReplacer(_key: string, value: unknown): unknown {
3
+ if (typeof value === "bigint") return value.toString();
4
+ return value;
5
+ }
6
+
7
+ export function serialize(data: unknown): string {
8
+ return JSON.stringify(data, bigintReplacer, 2);
9
+ }
@@ -0,0 +1,34 @@
1
+ import { fatal } from "./errors.js";
2
+
3
+ export function requireNotMainnetForWrites(network: string): void {
4
+ if (network.toLowerCase() === "mainnet" || network === "ethereum") {
5
+ fatal(
6
+ "Mainnet writes require DH_NETWORK=mainnet to be set explicitly. " +
7
+ "This is a safety check — verify your configuration before retrying.",
8
+ );
9
+ }
10
+ }
11
+
12
+ export function assertSafeServiceEndpoint(endpoint: string): void {
13
+ let url: URL;
14
+ try {
15
+ url = new URL(endpoint);
16
+ } catch {
17
+ fatal(`Invalid serviceEndpoint: ${endpoint}`);
18
+ }
19
+ if (url.protocol === "https:") return;
20
+ if (url.protocol === "http:") {
21
+ const host = url.hostname;
22
+ const isLoopback =
23
+ host === "localhost" ||
24
+ host === "127.0.0.1" ||
25
+ host === "::1" ||
26
+ host.endsWith(".localhost");
27
+ if (isLoopback) return;
28
+ fatal(
29
+ `Refusing to use plaintext http:// for non-loopback endpoint: ${endpoint}. ` +
30
+ `Use https:// or run the lit-ops-server on localhost.`,
31
+ );
32
+ }
33
+ fatal(`Unsupported serviceEndpoint protocol '${url.protocol}': ${endpoint}`);
34
+ }
@@ -0,0 +1,27 @@
1
+ import { ServiceUnavailableError } from "./errors.js";
2
+
3
+ export async function postJson<T>(
4
+ url: string,
5
+ body: unknown,
6
+ headers: Record<string, string>,
7
+ ): Promise<T> {
8
+ let resp: Response;
9
+ try {
10
+ resp = await fetch(url, {
11
+ method: "POST",
12
+ headers: { "Content-Type": "application/json", ...headers },
13
+ body: JSON.stringify(body),
14
+ });
15
+ } catch {
16
+ throw new ServiceUnavailableError();
17
+ }
18
+ if (!resp.ok) {
19
+ const text = await resp.text().catch(() => "");
20
+ throw new Error(`POST ${url} → HTTP ${resp.status}: ${text.slice(0, 500)}`);
21
+ }
22
+ try {
23
+ return (await resp.json()) as T;
24
+ } catch (e) {
25
+ throw new Error(`POST ${url} returned non-JSON body: ${(e as Error).message}`);
26
+ }
27
+ }
@@ -0,0 +1,108 @@
1
+ import { ethers } from "ethers";
2
+ import type { McpConfig } from "../config.js";
3
+ import type { DHSigner } from "../signer/types.js";
4
+ import { postJson } from "./server-fetch.js";
5
+ import { authHeader } from "./server-session.js";
6
+ import { buildValidationContext, validateUnsignedTx } from "./tx-validator.js";
7
+
8
+ export interface ServerMintResult {
9
+ success: boolean;
10
+ transactionHash?: string;
11
+ amountMintedUCD?: number;
12
+ blockNumber?: number;
13
+ error?: string;
14
+ amountMismatchWarning?: string;
15
+ }
16
+
17
+ function nextQuantumTimestamp(): number {
18
+ const QUANTUM_SECONDS = 60;
19
+ const now = Math.floor(Date.now() / 1000);
20
+ const currentQuantum = Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS;
21
+ return currentQuantum + QUANTUM_SECONDS;
22
+ }
23
+
24
+ function modeForChainId(chainId: number): string {
25
+ return chainId === 1 ? "prod" : "dev";
26
+ }
27
+
28
+ function randomNonceHex(): string {
29
+ return "0x" + Buffer.from(ethers.randomBytes(16)).toString("hex");
30
+ }
31
+
32
+ export async function mintViaServer(
33
+ dhSigner: DHSigner,
34
+ config: McpConfig,
35
+ chainId: number,
36
+ positionId: string,
37
+ amount: number,
38
+ ): Promise<ServerMintResult> {
39
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
40
+ const timestamp = nextQuantumTimestamp();
41
+ const nonce = randomNonceHex();
42
+ const action = "mint-ucd";
43
+ const actionHash = ethers.keccak256(ethers.toUtf8Bytes(action));
44
+ const amountWei = ethers.parseEther(amount.toString());
45
+ const messageHash = ethers.solidityPackedKeccak256(
46
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
47
+ [positionId, timestamp, chainId, amountWei, actionHash],
48
+ );
49
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
50
+ const authMessage = { positionId, timestamp, chainId, amount: amountWei.toString(), action, mode: modeForChainId(chainId), nonce };
51
+
52
+ let headers: Record<string, string>;
53
+ try {
54
+ headers = await authHeader({ config, chainId, signer: dhSigner });
55
+ } catch (e) {
56
+ return { success: false, error: `lit-ops-server login: ${(e as Error).message}` };
57
+ }
58
+
59
+ let execJson: { success: boolean; data?: { approved: boolean; unsignedTx?: Record<string, unknown>; mintAmount?: string; mintFee?: string; error?: string }; error?: string };
60
+ try {
61
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/mint/execute`, { authMessage, userSignature, borrowerAddress }, headers);
62
+ } catch (e) {
63
+ return { success: false, error: (e as Error).message };
64
+ }
65
+
66
+ if (!execJson.success || !execJson.data?.approved) {
67
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Mint authorization failed" };
68
+ }
69
+
70
+ const { unsignedTx, mintAmount, mintFee } = execJson.data;
71
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
72
+ if (typeof mintFee !== "string" || mintFee.length === 0) {
73
+ return { success: false, error: "Server response missing `mintFee` — refusing to sign." };
74
+ }
75
+
76
+ try {
77
+ const vctx = buildValidationContext(config.network, chainId);
78
+ validateUnsignedTx(unsignedTx, { kind: "mint", positionId, amountWei: amountWei.toString(), mintFeeWei: mintFee }, vctx);
79
+ } catch (e) {
80
+ return { success: false, error: (e as Error).message };
81
+ }
82
+
83
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx as ethers.TransactionRequest);
84
+ const signedTx = await dhSigner.signTransaction(outerTx);
85
+
86
+ const mintMeta = mintAmount ? { positionId, borrowerAddress, mintAmountWei: mintAmount, mintFeeWei: mintFee ?? "0", chainId } : undefined;
87
+ let broadcastJson: { success: boolean; data?: { txHash: string; blockNumber?: number }; error?: string };
88
+ try {
89
+ broadcastJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx, mintMeta }, headers);
90
+ } catch (e) {
91
+ return { success: false, error: (e as Error).message };
92
+ }
93
+
94
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
95
+
96
+ let amountMismatchWarning: string | undefined;
97
+ if (mintAmount && mintAmount !== amountWei.toString()) {
98
+ amountMismatchWarning = `Server-echoed mintAmount (${mintAmount}) differs from authorized amount (${amountWei.toString()}). On-chain tx is correct (validated pre-sign); this is a server display bug.`;
99
+ }
100
+
101
+ return {
102
+ success: true,
103
+ transactionHash: broadcastJson.data?.txHash,
104
+ blockNumber: broadcastJson.data?.blockNumber,
105
+ amountMintedUCD: mintAmount ? parseFloat(ethers.formatEther(mintAmount)) : amount,
106
+ amountMismatchWarning,
107
+ };
108
+ }
@@ -0,0 +1,107 @@
1
+ import { ethers } from "ethers";
2
+ import type { McpConfig } from "../config.js";
3
+ import type { DHSigner } from "../signer/types.js";
4
+ import { postJson } from "./server-fetch.js";
5
+ import { authHeader } from "./server-session.js";
6
+ import { buildValidationContext, validateUnsignedTx } from "./tx-validator.js";
7
+ import { computeExtendFeeUpperBound } from "./extend-fee-bound.js";
8
+
9
+ export interface ServerRenewResult {
10
+ success: boolean;
11
+ transactionHash?: string;
12
+ blockNumber?: number;
13
+ selectedTerm?: number;
14
+ error?: string;
15
+ termMismatchWarning?: string;
16
+ }
17
+
18
+ function nextQuantumTimestamp(): number {
19
+ const QUANTUM_SECONDS = 60;
20
+ const now = Math.floor(Date.now() / 1000);
21
+ return Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS + QUANTUM_SECONDS;
22
+ }
23
+
24
+ function modeForChainId(chainId: number): string { return chainId === 1 ? "prod" : "dev"; }
25
+ function randomNonceHex(): string { return "0x" + Buffer.from(ethers.randomBytes(16)).toString("hex"); }
26
+
27
+ export async function renewViaServer(
28
+ dhSigner: DHSigner,
29
+ config: McpConfig,
30
+ chainId: number,
31
+ positionId: string,
32
+ selectedTerm: number,
33
+ ): Promise<ServerRenewResult> {
34
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
35
+ const timestamp = nextQuantumTimestamp();
36
+ const nonce = randomNonceHex();
37
+ const action = "extend-position";
38
+ const actionHash = ethers.keccak256(ethers.toUtf8Bytes(action));
39
+ const messageHash = ethers.solidityPackedKeccak256(
40
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
41
+ [positionId, timestamp, chainId, selectedTerm, actionHash],
42
+ );
43
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
44
+ const authMessage = { positionId, timestamp, chainId, newTerm: selectedTerm, action, mode: modeForChainId(chainId), nonce };
45
+
46
+ let headers: Record<string, string>;
47
+ try {
48
+ headers = await authHeader({ config, chainId, signer: dhSigner });
49
+ } catch (e) {
50
+ return { success: false, error: `lit-ops-server login: ${(e as Error).message}` };
51
+ }
52
+
53
+ let execJson: { success: boolean; data?: { approved: boolean; unsignedTx?: Record<string, unknown>; selectedTerm?: number; error?: string }; error?: string };
54
+ try {
55
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/renew/execute`, { authMessage, userSignature, borrowerAddress }, headers);
56
+ } catch (e) {
57
+ return { success: false, error: (e as Error).message };
58
+ }
59
+
60
+ if (!execJson.success || !execJson.data?.approved) {
61
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Renew authorization failed" };
62
+ }
63
+
64
+ const { unsignedTx, selectedTerm: confirmedTerm } = execJson.data;
65
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
66
+
67
+ try {
68
+ const vctx = buildValidationContext(config.network, chainId);
69
+ const feeBound = await computeExtendFeeUpperBound(config, vctx.contracts, positionId, selectedTerm);
70
+ validateUnsignedTx(
71
+ unsignedTx,
72
+ { kind: "extend", positionId, selectedTerm, upperBoundProRataFeeWei: feeBound?.upperBoundFeeWei.toString() },
73
+ vctx,
74
+ );
75
+ } catch (e) {
76
+ return { success: false, error: (e as Error).message };
77
+ }
78
+
79
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx as ethers.TransactionRequest);
80
+ const signedTx = await dhSigner.signTransaction(outerTx);
81
+
82
+ let broadcastJson: { success: boolean; data?: { txHash: string; blockNumber?: number }; error?: string };
83
+ try {
84
+ broadcastJson = await postJson(
85
+ `${config.serviceEndpoint}/api/lit/broadcast`,
86
+ { signedTx, renewMeta: { positionId, borrowerAddress, selectedTerm: confirmedTerm ?? selectedTerm, chainId } },
87
+ headers,
88
+ );
89
+ } catch (e) {
90
+ return { success: false, error: (e as Error).message };
91
+ }
92
+
93
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
94
+
95
+ let termMismatchWarning: string | undefined;
96
+ if (confirmedTerm != null && confirmedTerm !== selectedTerm) {
97
+ termMismatchWarning = `Server-echoed selectedTerm (${confirmedTerm}) differs from authorized term (${selectedTerm}).`;
98
+ }
99
+
100
+ return {
101
+ success: true,
102
+ transactionHash: broadcastJson.data?.txHash,
103
+ blockNumber: broadcastJson.data?.blockNumber,
104
+ selectedTerm: confirmedTerm ?? selectedTerm,
105
+ termMismatchWarning,
106
+ };
107
+ }
@@ -0,0 +1,118 @@
1
+ import { ethers } from "ethers";
2
+ import type { McpConfig } from "../config.js";
3
+ import type { DHSigner } from "../signer/types.js";
4
+ import { postJson } from "./server-fetch.js";
5
+ import { authHeader } from "./server-session.js";
6
+ import { buildValidationContext, validateUnsignedTx } from "./tx-validator.js";
7
+
8
+ export interface ServerRepayResult {
9
+ success: boolean;
10
+ transactionHash?: string;
11
+ blockNumber?: number;
12
+ paymentAmountUCD?: number;
13
+ error?: string;
14
+ amountMismatchWarning?: string;
15
+ }
16
+
17
+ function nextQuantumTimestamp(): number {
18
+ const QUANTUM_SECONDS = 60;
19
+ const now = Math.floor(Date.now() / 1000);
20
+ return Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS + QUANTUM_SECONDS;
21
+ }
22
+
23
+ function modeForChainId(chainId: number): string { return chainId === 1 ? "prod" : "dev"; }
24
+ function randomNonceHex(): string { return "0x" + Buffer.from(ethers.randomBytes(16)).toString("hex"); }
25
+
26
+ export async function repayViaServer(
27
+ dhSigner: DHSigner,
28
+ config: McpConfig,
29
+ chainId: number,
30
+ positionId: string,
31
+ paymentAmount: number,
32
+ ): Promise<ServerRepayResult> {
33
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
34
+ const timestamp = nextQuantumTimestamp();
35
+ const nonce = randomNonceHex();
36
+ const action = "make-payment";
37
+ const actionHash = ethers.keccak256(ethers.toUtf8Bytes(action));
38
+ const amountWei = ethers.parseEther(paymentAmount.toString());
39
+ const messageHash = ethers.solidityPackedKeccak256(
40
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
41
+ [positionId, timestamp, chainId, amountWei, actionHash],
42
+ );
43
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
44
+ const authMessage = { positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode: modeForChainId(chainId), nonce };
45
+
46
+ let headers: Record<string, string>;
47
+ try {
48
+ headers = await authHeader({ config, chainId, signer: dhSigner });
49
+ } catch (e) {
50
+ return { success: false, error: `lit-ops-server login: ${(e as Error).message}` };
51
+ }
52
+
53
+ let execJson: { success: boolean; data?: { approved: boolean; unsignedApproveTx?: Record<string, unknown>; unsignedTx?: Record<string, unknown>; paymentAmount?: string; error?: string }; error?: string };
54
+ try {
55
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/repay/execute`, { authMessage, userSignature, borrowerAddress }, headers);
56
+ } catch (e) {
57
+ return { success: false, error: (e as Error).message };
58
+ }
59
+
60
+ if (!execJson.success || !execJson.data?.approved) {
61
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Repay authorization failed" };
62
+ }
63
+
64
+ const { unsignedApproveTx, unsignedTx, paymentAmount: confirmedAmount } = execJson.data;
65
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
66
+
67
+ const vctx = buildValidationContext(config.network, chainId);
68
+
69
+ if (unsignedApproveTx) {
70
+ try {
71
+ const spenderCandidates = [vctx.contracts.PositionManager, vctx.contracts.LoanOperationsManagerModule].filter((s): s is string => !!s);
72
+ validateUnsignedTx(unsignedApproveTx, { kind: "ucd-approve", spenderCandidates, minAmountWei: amountWei.toString() }, vctx);
73
+ } catch (e) {
74
+ return { success: false, error: (e as Error).message };
75
+ }
76
+ const outerApproveTx = await dhSigner.wrapInnerTx(unsignedApproveTx as ethers.TransactionRequest);
77
+ const signedApprove = await dhSigner.signTransaction(outerApproveTx);
78
+ let approveJson: { success: boolean; error?: string };
79
+ try {
80
+ approveJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signedApprove }, headers);
81
+ } catch (e) {
82
+ return { success: false, error: `UCD approve broadcast: ${(e as Error).message}` };
83
+ }
84
+ if (!approveJson.success) return { success: false, error: approveJson.error ?? "UCD approve broadcast failed" };
85
+ }
86
+
87
+ try {
88
+ validateUnsignedTx(unsignedTx, { kind: "repay", positionId, amountWei: amountWei.toString() }, vctx);
89
+ } catch (e) {
90
+ return { success: false, error: (e as Error).message };
91
+ }
92
+
93
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx as ethers.TransactionRequest);
94
+ const signedTx = await dhSigner.signTransaction(outerTx);
95
+
96
+ const repayMeta = confirmedAmount ? { positionId, borrowerAddress, paymentAmountWei: confirmedAmount, chainId } : undefined;
97
+ let broadcastJson: { success: boolean; data?: { txHash: string; blockNumber?: number }; error?: string };
98
+ try {
99
+ broadcastJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx, repayMeta }, headers);
100
+ } catch (e) {
101
+ return { success: false, error: (e as Error).message };
102
+ }
103
+
104
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
105
+
106
+ let amountMismatchWarning: string | undefined;
107
+ if (confirmedAmount && confirmedAmount !== amountWei.toString()) {
108
+ amountMismatchWarning = `Server-echoed paymentAmount (${confirmedAmount}) differs from authorized amount (${amountWei.toString()}).`;
109
+ }
110
+
111
+ return {
112
+ success: true,
113
+ transactionHash: broadcastJson.data?.txHash,
114
+ blockNumber: broadcastJson.data?.blockNumber,
115
+ paymentAmountUCD: confirmedAmount ? parseFloat(ethers.formatEther(confirmedAmount)) : paymentAmount,
116
+ amountMismatchWarning,
117
+ };
118
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * In-memory JWT session cache for the lit-ops-server.
3
+ *
4
+ * The MCP server is a long-running daemon so the SDK's ServerSession handles
5
+ * re-auth automatically. This module caches the JWT for the server-helper
6
+ * paths (mint, repay, renew) that call lit-ops-server directly rather than
7
+ * via the SDK.
8
+ *
9
+ * No disk persistence — the process lifetime is sufficient.
10
+ */
11
+ import type { McpConfig } from "../config.js";
12
+ import type { DHSigner } from "../signer/types.js";
13
+ import { buildSignedDhServerLoginPayload } from "./eip712-login.js";
14
+
15
+ const REFRESH_LEEWAY_SECONDS = 30;
16
+
17
+ interface CachedSession {
18
+ address: string;
19
+ endpoint: string;
20
+ chainId: number;
21
+ token: string;
22
+ expiresAt: number;
23
+ }
24
+
25
+ interface LoginResponse {
26
+ token: string;
27
+ tokenType: "Bearer";
28
+ expiresAt: number;
29
+ jti: string;
30
+ }
31
+
32
+ export interface SessionContext {
33
+ config: McpConfig;
34
+ chainId: number;
35
+ signer: DHSigner;
36
+ }
37
+
38
+ let memoryCache: CachedSession | null = null;
39
+ let inFlight: Promise<CachedSession> | null = null;
40
+
41
+ function nowSec(): number {
42
+ return Math.floor(Date.now() / 1000);
43
+ }
44
+
45
+ function sessionMatchesCtx(s: CachedSession, ctx: SessionContext, address: string): boolean {
46
+ return (
47
+ s.address.toLowerCase() === address.toLowerCase() &&
48
+ s.endpoint === ctx.config.serviceEndpoint &&
49
+ s.chainId === ctx.chainId
50
+ );
51
+ }
52
+
53
+ async function loginAndCache(ctx: SessionContext, address: string): Promise<CachedSession> {
54
+ // Audit M-8: bind the login to the service endpoint it targets.
55
+ const payload = await buildSignedDhServerLoginPayload(
56
+ ctx.signer,
57
+ ctx.chainId,
58
+ ctx.config.serviceEndpoint,
59
+ );
60
+ const res = await fetch(`${ctx.config.serviceEndpoint}/api/auth/login`, {
61
+ method: "POST",
62
+ headers: { "Content-Type": "application/json" },
63
+ body: JSON.stringify(payload),
64
+ });
65
+ if (!res.ok) {
66
+ const detail = await res.text().catch(() => "");
67
+ throw new Error(`lit-ops-server login failed: HTTP ${res.status} ${detail.slice(0, 200)}`);
68
+ }
69
+ const body = (await res.json()) as LoginResponse;
70
+ if (!body?.token || !body?.expiresAt) {
71
+ throw new Error("lit-ops-server login returned malformed response");
72
+ }
73
+ const session: CachedSession = {
74
+ address: address.toLowerCase(),
75
+ endpoint: ctx.config.serviceEndpoint,
76
+ chainId: ctx.chainId,
77
+ token: body.token,
78
+ expiresAt: body.expiresAt,
79
+ };
80
+ memoryCache = session;
81
+ return session;
82
+ }
83
+
84
+ export async function getOrRefreshSessionToken(ctx: SessionContext): Promise<string> {
85
+ const address = (await ctx.signer.getAuthSignerAddress()).toLowerCase();
86
+ if (
87
+ memoryCache &&
88
+ sessionMatchesCtx(memoryCache, ctx, address) &&
89
+ memoryCache.expiresAt - REFRESH_LEEWAY_SECONDS > nowSec()
90
+ ) {
91
+ return memoryCache.token;
92
+ }
93
+ if (inFlight) {
94
+ return (await inFlight).token;
95
+ }
96
+ inFlight = (async () => {
97
+ try {
98
+ return await loginAndCache(ctx, address);
99
+ } finally {
100
+ inFlight = null;
101
+ }
102
+ })();
103
+ return (await inFlight).token;
104
+ }
105
+
106
+ export async function authHeader(ctx: SessionContext): Promise<Record<string, string>> {
107
+ return { Authorization: `Bearer ${await getOrRefreshSessionToken(ctx)}` };
108
+ }
@@ -0,0 +1,34 @@
1
+ import type { DiamondHandsSDK } from "@gvnrdao/dh-sdk";
2
+
3
+ export interface ServerWithdrawResult {
4
+ success: boolean;
5
+ txid?: string;
6
+ amountSats?: number;
7
+ networkFee?: number;
8
+ error?: string;
9
+ }
10
+
11
+ const DEFAULT_BTC_NETWORK_FEE_SATS = 1000;
12
+
13
+ export async function withdrawViaServer(
14
+ sdk: DiamondHandsSDK,
15
+ positionId: string,
16
+ btcAddress: string,
17
+ amountSats: number,
18
+ networkFee: number = DEFAULT_BTC_NETWORK_FEE_SATS,
19
+ ): Promise<ServerWithdrawResult> {
20
+ const result = await sdk.withdrawBTCAndExecute(positionId, btcAddress, amountSats, networkFee);
21
+ if (!result.success) {
22
+ return { success: false, error: result.error ?? "Withdrawal failed" };
23
+ }
24
+ const transfer = result.transfers && result.transfers[0];
25
+ if (!transfer || !transfer.success) {
26
+ return { success: false, error: transfer?.error ?? "Phase 2 (sign + broadcast) returned no result" };
27
+ }
28
+ return {
29
+ success: true,
30
+ txid: transfer.txid,
31
+ amountSats: transfer.amountSent ?? amountSats,
32
+ networkFee: transfer.networkFee ?? networkFee,
33
+ };
34
+ }