@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
package/dist/index.js ADDED
@@ -0,0 +1,1575 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/index.ts
5
+ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
6
+
7
+ // src/server.ts
8
+ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
9
+
10
+ // src/context.ts
11
+ var import_ethers5 = require("ethers");
12
+ var import_dh_sdk = require("@gvnrdao/dh-sdk");
13
+
14
+ // src/config.ts
15
+ function resolveConfig() {
16
+ return {
17
+ network: process.env["DH_NETWORK"] ?? "sepolia",
18
+ rpcUrl: process.env["ETH_RPC_URL"] ?? process.env["RPC_URL"],
19
+ serviceEndpoint: process.env["DH_SERVICE_ENDPOINT"] ?? process.env["LIT_OPS_ENDPOINT"] ?? "http://localhost:3005",
20
+ litNetwork: process.env["DH_LIT_NETWORK"] ?? "chipotle",
21
+ validatorVersion: process.env["DH_VALIDATOR_VERSION"] ? parseInt(process.env["DH_VALIDATOR_VERSION"], 10) : void 0,
22
+ safeMode: process.env["DH_SAFE_MODE"] ?? "none",
23
+ safeAddress: process.env["DH_SAFE_ADDRESS"],
24
+ agentModuleAddress: process.env["DH_AGENT_MODULE"]
25
+ };
26
+ }
27
+ function networkToChainId(network) {
28
+ const map = {
29
+ mainnet: 1,
30
+ ethereum: 1,
31
+ sepolia: 11155111,
32
+ hardhat: 31337,
33
+ local: 31337
34
+ };
35
+ const id = map[network.toLowerCase()];
36
+ if (!id) throw new Error(`Unknown network: ${network}`);
37
+ return id;
38
+ }
39
+
40
+ // src/signer/index.ts
41
+ var import_ethers = require("ethers");
42
+ function loadEnvSigner(provider) {
43
+ const key = process.env["DH_PRIVATE_KEY"] ?? process.env["PRIVATE_KEY"];
44
+ if (!key || key.trim().length === 0) {
45
+ throw new Error(
46
+ "No private key found. Set DH_PRIVATE_KEY environment variable."
47
+ );
48
+ }
49
+ const normalized = key.startsWith("0x") ? key : `0x${key}`;
50
+ return new import_ethers.ethers.Wallet(normalized, provider);
51
+ }
52
+
53
+ // src/signer/eoa-dh.ts
54
+ var import_ethers2 = require("ethers");
55
+ var EoaDHSigner = class {
56
+ kind = "eoa-env";
57
+ wallet;
58
+ constructor(wallet) {
59
+ this.wallet = wallet;
60
+ }
61
+ async getBorrowerAddress() {
62
+ return this.wallet.getAddress();
63
+ }
64
+ async getAuthSignerAddress() {
65
+ return this.wallet.getAddress();
66
+ }
67
+ async signAuthMessage(messageHash) {
68
+ return this.wallet.signMessage(import_ethers2.ethers.getBytes(messageHash));
69
+ }
70
+ async wrapInnerTx(innerTx) {
71
+ return innerTx;
72
+ }
73
+ async signTransaction(outerTx) {
74
+ return this.wallet.signTransaction(outerTx);
75
+ }
76
+ getEthersSigner() {
77
+ return this.wallet;
78
+ }
79
+ };
80
+
81
+ // src/signer/safe-module.ts
82
+ var import_ethers3 = require("ethers");
83
+ var AGENT_MODULE_ABI = [
84
+ "function execute(address target, bytes calldata data) external",
85
+ "function agent() view returns (address)",
86
+ "function safe() view returns (address)"
87
+ ];
88
+ var AGENT_MODULE_IFACE = new import_ethers3.ethers.Interface(
89
+ AGENT_MODULE_ABI
90
+ );
91
+ var SafeModuleDHSigner = class {
92
+ kind = "safe-module";
93
+ agentEoa;
94
+ safeAddress;
95
+ agentModuleAddress;
96
+ constructor(agentEoa, safeAddress, agentModuleAddress) {
97
+ if (!import_ethers3.ethers.isAddress(safeAddress)) {
98
+ throw new Error(`SafeModuleDHSigner: invalid safeAddress ${safeAddress}`);
99
+ }
100
+ if (!import_ethers3.ethers.isAddress(agentModuleAddress)) {
101
+ throw new Error(`SafeModuleDHSigner: invalid agentModuleAddress ${agentModuleAddress}`);
102
+ }
103
+ this.agentEoa = agentEoa;
104
+ this.safeAddress = import_ethers3.ethers.getAddress(safeAddress);
105
+ this.agentModuleAddress = import_ethers3.ethers.getAddress(agentModuleAddress);
106
+ }
107
+ async getBorrowerAddress() {
108
+ return this.safeAddress;
109
+ }
110
+ async getAuthSignerAddress() {
111
+ return this.agentEoa.getAddress();
112
+ }
113
+ async signAuthMessage(messageHash) {
114
+ return this.agentEoa.signMessage(import_ethers3.ethers.getBytes(messageHash));
115
+ }
116
+ async wrapInnerTx(innerTx) {
117
+ const innerTo = innerTx.to;
118
+ const innerData = innerTx.data;
119
+ if (typeof innerTo !== "string" || !import_ethers3.ethers.isAddress(innerTo)) {
120
+ throw new Error(`wrapInnerTx: innerTx.to is missing or not an address`);
121
+ }
122
+ if (typeof innerData !== "string" || !innerData.startsWith("0x")) {
123
+ throw new Error(`wrapInnerTx: innerTx.data is missing or malformed`);
124
+ }
125
+ if (innerTx.value != null) {
126
+ const v = typeof innerTx.value === "bigint" ? innerTx.value : BigInt(String(innerTx.value));
127
+ if (v !== 0n) {
128
+ throw new Error(`wrapInnerTx: inner value ${v.toString()} is non-zero \u2014 refusing to wrap`);
129
+ }
130
+ }
131
+ const outerData = AGENT_MODULE_IFACE.encodeFunctionData("execute", [innerTo, innerData]);
132
+ return {
133
+ to: this.agentModuleAddress,
134
+ data: outerData,
135
+ value: 0,
136
+ chainId: innerTx.chainId
137
+ };
138
+ }
139
+ async signTransaction(outerTx) {
140
+ if (!outerTx.to || import_ethers3.ethers.getAddress(outerTx.to) !== this.agentModuleAddress) {
141
+ throw new Error(
142
+ `signTransaction: outer tx target is ${outerTx.to}, expected agent module ${this.agentModuleAddress} \u2014 refusing to sign`
143
+ );
144
+ }
145
+ const provider = this.agentEoa.provider;
146
+ if (!provider) {
147
+ throw new Error(`SafeModuleDHSigner.signTransaction: agent signer has no provider attached`);
148
+ }
149
+ const populated = { ...outerTx };
150
+ const fromAddr = await this.agentEoa.getAddress();
151
+ if (populated.nonce == null) {
152
+ populated.nonce = await provider.getTransactionCount(fromAddr, "pending");
153
+ }
154
+ if (populated.gasLimit == null) {
155
+ try {
156
+ const est = await provider.estimateGas({ ...populated, from: fromAddr });
157
+ populated.gasLimit = est * 125n / 100n;
158
+ } catch {
159
+ populated.gasLimit = 600000n;
160
+ }
161
+ }
162
+ if (populated.maxFeePerGas == null && populated.maxPriorityFeePerGas == null && populated.gasPrice == null) {
163
+ const fee = await provider.getFeeData();
164
+ const MIN_PRIORITY_FEE = 1500000000n;
165
+ if (fee.maxFeePerGas != null && fee.maxPriorityFeePerGas != null) {
166
+ populated.type = 2;
167
+ const priority = fee.maxPriorityFeePerGas > MIN_PRIORITY_FEE ? fee.maxPriorityFeePerGas : MIN_PRIORITY_FEE;
168
+ const networkMax = fee.maxFeePerGas > priority ? fee.maxFeePerGas : priority;
169
+ populated.maxFeePerGas = networkMax > priority * 2n ? networkMax : priority * 2n;
170
+ populated.maxPriorityFeePerGas = priority;
171
+ } else if (fee.gasPrice != null) {
172
+ populated.gasPrice = fee.gasPrice > MIN_PRIORITY_FEE ? fee.gasPrice : MIN_PRIORITY_FEE;
173
+ }
174
+ }
175
+ return this.agentEoa.signTransaction(populated);
176
+ }
177
+ getEthersSigner() {
178
+ return this.agentEoa;
179
+ }
180
+ };
181
+
182
+ // src/signer/safe-module-signer-adapter.ts
183
+ var import_ethers4 = require("ethers");
184
+ var SafeModuleSignerAdapter = class _SafeModuleSignerAdapter extends import_ethers4.ethers.AbstractSigner {
185
+ constructor(dhSigner, safeAddress, provider) {
186
+ super(provider);
187
+ this.dhSigner = dhSigner;
188
+ this.safeAddress = safeAddress;
189
+ }
190
+ dhSigner;
191
+ safeAddress;
192
+ async getAddress() {
193
+ return this.safeAddress;
194
+ }
195
+ async signMessage(message) {
196
+ const bytes = message instanceof Uint8Array ? message : import_ethers4.ethers.getBytes(message);
197
+ return this.dhSigner.getEthersSigner().signMessage(bytes);
198
+ }
199
+ async sendTransaction(tx) {
200
+ if (!this.provider) {
201
+ throw new Error("SafeModuleSignerAdapter: no provider attached \u2014 call connect(provider) first");
202
+ }
203
+ if (!tx.to) {
204
+ throw new Error("SafeModuleSignerAdapter.sendTransaction: tx.to is required");
205
+ }
206
+ if (typeof tx.data !== "string" || !tx.data.startsWith("0x")) {
207
+ throw new Error("SafeModuleSignerAdapter.sendTransaction: tx.data is required and must be hex calldata");
208
+ }
209
+ const network = await this.provider.getNetwork();
210
+ const chainId = tx.chainId ?? network.chainId;
211
+ const outer = await this.dhSigner.wrapInnerTx({
212
+ to: tx.to,
213
+ data: tx.data,
214
+ value: 0,
215
+ chainId
216
+ });
217
+ const signed = await this.dhSigner.signTransaction(outer);
218
+ return await this.provider.broadcastTransaction(signed);
219
+ }
220
+ async signTransaction(_tx) {
221
+ throw new Error(
222
+ "SafeModuleSignerAdapter: signTransaction is not supported \u2014 use sendTransaction."
223
+ );
224
+ }
225
+ async signTypedData(domain, types, value) {
226
+ return this.dhSigner.getEthersSigner().signTypedData(domain, types, value);
227
+ }
228
+ connect(provider) {
229
+ return new _SafeModuleSignerAdapter(this.dhSigner, this.safeAddress, provider);
230
+ }
231
+ };
232
+
233
+ // src/util/errors.ts
234
+ var ServiceUnavailableError = class extends Error {
235
+ constructor() {
236
+ super("Service unavailable");
237
+ this.name = "ServiceUnavailableError";
238
+ }
239
+ };
240
+ function formatSDKError(err2) {
241
+ const parts = [`[${err2.category ?? "ERROR"}] ${err2.message}`];
242
+ if (err2.context?.["revertReason"]) {
243
+ parts.push(` Revert: ${err2.context["revertReason"]}`);
244
+ }
245
+ if (err2.originalError?.message && err2.originalError.message !== err2.message) {
246
+ parts.push(` Cause: ${err2.originalError.message}`);
247
+ }
248
+ return parts.join("\n");
249
+ }
250
+ function fatal(message) {
251
+ throw new Error(message);
252
+ }
253
+
254
+ // src/util/network.ts
255
+ function requireNotMainnetForWrites(network) {
256
+ if (network.toLowerCase() === "mainnet" || network === "ethereum") {
257
+ fatal(
258
+ "Mainnet writes require DH_NETWORK=mainnet to be set explicitly. This is a safety check \u2014 verify your configuration before retrying."
259
+ );
260
+ }
261
+ }
262
+ function assertSafeServiceEndpoint(endpoint) {
263
+ let url;
264
+ try {
265
+ url = new URL(endpoint);
266
+ } catch {
267
+ fatal(`Invalid serviceEndpoint: ${endpoint}`);
268
+ }
269
+ if (url.protocol === "https:") return;
270
+ if (url.protocol === "http:") {
271
+ const host = url.hostname;
272
+ const isLoopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host.endsWith(".localhost");
273
+ if (isLoopback) return;
274
+ fatal(
275
+ `Refusing to use plaintext http:// for non-loopback endpoint: ${endpoint}. Use https:// or run the lit-ops-server on localhost.`
276
+ );
277
+ }
278
+ fatal(`Unsupported serviceEndpoint protocol '${url.protocol}': ${endpoint}`);
279
+ }
280
+
281
+ // src/context.ts
282
+ async function buildContext(requireSigner) {
283
+ const config = resolveConfig();
284
+ assertSafeServiceEndpoint(config.serviceEndpoint);
285
+ const chainId = networkToChainId(config.network);
286
+ const provider = config.rpcUrl ? new import_ethers5.ethers.JsonRpcProvider(config.rpcUrl, chainId) : import_ethers5.ethers.getDefaultProvider(chainId === 1 ? "homestead" : config.network);
287
+ let contractSigner;
288
+ if (requireSigner) {
289
+ contractSigner = loadEnvSigner(provider);
290
+ }
291
+ let dhSigner;
292
+ let sdkContractSigner = contractSigner;
293
+ if (contractSigner) {
294
+ if (config.safeMode === "module") {
295
+ if (!config.safeAddress || !config.agentModuleAddress) {
296
+ throw new Error(
297
+ "DH_SAFE_MODE=module but DH_SAFE_ADDRESS / DH_AGENT_MODULE are not set."
298
+ );
299
+ }
300
+ const safeModuleDh = new SafeModuleDHSigner(
301
+ contractSigner,
302
+ config.safeAddress,
303
+ config.agentModuleAddress
304
+ );
305
+ dhSigner = safeModuleDh;
306
+ sdkContractSigner = new SafeModuleSignerAdapter(
307
+ safeModuleDh,
308
+ config.safeAddress,
309
+ provider
310
+ );
311
+ } else {
312
+ dhSigner = new EoaDHSigner(contractSigner);
313
+ }
314
+ }
315
+ const sdkConfig = {
316
+ mode: "service",
317
+ serviceEndpoint: config.serviceEndpoint,
318
+ contractSigner: sdkContractSigner,
319
+ authSigner: contractSigner,
320
+ provider,
321
+ ethRpcUrl: config.rpcUrl,
322
+ chainId,
323
+ litNetwork: config.litNetwork,
324
+ ...config.validatorVersion !== void 0 && {
325
+ validators: {
326
+ loanCreation: config.validatorVersion,
327
+ minting: config.validatorVersion,
328
+ payment: config.validatorVersion,
329
+ extension: config.validatorVersion
330
+ }
331
+ }
332
+ };
333
+ const result = await import_dh_sdk.DiamondHandsSDK.create(sdkConfig);
334
+ if (!result.success) {
335
+ throw new Error(`SDK initialization failed: ${result.error.message}`);
336
+ }
337
+ return { sdk: result.value, config, chainId, signer: contractSigner, dhSigner };
338
+ }
339
+
340
+ // src/tools/loan.ts
341
+ var import_zod = require("zod");
342
+
343
+ // src/actions/loan-create.action.ts
344
+ var import_dh_sdk2 = require("@gvnrdao/dh-sdk");
345
+
346
+ // src/util/validate.ts
347
+ var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
348
+ var SATS_SANITY_CAP = 1e10;
349
+ var UCD_SANITY_CAP = 1e9;
350
+ function assertPositionIdHex(id, label = "Position ID") {
351
+ if (!POSITION_ID_RE.test(id)) {
352
+ fatal(`${label} must be 0x-prefixed 32-byte hex (got '${id}').`);
353
+ }
354
+ }
355
+ function assertUcdAmount(amount, label = "Amount") {
356
+ if (!Number.isFinite(amount) || amount <= 0) {
357
+ fatal(`${label} must be a positive finite number (got ${amount}).`);
358
+ }
359
+ if (amount > UCD_SANITY_CAP) {
360
+ fatal(`${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`);
361
+ }
362
+ if (amount > 0 && amount < 1e-6) {
363
+ fatal(`${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`);
364
+ }
365
+ }
366
+ function assertSatsAmount(sats, label = "Amount") {
367
+ if (!Number.isInteger(sats) || sats <= 0) {
368
+ fatal(`${label} must be a positive integer (satoshis), got ${sats}.`);
369
+ }
370
+ if (sats > SATS_SANITY_CAP) {
371
+ fatal(`${label} ${sats} sats exceeds the 100 BTC sanity cap.`);
372
+ }
373
+ }
374
+ function assertSelectedTerm(months, label = "Term") {
375
+ if (!Number.isInteger(months) || months <= 0) {
376
+ fatal(`${label} must be a positive integer (months), got ${months}.`);
377
+ }
378
+ if (months > 120) {
379
+ fatal(`${label} ${months} months exceeds the 10-year sanity cap.`);
380
+ }
381
+ }
382
+
383
+ // src/actions/loan-create.action.ts
384
+ async function createPositionAction(ctx, params) {
385
+ assertSelectedTerm(params.selectedTerm);
386
+ const result = await ctx.sdk.createLoan({ selectedTerm: params.selectedTerm });
387
+ if (!(0, import_dh_sdk2.isSuccess)(result)) {
388
+ return { success: false, error: result.error.message };
389
+ }
390
+ const loan = result.value;
391
+ if (!loan.success) {
392
+ return { success: false, error: loan.error ?? "Loan creation failed." };
393
+ }
394
+ return {
395
+ success: true,
396
+ positionId: loan.positionId,
397
+ vaultAddress: loan.vaultAddress,
398
+ transactionHash: loan.transactionHash
399
+ };
400
+ }
401
+
402
+ // src/util/server-mint.ts
403
+ var import_ethers8 = require("ethers");
404
+
405
+ // src/util/server-fetch.ts
406
+ async function postJson(url, body, headers) {
407
+ let resp;
408
+ try {
409
+ resp = await fetch(url, {
410
+ method: "POST",
411
+ headers: { "Content-Type": "application/json", ...headers },
412
+ body: JSON.stringify(body)
413
+ });
414
+ } catch {
415
+ throw new ServiceUnavailableError();
416
+ }
417
+ if (!resp.ok) {
418
+ const text = await resp.text().catch(() => "");
419
+ throw new Error(`POST ${url} \u2192 HTTP ${resp.status}: ${text.slice(0, 500)}`);
420
+ }
421
+ try {
422
+ return await resp.json();
423
+ } catch (e) {
424
+ throw new Error(`POST ${url} returned non-JSON body: ${e.message}`);
425
+ }
426
+ }
427
+
428
+ // src/util/eip712-login.ts
429
+ var import_ethers6 = require("ethers");
430
+ var LOGIN_TYPES = {
431
+ DiamondHands: [
432
+ { name: "address", type: "address" },
433
+ { name: "issuedAt", type: "uint256" },
434
+ { name: "nonce", type: "bytes32" }
435
+ ]
436
+ };
437
+ var LOGIN_TYPES_WITH_AUDIENCE = {
438
+ DiamondHands: [
439
+ { name: "address", type: "address" },
440
+ { name: "issuedAt", type: "uint256" },
441
+ { name: "nonce", type: "bytes32" },
442
+ { name: "audience", type: "string" }
443
+ ]
444
+ };
445
+ function loginDomain(chainId) {
446
+ return { name: "Diamond Hands lit-ops-server", version: "1", chainId };
447
+ }
448
+ function randomNonceHex() {
449
+ return "0x" + Buffer.from(import_ethers6.ethers.randomBytes(32)).toString("hex");
450
+ }
451
+ async function buildSignedDhServerLoginPayload(dhSigner, chainId, audience) {
452
+ const signer = dhSigner.getEthersSigner();
453
+ const address = await signer.getAddress();
454
+ const message = {
455
+ address,
456
+ issuedAt: Math.floor(Date.now() / 1e3),
457
+ nonce: randomNonceHex(),
458
+ ...audience ? { audience } : {}
459
+ };
460
+ const signature = await signer.signTypedData(
461
+ loginDomain(chainId),
462
+ audience ? LOGIN_TYPES_WITH_AUDIENCE : LOGIN_TYPES,
463
+ message
464
+ );
465
+ return { chainId, message, signature };
466
+ }
467
+
468
+ // src/util/server-session.ts
469
+ var REFRESH_LEEWAY_SECONDS = 30;
470
+ var memoryCache = null;
471
+ var inFlight = null;
472
+ function nowSec() {
473
+ return Math.floor(Date.now() / 1e3);
474
+ }
475
+ function sessionMatchesCtx(s, ctx, address) {
476
+ return s.address.toLowerCase() === address.toLowerCase() && s.endpoint === ctx.config.serviceEndpoint && s.chainId === ctx.chainId;
477
+ }
478
+ async function loginAndCache(ctx, address) {
479
+ const payload = await buildSignedDhServerLoginPayload(
480
+ ctx.signer,
481
+ ctx.chainId,
482
+ ctx.config.serviceEndpoint
483
+ );
484
+ const res = await fetch(`${ctx.config.serviceEndpoint}/api/auth/login`, {
485
+ method: "POST",
486
+ headers: { "Content-Type": "application/json" },
487
+ body: JSON.stringify(payload)
488
+ });
489
+ if (!res.ok) {
490
+ const detail = await res.text().catch(() => "");
491
+ throw new Error(`lit-ops-server login failed: HTTP ${res.status} ${detail.slice(0, 200)}`);
492
+ }
493
+ const body = await res.json();
494
+ if (!body?.token || !body?.expiresAt) {
495
+ throw new Error("lit-ops-server login returned malformed response");
496
+ }
497
+ const session = {
498
+ address: address.toLowerCase(),
499
+ endpoint: ctx.config.serviceEndpoint,
500
+ chainId: ctx.chainId,
501
+ token: body.token,
502
+ expiresAt: body.expiresAt
503
+ };
504
+ memoryCache = session;
505
+ return session;
506
+ }
507
+ async function getOrRefreshSessionToken(ctx) {
508
+ const address = (await ctx.signer.getAuthSignerAddress()).toLowerCase();
509
+ if (memoryCache && sessionMatchesCtx(memoryCache, ctx, address) && memoryCache.expiresAt - REFRESH_LEEWAY_SECONDS > nowSec()) {
510
+ return memoryCache.token;
511
+ }
512
+ if (inFlight) {
513
+ return (await inFlight).token;
514
+ }
515
+ inFlight = (async () => {
516
+ try {
517
+ return await loginAndCache(ctx, address);
518
+ } finally {
519
+ inFlight = null;
520
+ }
521
+ })();
522
+ return (await inFlight).token;
523
+ }
524
+ async function authHeader(ctx) {
525
+ return { Authorization: `Bearer ${await getOrRefreshSessionToken(ctx)}` };
526
+ }
527
+
528
+ // src/util/tx-validator.ts
529
+ var import_ethers7 = require("ethers");
530
+ var import_dh_sdk3 = require("@gvnrdao/dh-sdk");
531
+ var SIGNABLE_FUNCTIONS = [
532
+ "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)",
533
+ "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)",
534
+ "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)",
535
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, uint256 proRataRenewalFee, bytes calldata extensionValidatorSignature) external returns (bool)",
536
+ "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)",
537
+ "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)",
538
+ "function approve(address spender, uint256 amount) external returns (bool)",
539
+ "function setPositionDelegate(bytes32 positionId, address newDelegate) external"
540
+ ];
541
+ var IFACE = new import_ethers7.ethers.Interface(SIGNABLE_FUNCTIONS);
542
+ var TxValidationError = class extends Error {
543
+ constructor(msg) {
544
+ super(`Refusing to sign server-returned transaction: ${msg}`);
545
+ this.name = "TxValidationError";
546
+ }
547
+ };
548
+ function buildValidationContext(network, chainId) {
549
+ const sdkKey = chainId === 31337 ? "localhost" : chainId === 11155111 ? "sepolia" : network.toLowerCase();
550
+ const contracts = (0, import_dh_sdk3.getContractsByNetwork)(sdkKey);
551
+ if (!contracts) {
552
+ throw new TxValidationError(
553
+ `no SDK contract registry for network='${network}' chainId=${chainId} (sdkKey='${sdkKey}')`
554
+ );
555
+ }
556
+ return { chainId, network, contracts };
557
+ }
558
+ function eqAddr(a, b) {
559
+ if (!a || !b) return false;
560
+ try {
561
+ return import_ethers7.ethers.getAddress(a) === import_ethers7.ethers.getAddress(b);
562
+ } catch {
563
+ return false;
564
+ }
565
+ }
566
+ function readToAddress(tx) {
567
+ const to = tx["to"];
568
+ if (typeof to !== "string") throw new TxValidationError(`unsignedTx.to is missing or not a string`);
569
+ return to;
570
+ }
571
+ function readData(tx) {
572
+ const data = tx["data"];
573
+ if (typeof data !== "string" || !data.startsWith("0x")) throw new TxValidationError(`unsignedTx.data missing or malformed`);
574
+ return data;
575
+ }
576
+ function readChainId(tx) {
577
+ const c = tx["chainId"];
578
+ if (c == null) return null;
579
+ if (typeof c === "number") return c;
580
+ if (typeof c === "string") return parseInt(c.startsWith("0x") ? c.slice(2) : c, c.startsWith("0x") ? 16 : 10);
581
+ if (typeof c === "bigint") return Number(c);
582
+ return null;
583
+ }
584
+ function readValue(tx) {
585
+ const v = tx["value"];
586
+ if (v == null) return 0n;
587
+ if (typeof v === "string") return BigInt(v.startsWith("0x") ? v : v);
588
+ if (typeof v === "number") return BigInt(v);
589
+ if (typeof v === "bigint") return v;
590
+ if (typeof v?.toBigInt === "function") return v.toBigInt();
591
+ if (typeof v?.toString === "function") return BigInt(v.toString());
592
+ throw new TxValidationError(`unsignedTx.value has unrecognized type`);
593
+ }
594
+ function decode(data) {
595
+ try {
596
+ const parsed = IFACE.parseTransaction({ data });
597
+ if (!parsed) throw new TxValidationError(`unsignedTx.data does not decode against the signable-function whitelist`);
598
+ return { name: parsed.name, args: parsed.args };
599
+ } catch (e) {
600
+ if (e instanceof TxValidationError) throw e;
601
+ throw new TxValidationError(
602
+ `unsignedTx.data does not decode against the signable-function whitelist: ${e.message}`
603
+ );
604
+ }
605
+ }
606
+ function normalizePositionId(id) {
607
+ const hex = id.startsWith("0x") ? id : `0x${id}`;
608
+ return import_ethers7.ethers.zeroPadValue(hex, 32).toLowerCase();
609
+ }
610
+ function validateUnsignedTx(unsignedTx, expected, vctx) {
611
+ const txChainId = readChainId(unsignedTx);
612
+ if (txChainId != null && txChainId !== vctx.chainId) {
613
+ throw new TxValidationError(`chainId mismatch \u2014 tx says ${txChainId}, expected ${vctx.chainId}`);
614
+ }
615
+ const value = readValue(unsignedTx);
616
+ if (value !== 0n) throw new TxValidationError(`unsignedTx.value is non-zero (${value})`);
617
+ const to = readToAddress(unsignedTx);
618
+ const data = readData(unsignedTx);
619
+ const { name, args } = decode(data);
620
+ const pm = vctx.contracts.PositionManager;
621
+ switch (expected.kind) {
622
+ case "mint": {
623
+ if (name !== "mintUCD") throw new TxValidationError(`expected mintUCD, server returned ${name}`);
624
+ if (!eqAddr(to, pm)) throw new TxValidationError(`mintUCD must target PositionManager (${pm}), got ${to}`);
625
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
626
+ throw new TxValidationError(`positionId mismatch`);
627
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
628
+ throw new TxValidationError(`mintAmount mismatch`);
629
+ if (BigInt(String(args[2])).toString() !== expected.mintFeeWei)
630
+ throw new TxValidationError(`mintFee mismatch`);
631
+ break;
632
+ }
633
+ case "repay": {
634
+ if (name !== "makePayment" && name !== "repayPosition")
635
+ throw new TxValidationError(`expected makePayment/repayPosition, server returned ${name}`);
636
+ if (!eqAddr(to, pm)) throw new TxValidationError(`${name} must target PositionManager`);
637
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
638
+ throw new TxValidationError(`positionId mismatch`);
639
+ if (BigInt(String(args[1])).toString() !== expected.amountWei)
640
+ throw new TxValidationError(`paymentAmount mismatch`);
641
+ break;
642
+ }
643
+ case "extend": {
644
+ if (name !== "extendPosition") throw new TxValidationError(`expected extendPosition, server returned ${name}`);
645
+ if (!eqAddr(to, pm)) throw new TxValidationError(`extendPosition must target PositionManager`);
646
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
647
+ throw new TxValidationError(`positionId mismatch`);
648
+ if (Number(args[1]) !== expected.selectedTerm) throw new TxValidationError(`selectedTerm mismatch`);
649
+ if (expected.upperBoundProRataFeeWei != null && args.length >= 7) {
650
+ const txFee = BigInt(String(args[5]));
651
+ const upper = BigInt(expected.upperBoundProRataFeeWei);
652
+ if (txFee > upper) throw new TxValidationError(`proRataRenewalFee=${txFee} exceeds upper bound=${upper}`);
653
+ }
654
+ break;
655
+ }
656
+ case "withdraw-btc": {
657
+ if (name !== "withdrawBTC") throw new TxValidationError(`expected withdrawBTC, server returned ${name}`);
658
+ if (!eqAddr(to, pm)) throw new TxValidationError(`withdrawBTC must target PositionManager`);
659
+ const paramsTuple = args[0];
660
+ if (String(paramsTuple[0]).toLowerCase() !== normalizePositionId(expected.positionId))
661
+ throw new TxValidationError(`positionId mismatch`);
662
+ if (String(paramsTuple[5]) !== expected.btcAddress) throw new TxValidationError(`btcAddress mismatch`);
663
+ if (expected.upperBoundTotalDeduction != null) {
664
+ const txDeduction = BigInt(String(paramsTuple[6]));
665
+ const upper = BigInt(expected.upperBoundTotalDeduction);
666
+ if (txDeduction > upper)
667
+ throw new TxValidationError(
668
+ `totalDeduction=${txDeduction} exceeds approved upper bound=${upper}`
669
+ );
670
+ }
671
+ break;
672
+ }
673
+ case "ucd-approve": {
674
+ if (name !== "approve") throw new TxValidationError(`expected ERC-20 approve, server returned ${name}`);
675
+ const ucd = vctx.contracts.UCDToken;
676
+ if (!eqAddr(to, ucd)) throw new TxValidationError(`approve must target UCDToken`);
677
+ if (!expected.spenderCandidates.some((s) => eqAddr(String(args[0]), s)))
678
+ throw new TxValidationError(`approve spender not in expected set`);
679
+ const amt = BigInt(String(args[1]));
680
+ const min = BigInt(expected.minAmountWei);
681
+ if (amt < min) throw new TxValidationError(`approve amount ${amt} is less than required ${min}`);
682
+ if (amt > min * 1000n) throw new TxValidationError(`approve amount ${amt} exceeds sanity cap`);
683
+ break;
684
+ }
685
+ case "set-position-delegate": {
686
+ if (name !== "setPositionDelegate") throw new TxValidationError(`expected setPositionDelegate`);
687
+ if (!eqAddr(to, expected.registryAddress)) throw new TxValidationError(`setPositionDelegate wrong target`);
688
+ if (String(args[0]).toLowerCase() !== normalizePositionId(expected.positionId))
689
+ throw new TxValidationError(`positionId mismatch`);
690
+ if (!eqAddr(String(args[1]), expected.delegate)) throw new TxValidationError(`delegate mismatch`);
691
+ break;
692
+ }
693
+ }
694
+ }
695
+
696
+ // src/util/server-mint.ts
697
+ function nextQuantumTimestamp() {
698
+ const QUANTUM_SECONDS = 60;
699
+ const now = Math.floor(Date.now() / 1e3);
700
+ const currentQuantum = Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS;
701
+ return currentQuantum + QUANTUM_SECONDS;
702
+ }
703
+ function modeForChainId(chainId) {
704
+ return chainId === 1 ? "prod" : "dev";
705
+ }
706
+ function randomNonceHex2() {
707
+ return "0x" + Buffer.from(import_ethers8.ethers.randomBytes(16)).toString("hex");
708
+ }
709
+ async function mintViaServer(dhSigner, config, chainId, positionId, amount) {
710
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
711
+ const timestamp = nextQuantumTimestamp();
712
+ const nonce = randomNonceHex2();
713
+ const action = "mint-ucd";
714
+ const actionHash = import_ethers8.ethers.keccak256(import_ethers8.ethers.toUtf8Bytes(action));
715
+ const amountWei = import_ethers8.ethers.parseEther(amount.toString());
716
+ const messageHash = import_ethers8.ethers.solidityPackedKeccak256(
717
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
718
+ [positionId, timestamp, chainId, amountWei, actionHash]
719
+ );
720
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
721
+ const authMessage = { positionId, timestamp, chainId, amount: amountWei.toString(), action, mode: modeForChainId(chainId), nonce };
722
+ let headers;
723
+ try {
724
+ headers = await authHeader({ config, chainId, signer: dhSigner });
725
+ } catch (e) {
726
+ return { success: false, error: `lit-ops-server login: ${e.message}` };
727
+ }
728
+ let execJson;
729
+ try {
730
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/mint/execute`, { authMessage, userSignature, borrowerAddress }, headers);
731
+ } catch (e) {
732
+ return { success: false, error: e.message };
733
+ }
734
+ if (!execJson.success || !execJson.data?.approved) {
735
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Mint authorization failed" };
736
+ }
737
+ const { unsignedTx, mintAmount, mintFee } = execJson.data;
738
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
739
+ if (typeof mintFee !== "string" || mintFee.length === 0) {
740
+ return { success: false, error: "Server response missing `mintFee` \u2014 refusing to sign." };
741
+ }
742
+ try {
743
+ const vctx = buildValidationContext(config.network, chainId);
744
+ validateUnsignedTx(unsignedTx, { kind: "mint", positionId, amountWei: amountWei.toString(), mintFeeWei: mintFee }, vctx);
745
+ } catch (e) {
746
+ return { success: false, error: e.message };
747
+ }
748
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx);
749
+ const signedTx = await dhSigner.signTransaction(outerTx);
750
+ const mintMeta = mintAmount ? { positionId, borrowerAddress, mintAmountWei: mintAmount, mintFeeWei: mintFee ?? "0", chainId } : void 0;
751
+ let broadcastJson;
752
+ try {
753
+ broadcastJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx, mintMeta }, headers);
754
+ } catch (e) {
755
+ return { success: false, error: e.message };
756
+ }
757
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
758
+ let amountMismatchWarning;
759
+ if (mintAmount && mintAmount !== amountWei.toString()) {
760
+ 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.`;
761
+ }
762
+ return {
763
+ success: true,
764
+ transactionHash: broadcastJson.data?.txHash,
765
+ blockNumber: broadcastJson.data?.blockNumber,
766
+ amountMintedUCD: mintAmount ? parseFloat(import_ethers8.ethers.formatEther(mintAmount)) : amount,
767
+ amountMismatchWarning
768
+ };
769
+ }
770
+
771
+ // src/actions/loan-mint.action.ts
772
+ async function mintAction(ctx, params) {
773
+ assertPositionIdHex(params.positionId);
774
+ assertUcdAmount(params.amountUcd);
775
+ const chainId = networkToChainId(ctx.config.network);
776
+ if (!ctx.dhSigner) {
777
+ return { success: false, error: "mintAction requires a signer (set DH_PRIVATE_KEY)" };
778
+ }
779
+ return mintViaServer(ctx.dhSigner, ctx.config, chainId, params.positionId, params.amountUcd);
780
+ }
781
+
782
+ // src/util/server-repay.ts
783
+ var import_ethers9 = require("ethers");
784
+ function nextQuantumTimestamp2() {
785
+ const QUANTUM_SECONDS = 60;
786
+ const now = Math.floor(Date.now() / 1e3);
787
+ return Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS + QUANTUM_SECONDS;
788
+ }
789
+ function modeForChainId2(chainId) {
790
+ return chainId === 1 ? "prod" : "dev";
791
+ }
792
+ function randomNonceHex3() {
793
+ return "0x" + Buffer.from(import_ethers9.ethers.randomBytes(16)).toString("hex");
794
+ }
795
+ async function repayViaServer(dhSigner, config, chainId, positionId, paymentAmount) {
796
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
797
+ const timestamp = nextQuantumTimestamp2();
798
+ const nonce = randomNonceHex3();
799
+ const action = "make-payment";
800
+ const actionHash = import_ethers9.ethers.keccak256(import_ethers9.ethers.toUtf8Bytes(action));
801
+ const amountWei = import_ethers9.ethers.parseEther(paymentAmount.toString());
802
+ const messageHash = import_ethers9.ethers.solidityPackedKeccak256(
803
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
804
+ [positionId, timestamp, chainId, amountWei, actionHash]
805
+ );
806
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
807
+ const authMessage = { positionId, timestamp, chainId, paymentAmount: amountWei.toString(), action, mode: modeForChainId2(chainId), nonce };
808
+ let headers;
809
+ try {
810
+ headers = await authHeader({ config, chainId, signer: dhSigner });
811
+ } catch (e) {
812
+ return { success: false, error: `lit-ops-server login: ${e.message}` };
813
+ }
814
+ let execJson;
815
+ try {
816
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/repay/execute`, { authMessage, userSignature, borrowerAddress }, headers);
817
+ } catch (e) {
818
+ return { success: false, error: e.message };
819
+ }
820
+ if (!execJson.success || !execJson.data?.approved) {
821
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Repay authorization failed" };
822
+ }
823
+ const { unsignedApproveTx, unsignedTx, paymentAmount: confirmedAmount } = execJson.data;
824
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
825
+ const vctx = buildValidationContext(config.network, chainId);
826
+ if (unsignedApproveTx) {
827
+ try {
828
+ const spenderCandidates = [vctx.contracts.PositionManager, vctx.contracts.LoanOperationsManagerModule].filter((s) => !!s);
829
+ validateUnsignedTx(unsignedApproveTx, { kind: "ucd-approve", spenderCandidates, minAmountWei: amountWei.toString() }, vctx);
830
+ } catch (e) {
831
+ return { success: false, error: e.message };
832
+ }
833
+ const outerApproveTx = await dhSigner.wrapInnerTx(unsignedApproveTx);
834
+ const signedApprove = await dhSigner.signTransaction(outerApproveTx);
835
+ let approveJson;
836
+ try {
837
+ approveJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx: signedApprove }, headers);
838
+ } catch (e) {
839
+ return { success: false, error: `UCD approve broadcast: ${e.message}` };
840
+ }
841
+ if (!approveJson.success) return { success: false, error: approveJson.error ?? "UCD approve broadcast failed" };
842
+ }
843
+ try {
844
+ validateUnsignedTx(unsignedTx, { kind: "repay", positionId, amountWei: amountWei.toString() }, vctx);
845
+ } catch (e) {
846
+ return { success: false, error: e.message };
847
+ }
848
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx);
849
+ const signedTx = await dhSigner.signTransaction(outerTx);
850
+ const repayMeta = confirmedAmount ? { positionId, borrowerAddress, paymentAmountWei: confirmedAmount, chainId } : void 0;
851
+ let broadcastJson;
852
+ try {
853
+ broadcastJson = await postJson(`${config.serviceEndpoint}/api/lit/broadcast`, { signedTx, repayMeta }, headers);
854
+ } catch (e) {
855
+ return { success: false, error: e.message };
856
+ }
857
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
858
+ let amountMismatchWarning;
859
+ if (confirmedAmount && confirmedAmount !== amountWei.toString()) {
860
+ amountMismatchWarning = `Server-echoed paymentAmount (${confirmedAmount}) differs from authorized amount (${amountWei.toString()}).`;
861
+ }
862
+ return {
863
+ success: true,
864
+ transactionHash: broadcastJson.data?.txHash,
865
+ blockNumber: broadcastJson.data?.blockNumber,
866
+ paymentAmountUCD: confirmedAmount ? parseFloat(import_ethers9.ethers.formatEther(confirmedAmount)) : paymentAmount,
867
+ amountMismatchWarning
868
+ };
869
+ }
870
+
871
+ // src/actions/loan-pay.action.ts
872
+ async function payAction(ctx, params) {
873
+ assertPositionIdHex(params.positionId);
874
+ assertUcdAmount(params.amountUcd, "Payment amount");
875
+ const chainId = networkToChainId(ctx.config.network);
876
+ if (!ctx.dhSigner) {
877
+ return { success: false, error: "payAction requires a signer (set DH_PRIVATE_KEY)" };
878
+ }
879
+ return repayViaServer(ctx.dhSigner, ctx.config, chainId, params.positionId, params.amountUcd);
880
+ }
881
+
882
+ // src/util/server-renew.ts
883
+ var import_ethers11 = require("ethers");
884
+
885
+ // src/util/extend-fee-bound.ts
886
+ var import_ethers10 = require("ethers");
887
+ var POSITION_DETAILS_ABI = [
888
+ "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))"
889
+ ];
890
+ var TERM_MANAGER_ABI = [
891
+ "function getExtensionFeeRateBps(uint16 termMonths) view returns (uint256)"
892
+ ];
893
+ async function computeExtendFeeUpperBound(config, contracts, positionId, selectedTerm) {
894
+ const corePm = contracts.PositionManagerCoreModule;
895
+ const termMgr = contracts.TermManagerModule;
896
+ if (!corePm || !termMgr) return null;
897
+ if (!config.rpcUrl) return null;
898
+ let provider;
899
+ try {
900
+ provider = new import_ethers10.ethers.JsonRpcProvider(config.rpcUrl);
901
+ } catch {
902
+ return null;
903
+ }
904
+ const positionIdBytes32 = import_ethers10.ethers.zeroPadValue(
905
+ positionId.startsWith("0x") ? positionId : `0x${positionId}`,
906
+ 32
907
+ );
908
+ try {
909
+ const pm = new import_ethers10.ethers.Contract(corePm, POSITION_DETAILS_ABI, provider);
910
+ const details = await pm["getPositionDetails"](positionIdBytes32);
911
+ const ucdDebt = BigInt(details.ucdDebt?.toString?.() ?? "0");
912
+ const tm = new import_ethers10.ethers.Contract(termMgr, TERM_MANAGER_ABI, provider);
913
+ const bps = await tm["getExtensionFeeRateBps"](selectedTerm);
914
+ const extensionFeeRateBps = BigInt(bps.toString());
915
+ const upperBoundFeeWei = ucdDebt * extensionFeeRateBps / 10000n;
916
+ return { ucdDebt, extensionFeeRateBps, upperBoundFeeWei };
917
+ } catch {
918
+ return null;
919
+ }
920
+ }
921
+
922
+ // src/util/server-renew.ts
923
+ function nextQuantumTimestamp3() {
924
+ const QUANTUM_SECONDS = 60;
925
+ const now = Math.floor(Date.now() / 1e3);
926
+ return Math.floor(now / QUANTUM_SECONDS) * QUANTUM_SECONDS + QUANTUM_SECONDS;
927
+ }
928
+ function modeForChainId3(chainId) {
929
+ return chainId === 1 ? "prod" : "dev";
930
+ }
931
+ function randomNonceHex4() {
932
+ return "0x" + Buffer.from(import_ethers11.ethers.randomBytes(16)).toString("hex");
933
+ }
934
+ async function renewViaServer(dhSigner, config, chainId, positionId, selectedTerm) {
935
+ const borrowerAddress = await dhSigner.getBorrowerAddress();
936
+ const timestamp = nextQuantumTimestamp3();
937
+ const nonce = randomNonceHex4();
938
+ const action = "extend-position";
939
+ const actionHash = import_ethers11.ethers.keccak256(import_ethers11.ethers.toUtf8Bytes(action));
940
+ const messageHash = import_ethers11.ethers.solidityPackedKeccak256(
941
+ ["bytes32", "uint256", "uint256", "uint256", "bytes32"],
942
+ [positionId, timestamp, chainId, selectedTerm, actionHash]
943
+ );
944
+ const userSignature = await dhSigner.signAuthMessage(messageHash);
945
+ const authMessage = { positionId, timestamp, chainId, newTerm: selectedTerm, action, mode: modeForChainId3(chainId), nonce };
946
+ let headers;
947
+ try {
948
+ headers = await authHeader({ config, chainId, signer: dhSigner });
949
+ } catch (e) {
950
+ return { success: false, error: `lit-ops-server login: ${e.message}` };
951
+ }
952
+ let execJson;
953
+ try {
954
+ execJson = await postJson(`${config.serviceEndpoint}/api/lit/renew/execute`, { authMessage, userSignature, borrowerAddress }, headers);
955
+ } catch (e) {
956
+ return { success: false, error: e.message };
957
+ }
958
+ if (!execJson.success || !execJson.data?.approved) {
959
+ return { success: false, error: execJson.data?.error ?? execJson.error ?? "Renew authorization failed" };
960
+ }
961
+ const { unsignedTx, selectedTerm: confirmedTerm } = execJson.data;
962
+ if (!unsignedTx) return { success: false, error: "Server did not return unsigned transaction" };
963
+ try {
964
+ const vctx = buildValidationContext(config.network, chainId);
965
+ const feeBound = await computeExtendFeeUpperBound(config, vctx.contracts, positionId, selectedTerm);
966
+ validateUnsignedTx(
967
+ unsignedTx,
968
+ { kind: "extend", positionId, selectedTerm, upperBoundProRataFeeWei: feeBound?.upperBoundFeeWei.toString() },
969
+ vctx
970
+ );
971
+ } catch (e) {
972
+ return { success: false, error: e.message };
973
+ }
974
+ const outerTx = await dhSigner.wrapInnerTx(unsignedTx);
975
+ const signedTx = await dhSigner.signTransaction(outerTx);
976
+ let broadcastJson;
977
+ try {
978
+ broadcastJson = await postJson(
979
+ `${config.serviceEndpoint}/api/lit/broadcast`,
980
+ { signedTx, renewMeta: { positionId, borrowerAddress, selectedTerm: confirmedTerm ?? selectedTerm, chainId } },
981
+ headers
982
+ );
983
+ } catch (e) {
984
+ return { success: false, error: e.message };
985
+ }
986
+ if (!broadcastJson.success) return { success: false, error: broadcastJson.error ?? "Broadcast failed" };
987
+ let termMismatchWarning;
988
+ if (confirmedTerm != null && confirmedTerm !== selectedTerm) {
989
+ termMismatchWarning = `Server-echoed selectedTerm (${confirmedTerm}) differs from authorized term (${selectedTerm}).`;
990
+ }
991
+ return {
992
+ success: true,
993
+ transactionHash: broadcastJson.data?.txHash,
994
+ blockNumber: broadcastJson.data?.blockNumber,
995
+ selectedTerm: confirmedTerm ?? selectedTerm,
996
+ termMismatchWarning
997
+ };
998
+ }
999
+
1000
+ // src/actions/loan-extend.action.ts
1001
+ async function extendAction(ctx, params) {
1002
+ assertPositionIdHex(params.positionId);
1003
+ assertSelectedTerm(params.selectedTerm);
1004
+ const chainId = networkToChainId(ctx.config.network);
1005
+ if (!ctx.dhSigner) {
1006
+ return { success: false, error: "extendAction requires a signer (set DH_PRIVATE_KEY)" };
1007
+ }
1008
+ return renewViaServer(ctx.dhSigner, ctx.config, chainId, params.positionId, params.selectedTerm);
1009
+ }
1010
+
1011
+ // src/util/server-withdraw.ts
1012
+ var DEFAULT_BTC_NETWORK_FEE_SATS = 1e3;
1013
+ async function withdrawViaServer(sdk, positionId, btcAddress2, amountSats, networkFee = DEFAULT_BTC_NETWORK_FEE_SATS) {
1014
+ const result = await sdk.withdrawBTCAndExecute(positionId, btcAddress2, amountSats, networkFee);
1015
+ if (!result.success) {
1016
+ return { success: false, error: result.error ?? "Withdrawal failed" };
1017
+ }
1018
+ const transfer = result.transfers && result.transfers[0];
1019
+ if (!transfer || !transfer.success) {
1020
+ return { success: false, error: transfer?.error ?? "Phase 2 (sign + broadcast) returned no result" };
1021
+ }
1022
+ return {
1023
+ success: true,
1024
+ txid: transfer.txid,
1025
+ amountSats: transfer.amountSent ?? amountSats,
1026
+ networkFee: transfer.networkFee ?? networkFee
1027
+ };
1028
+ }
1029
+
1030
+ // src/util/btc-address.ts
1031
+ var import_bitcoinjs_lib = require("bitcoinjs-lib");
1032
+ function btcNetworkFor(evmNetwork, chainId) {
1033
+ if (chainId === 1) return "mainnet";
1034
+ const lower = evmNetwork.toLowerCase();
1035
+ if (lower === "mainnet" || lower === "ethereum") return "mainnet";
1036
+ return "regtest";
1037
+ }
1038
+ function networkObj(net) {
1039
+ if (net === "mainnet") return import_bitcoinjs_lib.networks.bitcoin;
1040
+ if (net === "testnet") return import_bitcoinjs_lib.networks.testnet;
1041
+ return import_bitcoinjs_lib.networks.regtest;
1042
+ }
1043
+ function validateBtcAddress(addr, expected) {
1044
+ if (typeof addr !== "string" || addr.length === 0) {
1045
+ throw new Error("BTC address is empty");
1046
+ }
1047
+ const trimmed = addr.trim();
1048
+ if (trimmed !== addr) {
1049
+ throw new Error("BTC address has leading/trailing whitespace");
1050
+ }
1051
+ const net = networkObj(expected);
1052
+ let kind = "unknown";
1053
+ try {
1054
+ const decoded = import_bitcoinjs_lib.address.toOutputScript(addr, net);
1055
+ const hex = decoded.toString("hex");
1056
+ if (/^76a914[0-9a-f]{40}88ac$/.test(hex)) kind = "p2pkh";
1057
+ else if (/^a914[0-9a-f]{40}87$/.test(hex)) kind = "p2sh";
1058
+ else if (/^0014[0-9a-f]{40}$/.test(hex)) kind = "p2wpkh";
1059
+ else if (/^0020[0-9a-f]{64}$/.test(hex)) kind = "p2wsh";
1060
+ else if (/^5120[0-9a-f]{64}$/.test(hex)) kind = "p2tr";
1061
+ } catch (e) {
1062
+ const msg = e.message;
1063
+ const others = ["mainnet", "testnet", "regtest"].filter((n) => n !== expected);
1064
+ for (const n of others) {
1065
+ try {
1066
+ import_bitcoinjs_lib.address.toOutputScript(addr, networkObj(n));
1067
+ throw new Error(
1068
+ `BTC address '${addr}' is valid on ${n} but you are operating on ${expected}. Sending across networks would lose the funds.`
1069
+ );
1070
+ } catch (innerErr) {
1071
+ if (innerErr.message.startsWith("BTC address")) throw innerErr;
1072
+ }
1073
+ }
1074
+ throw new Error(`Invalid BTC address '${addr}': ${msg}`);
1075
+ }
1076
+ return { normalized: addr, network: expected, kind };
1077
+ }
1078
+
1079
+ // src/actions/loan-withdraw.action.ts
1080
+ async function withdrawAction(ctx, params) {
1081
+ assertPositionIdHex(params.positionId);
1082
+ assertSatsAmount(params.amountSats);
1083
+ const chainId = networkToChainId(ctx.config.network);
1084
+ const expectedBtcNet = btcNetworkFor(ctx.config.network, chainId);
1085
+ validateBtcAddress(params.btcAddress, expectedBtcNet);
1086
+ return withdrawViaServer(ctx.sdk, params.positionId, params.btcAddress, params.amountSats, params.networkFeeSats);
1087
+ }
1088
+
1089
+ // src/tools/_helpers.ts
1090
+ var import_dh_sdk4 = require("@gvnrdao/dh-sdk");
1091
+
1092
+ // src/util/format.ts
1093
+ function bigintReplacer(_key, value) {
1094
+ if (typeof value === "bigint") return value.toString();
1095
+ return value;
1096
+ }
1097
+ function serialize(data) {
1098
+ return JSON.stringify(data, bigintReplacer, 2);
1099
+ }
1100
+
1101
+ // src/tools/_helpers.ts
1102
+ function ok(data) {
1103
+ return { content: [{ type: "text", text: serialize(data) }] };
1104
+ }
1105
+ function err(message) {
1106
+ return { content: [{ type: "text", text: message }], isError: true };
1107
+ }
1108
+ function requireConfirmation(confirmed, actionLabel) {
1109
+ if (confirmed === true) return null;
1110
+ return err(
1111
+ `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
1112
+ This is an irreversible, fund-moving action. A human must explicitly authorize it.
1113
+ Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
1114
+ );
1115
+ }
1116
+ function fromSdkResult(result) {
1117
+ if ((0, import_dh_sdk4.isSuccess)(result)) return ok(result.value);
1118
+ return err(formatSDKError(result.error));
1119
+ }
1120
+ async function safe(fn) {
1121
+ try {
1122
+ return await fn();
1123
+ } catch (e) {
1124
+ return err(e.message);
1125
+ }
1126
+ }
1127
+
1128
+ // src/tools/loan.ts
1129
+ var LATENCY_NOTE = "Takes 60\u201390 seconds \u2014 invokes a LIT Action on the Lit network.";
1130
+ var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
1131
+ var confirmedSchema = import_zod.z.boolean().optional().describe(
1132
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
1133
+ );
1134
+ var DESTRUCTIVE_WRITE_ANNOTATIONS = {
1135
+ readOnlyHint: false,
1136
+ destructiveHint: true,
1137
+ idempotentHint: false,
1138
+ openWorldHint: true
1139
+ };
1140
+ function registerLoanTools(server, getCtx) {
1141
+ server.registerTool(
1142
+ "loan_create",
1143
+ {
1144
+ title: "Create a new lending position",
1145
+ description: `Mint a new PKP, create a Bitcoin custody vault, and register a new lending position with the given term. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
1146
+ inputSchema: {
1147
+ selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
1148
+ confirmed: confirmedSchema
1149
+ },
1150
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
1151
+ },
1152
+ async ({ selectedTerm, confirmed }) => safe(async () => {
1153
+ const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
1154
+ if (gate) return gate;
1155
+ const ctx = await getCtx();
1156
+ requireNotMainnetForWrites(ctx.config.network);
1157
+ const result = await createPositionAction(ctx, { selectedTerm });
1158
+ return result.success ? ok(result) : err(result.error ?? "Loan creation failed.");
1159
+ })
1160
+ );
1161
+ server.registerTool(
1162
+ "loan_mint",
1163
+ {
1164
+ title: "Mint UCD against a position",
1165
+ description: `Mint UCD against an existing lending position's BTC collateral. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
1166
+ inputSchema: {
1167
+ positionId: positionIdSchema,
1168
+ amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
1169
+ confirmed: confirmedSchema
1170
+ },
1171
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
1172
+ },
1173
+ async ({ positionId, amountUcd, confirmed }) => safe(async () => {
1174
+ const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
1175
+ if (gate) return gate;
1176
+ const ctx = await getCtx();
1177
+ requireNotMainnetForWrites(ctx.config.network);
1178
+ const result = await mintAction(ctx, { positionId, amountUcd });
1179
+ return result.success ? ok(result) : err(result.error ?? "Mint failed.");
1180
+ })
1181
+ );
1182
+ server.registerTool(
1183
+ "loan_pay",
1184
+ {
1185
+ title: "Make a UCD payment toward a position's debt",
1186
+ description: `Repay (full or partial) a position's UCD debt. Moves UCD out of your wallet (irreversible). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
1187
+ inputSchema: {
1188
+ positionId: positionIdSchema,
1189
+ amountUcd: import_zod.z.number().positive().describe("Amount of UCD to repay"),
1190
+ confirmed: confirmedSchema
1191
+ },
1192
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
1193
+ },
1194
+ async ({ positionId, amountUcd, confirmed }) => safe(async () => {
1195
+ const gate = requireConfirmation(confirmed, `repay ${amountUcd} UCD toward position ${positionId}`);
1196
+ if (gate) return gate;
1197
+ const ctx = await getCtx();
1198
+ requireNotMainnetForWrites(ctx.config.network);
1199
+ const result = await payAction(ctx, { positionId, amountUcd });
1200
+ return result.success ? ok(result) : err(result.error ?? "Payment failed.");
1201
+ })
1202
+ );
1203
+ server.registerTool(
1204
+ "loan_extend",
1205
+ {
1206
+ title: "Extend / renew a position's term",
1207
+ description: `Renew an active position with a new term. Pays a pro-rata renewal fee in UCD (irreversible on-chain write). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
1208
+ inputSchema: {
1209
+ positionId: positionIdSchema,
1210
+ selectedTerm: import_zod.z.number().int().positive().describe("New term in months"),
1211
+ confirmed: confirmedSchema
1212
+ },
1213
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
1214
+ },
1215
+ async ({ positionId, selectedTerm, confirmed }) => safe(async () => {
1216
+ const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
1217
+ if (gate) return gate;
1218
+ const ctx = await getCtx();
1219
+ requireNotMainnetForWrites(ctx.config.network);
1220
+ const result = await extendAction(ctx, { positionId, selectedTerm });
1221
+ return result.success ? ok(result) : err(result.error ?? "Renewal failed.");
1222
+ })
1223
+ );
1224
+ server.registerTool(
1225
+ "loan_withdraw",
1226
+ {
1227
+ title: "Withdraw BTC from a position vault",
1228
+ description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
1229
+ inputSchema: {
1230
+ positionId: positionIdSchema,
1231
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
1232
+ amountSats: import_zod.z.number().int().positive().describe("Amount in satoshis (1 BTC = 100,000,000 sats)"),
1233
+ networkFeeSats: import_zod.z.number().int().positive().optional().describe("Optional BTC network fee in sats (default 1000)"),
1234
+ confirmed: confirmedSchema
1235
+ },
1236
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
1237
+ },
1238
+ async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => safe(async () => {
1239
+ const gate = requireConfirmation(
1240
+ confirmed,
1241
+ `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
1242
+ );
1243
+ if (gate) return gate;
1244
+ const ctx = await getCtx();
1245
+ requireNotMainnetForWrites(ctx.config.network);
1246
+ const result = await withdrawAction(ctx, { positionId, btcAddress: btcAddress2, amountSats, networkFeeSats });
1247
+ return result.success ? ok(result) : err(result.error ?? "Withdrawal failed.");
1248
+ })
1249
+ );
1250
+ server.registerTool(
1251
+ "loan_recover_stale_spend",
1252
+ {
1253
+ title: "Recover a stale BTC reservation via LIT-attested proof",
1254
+ description: "Clear a stale authorized BTC spend on BTCSpendAuthorizer using a LIT-attested StaleSpendRecovery attestation. The original UTXO must already be consumed on Bitcoin with \u22656 confirmations. `invalidatorTxid` is either the borrower's authorized broadcast (after confirmations) or a PKP self-spend that invalidated the reservation. Permissionless on-chain.",
1255
+ inputSchema: {
1256
+ positionId: positionIdSchema,
1257
+ utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
1258
+ utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
1259
+ invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
1260
+ minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
1261
+ },
1262
+ // On-chain write, but permissionless and user-beneficial (clears a stale reservation;
1263
+ // does not move funds), so no confirmed gate — but it is NOT read-only.
1264
+ annotations: {
1265
+ readOnlyHint: false,
1266
+ destructiveHint: false,
1267
+ idempotentHint: true,
1268
+ openWorldHint: true
1269
+ }
1270
+ },
1271
+ async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => safe(async () => {
1272
+ const ctx = await getCtx();
1273
+ requireNotMainnetForWrites(ctx.config.network);
1274
+ const result = await ctx.sdk.recoverStaleSpend({
1275
+ positionId,
1276
+ utxoTxid,
1277
+ utxoVout,
1278
+ invalidatorTxid,
1279
+ ...minConfirmations !== void 0 && { minConfirmations },
1280
+ ...ctx.config.rpcUrl && { rpcUrl: ctx.config.rpcUrl }
1281
+ });
1282
+ return result.success ? ok(result) : err(result.error ?? "Stale spend recovery failed.");
1283
+ })
1284
+ );
1285
+ }
1286
+
1287
+ // src/tools/position.ts
1288
+ var import_zod2 = require("zod");
1289
+ var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
1290
+ function registerPositionTools(server, getCtx) {
1291
+ server.registerTool(
1292
+ "position_status",
1293
+ {
1294
+ title: "Get a position's full status",
1295
+ description: "Return detailed status (debt, term, expiry, vault, borrower) for a single position.",
1296
+ inputSchema: {
1297
+ id: positionIdSchema2
1298
+ }
1299
+ },
1300
+ async ({ id }) => safe(async () => {
1301
+ const ctx = await getCtx();
1302
+ const result = await ctx.sdk.getLoanById(id, true);
1303
+ if (!result.success) return err(result.error.message);
1304
+ if (!result.value) return err(`Position ${id} not found.`);
1305
+ return ok(result.value);
1306
+ })
1307
+ );
1308
+ server.registerTool(
1309
+ "position_list",
1310
+ {
1311
+ title: "List lending positions",
1312
+ description: "List positions with optional filters. With no filter, returns currently active positions.",
1313
+ inputSchema: {
1314
+ borrower: import_zod2.z.string().optional().describe("Filter by borrower address (0x-prefixed)"),
1315
+ state: import_zod2.z.string().optional().describe("Filter by state (e.g. ACTIVE, EXPIRED, REPAID, LIQUIDATED)"),
1316
+ page: import_zod2.z.number().int().positive().optional().describe("Page number (default 1)"),
1317
+ pageSize: import_zod2.z.number().int().positive().max(100).optional().describe("Page size (default 20)")
1318
+ }
1319
+ },
1320
+ async ({ borrower, state, page, pageSize }) => safe(async () => {
1321
+ const ctx = await getCtx();
1322
+ const p = page ?? 1;
1323
+ const size = pageSize ?? 20;
1324
+ let result;
1325
+ if (borrower) {
1326
+ result = await ctx.sdk.getLoansByBorrower(borrower, { page: p, pageSize: size });
1327
+ } else if (state) {
1328
+ result = await ctx.sdk.getLoansByState(state, { page: p, pageSize: size });
1329
+ } else {
1330
+ result = await ctx.sdk.getActiveLoans({ page: p, pageSize: size });
1331
+ }
1332
+ return fromSdkResult(result);
1333
+ })
1334
+ );
1335
+ server.registerTool(
1336
+ "position_events",
1337
+ {
1338
+ title: "Get a position's event history",
1339
+ description: "Return mint, payment, withdrawal, renewal, status-update, and liquidation events for a position.",
1340
+ inputSchema: {
1341
+ id: positionIdSchema2
1342
+ }
1343
+ },
1344
+ async ({ id }) => safe(async () => {
1345
+ const ctx = await getCtx();
1346
+ const result = await ctx.sdk.getLoanEvents(id);
1347
+ return fromSdkResult(result);
1348
+ })
1349
+ );
1350
+ server.registerTool(
1351
+ "position_pending_withdrawals",
1352
+ {
1353
+ title: "List a position's pending BTC withdrawal reservations",
1354
+ description: "Query BTCSpendAuthorizer for authorized-but-unspent BTC withdrawal reservations on a position. Each entry has txid/vout (the original UTXO), satoshis, target address, and `utxoKey` (for recovery).",
1355
+ inputSchema: {
1356
+ id: positionIdSchema2
1357
+ }
1358
+ },
1359
+ async ({ id }) => safe(async () => {
1360
+ const ctx = await getCtx();
1361
+ const list = await ctx.sdk.getPendingWithdrawals(id);
1362
+ return ok(list);
1363
+ })
1364
+ );
1365
+ }
1366
+
1367
+ // src/tools/btc.ts
1368
+ var import_zod3 = require("zod");
1369
+ function registerBtcTools(server, getCtx) {
1370
+ server.registerTool(
1371
+ "btc_balance",
1372
+ {
1373
+ title: "Get BTC balance for an address",
1374
+ description: "Query the current BTC balance and UTXOs for any BTC address (uses configured providers).",
1375
+ inputSchema: {
1376
+ address: import_zod3.z.string().min(1).describe("BTC address to query")
1377
+ }
1378
+ },
1379
+ async ({ address }) => safe(async () => {
1380
+ const ctx = await getCtx();
1381
+ const result = await ctx.sdk.getBitcoinBalance(address);
1382
+ return fromSdkResult(result);
1383
+ })
1384
+ );
1385
+ server.registerTool(
1386
+ "btc_price",
1387
+ {
1388
+ title: "Get the current BTC price",
1389
+ description: "Return the current BTC price (USD, 8 decimals) signed by the price oracle PKP.",
1390
+ inputSchema: {}
1391
+ },
1392
+ async () => safe(async () => {
1393
+ const ctx = await getCtx();
1394
+ const result = await ctx.sdk.getBitcoinPrice();
1395
+ return ok(result);
1396
+ })
1397
+ );
1398
+ }
1399
+
1400
+ // src/tools/protocol.ts
1401
+ function registerProtocolTools(server, getCtx) {
1402
+ server.registerTool(
1403
+ "protocol_status",
1404
+ {
1405
+ title: "Get protocol configuration and status",
1406
+ description: "Return protocol contract addresses, pause status, and circuit breaker state.",
1407
+ inputSchema: {}
1408
+ },
1409
+ async () => safe(async () => {
1410
+ const ctx = await getCtx();
1411
+ const result = await ctx.sdk.getProtocolConfig();
1412
+ return fromSdkResult(result);
1413
+ })
1414
+ );
1415
+ server.registerTool(
1416
+ "protocol_terms",
1417
+ {
1418
+ title: "List available loan terms with fees",
1419
+ description: "Return all configured loan terms (in months) with their origination fees and extension fees.",
1420
+ inputSchema: {}
1421
+ },
1422
+ async () => safe(async () => {
1423
+ const ctx = await getCtx();
1424
+ const result = await ctx.sdk.getTermsWithFees();
1425
+ return fromSdkResult(result);
1426
+ })
1427
+ );
1428
+ }
1429
+
1430
+ // src/resources/position.ts
1431
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
1432
+ function registerPositionResource(server, getCtx) {
1433
+ server.registerResource(
1434
+ "position",
1435
+ new import_mcp.ResourceTemplate("position://{id}", { list: void 0 }),
1436
+ {
1437
+ title: "Lending position",
1438
+ description: "Full position state by ID (debt, term, expiry, vault, borrower).",
1439
+ mimeType: "application/json"
1440
+ },
1441
+ async (uri, { id }) => {
1442
+ const ctx = await getCtx();
1443
+ const positionId = Array.isArray(id) ? id[0] : id;
1444
+ if (!positionId) {
1445
+ throw new Error("position resource requires an `id` segment");
1446
+ }
1447
+ const result = await ctx.sdk.getLoanById(positionId, true);
1448
+ if (!result.success) {
1449
+ throw new Error(`Failed to fetch position ${positionId}: ${result.error.message}`);
1450
+ }
1451
+ if (!result.value) {
1452
+ throw new Error(`Position ${positionId} not found`);
1453
+ }
1454
+ return {
1455
+ contents: [
1456
+ {
1457
+ uri: uri.href,
1458
+ mimeType: "application/json",
1459
+ text: serialize(result.value)
1460
+ }
1461
+ ]
1462
+ };
1463
+ }
1464
+ );
1465
+ }
1466
+
1467
+ // src/resources/protocol.ts
1468
+ function registerProtocolResources(server, getCtx) {
1469
+ server.registerResource(
1470
+ "protocol-config",
1471
+ "protocol://config",
1472
+ {
1473
+ title: "Protocol configuration",
1474
+ description: "Diamond Hands protocol config: contract addresses, pause status, circuit breaker state.",
1475
+ mimeType: "application/json"
1476
+ },
1477
+ async (uri) => {
1478
+ const ctx = await getCtx();
1479
+ const result = await ctx.sdk.getProtocolConfig();
1480
+ if (!result.success) {
1481
+ throw new Error(`Failed to fetch protocol config: ${result.error.message}`);
1482
+ }
1483
+ return {
1484
+ contents: [
1485
+ {
1486
+ uri: uri.href,
1487
+ mimeType: "application/json",
1488
+ text: serialize(result.value)
1489
+ }
1490
+ ]
1491
+ };
1492
+ }
1493
+ );
1494
+ server.registerResource(
1495
+ "protocol-terms",
1496
+ "protocol://terms",
1497
+ {
1498
+ title: "Available loan terms",
1499
+ description: "All configured loan terms (months) with origination and extension fees.",
1500
+ mimeType: "application/json"
1501
+ },
1502
+ async (uri) => {
1503
+ const ctx = await getCtx();
1504
+ const result = await ctx.sdk.getTermsWithFees();
1505
+ if (!result.success) {
1506
+ throw new Error(`Failed to fetch terms: ${result.error.message}`);
1507
+ }
1508
+ return {
1509
+ contents: [
1510
+ {
1511
+ uri: uri.href,
1512
+ mimeType: "application/json",
1513
+ text: serialize(result.value)
1514
+ }
1515
+ ]
1516
+ };
1517
+ }
1518
+ );
1519
+ }
1520
+
1521
+ // src/server.ts
1522
+ var cached = null;
1523
+ var cachedSigned = null;
1524
+ async function getReadCtx() {
1525
+ if (cached) return cached;
1526
+ const hasKey = !!(process.env["DH_PRIVATE_KEY"] ?? process.env["PRIVATE_KEY"]);
1527
+ cached = await buildContext(hasKey);
1528
+ if (hasKey) cachedSigned = cached;
1529
+ return cached;
1530
+ }
1531
+ async function getSignedCtx() {
1532
+ if (cachedSigned) return cachedSigned;
1533
+ cachedSigned = await buildContext(true);
1534
+ cached = cachedSigned;
1535
+ return cachedSigned;
1536
+ }
1537
+ function createServer() {
1538
+ const server = new import_mcp2.McpServer({
1539
+ name: "diamond-hands",
1540
+ version: "0.0.1"
1541
+ });
1542
+ registerLoanTools(server, getSignedCtx);
1543
+ registerPositionTools(server, getReadCtx);
1544
+ registerBtcTools(server, getReadCtx);
1545
+ registerProtocolTools(server, getReadCtx);
1546
+ registerPositionResource(server, getReadCtx);
1547
+ registerProtocolResources(server, getReadCtx);
1548
+ return server;
1549
+ }
1550
+ function disposeCachedContext() {
1551
+ if (cached) {
1552
+ cached.sdk.dispose();
1553
+ cached = null;
1554
+ cachedSigned = null;
1555
+ }
1556
+ }
1557
+
1558
+ // src/index.ts
1559
+ async function main() {
1560
+ const server = createServer();
1561
+ const transport = new import_stdio.StdioServerTransport();
1562
+ const cleanup = () => {
1563
+ disposeCachedContext();
1564
+ process.exit(0);
1565
+ };
1566
+ process.on("SIGINT", cleanup);
1567
+ process.on("SIGTERM", cleanup);
1568
+ await server.connect(transport);
1569
+ process.stderr.write("[dh-mcp] Diamond Hands MCP server connected over stdio.\n");
1570
+ }
1571
+ main().catch((err2) => {
1572
+ process.stderr.write(`[dh-mcp] fatal: ${err2.stack ?? err2.message}
1573
+ `);
1574
+ process.exit(1);
1575
+ });