@gvnrdao/dh-mcp 0.5.9 → 0.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -498,7 +498,7 @@ var require_utils = __commonJS({
498
498
  exports2.createHasher = createHasher2;
499
499
  exports2.createOptHasher = createOptHasher;
500
500
  exports2.createXOFer = createXOFer;
501
- exports2.randomBytes = randomBytes3;
501
+ exports2.randomBytes = randomBytes4;
502
502
  var crypto_1 = require_cryptoNode();
503
503
  function isBytes2(a) {
504
504
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
@@ -696,7 +696,7 @@ var require_utils = __commonJS({
696
696
  exports2.wrapConstructor = createHasher2;
697
697
  exports2.wrapConstructorWithOpts = createOptHasher;
698
698
  exports2.wrapXOFConstructorWithOpts = createXOFer;
699
- function randomBytes3(bytesLength = 32) {
699
+ function randomBytes4(bytesLength = 32) {
700
700
  if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
701
701
  return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
702
702
  }
@@ -40829,7 +40829,7 @@ var fs6 = __toESM(require("fs"));
40829
40829
  var import_ethers39 = require("ethers");
40830
40830
 
40831
40831
  // src/boundary/index.ts
40832
- var import_node_crypto7 = require("crypto");
40832
+ var import_node_crypto8 = require("crypto");
40833
40833
  var fs5 = __toESM(require("fs"));
40834
40834
  var os2 = __toESM(require("os"));
40835
40835
  var path4 = __toESM(require("path"));
@@ -42337,11 +42337,10 @@ var World = class {
42337
42337
  const spend = BigInt(p.amountSats);
42338
42338
  const fee = BigInt(p.networkFeeSats);
42339
42339
  const available = this.availableSats(p.positionId);
42340
- if (spend + fee > available) {
42341
- const maxSpend = available > fee ? available - fee : 0n;
42340
+ if (spend > available) {
42342
42341
  return {
42343
42342
  ok: false,
42344
- reason: `withdrawal of ${spend.toString()} sats leaves no room for the ${fee.toString()}-sat network fee (TargetMustLeaveFeeRoom) \u2014 max amountSats now is ${maxSpend.toString()} (destination then receives ${(maxSpend > fee ? maxSpend - fee : 0n).toString()} after the fee)`
42343
+ reason: `withdrawal of ${spend.toString()} sats exceeds the ${available.toString()} sats available (TargetExceedsInputValue) \u2014 max amountSats now is ${available.toString()} (destination then receives ${(available > fee ? available - fee : 0n).toString()} after the fee)`
42345
42344
  };
42346
42345
  }
42347
42346
  const debt = BigInt(pos.debtUcdWei);
@@ -51513,9 +51512,9 @@ var init_deployment_addresses = __esm2({
51513
51512
  reason: "Shared upgrade script: LiquidationManagerModule implementation update"
51514
51513
  },
51515
51514
  BTCSpendAuthorizer: {
51516
- previousImplementation: "0x8775a520cAA18c03Cc3f51ee254cAB830960f80E",
51517
- newImplementation: "0xdd3DFaEc50d6214d57eA64e8b76ff318b501607b",
51518
- upgradedAt: "2026-07-03T20:09:36.466Z",
51515
+ previousImplementation: "0xdd3DFaEc50d6214d57eA64e8b76ff318b501607b",
51516
+ newImplementation: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
51517
+ upgradedAt: "2026-09-06T15:03:13.627Z",
51519
51518
  upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
51520
51519
  reason: "Shared upgrade script: BTCSpendAuthorizer implementation update"
51521
51520
  },
@@ -51581,6 +51580,13 @@ var init_deployment_addresses = __esm2({
51581
51580
  upgradedAt: "2026-07-07T16:56:49.844Z",
51582
51581
  upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
51583
51582
  reason: "Shared upgrade script: BitcoinWithdrawalAddressRegistry implementation update"
51583
+ },
51584
+ AgentDelegationRegistry: {
51585
+ previousImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
51586
+ newImplementation: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
51587
+ upgradedAt: "2026-09-06T15:06:02.814Z",
51588
+ upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
51589
+ reason: "Reconciled implementation from chain"
51584
51590
  }
51585
51591
  },
51586
51592
  history: {
@@ -51666,7 +51672,7 @@ var init_deployment_addresses = __esm2({
51666
51672
  LIQUIDATION_MANAGER_MODULE: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76",
51667
51673
  LIQUIDATION_MANAGER_MODULE_IMPL: "0xCe7587C47094BBb3dCa13D7a2299Ec9beA6cd759",
51668
51674
  BTC_SPEND_AUTHORIZER: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
51669
- BTC_SPEND_AUTHORIZER_IMPL: "0xdd3DFaEc50d6214d57eA64e8b76ff318b501607b",
51675
+ BTC_SPEND_AUTHORIZER_IMPL: "0xf3282B5A1AE6428ee1b08cfaAF4EB4e198877484",
51670
51676
  UPGRADE_VALIDATOR: "0x592e650edD9bA26ecc407989fdd6F9cdcDeC27A6",
51671
51677
  UPGRADE_VALIDATOR_IMPL: "0x9E70e1D07AB11ac9dD37B67AA091Efe97d7Ed84b",
51672
51678
  BITCOIN_PROVIDER_REGISTRY: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
@@ -58784,12 +58790,12 @@ async function reconcileAuthorizedSpend(spend, esploraBaseUrl, httpGetJson = def
58784
58790
  { txid: spend.txid, vout: spend.vout }
58785
58791
  );
58786
58792
  }
58787
- if (spend.targetAmount >= spend.satoshis) {
58793
+ if (spend.targetAmount > spend.satoshis) {
58788
58794
  return {
58789
58795
  spend,
58790
58796
  status: "CORRUPT",
58791
58797
  onChainOutputValue,
58792
- reason: `Authorized targetAmount ${spend.targetAmount} sats is not below the ${spend.satoshis}-sat aggregate input value \u2014 the contract could never have authorized this`
58798
+ reason: `Authorized targetAmount ${spend.targetAmount} sats exceeds the ${spend.satoshis}-sat aggregate input value \u2014 the contract could never have authorized this`
58793
58799
  };
58794
58800
  }
58795
58801
  const outspendRes = await httpGetJson(
@@ -79734,13 +79740,20 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79734
79740
  const outcome = await this.deps.bridge.requestSignature({
79735
79741
  id: (0, import_node_crypto5.randomUUID)(),
79736
79742
  kind: "personal-sign",
79737
- action: "btc-withdrawal authorization (blind hash)",
79743
+ action: "btc-withdrawal EXECUTE step (blind hash)",
79738
79744
  card: [
79739
- "BLIND SIGNATURE \u2014 BTC withdrawal authorization step",
79745
+ "BLIND SIGNATURE \u2014 BTC withdrawal, EXECUTE step",
79740
79746
  `hash: ${hashHex}`,
79741
79747
  "This hash is built inside the SDK and its contents CANNOT be decoded or verified by this page",
79742
79748
  "(identical to how diamondhands.credit signs withdrawals).",
79743
- "Approve ONLY if you initiated this exact BTC withdrawal in the conversation."
79749
+ "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79750
+ "",
79751
+ "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
79752
+ `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
79753
+ "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
79754
+ "itself allows. If it expires the signature is refused, the withdrawal does not",
79755
+ "complete, and the reserved coins stay reserved until that is cleared. Decline and",
79756
+ "start again rather than signing something you have not finished reading."
79744
79757
  ],
79745
79758
  expectedSigner: this.deps.borrower,
79746
79759
  chainId: this.deps.chainId,
@@ -80673,10 +80686,10 @@ var RealUpstreamPlugin = class {
80673
80686
  // src/boundary/upstream/shared/external-bridge/bridge.ts
80674
80687
  var fs4 = __toESM(require("fs"));
80675
80688
  var http3 = __toESM(require("http"));
80676
- var import_node_crypto6 = require("crypto");
80689
+ var import_node_crypto7 = require("crypto");
80677
80690
 
80678
80691
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
80679
- function renderApprovalPage(sessionId) {
80692
+ function renderApprovalPage(sessionId, nonce) {
80680
80693
  return `<!doctype html>
80681
80694
  <html lang="en">
80682
80695
  <head>
@@ -80726,15 +80739,17 @@ function renderApprovalPage(sessionId) {
80726
80739
  </div>
80727
80740
  </div>
80728
80741
  </main>
80729
- <script>
80742
+ <script nonce="${nonce}">
80730
80743
  ${PAGE_CRYPTO_JS}
80731
80744
  </script>
80732
- <script>
80745
+ <script nonce="${nonce}">
80733
80746
  "use strict";
80734
80747
  const SESSION = ${JSON.stringify(sessionId)};
80735
80748
  // One-time token leaves the address bar (and history) immediately.
80736
80749
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
80737
80750
  // at loopback root ("/") and under a hosted tenant mount ("/approval/<id>/").
80751
+ // EVERY endpoint reference goes through BASE \u2014 an origin-absolute "/x" resolves to the
80752
+ // ORIGIN root, which on a mount is the host, not the bridge, and 404s silently.
80738
80753
  const BASE = location.pathname.replace(/[^/]*$/, "");
80739
80754
  history.replaceState(null, "", location.pathname);
80740
80755
 
@@ -80806,14 +80821,14 @@ async function connect() {
80806
80821
  // wallet's own state transition and can report the stale value.
80807
80822
  async function onAccountsChanged(accounts) {
80808
80823
  account = (accounts && accounts[0]) || null;
80809
- await post("/wallet-event", { account: account, chainId: chainId });
80824
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
80810
80825
  showWallet();
80811
80826
  clearRequest("Wallet changed \u2014 pending request invalidated.");
80812
80827
  }
80813
80828
 
80814
80829
  async function onChainChanged(cid) {
80815
80830
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
80816
- await post("/wallet-event", { account: account, chainId: chainId });
80831
+ await post(BASE + "wallet-event", { account: account, chainId: chainId });
80817
80832
  showWallet();
80818
80833
  clearRequest("Network changed \u2014 pending request invalidated.");
80819
80834
  }
@@ -80921,7 +80936,7 @@ connect();
80921
80936
  </body>
80922
80937
  </html>`;
80923
80938
  }
80924
- function renderUnlockPage(sessionId) {
80939
+ function renderUnlockPage(sessionId, nonce) {
80925
80940
  return `<!doctype html>
80926
80941
  <html lang="en">
80927
80942
  <head>
@@ -80963,7 +80978,7 @@ function renderUnlockPage(sessionId) {
80963
80978
  <div id="status" class="status"></div>
80964
80979
  </div>
80965
80980
  </main>
80966
- <script>
80981
+ <script nonce="${nonce}">
80967
80982
  "use strict";
80968
80983
  const SESSION = ${JSON.stringify(sessionId)};
80969
80984
  // Plan 12 C1: endpoints resolve relative to the page DIRECTORY, so the same page works
@@ -80994,6 +81009,21 @@ document.getElementById("generate").onclick = () => submit(true);
80994
81009
  </html>`;
80995
81010
  }
80996
81011
 
81012
+ // src/util/page-headers.ts
81013
+ var import_node_crypto6 = require("crypto");
81014
+ function htmlPageSecurityHeaders() {
81015
+ const nonce = (0, import_node_crypto6.randomBytes)(16).toString("base64");
81016
+ return {
81017
+ nonce,
81018
+ headers: {
81019
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
81020
+ "X-Frame-Options": "DENY",
81021
+ "Referrer-Policy": "no-referrer",
81022
+ "X-Content-Type-Options": "nosniff"
81023
+ }
81024
+ };
81025
+ }
81026
+
80997
81027
  // src/boundary/upstream/shared/external-bridge/bridge.ts
80998
81028
  var MAX_SESSIONS = 16;
80999
81029
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
@@ -81021,7 +81051,7 @@ var SignatureBridge = class {
81021
81051
  /** Started state independent of the transport binding (mounted bridges own no server). */
81022
81052
  started = false;
81023
81053
  mount;
81024
- token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81054
+ token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81025
81055
  /** Hosted mounts: when the current page token was minted (rotation basis). */
81026
81056
  tokenMintedAt = 0;
81027
81057
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
@@ -81058,7 +81088,7 @@ var SignatureBridge = class {
81058
81088
  unlockUrl() {
81059
81089
  if (!this.started) throw new Error("bridge is not started");
81060
81090
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
81061
- this.unlockToken = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81091
+ this.unlockToken = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81062
81092
  return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
81063
81093
  }
81064
81094
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
@@ -81099,7 +81129,7 @@ var SignatureBridge = class {
81099
81129
  if (this.mount) {
81100
81130
  const now = this.clock();
81101
81131
  if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
81102
- this.token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81132
+ this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81103
81133
  this.tokenMintedAt = now;
81104
81134
  }
81105
81135
  return `${this.mount.baseUrl}/?t=${this.token}`;
@@ -81315,7 +81345,7 @@ var SignatureBridge = class {
81315
81345
  this.server = null;
81316
81346
  this.started = false;
81317
81347
  this.wallet = null;
81318
- this.token = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81348
+ this.token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81319
81349
  this.tokenMintedAt = 0;
81320
81350
  if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
81321
81351
  void this.wcTransport?.close().catch(() => void 0);
@@ -81385,10 +81415,11 @@ var SignatureBridge = class {
81385
81415
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
81386
81416
  return;
81387
81417
  }
81388
- const sessionId = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81418
+ const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81389
81419
  this.sessions.set(sessionId, { wallet: null, sse: null });
81390
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81391
- res.end(renderApprovalPage(sessionId));
81420
+ const page = htmlPageSecurityHeaders();
81421
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81422
+ res.end(renderApprovalPage(sessionId, page.nonce));
81392
81423
  }
81393
81424
  /** Target-network hints for the page's chain self-heal (session-gated). */
81394
81425
  serveConfig(url2, res) {
@@ -81448,9 +81479,10 @@ var SignatureBridge = class {
81448
81479
  return;
81449
81480
  }
81450
81481
  this.unlockToken = null;
81451
- this.unlockSession = (0, import_node_crypto6.randomBytes)(24).toString("hex");
81452
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
81453
- res.end(renderUnlockPage(this.unlockSession));
81482
+ this.unlockSession = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81483
+ const page = htmlPageSecurityHeaders();
81484
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81485
+ res.end(renderUnlockPage(this.unlockSession, page.nonce));
81454
81486
  }
81455
81487
  async onUnlockSubmit(body, res) {
81456
81488
  if (!this.keystoreUnlock) {
@@ -81696,7 +81728,7 @@ function createBoundary(config, opts) {
81696
81728
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
81697
81729
  );
81698
81730
  }
81699
- const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
81731
+ const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
81700
81732
  if (opts?.ceremony) {
81701
81733
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
81702
81734
  const boundary2 = new BoundaryCore({
@@ -81865,7 +81897,7 @@ async function createRealBoundary(config, wallet, overrides) {
81865
81897
  }
81866
81898
  const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
81867
81899
  await plugin.initWriteSdk();
81868
- const configFingerprint = (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
81900
+ const configFingerprint = (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
81869
81901
  const capabilities = () => ({
81870
81902
  reads: {
81871
81903
  public: true,
@@ -81965,469 +81997,6 @@ async function buildBoundary(configResult, overrides) {
81965
81997
  return { boundaryResult: { ok: true, boundary }, signer, dispose };
81966
81998
  }
81967
81999
 
81968
- // src/network-switch.ts
81969
- var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
81970
- function createNetworkSwitchRuntime(opts) {
81971
- return {
81972
- current() {
81973
- const b = opts.getBoot().boundaryResult;
81974
- if (!b.ok) return null;
81975
- const w = b.boundary.world();
81976
- return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
81977
- },
81978
- async switchTo(network) {
81979
- const allowed = opts.overrides?.allowedNetworks;
81980
- if (allowed && !allowed.includes(network)) {
81981
- return {
81982
- ok: false,
81983
- error: boundaryError(
81984
- "VALIDATION_FAILED",
81985
- `this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
81986
- )
81987
- };
81988
- }
81989
- const targetEnv = { ...opts.env, DH_NETWORK: network };
81990
- const configResult = resolveBoundaryConfig(targetEnv);
81991
- if (!configResult.ok) return { ok: false, error: configResult.error };
81992
- const next = await buildBoundary(configResult, opts.overrides);
81993
- if (!next.boundaryResult.ok) {
81994
- next.dispose();
81995
- return { ok: false, error: next.boundaryResult.error };
81996
- }
81997
- opts.swap(next);
81998
- return { ok: true };
81999
- }
82000
- };
82001
- }
82002
- function assembleWorld(opts) {
82003
- let boot = opts.boot;
82004
- const deps = {
82005
- boundaryResult: boot.boundaryResult,
82006
- ...boot.mockControl ? { mockControl: boot.mockControl } : {},
82007
- ...boot.signer ? { signer: boot.signer } : {},
82008
- ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
82009
- ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
82010
- };
82011
- if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
82012
- deps.networkSwitch = createNetworkSwitchRuntime({
82013
- env: opts.env,
82014
- getBoot: () => boot,
82015
- ...opts.overrides ? { overrides: opts.overrides } : {},
82016
- swap: (next) => {
82017
- const old = boot;
82018
- boot = next;
82019
- deps.boundaryResult = next.boundaryResult;
82020
- if (next.signer) deps.signer = next.signer;
82021
- else delete deps.signer;
82022
- old.dispose();
82023
- const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
82024
- opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
82025
- }
82026
- });
82027
- }
82028
- return { deps, dispose: () => boot.dispose() };
82029
- }
82030
-
82031
- // src/server.ts
82032
- var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
82033
-
82034
- // src/tools/loan.ts
82035
- var import_zod = require("zod");
82036
- var import_ethers40 = require("ethers");
82037
-
82038
- // src/util/format.ts
82039
- function bigintReplacer(_key, value) {
82040
- if (typeof value === "bigint") return value.toString();
82041
- return value;
82042
- }
82043
- function serialize(data) {
82044
- return JSON.stringify(data, bigintReplacer, 2);
82045
- }
82046
-
82047
- // src/tools/_helpers.ts
82048
- function registerBoundaryTool(server, name, config, handler) {
82049
- server.registerTool(name, config, handler);
82050
- }
82051
- function renderError(error) {
82052
- const lines = [`ERROR [${error.code}]: ${error.message}`];
82053
- if (error.source) lines.push(`source: ${error.source}`);
82054
- return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
82055
- }
82056
- function renderEnvelope(env) {
82057
- if (!env.ok) return renderError(env.error);
82058
- const parts = [serialize(env.data)];
82059
- if (env.warnings.length > 0) {
82060
- parts.push(
82061
- "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
82062
- );
82063
- }
82064
- parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
82065
- return { content: [{ type: "text", text: parts.join("\n\n") }] };
82066
- }
82067
- function validationFailed(problem) {
82068
- return renderError(boundaryError("VALIDATION_FAILED", problem));
82069
- }
82070
- function resourceJson(env) {
82071
- if (!env.ok) return serialize({ error: env.error });
82072
- return serialize({ data: env.data, warnings: env.warnings, source: env.source });
82073
- }
82074
- function resourceErrorJson(error) {
82075
- return serialize({ error });
82076
- }
82077
- function requireConfirmation(confirmed, actionLabel) {
82078
- if (confirmed === true) return null;
82079
- return {
82080
- content: [
82081
- {
82082
- type: "text",
82083
- text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
82084
- This is an irreversible, fund-moving action. A human must explicitly authorize it.
82085
- Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
82086
- }
82087
- ],
82088
- isError: true
82089
- };
82090
- }
82091
- function envStamp(b) {
82092
- if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
82093
- const w = b.boundary.world();
82094
- const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
82095
- return `environment: ${w.network} \u2014 ${money}`;
82096
- }
82097
- async function guardedWrite(getB, fn) {
82098
- const result = await guarded(fn);
82099
- const stamp = envStamp(getB());
82100
- const content = result.content.map(
82101
- (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
82102
-
82103
- ${stamp}` } : c
82104
- );
82105
- return { ...result, content };
82106
- }
82107
- async function guarded(fn) {
82108
- try {
82109
- return await fn();
82110
- } catch (e) {
82111
- return renderError(
82112
- boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
82113
- details: { stack: e.stack }
82114
- })
82115
- );
82116
- }
82117
- }
82118
-
82119
- // src/util/validate.ts
82120
- var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
82121
- var SATS_SANITY_CAP = 1e10;
82122
- var UCD_SANITY_CAP = 1e9;
82123
- function checkPositionIdHex(id, label = "Position ID") {
82124
- if (!POSITION_ID_RE.test(id)) {
82125
- return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
82126
- }
82127
- return null;
82128
- }
82129
- function checkUcdAmount(amount, label = "Amount") {
82130
- if (!Number.isFinite(amount) || amount <= 0) {
82131
- return `${label} must be a positive finite number (got ${amount}).`;
82132
- }
82133
- if (amount > UCD_SANITY_CAP) {
82134
- return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
82135
- }
82136
- if (amount > 0 && amount < 1e-6) {
82137
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
82138
- }
82139
- const decimals = amount.toString().split(".")[1];
82140
- if (decimals && decimals.length > 6) {
82141
- return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
82142
- }
82143
- return null;
82144
- }
82145
- function checkSatsAmount(sats, label = "Amount") {
82146
- if (!Number.isInteger(sats) || sats <= 0) {
82147
- return `${label} must be a positive integer (satoshis), got ${sats}.`;
82148
- }
82149
- if (sats > SATS_SANITY_CAP) {
82150
- return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
82151
- }
82152
- return null;
82153
- }
82154
- function checkSelectedTerm(months, label = "Term") {
82155
- if (!Number.isInteger(months) || months <= 0) {
82156
- return `${label} must be a positive integer (months), got ${months}.`;
82157
- }
82158
- if (months > 120) {
82159
- return `${label} ${months} months exceeds the 10-year sanity cap.`;
82160
- }
82161
- return null;
82162
- }
82163
-
82164
- // src/tools/loan.ts
82165
- var LATENCY_NOTES = {
82166
- mock: "Instant in this practice world.",
82167
- real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
82168
- };
82169
- var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
82170
- var confirmedSchema = import_zod.z.boolean().optional().describe(
82171
- "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
82172
- );
82173
- var DESTRUCTIVE_WRITE_ANNOTATIONS = {
82174
- readOnlyHint: false,
82175
- destructiveHint: true,
82176
- idempotentHint: false,
82177
- openWorldHint: true
82178
- };
82179
- function registerLoanTools(server, getB, adapter2 = "real") {
82180
- const LATENCY_NOTE = LATENCY_NOTES[adapter2];
82181
- registerBoundaryTool(
82182
- server,
82183
- "loan_create",
82184
- {
82185
- title: "Create a new lending position",
82186
- 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).`,
82187
- inputSchema: {
82188
- selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
82189
- confirmed: confirmedSchema
82190
- },
82191
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82192
- },
82193
- async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82194
- const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
82195
- if (gate) return gate;
82196
- const problem = checkSelectedTerm(selectedTerm);
82197
- if (problem) return validationFailed(problem);
82198
- const b = getB();
82199
- if (!b.ok) return renderError(b.error);
82200
- return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
82201
- })
82202
- );
82203
- registerBoundaryTool(
82204
- server,
82205
- "loan_mint",
82206
- {
82207
- title: "Mint UCD against a position",
82208
- description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82209
- inputSchema: {
82210
- positionId: positionIdSchema,
82211
- amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
82212
- confirmed: confirmedSchema
82213
- },
82214
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82215
- },
82216
- async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
82217
- const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
82218
- if (gate) return gate;
82219
- const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
82220
- if (problem) return validationFailed(problem);
82221
- const b = getB();
82222
- if (!b.ok) return renderError(b.error);
82223
- return renderEnvelope(
82224
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers40.parseEther)(amountUcd.toString()).toString() })
82225
- );
82226
- })
82227
- );
82228
- registerBoundaryTool(
82229
- server,
82230
- "loan_pay",
82231
- {
82232
- title: "Make a UCD payment toward a position's debt",
82233
- description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82234
- inputSchema: {
82235
- positionId: positionIdSchema,
82236
- amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
82237
- repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
82238
- confirmed: confirmedSchema
82239
- },
82240
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82241
- },
82242
- async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
82243
- if (repayAll === true === (amountUcd !== void 0)) {
82244
- return validationFailed("provide exactly one of amountUcd or repayAll: true");
82245
- }
82246
- const gate = requireConfirmation(
82247
- confirmed,
82248
- repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
82249
- );
82250
- if (gate) return gate;
82251
- const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
82252
- if (problem) return validationFailed(problem);
82253
- const b = getB();
82254
- if (!b.ok) return renderError(b.error);
82255
- let amountUcdWei;
82256
- if (repayAll) {
82257
- const detail = await b.boundary.getPosition(positionId);
82258
- if (!detail.ok) return renderError(detail.error);
82259
- if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
82260
- amountUcdWei = detail.data.debtUcdWei;
82261
- } else {
82262
- amountUcdWei = (0, import_ethers40.parseEther)(amountUcd.toString()).toString();
82263
- }
82264
- return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
82265
- })
82266
- );
82267
- registerBoundaryTool(
82268
- server,
82269
- "loan_extend",
82270
- {
82271
- title: "Extend / renew a position's term",
82272
- description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82273
- inputSchema: {
82274
- positionId: positionIdSchema,
82275
- selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
82276
- confirmed: confirmedSchema
82277
- },
82278
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82279
- },
82280
- async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
82281
- const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
82282
- if (gate) return gate;
82283
- const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
82284
- if (problem) return validationFailed(problem);
82285
- const b = getB();
82286
- if (!b.ok) return renderError(b.error);
82287
- return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
82288
- })
82289
- );
82290
- registerBoundaryTool(
82291
- server,
82292
- "loan_withdraw",
82293
- {
82294
- title: "Withdraw BTC from a position vault",
82295
- description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
82296
- inputSchema: {
82297
- positionId: positionIdSchema,
82298
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
82299
- amountSats: import_zod.z.number().int().positive().describe(
82300
- "GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. You cannot spend the whole balance \u2014 the vault must keep room for the fee (TargetMustLeaveFeeRoom), so max amountSats = available \u2212 fee and a withdrawal always leaves fee-sized dust behind."
82301
- ),
82302
- networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
82303
- confirmed: confirmedSchema
82304
- },
82305
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82306
- },
82307
- async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
82308
- const gate = requireConfirmation(
82309
- confirmed,
82310
- `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
82311
- );
82312
- if (gate) return gate;
82313
- const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
82314
- if (problem) return validationFailed(problem);
82315
- const b = getB();
82316
- if (!b.ok) return renderError(b.error);
82317
- return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
82318
- })
82319
- );
82320
- registerBoundaryTool(
82321
- server,
82322
- "loan_allowlist_destination",
82323
- {
82324
- title: "Allowlist a BTC withdrawal destination",
82325
- description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
82326
- inputSchema: {
82327
- btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
82328
- confirmed: confirmedSchema
82329
- },
82330
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82331
- },
82332
- async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
82333
- const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
82334
- if (gate) return gate;
82335
- const b = getB();
82336
- if (!b.ok) return renderError(b.error);
82337
- return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
82338
- })
82339
- );
82340
- registerBoundaryTool(
82341
- server,
82342
- "loan_delegation_setup",
82343
- {
82344
- title: "Install delegation on the Safe (one owner ceremony)",
82345
- description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
82346
- inputSchema: {
82347
- btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
82348
- confirmed: confirmedSchema
82349
- },
82350
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82351
- },
82352
- async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
82353
- const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
82354
- if (gate) return gate;
82355
- const b = getB();
82356
- if (!b.ok) return renderError(b.error);
82357
- return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
82358
- })
82359
- );
82360
- registerBoundaryTool(
82361
- server,
82362
- "loan_delegation_grant",
82363
- {
82364
- title: "Grant the agent per-position scopes (owners sign)",
82365
- description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
82366
- inputSchema: {
82367
- positionId: positionIdSchema,
82368
- renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
82369
- repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
82370
- mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
82371
- confirmed: confirmedSchema
82372
- },
82373
- annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
82374
- },
82375
- async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
82376
- const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
82377
- if (gate) return gate;
82378
- const b = getB();
82379
- if (!b.ok) return renderError(b.error);
82380
- return renderEnvelope(
82381
- await b.boundary.delegationGrant({
82382
- positionId,
82383
- renew: renew ?? false,
82384
- repay: repay ?? false,
82385
- mintFloorBps: mintFloorBps ?? null
82386
- })
82387
- );
82388
- })
82389
- );
82390
- registerBoundaryTool(
82391
- server,
82392
- "loan_recover_stale_spend",
82393
- {
82394
- title: "Recover a stale BTC reservation via LIT-attested proof",
82395
- 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.",
82396
- inputSchema: {
82397
- positionId: positionIdSchema,
82398
- utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
82399
- utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
82400
- invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
82401
- minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
82402
- },
82403
- annotations: {
82404
- readOnlyHint: false,
82405
- destructiveHint: false,
82406
- idempotentHint: true,
82407
- openWorldHint: true
82408
- }
82409
- },
82410
- async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
82411
- const problem = checkPositionIdHex(positionId);
82412
- if (problem) return validationFailed(problem);
82413
- const b = getB();
82414
- if (!b.ok) return renderError(b.error);
82415
- return renderEnvelope(
82416
- await b.boundary.recoverStaleSpend({
82417
- positionId,
82418
- utxoTxid,
82419
- utxoVout,
82420
- invalidatorTxid,
82421
- ...minConfirmations !== void 0 ? { minConfirmations } : {}
82422
- })
82423
- );
82424
- })
82425
- );
82426
- }
82427
-
82428
- // src/tools/position.ts
82429
- var import_zod2 = require("zod");
82430
-
82431
82000
  // src/boundary/field-glossary.ts
82432
82001
  var FIELD_GLOSSARY = {
82433
82002
  // ---- identity / envelope structure ----
@@ -82553,7 +82122,1288 @@ response \u2014 follow them over any prior assumption.
82553
82122
  ${lines.join("\n")}`;
82554
82123
  }
82555
82124
 
82125
+ // src/guide/content.ts
82126
+ var GUIDE_TOPICS = [
82127
+ "getting-started",
82128
+ "first-setup",
82129
+ "connect-wallet",
82130
+ "lifecycle",
82131
+ "fees",
82132
+ "psm",
82133
+ "authorization",
82134
+ "safe",
82135
+ "delegation",
82136
+ "safety",
82137
+ "switch-network",
82138
+ "connector",
82139
+ "troubleshooting",
82140
+ "glossary",
82141
+ "reading-data"
82142
+ ];
82143
+ var GUIDE_SIGNER_MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
82144
+ var EXTERNAL_ONLY_SIGNER_MODES = ["external"];
82145
+ function offers(d, mode) {
82146
+ return d.signerModes.includes(mode);
82147
+ }
82148
+ function signerModeSourceClause(d) {
82149
+ return offers(d, "keystore") ? "the set `signer_setup` offers. `boundary://info` reports the NARROWER set the active adapter actually constructs under `capabilities.writes.signerModes` (the real adapter builds `external` + `keystore`; the practice ceremonies are mock-adapter only) \u2014 when the two differ, `boundary://info` is authoritative" : "the same set `signer_setup` offers and `boundary://info` reports under `capabilities.writes.signerModes`";
82150
+ }
82151
+ var LOCAL_GUIDE_DEPLOYMENT = {
82152
+ tier: "local",
82153
+ networks: ["sepolia", "mainnet"],
82154
+ // A local install constructs the whole signer runtime: the real adapter offers
82155
+ // external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
82156
+ // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
82157
+ // on the real adapter these modes refuse") carry the narrower adapter axis.
82158
+ signerModes: GUIDE_SIGNER_MODES
82159
+ };
82160
+ function servedNetworks(d) {
82161
+ if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
82162
+ const mainnet = d.networks.includes("mainnet");
82163
+ const sepolia = d.networks.includes("sepolia");
82164
+ if (mainnet && sepolia) {
82165
+ return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
82166
+ }
82167
+ if (mainnet) {
82168
+ return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
82169
+ }
82170
+ return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
82171
+ }
82172
+ function connectorStatusTruth(d) {
82173
+ if (d.tier === "hosted") {
82174
+ return `**STATUS TRUTH (say this first when asked):** this session IS the hosted
82175
+ connector \u2014 the user is already on it, so there is nothing to install and no URL to hand
82176
+ out. It serves ${servedNetworks(d)}. State that money reality unprompted, and never
82177
+ promise a network, a tier or a timing this deployment does not already serve.`;
82178
+ }
82179
+ return `**STATUS TRUTH (say this first when asked):** this session is a LOCAL install,
82180
+ not the hosted connector. Whether a public connector URL is being served today is the
82181
+ operator's rollout decision and this build cannot see it \u2014 so never assert that one is
82182
+ available, and never assert that one is not. If the user already has a URL, everything
82183
+ below describes what they get; otherwise the local install paths (\`first-setup\`) are the
82184
+ way in. Never promise availability or timing.`;
82185
+ }
82186
+ function connectorNetworkTruth(d) {
82187
+ if (d.tier === "hosted") {
82188
+ return `And it serves only the networks its deployment is rolled out to \u2014 this one
82189
+ serves ${servedNetworks(d)}. Which networks a deployment is rolled out to is the
82190
+ operator's deploy decision, never a hidden knob \u2014 and it is not a field of
82191
+ \`boundary://info\`, whose capabilities block reports the world THIS session is on right
82192
+ now (network, chainId, practiceWorld) plus the read/write/signer planes. \`network_switch\`
82193
+ is what states the rollout: asked for a network this deployment is not rolled out to, it
82194
+ refuses and names the ones it is.`;
82195
+ }
82196
+ return `And any connector deployment serves only the networks it is rolled out to \u2014
82197
+ which ones is the operator's deploy decision, never a hidden knob. Do not go looking for
82198
+ that list in \`boundary://info\`: its capabilities block reports the world THIS session is
82199
+ on (network, chainId, practiceWorld) plus the read/write/signer planes, never another
82200
+ deployment's rollout. \`network_switch\` is what states it \u2014 asked for a network a
82201
+ deployment is not rolled out to, it refuses and names the ones it is. This local build
82202
+ cannot see another deployment's rollout at all: ask that server, never assume.`;
82203
+ }
82204
+ function connectorInstallNote(d) {
82205
+ if (d.tier === "hosted") {
82206
+ return `(The user is ALREADY on the fourth, zero-install path \u2014 the claude.ai
82207
+ connector \u2014 so none of the above is needed HERE; those paths are for other machines.
82208
+ Truth and trust model: \`guide connector\`.)`;
82209
+ }
82210
+ return `(A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented in this
82211
+ build. Whether it is publicly served today is the operator's rollout decision and this
82212
+ session cannot see it: do not assert either way. Truth and trust model:
82213
+ \`guide connector\`.)`;
82214
+ }
82215
+ function connectorTroubleshootingRow(d) {
82216
+ if (d.tier === "hosted") {
82217
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 that is THIS
82218
+ session. Nothing to install, no URL to look up; it serves ${servedNetworks(d)}. Full
82219
+ truth: \`guide connector\`.`;
82220
+ }
82221
+ return `- **Asked for the claude.ai connector / remote / hosted tier** \u2014 this session is
82222
+ a local install, not that tier. Whether a public URL is being served today is the
82223
+ operator's rollout decision and this build cannot see it: do not assert either way. The
82224
+ local install paths work regardless. Full truth: \`guide connector\`.`;
82225
+ }
82226
+ function approvalPageLocation(d) {
82227
+ if (d.tier === "hosted") {
82228
+ return `its URL is ALSO in the tool result. On this hosted tier the page is served by
82229
+ the connector itself over HTTPS on its own public origin, so ANY browser reaches it,
82230
+ including a phone's. The link carries a one-time session token \u2014 treat it as a secret,
82231
+ never forward it, and check the address bar shows that same origin before connecting a
82232
+ wallet.`;
82233
+ }
82234
+ return `its URL is ALSO in the tool result. On this local install the page is served by
82235
+ the server's own loopback listener (127.0.0.1): it exists only on the machine the
82236
+ server runs on, so open it there \u2014 no other device can reach it.`;
82237
+ }
82238
+ function switchNetworkHeadline(d) {
82239
+ return d.networks.length > 1 ? "sepolia \u2194 mainnet by conversation (real adapter)" : `${d.networks[0]} ONLY on this deployment (real adapter)`;
82240
+ }
82241
+ function switchNetworkRules(d) {
82242
+ if (d.networks.length > 1) {
82243
+ return `- \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
82244
+ the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
82245
+ - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
82246
+ A sepolia position does not exist on mainnet and vice versa.
82247
+ - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
82248
+ and every one still requires the user's explicit confirmation plus the signer
82249
+ ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
82250
+ }
82251
+ const only = d.networks[0];
82252
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82253
+ const psm = d.networks.includes("mainnet") ? "The exception is PSM swaps \u2014 the write port refuses them here." : "PSM swaps run here, and are refused on every other network.";
82254
+ return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
82255
+ network this deployment is rolled out to \u2014 every other target is REFUSED with that
82256
+ rollout truth. There is nothing to switch TO here; never offer the user another world.
82257
+ Money reality: ${money}.
82258
+ - State is per-network by construction: positions, vaults, signer bindings and logins
82259
+ belong to ${only} and would not exist anywhere else.
82260
+ - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
82261
+ confirmation plus the signer ceremony.
82262
+ - ${psm}`;
82263
+ }
82264
+ function wrongNetworkTroubleshootingRow(d) {
82265
+ if (d.networks.length > 1) {
82266
+ return `- **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
82267
+ (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
82268
+ config \u2014 no switch exists there.`;
82269
+ }
82270
+ return `- **Wrong network / asks for another one** \u2014 this deployment is rolled out to
82271
+ ${d.networks[0]} alone, so \`network_switch\` refuses every other target with that
82272
+ rollout truth. Relay the refusal; do not suggest a world this service does not serve.`;
82273
+ }
82274
+ function switchNetworkIndexLine(d) {
82275
+ if (d.networks.length > 1) {
82276
+ return "- switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated";
82277
+ }
82278
+ const only = d.networks[0];
82279
+ const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82280
+ return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
82281
+ }
82282
+ function psmAvailabilityNote(d) {
82283
+ if (d.networks.includes("sepolia")) return "";
82284
+ return `**Not executable on this deployment.** The PSM write port refuses on every network
82285
+ but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
82286
+ \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
82287
+ the mechanism, not an offer: say so before a user plans around it.
82288
+
82289
+ `;
82290
+ }
82291
+ function authorizationModeBullets(d) {
82292
+ const bullets = [];
82293
+ if (offers(d, "external")) {
82294
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
82295
+ mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
82296
+ is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
82297
+ The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
82298
+ approval page states plainly it CANNOT decode. Never extend the card promise over
82299
+ that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
82300
+ }
82301
+ if (offers(d, "keystore")) {
82302
+ bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
82303
+ Real adapter and mock.`);
82304
+ }
82305
+ if (offers(d, "safe") || offers(d, "safe-module")) {
82306
+ bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
82307
+ refuse with that true reason (their planes ship in their own deliveries).`);
82308
+ }
82309
+ if (offers(d, "mock-simulated")) {
82310
+ bullets.push(` - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).`);
82311
+ }
82312
+ return bullets.join("\n");
82313
+ }
82314
+ function keystoreAbsenceParagraph(d) {
82315
+ if (offers(d, "keystore")) return "";
82316
+ return `
82317
+ **There is no keystore mode on this build.** It is ABSENT, not disabled: the provider
82318
+ is never constructed, so no key material can exist server-side and there is nothing to
82319
+ unlock. "Sign automatically, without popups" is impossible here \u2014 say that true reason
82320
+ instead of describing a keystore, and never ask for a password.
82321
+ `;
82322
+ }
82323
+ function keystoreAbsenceBullet() {
82324
+ return `- **"Sign automatically / no popups" cannot happen here** \u2014 there is no keystore mode
82325
+ on this build. It is ABSENT, not disabled: the provider is never constructed, so no key
82326
+ material can exist server-side and nothing can be unlocked. Give that true reason, and
82327
+ never ask for a password.`;
82328
+ }
82329
+ var GUIDE_TOPIC_SOURCES = {
82330
+ "getting-started": `# Diamond Hands \u2014 what this is
82331
+
82332
+ Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
82333
+ without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
82334
+ against it, pay it back whenever you like, and take your BTC out again.
82335
+
82336
+ **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
82337
+ topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
82338
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
82339
+ are enabled (and the true reason when not), and which signer modes this build offers;
82340
+ never promise a capability it does not list. The money truth has THREE cases:
82341
+ - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
82342
+ - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
82343
+ the test network: real ceremonies and signatures, PRACTICE money (test funds).
82344
+ - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
82345
+ explicitly arms them; the capabilities block states which applies.
82346
+ SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
82347
+
82348
+ A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
82349
+ authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
82350
+ calls. Every operation that moves funds requires the user's explicit confirmation
82351
+ (\`confirmed: true\`) \u2014 nothing is ever silent.`,
82352
+ "first-setup": (d) => `# First setup \u2014 from zero to ready, by conversation only
82353
+
82354
+ Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
82355
+ \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
82356
+ host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
82357
+ developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
82358
+ install matrix. ${connectorInstallNote(d)}
82359
+
82360
+ Nothing needs a config file. Three steps:
82361
+
82362
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
82363
+ \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
82364
+ (practice money) or mainnet (real money); whether writes are enabled here and which
82365
+ signer modes exist; current terms (\`protocol_terms\`).
82366
+
82367
+ **2. Choose HOW to authorize operations** (the user's choice, made by talking):
82368
+ - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
82369
+ on the real adapter and the mock. The approval page auto-opens in the browser (its URL
82370
+ is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
82371
+ / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
82372
+ their own wallet. The first verified signature binds their wallet address as the
82373
+ borrower. Full walkthrough: \`guide connect-wallet\`.
82374
+ ${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
82375
+ signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
82376
+ \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
82377
+ LOCAL PAGE opens where the user types the password or generates a fresh keystore.
82378
+ NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
82379
+ them to use the unlock page instead.` : keystoreAbsenceBullet()}
82380
+ ${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
82381
+ real adapter they refuse with that true reason. Try them in a mock world.` : `- **Safe / delegation borrowing is not offered by this build** \u2014 its authorization
82382
+ surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
82383
+ \`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
82384
+ - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
82385
+ - **No signer is also a valid start:** every public read works without one \u2014
82386
+ \`position_list {borrower}\` with the user's address needs no signer and no login.
82387
+ ${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
82388
+ talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
82389
+ the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
82390
+ \`network_switch\` refuses every other target with that rollout truth. See
82391
+ \`guide switch-network\`; never offer a world this service does not serve.`}
82392
+
82393
+ **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
82394
+ \`confirmed: true\` from the user). Then deposit BTC to the vault address
82395
+ (practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
82396
+ and mint with \`loan_mint\`.
82397
+
82398
+ The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
82399
+ "connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
82400
+
82401
+ External mode means the user approves every operation in their OWN wallet \u2014 a browser
82402
+ extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
82403
+ the mock.
82404
+
82405
+ **The walkthrough:**
82406
+ 1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
82407
+ desktop browser; ${approvalPageLocation(d)}
82408
+ 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
82409
+ WalletConnect QR code or paste the pairing code.
82410
+ 3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
82411
+ login ceremony explicitly (one typed-data signature in the wallet).
82412
+ 4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
82413
+ across sessions (\`signer_setup reset-borrower\` unbinds it).
82414
+ 5. From then on, every fund-moving operation shows an approval card in the wallet. For
82415
+ TRANSACTIONS that card is decoded from the exact bytes being signed \u2014 what you read
82416
+ IS what executes. The ONE exception is the BTC withdrawal, which signs an opaque
82417
+ 32-byte hash the page states plainly it CANNOT decode (honesty note below); say so
82418
+ before those popups, never "what you read is what executes". Declining always safely
82419
+ cancels.
82420
+
82421
+ **Popup cadence \u2014 exactly this many wallet interactions per operation:**
82422
+
82423
+ | Operation | Wallet interactions (external mode) |
82424
+ |---|---|
82425
+ | login (per login-session lifetime) | 1 typed-data |
82426
+ | create position | 1 tx (plus 1 login typed-data the first time \u2014 the protocol SDK keeps its own session) |
82427
+ | mint | 1 personal-sign + 1 tx |
82428
+ | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
82429
+ | extend | 1 personal-sign + 1 tx |
82430
+ | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
82431
+ | withdraw BTC | 1\u20133 typed-data (decodable) + 1 personal-sign \u2014 a BLIND hash the page cannot decode (see the honesty note below) |
82432
+ | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
82433
+
82434
+ **Honesty notes (say these plainly):**
82435
+ - **Reads never pop the wallet.** If a read needs a login the user does not have, the
82436
+ tool refuses legibly and the user says "connect my wallet" (\`signer_setup\` action
82437
+ \`connect\`). The wallet never appears unrequested.
82438
+ - **Logins expire.** When the session token dies mid-conversation, the next
82439
+ authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
82440
+ surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
82441
+ login means "wait and retry", not a wallet failure.
82442
+ - **Withdraw-BTC under external mode has ONE blind signature, not two.** The
82443
+ authorization phase is EIP-712 typed data \u2014 the wallet renders position, amount and
82444
+ destination and the user can read it. Only the EXECUTE phase signs an opaque 32-byte
82445
+ hash the SDK builds internally, which the approval page shows bare and says plainly it
82446
+ cannot decode (the production web app signs the same way). Tell the user before that
82447
+ ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
82448
+ expect an unreadable card and click through the readable one.
82449
+ - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
82450
+ valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
82451
+ attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
82452
+ back. Warn the user: a second or third identical card is the retry, NOT a duplicate
82453
+ charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
82454
+ signature. The blind execute popup happens once.
82455
+ - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
82456
+ (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
82457
+ hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
82458
+ card states the live figure.
82459
+ - **Mainnet:** every fund-moving operation spends REAL money, and the minimum mint is
82460
+ 10 UCD.
82461
+
82462
+ **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
82463
+ \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
82464
+ WalletConnect session (pending approvals are cancelled loudly), discards the login
82465
+ token from server memory AND revokes it at the service, and unbinds the borrower
82466
+ identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
82467
+ a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
82468
+ state: (1) \`reset-borrower\` is NOT a disconnect \u2014 it only swaps identity and leaves
82469
+ the connection and login alive; (2) no server can revoke the wallet's own site
82470
+ permission for the approval page \u2014 remove that inside the wallet (MetaMask: Settings \u2192
82471
+ Connections / Connected sites).`,
82472
+ lifecycle: `# The full lifecycle \u2014 exact calls
82473
+
82474
+ 1. **Create** \u2014 \`loan_create {selectedTerm, confirmed:true}\` \u2192 position id, vault address.
82475
+ 2. **Deposit BTC** \u2014 send BTC to the vault address; it becomes usable after the
82476
+ confirmation threshold (\`protocol_status.minConfirmations\`). Practice worlds:
82477
+ \`mock_control {action:"submit-deposit", positionId, sats}\` then
82478
+ \`{action:"confirm-deposit", txid, confirmations}\`.
82479
+ 3. **Borrow (mint)** \u2014 \`loan_mint {positionId, amountUcd, confirmed:true}\`. Ceiling:
82480
+ \`position_status\` \u2192 \`valuation.maxMintableUcd\`. The origination fee is ADDED to debt.
82481
+ 4. **Repay** \u2014 \`loan_pay {positionId, amountUcd, confirmed:true}\`. Fee-free, partial or
82482
+ full; full repayment moves the position to REPAID.
82483
+ 5. **Extend (renew)** \u2014 \`loan_extend {positionId, selectedTerm, confirmed:true}\`, only
82484
+ within the FINAL 30 DAYS of the current term. The extension fee is ADDED TO YOUR DEBT
82485
+ (your wallet is not charged); it is at most the term's rate \xD7 your current debt,
82486
+ reduced by unused origination-fee credit from the current term.
82487
+ 6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
82488
+ BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
82489
+ amountSats is gross (fee comes out of it) and may be the whole available balance.
82490
+ 7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
82491
+ \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
82492
+
82493
+ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
82494
+ fees: `# Fees \u2014 the two models, stated plainly
82495
+
82496
+ - **Origination fee (minting):** a percentage of what you borrow
82497
+ (\`protocol_terms.originationFeeBps\`, e.g. 200 = 2%). It is ADDED TO YOUR DEBT: borrow
82498
+ 100 UCD \u2192 you receive 100, you owe 102. It is never taken out of what you receive.
82499
+ - **Extension fee (renewing):** ADDED TO YOUR DEBT, like the origination fee \u2014 your
82500
+ wallet is not charged. The CEILING is \`extensionFeeRateBps\` \xD7 your CURRENT DEBT (a
82501
+ flat rate per renewal, not per month); origination fees you already paid this term are
82502
+ CREDITED against it, so the charged fee lands between (ceiling \u2212 that credit) and the
82503
+ ceiling.
82504
+ - **Repayment:** no fee, any amount up to the debt.
82505
+ - **BTC network fee (withdrawals):** deducted FROM the amount you withdraw (default
82506
+ 1000 sats) \u2014 the destination receives amountSats \u2212 fee.
82507
+
82508
+ Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
82509
+ signed, amounts included. Read it back when the user asks what happened.`,
82510
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
82511
+
82512
+ ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
82513
+ directions, in user words:
82514
+
82515
+ - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
82516
+ mints UCD **to you** (output always goes to the caller \u2014 there is no recipient field).
82517
+ The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
82518
+ UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
82519
+ and you receive 99 UCD.
82520
+ - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
82521
+ and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
82522
+ USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
82523
+ only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
82524
+ shortfall refuses with both figures (available vs required).
82525
+
82526
+ The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
82527
+ is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
82528
+ 1e18 = 1:1) and can be changed by protocol governance.
82529
+
82530
+ **Limits and switches** (all visible in \`protocol://psm\`):
82531
+ - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
82532
+ units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
82533
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
82534
+ direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
82535
+ - Per-block volume caps may exist per direction ("uncapped" when none is set).
82536
+
82537
+ **Why a slippage floor exists:** executing an exchange on-chain REQUIRES a minimum-out
82538
+ floor \u2014 submitting with a zero floor is refused by the contract. Fees or the rate can
82539
+ change between your quote and execution; the floor makes a drifted execution REFUSE
82540
+ rather than silently deliver less than quoted.
82541
+
82542
+ **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
82543
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
82544
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
82545
+ the money is real. On mainnet the stablecoin is real Circle USDC.
82546
+
82547
+ **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
82548
+ result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
82549
+ differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
82550
+ USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
82551
+ UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
82552
+ swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
82553
+ tolerance; if fees or the rate drifted beyond that between quote and execution, the
82554
+ contract refuses \u2014 you never silently receive less. Output always lands at the signer's
82555
+ own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
82556
+ standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
82557
+ On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
82558
+ (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
82559
+ authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
82560
+
82561
+ Every fund-moving operation needs TWO things, always in this order:
82562
+ 1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
82563
+ must ask, never assume.
82564
+ 2. **A cryptographic authorization** by the chosen signer mode. This build offers
82565
+ exactly ${d.signerModes.map((m) => `\`${m}\``).join(", ")} \u2014 ${signerModeSourceClause(d)}. Never
82566
+ describe a mode outside it:
82567
+ ${authorizationModeBullets(d)}
82568
+ ${keystoreAbsenceParagraph(d)}
82569
+ **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
82570
+ reads need a login \u2014 ${offers(d, "keystore") ? "the keystore env pair, or " : ""}an explicit "connect my wallet"
82571
+ (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
82572
+ only ever caused by a write ceremony or that explicit connect. The login (one typed-data
82573
+ signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
82574
+ way \u2014 reconnect on the user's word.
82575
+
82576
+ Results carry \`authorization\`: \`scheme\` (external-wallet | eip712-eoa | mock-signature),
82577
+ \`signer\` (who signed), \`card\` (what was signed, human-readable), \`digest\` (the signature
82578
+ or transaction hash). Declining in the wallet ALWAYS safely cancels the operation.
82579
+
82580
+ \`signer_setup status\` vocabulary: a **candidate** is a wallet that is CONNECTED to the
82581
+ approval page but has not yet proven itself by signing; the **borrower** is the identity
82582
+ BOUND by the first verified signature (it persists across sessions). Connected \u2260 chosen:
82583
+ picking external mode is a preference \u2014 a wallet still has to connect on the approval
82584
+ page, and the page link comes from \`signer_setup status\`.
82585
+
82586
+ Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat${offers(d, "keystore") ? ";\nkeystore passwords go only into the secure unlock page." : " \u2014\nand this build has no password to ask for in the first place."}`,
82587
+ // Rendered on the capability axis: a build that constructs no Safe-shaped mode must not
82588
+ // hand a user a setup walkthrough its `signer_setup` cannot accept (the F1/F2 class,
82589
+ // one topic over). The concepts a Safe owner still needs stay; the instructions go.
82590
+ safe: (d) => !offers(d, "safe") ? `# Safe accounts \u2014 not offered by this build
82591
+
82592
+ A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
82593
+ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Diamond Hands can
82594
+ treat a Safe AS THE BORROWER \u2014 but not from here. This build's authorization surface is
82595
+ the wallet ceremony alone; \`signer_setup\` lists no Safe-shaped option, so there is
82596
+ nothing to set up. Say that plainly instead of walking a user through a ceremony this
82597
+ service cannot run.
82598
+
82599
+ **What still holds for a Safe's position anywhere:** its BTC withdrawal destination must
82600
+ be ALLOWLISTED first, and the allowlist delay is READ LIVE from the chain \u2014 24 hours on
82601
+ mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS. Owner authorizations
82602
+ for mint/pay/renew expire in minutes and withdrawal authorizations within the minute, so
82603
+ a multi-owner signing session happens TOGETHER, live.
82604
+
82605
+ **Where it does exist:** the local install's practice worlds run the Safe borrower plane
82606
+ end to end, and the web app (diamondhands.credit) speaks to the same chain state. A user
82607
+ who needs it is not blocked \u2014 they are on the wrong surface for it.` : `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
82608
+
82609
+ A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
82610
+ signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
82611
+ teams use Safes so no single key controls the funds. Diamond Hands supports a Safe AS THE
82612
+ BORROWER: the position belongs to the Safe, and operations are authorized by its owners.
82613
+
82614
+ **Adapter truth:** the Safe borrower plane is PRACTICE-ONLY today \u2014 on the real adapter,
82615
+ \`signer_setup use safe\` refuses with exactly that reason. Everything below runs in mock
82616
+ worlds until the Safe plane's own delivery; never present it as available on real.
82617
+
82618
+ **Setup:** \`signer_setup\` action \`use\`, mode \`safe\`, with \`safeAddress\`. Owners and
82619
+ threshold are DISCOVERED from the Safe itself \u2014 never typed in. (Practice worlds: create
82620
+ a test Safe first with \`mock_control deploy-safe\`.) If keystore material is already
82621
+ configured (\`signer_setup status\` \u2192 keystoreConfigured), \`use safe\` unlocks it
82622
+ AUTOMATICALLY \u2014 do not send the user to the unlock page in that case.
82623
+
82624
+ **Who signs what (say this plainly):**
82625
+ - Every operation still needs the user's \`confirmed: true\` first \u2014 nothing changed there.
82626
+ - Owner signatures then authorize the operation. In the current phase the local keystore
82627
+ is the owner-signer (a 1-of-1 Safe); external owner wallets join in a later phase.
82628
+ - Creating a position and withdrawing BTC are executed BY the Safe itself (a Safe
82629
+ transaction \u2014 you may see a "Safe nonce" on the card). Minting, paying and renewing
82630
+ are authorized by the owners and submitted by an executor \u2014 the result card names it.
82631
+
82632
+ **Withdrawals have one extra rule:** the destination BTC address must be ALLOWLISTED for
82633
+ the Safe first \u2014 \`loan_allowlist_destination\` (its own owner-signed ceremony; the address
82634
+ becomes usable after a delay READ LIVE from the chain \u2014 immediate in practice worlds,
82635
+ 24 hours on mainnet, where allowlisting and withdrawing happen on different days). A
82636
+ withdrawal to an unlisted address refuses with exactly this instruction.
82637
+
82638
+ **Timing honesty (multi-owner Safes, later phases):** authorizations for mint/pay/renew
82639
+ expire after ~3 minutes, and withdrawal authorizations within the minute \u2014 so a multi-
82640
+ owner signing session happens TOGETHER, live ("gather first, sign in one burst").
82641
+ Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
82642
+ those at their own pace. The ceremony guides this; never widen a window.`,
82643
+ delegation: (d) => !offers(d, "safe-module") ? `# Delegation \u2014 not offered by this build
82644
+
82645
+ Delegation is the protocol's answer to multi-owner Safes: the owners sign ONCE to install
82646
+ a tightly-caged AGENT key, and day-to-day work then runs without disturbing them. It is a
82647
+ Safe-shaped authorization plane, and this build constructs none \u2014 \`signer_setup\` lists
82648
+ no such option and \`loan_delegation_setup\` has no plane to install into here. Say that
82649
+ plainly rather than describing a ceremony this service cannot run.
82650
+
82651
+ **The cage, for a user who asks what it would mean:** an agent may create a position and
82652
+ \u2014 only after the owners grant it, per position \u2014 repay, renew, and mint while the
82653
+ post-mint collateral ratio stays at or above the floor the owners set. It can NEVER
82654
+ withdraw Bitcoin alone, never add or change withdrawal destinations, never touch the
82655
+ module or the registry, never move ETH. A stolen agent key can shuffle money WITHIN a
82656
+ position \u2014 never out. Revoking an agent BURNS its address forever, which is why
82657
+ revocation is always safe.
82658
+
82659
+ **Where it does exist:** the local install's practice worlds, pending the plane's own
82660
+ delivery on the real adapter. The web app and the SDK reach the same chain state.` : `# Delegation \u2014 one owner ceremony, then day-to-day solo
82661
+
82662
+ Multi-owner Safes cannot practically sign every operation inside the protocol's short
82663
+ signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
82664
+ tightly-caged AGENT key; afterwards daily work runs without disturbing them.
82665
+
82666
+ **Adapter truth:** delegation (mode \`safe-module\`) is PRACTICE-ONLY today \u2014 on the real
82667
+ adapter it refuses with exactly that reason, pending its own delivery. Everything below
82668
+ runs in mock worlds; never present it as available on real.
82669
+
82670
+ **Setup (mode \`safe-module\`):** \`signer_setup use safe-module\` with your Safe's address,
82671
+ then \`loan_delegation_setup\` \u2014 ONE durable Safe transaction the owners sign at their
82672
+ leisure (no time window). It enables the Safe's AgentModule, binds the agent key, registers
82673
+ it in the delegation registry, and pre-approves your BTC withdrawal destinations (so your
82674
+ first withdrawal never needs a second gathering).
82675
+
82676
+ **What the agent CAN do alone** (an unchangeable, contract-hardcoded list): create a
82677
+ position; and \u2014 per position, only after the owners grant it (\`loan_delegation_grant\`,
82678
+ a quorum signature; the agent can NEVER widen its own powers) \u2014 pay down debt (REPAY),
82679
+ extend the term (RENEW), and borrow (MINT, only while the post-mint collateral ratio
82680
+ stays at or above the floor the owners granted \u2014 their risk bound).
82681
+
82682
+ **What the agent can NEVER do, ever:** withdraw Bitcoin alone (withdrawal signatures are
82683
+ owners-only, permanently \u2014 the verifier has no delegate arm); add or change withdrawal
82684
+ destinations (owners-only, forever); touch the module, the registry, or any other
82685
+ contract; move ETH. A stolen agent key can shuffle money WITHIN your position \u2014 never out.
82686
+
82687
+ **Withdrawals stay a short owners' moment:** the agent prepares and submits, but the
82688
+ owners sign together inside the short window, and only to destinations they pre-approved.
82689
+ Where the destination registry is wired on-chain this bound is enforced by the contract;
82690
+ verify the wiring on your network before relying on it (test networks: wired and verified;
82691
+ mainnet wiring is confirmed at deployment review).
82692
+
82693
+ **Rotation and revocation:** revoking the agent BURNS its address forever (AR-1) \u2014 that
82694
+ is deliberate, so revocation is always safe to use. Rotation = mint a FRESH key and run a
82695
+ new setup ceremony; never reuse keys, never bind a personal or owner key as agent.
82696
+
82697
+ **Currency exchange (PSM):** the module cannot reach the PSM at all \u2014 its allowlist stops
82698
+ at the loan contracts. A Safe's UCD\u2194USDC swaps are TWO durable Safe transactions the
82699
+ owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Safe PSM path.`,
82700
+ safety: `# Safety \u2014 what protects the user
82701
+
82702
+ - **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
82703
+ ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
82704
+ - **The card is the truth \u2014 with one named exception.** In external mode the wallet card
82705
+ is decoded from the exact TRANSACTION bytes being signed: what you read IS what
82706
+ executes. The exception is the BTC-withdraw blind signature \u2014 an opaque 32-byte hash
82707
+ the approval page says plainly it cannot decode (\`guide connect-wallet\`). Never
82708
+ extend the "what you read is what executes" promise over that one.
82709
+ - **Liquidation:** if collateral value falls so the collateral ratio drops under the
82710
+ liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
82711
+ position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
82712
+ threshold. Repaying debt or adding collateral restores safety.
82713
+ - **Expiry:** positions have terms; extend BEFORE expiry (\`loan_extend\`). An EXPIRED
82714
+ position cannot mint or extend.
82715
+ - **Withdrawals are irreversible.** Bitcoin sent to a wrong address is gone. Read the
82716
+ address back to the user before confirming.
82717
+ - **Can you lose your bitcoin?** Only through liquidation (undercollateralized debt) or
82718
+ withdrawing to a wrong address. Repaid-in-full positions release all collateral.
82719
+ - **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
82720
+ user believe practice gains/losses are real, or vice versa.`,
82721
+ "switch-network": (d) => `# Switch network \u2014 ${switchNetworkHeadline(d)}
82722
+
82723
+ The \`network_switch\` tool moves THIS SESSION between worlds. Check
82724
+ \`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
82725
+ (real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
82726
+ no switch, and that is by design.
82727
+
82728
+ **Served here:** ${servedNetworks(d)}. A network this deployment does not serve is
82729
+ refused with that reason \u2014 the tool existing is not a promise that both worlds are
82730
+ reachable, so never offer the user a network this deployment does not serve.
82731
+
82732
+ **The rules, plainly:**
82733
+ - \`network_switch status\` \u2014 which network is active and whether money is real. Say
82734
+ this to the user BEFORE and AFTER any switch, always.
82735
+ ${switchNetworkRules(d)}
82736
+ - A pending signing ceremony blocks the switch (finish or decline it first).
82737
+ - The switch is session-scoped: when the server restarts, the configured default
82738
+ network returns.
82739
+
82740
+ After any switch: re-read \`boundary://info\`, then STATE the new network and money
82741
+ reality in your next message. The user must never have to ask which world they are in.`,
82742
+ // Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
82743
+ // the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
82744
+ // entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
82745
+ connector: (d) => `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
82746
+
82747
+ ${connectorStatusTruth(d)}
82748
+
82749
+ **What it is:** instead of installing anything, the user adds Diamond Hands to
82750
+ claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
82751
+ Sign-in IS the wallet: one Sign-In-with-Ethereum signature proves address ownership \u2014
82752
+ no password, no email, no account beyond the wallet address. The sign-in page offers a
82753
+ WalletConnect QR too, so a phone wallet works without any browser extension.
82754
+
82755
+ **Signature cadence, plainly:** the FIRST connect costs one SIWE signature (sign-in)
82756
+ plus one lit-ops login signature (read access). After that, every operation that moves
82757
+ funds asks for its OWN approval in the user's wallet, every time \u2014 and reads never pop
82758
+ the wallet. The login session lives ONLY in the server's memory: a server restart, or
82759
+ an idle spell long enough that the tenant's world is evicted, means signing in again.
82760
+ That is the flip side of "nothing stored at rest" \u2014 a re-login is normal, not a fault.
82761
+
82762
+ **What the hosted server IS trusted with** (the six residual trusts \u2014 state them
82763
+ honestly when asked "is this safe"):
82764
+ 1. **The approval page it serves.** Same security baseline as the diamondhands.credit
82765
+ web app (you already trust the pages gvnr serves over HTTPS). The wallet's own
82766
+ display is the independent backstop for transactions; personal-sign envelopes are
82767
+ action-pinned and expire in minutes; BTC destinations are defended by the on-chain
82768
+ allowlist delay, which no server can shorten.
82769
+ 2. **The read credential.** Your lit-ops login token is held in memory for the active
82770
+ session ONLY \u2014 it grants reads and advisory broadcast, it can sign NOTHING, and it
82771
+ is never written to disk. A breach here is privacy-class, never money-class.
82772
+ 3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
82773
+ a security concern is filed and audited for exactly this channel.
82774
+ 4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
82775
+ gets its own world: its own boundary, its own signer state, its own approval-page
82776
+ mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
82777
+ world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
82778
+ plus an earlier connection would make a different wallet this session's signer. That
82779
+ is signing-class, not merely privacy-class; do not tell a user it cannot be. What
82780
+ contains it: the mount id is freshly random per world and travels only in the user's
82781
+ own tool result (treat the link as a secret), and EVERY fund movement verifies the
82782
+ signature against that bound borrower \u2014 no key material exists server-side, so
82783
+ whoever reaches the page still cannot sign for anyone else. The gap is filed and
82784
+ audited; state it this way rather than claiming a binding that isn't there.
82785
+ 5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
82786
+ version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
82787
+ reports the exact server version.
82788
+ 6. **The BTC-withdraw blind sign.** Withdrawal serves an OPAQUE 32-byte hash \u2014 the
82789
+ card says plainly that its contents are NOT decodable on the page (site parity:
82790
+ diamondhands.credit serves the identical blind sign). Defenses stated with it:
82791
+ server-side borrower verification, the minutes-narrow signing window, and the
82792
+ on-chain allowlist delay.
82793
+
82794
+ **What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
82795
+ from the connector build (not disabled: never constructed), so every fund-moving
82796
+ action needs a fresh signature from the user's own wallet. ${connectorNetworkTruth(d)}
82797
+
82798
+ **Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
82799
+ chain state. The connector going down strands nothing and gates nothing.`,
82800
+ troubleshooting: (d) => `# Troubleshooting \u2014 what error codes mean, in plain words
82801
+
82802
+ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
82803
+ keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
82804
+ "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
82805
+ status\` explains what is active; \`first-setup\` step 2 has the full choice.
82806
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
82807
+ the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
82808
+ EXPIRED login refuses the same way \u2014 reconnect on the user's word.` : `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. This build has exactly
82809
+ ONE remedy: the user says "connect my wallet" \u2192 \`signer_setup\` action \`connect\`
82810
+ (external mode). There is no keystore here to configure and no password to supply \u2014
82811
+ saying otherwise sends the user hunting for a setting that does not exist.
82812
+ \`signer_setup status\` explains what is active; \`first-setup\` step 2 has the choice.
82813
+ - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
82814
+ the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
82815
+ the same way \u2014 reconnect on the user's word.`}
82816
+ ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
82817
+ not a bug); loan operations work on mainnet. Reads keep working everywhere.` : `- **PSM write refused** \u2014 the PSM write port answers on sepolia alone (a deliberate
82818
+ anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
82819
+ ${wrongNetworkTroubleshootingRow(d)}
82820
+ - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
82821
+ SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
82822
+ signature per withdrawal, not two: the authorization phase is EIP-712 typed data
82823
+ (\`WithdrawRequest\` \u2014 the wallet renders position, amount and destination), and only
82824
+ the execute phase is opaque. Warn the user before that one popup, and do not describe
82825
+ the typed one as blind \u2014 overstating it teaches them to expect an unreadable card and
82826
+ click through the readable one.
82827
+ - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
82828
+ That is the broker throttle, not a wallet failure.
82829
+ - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
82830
+ unknown field). The message names the exact problem; fix the input, don't retry blindly.
82831
+ - **UPSTREAM_REJECTED** \u2014 the protocol said no: over the mint ceiling, repaying more than
82832
+ owed, wrong position state, or the USER DECLINED in the wallet. The message says which.
82833
+ A decline is not an error to fix \u2014 it is the user's decision.
82834
+ - **UPSTREAM_UNAVAILABLE** \u2014 a data source or the signature bridge is unreachable/expired.
82835
+ Usually transient; re-check with \`protocol_status\` and retry once.
82836
+ - **NOT_FOUND** \u2014 the position id doesn't exist in this world (check \`position_list\`).
82837
+ - **STATE_DIVERGENCE / STALE_DATA warnings** \u2014 sources disagree or lag; the envelope says
82838
+ which source and when from. Prefer chain-sourced values; re-read before acting.
82839
+ - Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
82840
+ Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
82841
+ ${connectorTroubleshootingRow(d)}
82842
+ - **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
82843
+ the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
82844
+ Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
82845
+ Node \u2265 18 on PATH. Remedies: the one-line installer (self-contained binary, absolute
82846
+ path in the printed snippet), or the \`.mcpb\` bundle on macOS/Windows Claude Desktop.`,
82847
+ glossary: `# Glossary \u2014 map the user's words to the protocol's
82848
+
82849
+ Synonym sets (treat these as the SAME intent):
82850
+ - **mint** = borrow = take a loan = draw = "get UCD" \u2192 \`loan_mint\`
82851
+ - **pay** = repay = pay back = pay down = settle \u2192 \`loan_pay\`
82852
+ - **extend** = renew = roll over = prolong \u2192 \`loan_extend\`
82853
+ - **withdraw** = take out my bitcoin = cash out = get my BTC back \u2192 \`loan_withdraw\`
82854
+ - **position** = loan = account (the borrowing arrangement) \u2192 \`position_status\`
82855
+ - **disconnect** = log out = sign out = forget my wallet = remove my wallet \u2192
82856
+ \`signer_setup\` action \`disconnect\` (the FULL flush \u2014 never map these to
82857
+ \`reset-borrower\`, which only swaps identity)
82858
+ - **UCD** = the dollar-pegged token you borrow ("the dollars")
82859
+ - **sats** = satoshis, 1 BTC = 100,000,000 sats
82860
+ - **connector** = remote = hosted tier = "claude.ai integration" = "use it without
82861
+ installing" \u2192 \`guide connector\` (it states which tier THIS session is, and the
82862
+ trust model that comes with it)
82863
+
82864
+ Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
82865
+ - **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
82866
+ your loan. "How much is in my vault?" \u2192 collateral; "how much do I owe?" \u2192 debt.
82867
+ - **balance** \u2014 ask which: vault BTC (collateral) or UCD debt? They move independently.
82868
+ - **health** \u2014 collateral-value vs debt (\`indexedHealth\`, \`currentLtvBps\`): a SAFETY
82869
+ measure against liquidation, not an account balance.
82870
+ - **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
82871
+ interest; see \`fees\`.
82872
+
82873
+ Language: answer in the user's language, whatever it is. These mappings apply to meaning,
82874
+ not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
82875
+ "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
82876
+ // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
82877
+ // the same entries the anchor test pins against the actually-serialized fields.
82878
+ "reading-data": renderFieldGlossaryTopic()
82879
+ };
82880
+ function renderGuideContent(deployment) {
82881
+ const content = {};
82882
+ for (const topic of GUIDE_TOPICS) {
82883
+ const source = GUIDE_TOPIC_SOURCES[topic];
82884
+ content[topic] = typeof source === "string" ? source : source(deployment);
82885
+ }
82886
+ return content;
82887
+ }
82888
+ function renderGuideIndex(deployment) {
82889
+ const connectorLine = deployment.tier === "hosted" ? `- connector \u2014 the hosted claude.ai tier THIS session is running on (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Serves ${servedNetworks(deployment)}` : "- connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. THIS session is a local install, not that tier";
82890
+ return `# Diamond Hands guide \u2014 topics
82891
+
82892
+ - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
82893
+ - first-setup \u2014 zero to ready by conversation (authorization choice included)
82894
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
82895
+ - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
82896
+ - fees \u2014 the two fee models, plainly
82897
+ - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
82898
+ - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
82899
+ ${offers(deployment, "safe") ? "- safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today" : "- safe \u2014 borrowing as a Safe smart-account: NOT offered by this build (no Safe-shaped mode exists here), and what still holds wherever it is"}
82900
+ ${offers(deployment, "safe-module") ? "- delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today" : "- delegation \u2014 the caged agent key for multi-owner Safes: NOT offered by this build, and what the cage would mean where it is"}
82901
+ - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
82902
+ ${switchNetworkIndexLine(deployment)}
82903
+ ${connectorLine}
82904
+ - troubleshooting \u2014 error codes in plain words, with the real remedies
82905
+ - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
82906
+ - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
82907
+
82908
+ Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
82909
+ selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
82910
+ signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
82911
+ and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
82912
+ only mainnet is real money.`;
82913
+ }
82914
+ var deploymentKey = (d) => `${d.tier}|${d.networks.join(",")}|${d.signerModes.join(",")}`;
82915
+ var RENDERED = /* @__PURE__ */ new Map();
82916
+ function renderedGuide(deployment) {
82917
+ const key = deploymentKey(deployment);
82918
+ let rendered = RENDERED.get(key);
82919
+ if (!rendered) {
82920
+ rendered = Object.freeze({
82921
+ content: Object.freeze(renderGuideContent(deployment)),
82922
+ index: renderGuideIndex(deployment)
82923
+ });
82924
+ RENDERED.set(key, rendered);
82925
+ }
82926
+ return rendered;
82927
+ }
82928
+ function buildGuideContent(deployment) {
82929
+ return renderedGuide(deployment).content;
82930
+ }
82931
+ function buildGuideIndex(deployment) {
82932
+ return renderedGuide(deployment).index;
82933
+ }
82934
+ var GUIDE_CONTENT = buildGuideContent(LOCAL_GUIDE_DEPLOYMENT);
82935
+ var GUIDE_INDEX = buildGuideIndex(LOCAL_GUIDE_DEPLOYMENT);
82936
+
82937
+ // src/network-switch.ts
82938
+ var SWITCHABLE_NETWORKS = ["sepolia", "mainnet"];
82939
+ function createNetworkSwitchRuntime(opts) {
82940
+ return {
82941
+ current() {
82942
+ const b = opts.getBoot().boundaryResult;
82943
+ if (!b.ok) return null;
82944
+ const w = b.boundary.world();
82945
+ return { network: w.network, chainId: w.chainId, practiceWorld: w.practiceWorld };
82946
+ },
82947
+ async switchTo(network) {
82948
+ const allowed = opts.overrides?.allowedNetworks;
82949
+ if (allowed && !allowed.includes(network)) {
82950
+ return {
82951
+ ok: false,
82952
+ error: boundaryError(
82953
+ "VALIDATION_FAILED",
82954
+ `this deployment serves ${allowed.join(", ")} \u2014 '${network}' is not enabled on this service. Mainnet service enablement is a rollout step of the deployment, not a session setting.`
82955
+ )
82956
+ };
82957
+ }
82958
+ const targetEnv = { ...opts.env, DH_NETWORK: network };
82959
+ const configResult = resolveBoundaryConfig(targetEnv);
82960
+ if (!configResult.ok) return { ok: false, error: configResult.error };
82961
+ const next = await buildBoundary(configResult, opts.overrides);
82962
+ if (!next.boundaryResult.ok) {
82963
+ next.dispose();
82964
+ return { ok: false, error: next.boundaryResult.error };
82965
+ }
82966
+ opts.swap(next);
82967
+ return { ok: true };
82968
+ }
82969
+ };
82970
+ }
82971
+ function guideDeployment(overrides) {
82972
+ return {
82973
+ tier: overrides?.bridgeMount ? "hosted" : "local",
82974
+ networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
82975
+ signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
82976
+ };
82977
+ }
82978
+ function assembleWorld(opts) {
82979
+ let boot = opts.boot;
82980
+ const deps = {
82981
+ boundaryResult: boot.boundaryResult,
82982
+ ...boot.mockControl ? { mockControl: boot.mockControl } : {},
82983
+ ...boot.signer ? { signer: boot.signer } : {},
82984
+ ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
82985
+ deployment: guideDeployment(opts.overrides),
82986
+ ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
82987
+ };
82988
+ if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
82989
+ deps.networkSwitch = createNetworkSwitchRuntime({
82990
+ env: opts.env,
82991
+ getBoot: () => boot,
82992
+ ...opts.overrides ? { overrides: opts.overrides } : {},
82993
+ swap: (next) => {
82994
+ const old = boot;
82995
+ boot = next;
82996
+ deps.boundaryResult = next.boundaryResult;
82997
+ if (next.signer) deps.signer = next.signer;
82998
+ else delete deps.signer;
82999
+ old.dispose();
83000
+ const w = next.boundaryResult.ok ? next.boundaryResult.boundary.world() : null;
83001
+ opts.log?.(`network switched \u2014 now ${w ? `${w.network} (chainId ${w.chainId})` : "unavailable"}.`);
83002
+ }
83003
+ });
83004
+ }
83005
+ return { deps, dispose: () => boot.dispose() };
83006
+ }
83007
+
83008
+ // src/server.ts
83009
+ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
83010
+
83011
+ // src/tools/loan.ts
83012
+ var import_zod = require("zod");
83013
+ var import_ethers40 = require("ethers");
83014
+
83015
+ // src/util/format.ts
83016
+ function bigintReplacer(_key, value) {
83017
+ if (typeof value === "bigint") return value.toString();
83018
+ return value;
83019
+ }
83020
+ function serialize(data) {
83021
+ return JSON.stringify(data, bigintReplacer, 2);
83022
+ }
83023
+
83024
+ // src/tools/_helpers.ts
83025
+ function registerBoundaryTool(server, name, config, handler) {
83026
+ server.registerTool(name, config, handler);
83027
+ }
83028
+ function renderError(error) {
83029
+ const lines = [`ERROR [${error.code}]: ${error.message}`];
83030
+ if (error.source) lines.push(`source: ${error.source}`);
83031
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
83032
+ }
83033
+ function renderEnvelope(env) {
83034
+ if (!env.ok) return renderError(env.error);
83035
+ const parts = [serialize(env.data)];
83036
+ if (env.warnings.length > 0) {
83037
+ parts.push(
83038
+ "WARNINGS:\n" + env.warnings.map((w) => `- [${w.code}] ${w.message} (sources: ${w.sources.join(", ")})`).join("\n")
83039
+ );
83040
+ }
83041
+ parts.push(`source: ${env.source.id} (${env.source.kind}) @ ${env.source.fetchedAt}`);
83042
+ return { content: [{ type: "text", text: parts.join("\n\n") }] };
83043
+ }
83044
+ function validationFailed(problem) {
83045
+ return renderError(boundaryError("VALIDATION_FAILED", problem));
83046
+ }
83047
+ function resourceJson(env) {
83048
+ if (!env.ok) return serialize({ error: env.error });
83049
+ return serialize({ data: env.data, warnings: env.warnings, source: env.source });
83050
+ }
83051
+ function resourceErrorJson(error) {
83052
+ return serialize({ error });
83053
+ }
83054
+ function requireConfirmation(confirmed, actionLabel) {
83055
+ if (confirmed === true) return null;
83056
+ return {
83057
+ content: [
83058
+ {
83059
+ type: "text",
83060
+ text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
83061
+ This is an irreversible, fund-moving action. A human must explicitly authorize it.
83062
+ Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
83063
+ }
83064
+ ],
83065
+ isError: true
83066
+ };
83067
+ }
83068
+ function envStamp(b) {
83069
+ if (!b.ok) return "environment: UNKNOWN \u2014 boundary unavailable";
83070
+ const w = b.boundary.world();
83071
+ const money = w.network === "mainnet" ? "REAL MONEY" : w.network === "mock" ? "PRACTICE SANDBOX (no real money)" : "PRACTICE FUNDS (test network)";
83072
+ return `environment: ${w.network} \u2014 ${money}`;
83073
+ }
83074
+ async function guardedWrite(getB, fn) {
83075
+ const result = await guarded(fn);
83076
+ const stamp = envStamp(getB());
83077
+ const content = result.content.map(
83078
+ (c, i) => i === result.content.length - 1 ? { ...c, text: `${c.text}
83079
+
83080
+ ${stamp}` } : c
83081
+ );
83082
+ return { ...result, content };
83083
+ }
83084
+ async function guarded(fn) {
83085
+ try {
83086
+ return await fn();
83087
+ } catch (e) {
83088
+ return renderError(
83089
+ boundaryError("INTERNAL", `Internal boundary fault: ${e.message}`, {
83090
+ details: { stack: e.stack }
83091
+ })
83092
+ );
83093
+ }
83094
+ }
83095
+
83096
+ // src/util/validate.ts
83097
+ var POSITION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
83098
+ var SATS_SANITY_CAP = 1e10;
83099
+ var UCD_SANITY_CAP = 1e9;
83100
+ function checkPositionIdHex(id, label = "Position ID") {
83101
+ if (!POSITION_ID_RE.test(id)) {
83102
+ return `${label} must be 0x-prefixed 32-byte hex (got '${id}').`;
83103
+ }
83104
+ return null;
83105
+ }
83106
+ function checkUcdAmount(amount, label = "Amount") {
83107
+ if (!Number.isFinite(amount) || amount <= 0) {
83108
+ return `${label} must be a positive finite number (got ${amount}).`;
83109
+ }
83110
+ if (amount > UCD_SANITY_CAP) {
83111
+ return `${label} ${amount} exceeds the ${UCD_SANITY_CAP.toLocaleString()} UCD sanity cap.`;
83112
+ }
83113
+ if (amount > 0 && amount < 1e-6) {
83114
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
83115
+ }
83116
+ const decimals = amount.toString().split(".")[1];
83117
+ if (decimals && decimals.length > 6) {
83118
+ return `${label} ${amount} has more than 6 decimals of precision \u2014 likely a typo.`;
83119
+ }
83120
+ return null;
83121
+ }
83122
+ function checkSatsAmount(sats, label = "Amount") {
83123
+ if (!Number.isInteger(sats) || sats <= 0) {
83124
+ return `${label} must be a positive integer (satoshis), got ${sats}.`;
83125
+ }
83126
+ if (sats > SATS_SANITY_CAP) {
83127
+ return `${label} ${sats} sats exceeds the 100 BTC sanity cap.`;
83128
+ }
83129
+ return null;
83130
+ }
83131
+ function checkSelectedTerm(months, label = "Term") {
83132
+ if (!Number.isInteger(months) || months <= 0) {
83133
+ return `${label} must be a positive integer (months), got ${months}.`;
83134
+ }
83135
+ if (months > 120) {
83136
+ return `${label} ${months} months exceeds the 10-year sanity cap.`;
83137
+ }
83138
+ return null;
83139
+ }
83140
+
83141
+ // src/tools/loan.ts
83142
+ var LATENCY_NOTES = {
83143
+ mock: "Instant in this practice world.",
83144
+ real: "May take 60\u201390 seconds against the live protocol (LIT Action invocation)."
83145
+ };
83146
+ var positionIdSchema = import_zod.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
83147
+ var confirmedSchema = import_zod.z.boolean().optional().describe(
83148
+ "Human authorization gate \u2014 must be set to true by a HUMAN (not the model) to execute this irreversible action."
83149
+ );
83150
+ var DESTRUCTIVE_WRITE_ANNOTATIONS = {
83151
+ readOnlyHint: false,
83152
+ destructiveHint: true,
83153
+ idempotentHint: false,
83154
+ openWorldHint: true
83155
+ };
83156
+ function registerLoanTools(server, getB, adapter2 = "real") {
83157
+ const LATENCY_NOTE = LATENCY_NOTES[adapter2];
83158
+ registerBoundaryTool(
83159
+ server,
83160
+ "loan_create",
83161
+ {
83162
+ title: "Create a new lending position",
83163
+ 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).`,
83164
+ inputSchema: {
83165
+ selectedTerm: import_zod.z.number().int().positive().describe("Loan term in months (e.g. 3, 6, 12, 24)"),
83166
+ confirmed: confirmedSchema
83167
+ },
83168
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83169
+ },
83170
+ async ({ selectedTerm, confirmed }) => guardedWrite(getB, async () => {
83171
+ const gate = requireConfirmation(confirmed, `create a ${selectedTerm}-month lending position`);
83172
+ if (gate) return gate;
83173
+ const problem = checkSelectedTerm(selectedTerm);
83174
+ if (problem) return validationFailed(problem);
83175
+ const b = getB();
83176
+ if (!b.ok) return renderError(b.error);
83177
+ return renderEnvelope(await b.boundary.createPosition({ selectedTerm }));
83178
+ })
83179
+ );
83180
+ registerBoundaryTool(
83181
+ server,
83182
+ "loan_mint",
83183
+ {
83184
+ title: "Mint UCD against a position",
83185
+ description: `Mint (borrow) UCD against an existing lending position's BTC collateral. The origination fee is ADDED TO YOUR DEBT \u2014 you receive the full amount, you owe amount + fee. Ceiling: position_status \u2192 valuation.maxMintableUcd (directly usable as amountUcd). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83186
+ inputSchema: {
83187
+ positionId: positionIdSchema,
83188
+ amountUcd: import_zod.z.number().positive().describe("Amount of UCD to mint"),
83189
+ confirmed: confirmedSchema
83190
+ },
83191
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83192
+ },
83193
+ async ({ positionId, amountUcd, confirmed }) => guardedWrite(getB, async () => {
83194
+ const gate = requireConfirmation(confirmed, `mint ${amountUcd} UCD against position ${positionId}`);
83195
+ if (gate) return gate;
83196
+ const problem = checkPositionIdHex(positionId) ?? checkUcdAmount(amountUcd);
83197
+ if (problem) return validationFailed(problem);
83198
+ const b = getB();
83199
+ if (!b.ok) return renderError(b.error);
83200
+ return renderEnvelope(
83201
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers40.parseEther)(amountUcd.toString()).toString() })
83202
+ );
83203
+ })
83204
+ );
83205
+ registerBoundaryTool(
83206
+ server,
83207
+ "loan_pay",
83208
+ {
83209
+ title: "Make a UCD payment toward a position's debt",
83210
+ description: `Repay (partial or full) a position's UCD debt. Moves UCD out of your wallet (irreversible). To pay off EVERYTHING exactly \u2014 including dust smaller than the 6-decimal input allows \u2014 pass repayAll: true instead of amountUcd (fleet finding: debt can carry more precision than amountUcd accepts). ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83211
+ inputSchema: {
83212
+ positionId: positionIdSchema,
83213
+ amountUcd: import_zod.z.number().positive().optional().describe("Amount of UCD to repay (max 6 decimals; omit when repayAll)"),
83214
+ repayAll: import_zod.z.boolean().optional().describe("true = repay the position's EXACT outstanding debt (wei-precise)"),
83215
+ confirmed: confirmedSchema
83216
+ },
83217
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83218
+ },
83219
+ async ({ positionId, amountUcd, repayAll, confirmed }) => guardedWrite(getB, async () => {
83220
+ if (repayAll === true === (amountUcd !== void 0)) {
83221
+ return validationFailed("provide exactly one of amountUcd or repayAll: true");
83222
+ }
83223
+ const gate = requireConfirmation(
83224
+ confirmed,
83225
+ repayAll ? `repay the ENTIRE outstanding debt of position ${positionId}` : `repay ${amountUcd} UCD toward position ${positionId}`
83226
+ );
83227
+ if (gate) return gate;
83228
+ const problem = checkPositionIdHex(positionId) ?? (repayAll ? null : checkUcdAmount(amountUcd, "Payment amount"));
83229
+ if (problem) return validationFailed(problem);
83230
+ const b = getB();
83231
+ if (!b.ok) return renderError(b.error);
83232
+ let amountUcdWei;
83233
+ if (repayAll) {
83234
+ const detail = await b.boundary.getPosition(positionId);
83235
+ if (!detail.ok) return renderError(detail.error);
83236
+ if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
83237
+ amountUcdWei = detail.data.debtUcdWei;
83238
+ } else {
83239
+ amountUcdWei = (0, import_ethers40.parseEther)(amountUcd.toString()).toString();
83240
+ }
83241
+ return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
83242
+ })
83243
+ );
83244
+ registerBoundaryTool(
83245
+ server,
83246
+ "loan_extend",
83247
+ {
83248
+ title: "Extend / renew a position's term",
83249
+ description: `ADDS selectedTerm onto the position's CURRENT expiry (12 months = exactly 365 days; any other term = N \xD7 30-day months) \u2014 never replaces or shortens it. Only available in the FINAL 30 DAYS of the current term, and refused if the remaining runway would exceed 2\xD7 the new term. (Per-network caveat: some DEPLOYED contracts predate this window/runway rule \u2014 a live extend may execute from now rather than refuse; the MCP reports the on-chain result truthfully.) Fee: ADDED TO YOUR DEBT (your wallet is not charged), at most the term's extension fee rate \xD7 your current debt (see protocol_terms; a flat rate per renewal, not per month), reduced by origination fees already paid this term. Only an ACTIVE position can be renewed. Irreversible on-chain write. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83250
+ inputSchema: {
83251
+ positionId: positionIdSchema,
83252
+ selectedTerm: import_zod.z.number().int().positive().describe("Months to ADD to the current expiry (must be an offered term: see protocol_terms)"),
83253
+ confirmed: confirmedSchema
83254
+ },
83255
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83256
+ },
83257
+ async ({ positionId, selectedTerm, confirmed }) => guardedWrite(getB, async () => {
83258
+ const gate = requireConfirmation(confirmed, `renew position ${positionId} for a ${selectedTerm}-month term`);
83259
+ if (gate) return gate;
83260
+ const problem = checkPositionIdHex(positionId) ?? checkSelectedTerm(selectedTerm);
83261
+ if (problem) return validationFailed(problem);
83262
+ const b = getB();
83263
+ if (!b.ok) return renderError(b.error);
83264
+ return renderEnvelope(await b.boundary.extendPosition({ positionId, selectedTerm }));
83265
+ })
83266
+ );
83267
+ registerBoundaryTool(
83268
+ server,
83269
+ "loan_withdraw",
83270
+ {
83271
+ title: "Withdraw BTC from a position vault",
83272
+ description: `Withdraw BTC from a position's custody vault to an external BTC address. BTC sends are UNRECOVERABLE \u2014 verify the destination address carefully. Result identifiers: txid (and txRef.id) is the Bitcoin transaction of the withdrawal reservation; authorization.digest is the borrower wallet's signature over the approval \u2014 they are different things. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83273
+ inputSchema: {
83274
+ positionId: positionIdSchema,
83275
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address (must match the configured BTC network)"),
83276
+ amountSats: import_zod.z.number().int().positive().describe(
83277
+ "GROSS amount in satoshis committed from the vault (1 BTC = 100,000,000 sats). The destination receives amountSats \u2212 networkFeeSats; the vault's available drops by amountSats. amountSats may be up to the whole available balance (a full sweep leaves 0 sats; anything above available reverts TargetExceedsInputValue). position_status.maxWithdrawableSats is a ready-to-use value that already leaves the default fee aside."
83278
+ ),
83279
+ networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); deducted FROM amountSats, not added on top"),
83280
+ confirmed: confirmedSchema
83281
+ },
83282
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83283
+ },
83284
+ async ({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
83285
+ const gate = requireConfirmation(
83286
+ confirmed,
83287
+ `withdraw ${amountSats} sats from position ${positionId} to ${btcAddress2} (UNRECOVERABLE)`
83288
+ );
83289
+ if (gate) return gate;
83290
+ const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(amountSats) ?? checkSatsAmount(networkFeeSats, "Network fee");
83291
+ if (problem) return validationFailed(problem);
83292
+ const b = getB();
83293
+ if (!b.ok) return renderError(b.error);
83294
+ return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
83295
+ })
83296
+ );
83297
+ registerBoundaryTool(
83298
+ server,
83299
+ "loan_allowlist_destination",
83300
+ {
83301
+ title: "Allowlist a BTC withdrawal destination",
83302
+ description: `Add a BTC address to the borrower's withdrawal allowlist (BitcoinWithdrawalAddressRegistry). The protocol refuses withdrawBTC to any destination not on the borrower's own allowlist. For a SAFE borrower this is itself a Safe transaction \u2014 owner signatures are collected, and owners can sign at their leisure (no expiry on this ceremony). The destination becomes usable after the registry's address delay, read LIVE from the contract at execution \u2014 the result's usableAtSec is the chain-derived moment it becomes usable (never assume a fixed delay). Requires human confirmation (confirmed: true).`,
83303
+ inputSchema: {
83304
+ btcAddress: import_zod.z.string().min(1).describe("Destination BTC address to allowlist (must match the configured BTC network)"),
83305
+ confirmed: confirmedSchema
83306
+ },
83307
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83308
+ },
83309
+ async ({ btcAddress: btcAddress2, confirmed }) => guardedWrite(getB, async () => {
83310
+ const gate = requireConfirmation(confirmed, `allowlist ${btcAddress2} as a BTC withdrawal destination`);
83311
+ if (gate) return gate;
83312
+ const b = getB();
83313
+ if (!b.ok) return renderError(b.error);
83314
+ return renderEnvelope(await b.boundary.allowlistWithdrawalAddress({ btcAddress: btcAddress2 }));
83315
+ })
83316
+ );
83317
+ registerBoundaryTool(
83318
+ server,
83319
+ "loan_delegation_setup",
83320
+ {
83321
+ title: "Install delegation on the Safe (one owner ceremony)",
83322
+ description: `The ONE-TIME Safe delegation batch (signer mode 'safe-module'): your owners sign a single durable Safe transaction \u2014 at their leisure, no time window \u2014 that enables the Safe's AgentModule, binds the agent key, registers it in the delegation registry, and pre-approves the given BTC withdrawal destinations. After it, day-to-day operations (create/mint/pay/extend) run agent-solo; withdrawals always still need the owners' short signing burst, and only to destinations approved here (or later via loan_allowlist_destination \u2014 also owners-only). A revoked agent address burns FOREVER (AR-1) \u2014 rotation means a fresh key. Requires human confirmation (confirmed: true).`,
83323
+ inputSchema: {
83324
+ btcAddresses: import_zod.z.array(import_zod.z.string().min(1)).describe("BTC withdrawal destinations to pre-approve in the same ceremony (avoids a second owner gathering before the first withdrawal)"),
83325
+ confirmed: confirmedSchema
83326
+ },
83327
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83328
+ },
83329
+ async ({ btcAddresses, confirmed }) => guardedWrite(getB, async () => {
83330
+ const gate = requireConfirmation(confirmed, `install delegation (module + agent + ${btcAddresses.length} destination(s))`);
83331
+ if (gate) return gate;
83332
+ const b = getB();
83333
+ if (!b.ok) return renderError(b.error);
83334
+ return renderEnvelope(await b.boundary.delegationSetup({ btcAddresses }));
83335
+ })
83336
+ );
83337
+ registerBoundaryTool(
83338
+ server,
83339
+ "loan_delegation_grant",
83340
+ {
83341
+ title: "Grant the agent per-position scopes (owners sign)",
83342
+ description: `Set what the delegated agent may do on ONE position \u2014 RENEW (extend), REPAY (pay down), MINT (borrow, only while the post-mint collateral ratio stays at or above mintFloorBps \u2014 required for MINT, it is the owners' risk bound). Grants are user-only expansion: for a Safe this is a QUORUM signature (durable Safe transaction, owners sign at leisure) \u2014 the agent can never widen its own powers. Omitting a scope leaves it un-granted; a grant with no scopes clears the position's grant. Requires human confirmation (confirmed: true).`,
83343
+ inputSchema: {
83344
+ positionId: positionIdSchema,
83345
+ renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
83346
+ repay: import_zod.z.boolean().optional().describe("Allow the agent to pay down this position's debt"),
83347
+ mintFloorBps: import_zod.z.number().int().positive().optional().describe("Allow MINT while post-mint CR \u2265 this floor (bps, e.g. 15000 = 150%) \u2014 required for the MINT scope"),
83348
+ confirmed: confirmedSchema
83349
+ },
83350
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83351
+ },
83352
+ async ({ positionId, renew, repay, mintFloorBps, confirmed }) => guardedWrite(getB, async () => {
83353
+ const gate = requireConfirmation(confirmed, `grant agent scopes on ${positionId}`);
83354
+ if (gate) return gate;
83355
+ const b = getB();
83356
+ if (!b.ok) return renderError(b.error);
83357
+ return renderEnvelope(
83358
+ await b.boundary.delegationGrant({
83359
+ positionId,
83360
+ renew: renew ?? false,
83361
+ repay: repay ?? false,
83362
+ mintFloorBps: mintFloorBps ?? null
83363
+ })
83364
+ );
83365
+ })
83366
+ );
83367
+ registerBoundaryTool(
83368
+ server,
83369
+ "loan_recover_stale_spend",
83370
+ {
83371
+ title: "Recover a stale BTC reservation via LIT-attested proof",
83372
+ 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.",
83373
+ inputSchema: {
83374
+ positionId: positionIdSchema,
83375
+ utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
83376
+ utxoVout: import_zod.z.number().int().nonnegative().describe("The original authorized UTXO's vout"),
83377
+ invalidatorTxid: import_zod.z.string().describe("Txid of the BTC transaction that consumed the original UTXO (\u22656 confirmations)"),
83378
+ minConfirmations: import_zod.z.number().int().positive().optional().describe("Override minimum confirmations (default 6)")
83379
+ },
83380
+ annotations: {
83381
+ readOnlyHint: false,
83382
+ destructiveHint: false,
83383
+ idempotentHint: true,
83384
+ openWorldHint: true
83385
+ }
83386
+ },
83387
+ async ({ positionId, utxoTxid, utxoVout, invalidatorTxid, minConfirmations }) => guardedWrite(getB, async () => {
83388
+ const problem = checkPositionIdHex(positionId);
83389
+ if (problem) return validationFailed(problem);
83390
+ const b = getB();
83391
+ if (!b.ok) return renderError(b.error);
83392
+ return renderEnvelope(
83393
+ await b.boundary.recoverStaleSpend({
83394
+ positionId,
83395
+ utxoTxid,
83396
+ utxoVout,
83397
+ invalidatorTxid,
83398
+ ...minConfirmations !== void 0 ? { minConfirmations } : {}
83399
+ })
83400
+ );
83401
+ })
83402
+ );
83403
+ }
83404
+
82556
83405
  // src/tools/position.ts
83406
+ var import_zod2 = require("zod");
82557
83407
  var positionIdSchema2 = import_zod2.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be 0x-prefixed 32-byte hex");
82558
83408
  var POSITION_STATES = [
82559
83409
  "PENDING_DEPOSIT",
@@ -83110,547 +83960,9 @@ function ok(data) {
83110
83960
 
83111
83961
  // src/tools/guide.ts
83112
83962
  var import_zod7 = require("zod");
83113
-
83114
- // src/guide/content.ts
83115
- var GUIDE_TOPICS = [
83116
- "getting-started",
83117
- "first-setup",
83118
- "connect-wallet",
83119
- "lifecycle",
83120
- "fees",
83121
- "psm",
83122
- "authorization",
83123
- "safe",
83124
- "delegation",
83125
- "safety",
83126
- "switch-network",
83127
- "connector",
83128
- "troubleshooting",
83129
- "glossary",
83130
- "reading-data"
83131
- ];
83132
- var GUIDE_CONTENT = {
83133
- "getting-started": `# Diamond Hands \u2014 what this is
83134
-
83135
- Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
83136
- without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
83137
- against it, pay it back whenever you like, and take your BTC out again.
83138
-
83139
- **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
83140
- topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
83141
- \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
83142
- are enabled (and the true reason when not), and which signer modes this build offers;
83143
- never promise a capability it does not list. The money truth has THREE cases:
83144
- - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
83145
- - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
83146
- the test network: real ceremonies and signatures, PRACTICE money (test funds).
83147
- - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
83148
- explicitly arms them; the capabilities block states which applies.
83149
- SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
83150
-
83151
- A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
83152
- authorize) \u2192 create a position \u2192 deposit BTC \u2192 mint. The \`lifecycle\` topic has the exact
83153
- calls. Every operation that moves funds requires the user's explicit confirmation
83154
- (\`confirmed: true\`) \u2014 nothing is ever silent.`,
83155
- "first-setup": `# First setup \u2014 from zero to ready, by conversation only
83156
-
83157
- Installing on another machine? Three paths, by machine: Claude Desktop on macOS/Windows
83158
- \u2192 the \`.mcpb\` bundle from the releases page (no Node needed); Linux or any other MCP
83159
- host \u2192 the one-line installer (self-contained binary, prints the exact config snippet);
83160
- developers with Node \u2265 18 on PATH \u2192 \`npx -y @gvnrdao/dh-mcp\`. Details: the README
83161
- install matrix. (A fourth, zero-install path \u2014 the claude.ai connector \u2014 is implemented
83162
- but NOT yet publicly served; its rollout is operator-gated. Truth and trust model:
83163
- \`guide connector\`.)
83164
-
83165
- Nothing needs a config file. Three steps:
83166
-
83167
- **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83168
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83169
- (practice money) or mainnet (real money); whether writes are enabled here and which
83170
- signer modes exist; current terms (\`protocol_terms\`).
83171
-
83172
- **2. Choose HOW to authorize operations** (the user's choice, made by talking):
83173
- - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
83174
- on the real adapter and the mock. The approval page auto-opens in the browser (its URL
83175
- is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
83176
- / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
83177
- their own wallet. The first verified signature binds their wallet address as the
83178
- borrower. Full walkthrough: \`guide connect-wallet\`.
83179
- - **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
83180
- signs after each confirmation. Provision it via the env pair (\`DH_KEYSTORE_PATH\` +
83181
- \`DH_KEYSTORE_PASSWORD\`), or call \`signer_setup\` action \`unlock-keystore\`: a SECURE
83182
- LOCAL PAGE opens where the user types the password or generates a fresh keystore.
83183
- NEVER ask for or accept a password in the conversation \u2014 if a user pastes one, tell
83184
- them to use the unlock page instead.
83185
- - **Safe / delegation modes (\`safe\`, \`safe-module\`) are PRACTICE-ONLY today** \u2014 on the
83186
- real adapter they refuse with that true reason. Try them in a mock world.
83187
- - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
83188
- - **No signer is also a valid start:** every public read works without one \u2014
83189
- \`position_list {borrower}\` with the user's address needs no signer and no login.
83190
- - **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
83191
- talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
83192
- the money reality after any switch.
83193
-
83194
- **3. First position.** \`loan_create\` with a term from \`protocol_terms\` (needs
83195
- \`confirmed: true\` from the user). Then deposit BTC to the vault address
83196
- (practice worlds: simulate it with \`mock_control\` \`submit-deposit\` + \`confirm-deposit\`),
83197
- and mint with \`loan_mint\`.
83198
-
83199
- The user can switch authorization modes at ANY time by saying so \u2014 repeat step 2.`,
83200
- "connect-wallet": `# Connect your wallet \u2014 the external-signer walkthrough
83201
-
83202
- External mode means the user approves every operation in their OWN wallet \u2014 a browser
83203
- extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
83204
- the mock.
83205
-
83206
- **The walkthrough:**
83207
- 1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83208
- desktop browser; its URL is ALSO in the tool result (loopback-only \u2014 open it on the
83209
- same machine the server runs on).
83210
- 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
83211
- WalletConnect QR code or paste the pairing code.
83212
- 3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83213
- login ceremony explicitly (one typed-data signature in the wallet).
83214
- 4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
83215
- across sessions (\`signer_setup reset-borrower\` unbinds it).
83216
- 5. From then on, every fund-moving operation shows an approval card in the wallet,
83217
- decoded from the exact transaction bytes \u2014 what you read IS what executes. Declining
83218
- always safely cancels.
83219
-
83220
- **Popup cadence \u2014 exactly this many wallet interactions per operation:**
83221
-
83222
- | Operation | Wallet interactions (external mode) |
83223
- |---|---|
83224
- | login (per login-session lifetime) | 1 typed-data |
83225
- | create position | 1 tx (plus 1 login typed-data the first time \u2014 the protocol SDK keeps its own session) |
83226
- | mint | 1 personal-sign + 1 tx |
83227
- | repay | 1 personal-sign + 1-2 tx (UCD approve leg when the server returns one) |
83228
- | extend | 1 personal-sign + 1 tx |
83229
- | allowlist destination | 1 tx (plus 1 login typed-data the first time \u2014 same SDK session) |
83230
- | withdraw BTC | not available in external mode yet (refuses with that reason); keystore mode works, no popups |
83231
- | PSM swap/redeem | 2 tx (exact-amount approve + swap/redeem) |
83232
-
83233
- **Honesty notes (say these plainly):**
83234
- - **Reads never pop the wallet.** If a read needs a login the user does not have, the
83235
- tool refuses legibly and the user says "connect my wallet" (\`signer_setup\` action
83236
- \`connect\`). The wallet never appears unrequested.
83237
- - **Logins expire.** When the session token dies mid-conversation, the next
83238
- authenticated call refuses with the same remedy \u2014 an explicit reconnect, never a
83239
- surprise popup. On mainnet the broker also throttles logins per address \u2014 a throttled
83240
- login means "wait and retry", not a wallet failure.
83241
- - **Withdraw-BTC under external mode is a BLIND signature** \u2014 the SDK builds the two
83242
- withdrawal auth hashes internally, so the approval page shows the bare hash and says
83243
- plainly it cannot decode the contents (the production web app signs the same way).
83244
- Tell the user this before the popups: two hash signatures, then the BTC moves.
83245
- - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83246
- (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83247
- hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
83248
- card states the live figure.
83249
- - **Mainnet:** every fund-moving operation spends REAL money, and the minimum mint is
83250
- 10 UCD.
83251
-
83252
- **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
83253
- \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
83254
- WalletConnect session (pending approvals are cancelled loudly), discards the login
83255
- token from server memory AND revokes it at the service, and unbinds the borrower
83256
- identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
83257
- a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
83258
- state: (1) \`reset-borrower\` is NOT a disconnect \u2014 it only swaps identity and leaves
83259
- the connection and login alive; (2) no server can revoke the wallet's own site
83260
- permission for the approval page \u2014 remove that inside the wallet (MetaMask: Settings \u2192
83261
- Connections / Connected sites).`,
83262
- lifecycle: `# The full lifecycle \u2014 exact calls
83263
-
83264
- 1. **Create** \u2014 \`loan_create {selectedTerm, confirmed:true}\` \u2192 position id, vault address.
83265
- 2. **Deposit BTC** \u2014 send BTC to the vault address; it becomes usable after the
83266
- confirmation threshold (\`protocol_status.minConfirmations\`). Practice worlds:
83267
- \`mock_control {action:"submit-deposit", positionId, sats}\` then
83268
- \`{action:"confirm-deposit", txid, confirmations}\`.
83269
- 3. **Borrow (mint)** \u2014 \`loan_mint {positionId, amountUcd, confirmed:true}\`. Ceiling:
83270
- \`position_status\` \u2192 \`valuation.maxMintableUcd\`. The origination fee is ADDED to debt.
83271
- 4. **Repay** \u2014 \`loan_pay {positionId, amountUcd, confirmed:true}\`. Fee-free, partial or
83272
- full; full repayment moves the position to REPAID.
83273
- 5. **Extend (renew)** \u2014 \`loan_extend {positionId, selectedTerm, confirmed:true}\`, only
83274
- within the FINAL 30 DAYS of the current term. The extension fee is ADDED TO YOUR DEBT
83275
- (your wallet is not charged); it is at most the term's rate \xD7 your current debt,
83276
- reduced by unused origination-fee credit from the current term.
83277
- 6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
83278
- BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
83279
- The vault always keeps room for the network fee (you cannot drain to zero).
83280
- 7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83281
- \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83282
-
83283
- State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83284
- fees: `# Fees \u2014 the two models, stated plainly
83285
-
83286
- - **Origination fee (minting):** a percentage of what you borrow
83287
- (\`protocol_terms.originationFeeBps\`, e.g. 200 = 2%). It is ADDED TO YOUR DEBT: borrow
83288
- 100 UCD \u2192 you receive 100, you owe 102. It is never taken out of what you receive.
83289
- - **Extension fee (renewing):** ADDED TO YOUR DEBT, like the origination fee \u2014 your
83290
- wallet is not charged. The CEILING is \`extensionFeeRateBps\` \xD7 your CURRENT DEBT (a
83291
- flat rate per renewal, not per month); origination fees you already paid this term are
83292
- CREDITED against it, so the charged fee lands between (ceiling \u2212 that credit) and the
83293
- ceiling.
83294
- - **Repayment:** no fee, any amount up to the debt.
83295
- - **BTC network fee (withdrawals):** deducted FROM the amount you withdraw (default
83296
- 1000 sats) \u2014 the destination receives amountSats \u2212 fee.
83297
-
83298
- Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83299
- signed, amounts included. Read it back when the user asks what happened.`,
83300
- psm: `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83301
-
83302
- The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83303
- directions, in user words:
83304
-
83305
- - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
83306
- mints UCD **to you** (output always goes to the caller \u2014 there is no recipient field).
83307
- The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83308
- UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83309
- and you receive 99 UCD.
83310
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
83311
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
83312
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
83313
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
83314
- shortfall refuses with both figures (available vs required).
83315
-
83316
- The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83317
- is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83318
- 1e18 = 1:1) and can be changed by protocol governance.
83319
-
83320
- **Limits and switches** (all visible in \`protocol://psm\`):
83321
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
83322
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
83323
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
83324
- direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83325
- - Per-block volume caps may exist per direction ("uncapped" when none is set).
83326
-
83327
- **Why a slippage floor exists:** executing an exchange on-chain REQUIRES a minimum-out
83328
- floor \u2014 submitting with a zero floor is refused by the contract. Fees or the rate can
83329
- change between your quote and execution; the floor makes a drifted execution REFUSE
83330
- rather than silently deliver less than quoted.
83331
-
83332
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83333
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83334
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83335
- the money is real. On mainnet the stablecoin is real Circle USDC.
83336
-
83337
- **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83338
- result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83339
- differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83340
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
83341
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
83342
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83343
- tolerance; if fees or the rate drifted beyond that between quote and execution, the
83344
- contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83345
- own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83346
- standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83347
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83348
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
83349
- authorization: `# Authorization \u2014 who signs, and what a signature means
83350
-
83351
- Every fund-moving operation needs TWO things, always in this order:
83352
- 1. **The user's explicit confirmation** in conversation (\`confirmed: true\`) \u2014 the agent
83353
- must ask, never assume.
83354
- 2. **A cryptographic authorization** by the chosen signer mode:
83355
- - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83356
- mobile via QR/paste-code). Real adapter and mock. The approval card in the wallet
83357
- shows EXACTLY what executes \u2014 amounts are decoded from the transaction itself, never
83358
- re-formatted. Walkthrough: \`guide connect-wallet\`.
83359
- - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
83360
- Real adapter and mock.
83361
- - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
83362
- refuse with that true reason (their planes ship in their own deliveries).
83363
- - \`mock-simulated\` \u2014 practice-world stand-in ceremony (no cryptography; mock only).
83364
-
83365
- **Reads never summon the wallet.** Public reads need no signer at all. Authenticated
83366
- reads need a login \u2014 the keystore env pair, or an explicit "connect my wallet"
83367
- (\`signer_setup\` action \`connect\`). Without one they refuse legibly; a wallet popup is
83368
- only ever caused by a write ceremony or that explicit connect. The login (one typed-data
83369
- signature) lasts a JWT lifetime; when it expires, the next call refuses the same legible
83370
- way \u2014 reconnect on the user's word.
83371
-
83372
- Results carry \`authorization\`: \`scheme\` (external-wallet | eip712-eoa | mock-signature),
83373
- \`signer\` (who signed), \`card\` (what was signed, human-readable), \`digest\` (the signature
83374
- or transaction hash). Declining in the wallet ALWAYS safely cancels the operation.
83375
-
83376
- \`signer_setup status\` vocabulary: a **candidate** is a wallet that is CONNECTED to the
83377
- approval page but has not yet proven itself by signing; the **borrower** is the identity
83378
- BOUND by the first verified signature (it persists across sessions). Connected \u2260 chosen:
83379
- picking external mode is a preference \u2014 a wallet still has to connect on the approval
83380
- page, and the page link comes from \`signer_setup status\`.
83381
-
83382
- Switching modes: \`signer_setup\` \u2014 see \`first-setup\`. Secrets NEVER travel through chat;
83383
- keystore passwords go only into the secure unlock page.`,
83384
- safe: `# Safe accounts \u2014 borrowing as a smart-account (single or multi-owner)
83385
-
83386
- A **Safe** is a smart-contract account owned by one or more wallets ("owners") with a
83387
- signature **threshold** (e.g. 2-of-3: any 2 of the 3 owners must sign). Companies and
83388
- teams use Safes so no single key controls the funds. Diamond Hands supports a Safe AS THE
83389
- BORROWER: the position belongs to the Safe, and operations are authorized by its owners.
83390
-
83391
- **Adapter truth:** the Safe borrower plane is PRACTICE-ONLY today \u2014 on the real adapter,
83392
- \`signer_setup use safe\` refuses with exactly that reason. Everything below runs in mock
83393
- worlds until the Safe plane's own delivery; never present it as available on real.
83394
-
83395
- **Setup:** \`signer_setup\` action \`use\`, mode \`safe\`, with \`safeAddress\`. Owners and
83396
- threshold are DISCOVERED from the Safe itself \u2014 never typed in. (Practice worlds: create
83397
- a test Safe first with \`mock_control deploy-safe\`.) If keystore material is already
83398
- configured (\`signer_setup status\` \u2192 keystoreConfigured), \`use safe\` unlocks it
83399
- AUTOMATICALLY \u2014 do not send the user to the unlock page in that case.
83400
-
83401
- **Who signs what (say this plainly):**
83402
- - Every operation still needs the user's \`confirmed: true\` first \u2014 nothing changed there.
83403
- - Owner signatures then authorize the operation. In the current phase the local keystore
83404
- is the owner-signer (a 1-of-1 Safe); external owner wallets join in a later phase.
83405
- - Creating a position and withdrawing BTC are executed BY the Safe itself (a Safe
83406
- transaction \u2014 you may see a "Safe nonce" on the card). Minting, paying and renewing
83407
- are authorized by the owners and submitted by an executor \u2014 the result card names it.
83408
-
83409
- **Withdrawals have one extra rule:** the destination BTC address must be ALLOWLISTED for
83410
- the Safe first \u2014 \`loan_allowlist_destination\` (its own owner-signed ceremony; the address
83411
- becomes usable after a delay READ LIVE from the chain \u2014 immediate in practice worlds,
83412
- 24 hours on mainnet, where allowlisting and withdrawing happen on different days). A
83413
- withdrawal to an unlisted address refuses with exactly this instruction.
83414
-
83415
- **Timing honesty (multi-owner Safes, later phases):** authorizations for mint/pay/renew
83416
- expire after ~3 minutes, and withdrawal authorizations within the minute \u2014 so a multi-
83417
- owner signing session happens TOGETHER, live ("gather first, sign in one burst").
83418
- Creating a position and allowlisting a destination have NO expiry \u2014 owners can sign
83419
- those at their own pace. The ceremony guides this; never widen a window.`,
83420
- delegation: `# Delegation \u2014 one owner ceremony, then day-to-day solo
83421
-
83422
- Multi-owner Safes cannot practically sign every operation inside the protocol's short
83423
- signature window. Delegation is the protocol's answer: the owners sign ONCE to install a
83424
- tightly-caged AGENT key; afterwards daily work runs without disturbing them.
83425
-
83426
- **Adapter truth:** delegation (mode \`safe-module\`) is PRACTICE-ONLY today \u2014 on the real
83427
- adapter it refuses with exactly that reason, pending its own delivery. Everything below
83428
- runs in mock worlds; never present it as available on real.
83429
-
83430
- **Setup (mode \`safe-module\`):** \`signer_setup use safe-module\` with your Safe's address,
83431
- then \`loan_delegation_setup\` \u2014 ONE durable Safe transaction the owners sign at their
83432
- leisure (no time window). It enables the Safe's AgentModule, binds the agent key, registers
83433
- it in the delegation registry, and pre-approves your BTC withdrawal destinations (so your
83434
- first withdrawal never needs a second gathering).
83435
-
83436
- **What the agent CAN do alone** (an unchangeable, contract-hardcoded list): create a
83437
- position; and \u2014 per position, only after the owners grant it (\`loan_delegation_grant\`,
83438
- a quorum signature; the agent can NEVER widen its own powers) \u2014 pay down debt (REPAY),
83439
- extend the term (RENEW), and borrow (MINT, only while the post-mint collateral ratio
83440
- stays at or above the floor the owners granted \u2014 their risk bound).
83441
-
83442
- **What the agent can NEVER do, ever:** withdraw Bitcoin alone (withdrawal signatures are
83443
- owners-only, permanently \u2014 the verifier has no delegate arm); add or change withdrawal
83444
- destinations (owners-only, forever); touch the module, the registry, or any other
83445
- contract; move ETH. A stolen agent key can shuffle money WITHIN your position \u2014 never out.
83446
-
83447
- **Withdrawals stay a short owners' moment:** the agent prepares and submits, but the
83448
- owners sign together inside the short window, and only to destinations they pre-approved.
83449
- Where the destination registry is wired on-chain this bound is enforced by the contract;
83450
- verify the wiring on your network before relying on it (test networks: wired and verified;
83451
- mainnet wiring is confirmed at deployment review).
83452
-
83453
- **Rotation and revocation:** revoking the agent BURNS its address forever (AR-1) \u2014 that
83454
- is deliberate, so revocation is always safe to use. Rotation = mint a FRESH key and run a
83455
- new setup ceremony; never reuse keys, never bind a personal or owner key as agent.
83456
-
83457
- **Currency exchange (PSM):** the module cannot reach the PSM at all \u2014 its allowlist stops
83458
- at the loan contracts. A Safe's UCD\u2194USDC swaps are TWO durable Safe transactions the
83459
- owners sign at leisure (\`psm_swap\` builds the pair) \u2014 that is the only Safe PSM path.`,
83460
- safety: `# Safety \u2014 what protects the user
83461
-
83462
- - **Nothing moves without you.** Every write needs \`confirmed: true\` AND the signer
83463
- ceremony. A decline anywhere cleanly cancels \u2014 declining is always safe.
83464
- - **The card is the truth.** In external mode the wallet card is decoded from the exact
83465
- transaction bytes being signed \u2014 what you read IS what executes.
83466
- - **Liquidation:** if collateral value falls so the collateral ratio drops under the
83467
- liquidation threshold (\`protocol_status.liquidationThresholdBps\`, e.g. 110%), the
83468
- position can be liquidated. Watch \`position_status.valuation\` \u2014 \`currentLtvBps\` vs the
83469
- threshold. Repaying debt or adding collateral restores safety.
83470
- - **Expiry:** positions have terms; extend BEFORE expiry (\`loan_extend\`). An EXPIRED
83471
- position cannot mint or extend.
83472
- - **Withdrawals are irreversible.** Bitcoin sent to a wrong address is gone. Read the
83473
- address back to the user before confirming.
83474
- - **Can you lose your bitcoin?** Only through liquidation (undercollateralized debt) or
83475
- withdrawing to a wrong address. Repaid-in-full positions release all collateral.
83476
- - **Practice vs real:** mock worlds are stated as such (\`boundary://info\`). Never let a
83477
- user believe practice gains/losses are real, or vice versa.`,
83478
- "switch-network": `# Switch network \u2014 sepolia \u2194 mainnet by conversation (real adapter)
83479
-
83480
- The \`network_switch\` tool moves THIS SESSION between worlds. Check
83481
- \`boundary://info\` capabilities first: \`networkSwitch: true\` means it is available
83482
- (real adapter); in a practice sandbox (mock) the world is pinned by config \u2014 there is
83483
- no switch, and that is by design.
83484
-
83485
- **The rules, plainly:**
83486
- - \`network_switch status\` \u2014 which network is active and whether money is real. Say
83487
- this to the user BEFORE and AFTER any switch, always.
83488
- - \`network_switch switch { network, confirmed: true }\` \u2014 the switch runs only after
83489
- the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83490
- - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83491
- A sepolia position does not exist on mainnet and vice versa.
83492
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83493
- and every one still requires the user's explicit confirmation plus the signer
83494
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.
83495
- - A pending signing ceremony blocks the switch (finish or decline it first).
83496
- - The switch is session-scoped: when the server restarts, the configured default
83497
- network returns.
83498
-
83499
- After any switch: re-read \`boundary://info\`, then STATE the new network and money
83500
- reality in your next message. The user must never have to ask which world they are in.`,
83501
- // Plan 17 B1 — the hosted tier's truth, in user language. The trust ledger below is
83502
- // the plan-12 Part 0 ledger (BINDING, archive/12-remote-connector.md) — all six
83503
- // entries, verbatim-equivalent; G-CONN pins anchor phrases from every entry.
83504
- connector: `# The claude.ai connector \u2014 Diamond Hands with zero install (hosted tier)
83505
-
83506
- **STATUS TRUTH (say this first when asked):** the connector is IMPLEMENTED but NOT yet
83507
- publicly served \u2014 the operator's rollout gates (a security audit, then a URL) come
83508
- first. Until then there is no URL to give out, and the local install paths
83509
- (\`first-setup\`) are the way in. Never promise availability or timing.
83510
-
83511
- **What it is:** instead of installing anything, the user adds Diamond Hands to
83512
- claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
83513
- Sign-in IS the wallet: one Sign-In-with-Ethereum signature proves address ownership \u2014
83514
- no password, no email, no account beyond the wallet address. The sign-in page offers a
83515
- WalletConnect QR too, so a phone wallet works without any browser extension.
83516
-
83517
- **Signature cadence, plainly:** the FIRST connect costs one SIWE signature (sign-in)
83518
- plus one lit-ops login signature (read access). After that, every operation that moves
83519
- funds asks for its OWN approval in the user's wallet, every time \u2014 and reads never pop
83520
- the wallet. The login session lives ONLY in the server's memory: a server restart, or
83521
- an idle spell long enough that the tenant's world is evicted, means signing in again.
83522
- That is the flip side of "nothing stored at rest" \u2014 a re-login is normal, not a fault.
83523
-
83524
- **What the hosted server IS trusted with** (the six residual trusts \u2014 state them
83525
- honestly when asked "is this safe"):
83526
- 1. **The approval page it serves.** Same security baseline as the diamondhands.credit
83527
- web app (you already trust the pages gvnr serves over HTTPS). The wallet's own
83528
- display is the independent backstop for transactions; personal-sign envelopes are
83529
- action-pinned and expire in minutes; BTC destinations are defended by the on-chain
83530
- allowlist delay, which no server can shorten.
83531
- 2. **The read credential.** Your lit-ops login token is held in memory for the active
83532
- session ONLY \u2014 it grants reads and advisory broadcast, it can sign NOTHING, and it
83533
- is never written to disk. A breach here is privacy-class, never money-class.
83534
- 3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
83535
- a security concern is filed and audited for exactly this channel.
83536
- 4. **Tenant separation.** Your identity \u2194 wallet \u2194 session binding is isolated from
83537
- every other user's; a failure here would be privacy-class, never signing-class,
83538
- because no key material exists server-side to leak.
83539
- 5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
83540
- version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
83541
- reports the exact server version.
83542
- 6. **The BTC-withdraw blind sign.** Withdrawal serves an OPAQUE 32-byte hash \u2014 the
83543
- card says plainly that its contents are NOT decodable on the page (site parity:
83544
- diamondhands.credit serves the identical blind sign). Defenses stated with it:
83545
- server-side borrower verification, the minutes-narrow signing window, and the
83546
- on-chain allowlist delay.
83547
-
83548
- **What it structurally CANNOT do:** hold keys or custody \u2014 keystore mode is ABSENT
83549
- from the connector build (not disabled: never constructed), so every fund-moving
83550
- action needs a fresh signature from the user's own wallet. And it serves only the
83551
- networks its deployment is rolled out to \u2014 this deployment serves sepolia during
83552
- rollout; mainnet enablement is the operator's deploy decision, stated in capabilities
83553
- by reason, never a hidden knob.
83554
-
83555
- **Independent exits:** the web app (diamondhands.credit) and the SDK speak to the SAME
83556
- chain state. The connector going down strands nothing and gates nothing.`,
83557
- troubleshooting: `# Troubleshooting \u2014 what error codes mean, in plain words
83558
-
83559
- - **SIGNER_UNAVAILABLE** \u2014 no authorization mode chosen/ready. Two real remedies: the
83560
- keystore env pair (\`DH_KEYSTORE_PATH\` + \`DH_KEYSTORE_PASSWORD\`), or the user says
83561
- "connect my wallet" \u2192 \`signer_setup\` action \`connect\` (external mode). \`signer_setup
83562
- status\` explains what is active; \`first-setup\` step 2 has the full choice.
83563
- - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83564
- the same pair: keystore env pair, or "connect my wallet" (\`signer_setup connect\`). An
83565
- EXPIRED login refuses the same way \u2014 reconnect on the user's word.
83566
- - **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83567
- not a bug); loan operations work on mainnet. Reads keep working everywhere.
83568
- - **"Wrong network" / wants mainnet or sepolia** \u2014 real adapter: \`network_switch\`
83569
- (human-confirmed card; nothing carries across networks). Mock: the world is pinned by
83570
- config \u2014 no switch exists there.
83571
- - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
83572
- SDK builds the withdrawal auth hashes internally, so the page cannot decode them.
83573
- Two blind hash signatures per withdrawal; warn the user before triggering them.
83574
- - **Login throttled (mainnet)** \u2014 the broker limits logins per address; wait and retry.
83575
- That is the broker throttle, not a wallet failure.
83576
- - **VALIDATION_FAILED** \u2014 the input itself is off (bad address format, too many decimals,
83577
- unknown field). The message names the exact problem; fix the input, don't retry blindly.
83578
- - **UPSTREAM_REJECTED** \u2014 the protocol said no: over the mint ceiling, repaying more than
83579
- owed, wrong position state, or the USER DECLINED in the wallet. The message says which.
83580
- A decline is not an error to fix \u2014 it is the user's decision.
83581
- - **UPSTREAM_UNAVAILABLE** \u2014 a data source or the signature bridge is unreachable/expired.
83582
- Usually transient; re-check with \`protocol_status\` and retry once.
83583
- - **NOT_FOUND** \u2014 the position id doesn't exist in this world (check \`position_list\`).
83584
- - **STATE_DIVERGENCE / STALE_DATA warnings** \u2014 sources disagree or lag; the envelope says
83585
- which source and when from. Prefer chain-sourced values; re-read before acting.
83586
- - Approval popup never appeared? \`signer_setup status\` \u2192 reopen the approval page URL.
83587
- Wallet on the wrong network? The page offers the switch \u2014 approve it in the wallet.
83588
- - **Asked for the claude.ai connector / remote / hosted tier** \u2014 implemented, NOT yet
83589
- publicly served (the operator's audit + rollout gates come first). There is no URL to
83590
- give out; the local install paths work today. Full truth: \`guide connector\`.
83591
- - **\`spawn npx ENOENT\` at server start (another machine/host)** \u2014 the MCP host searched
83592
- the system PATH and found no \`npx\`: that machine has no Node.js, or the host (e.g. an
83593
- Electron app) cannot see a shell-managed Node. Not a server bug \u2014 the npx path requires
83594
- Node \u2265 18 on PATH. Remedies: the one-line installer (self-contained binary, absolute
83595
- path in the printed snippet), or the \`.mcpb\` bundle on macOS/Windows Claude Desktop.`,
83596
- glossary: `# Glossary \u2014 map the user's words to the protocol's
83597
-
83598
- Synonym sets (treat these as the SAME intent):
83599
- - **mint** = borrow = take a loan = draw = "get UCD" \u2192 \`loan_mint\`
83600
- - **pay** = repay = pay back = pay down = settle \u2192 \`loan_pay\`
83601
- - **extend** = renew = roll over = prolong \u2192 \`loan_extend\`
83602
- - **withdraw** = take out my bitcoin = cash out = get my BTC back \u2192 \`loan_withdraw\`
83603
- - **position** = loan = account (the borrowing arrangement) \u2192 \`position_status\`
83604
- - **disconnect** = log out = sign out = forget my wallet = remove my wallet \u2192
83605
- \`signer_setup\` action \`disconnect\` (the FULL flush \u2014 never map these to
83606
- \`reset-borrower\`, which only swaps identity)
83607
- - **UCD** = the dollar-pegged token you borrow ("the dollars")
83608
- - **sats** = satoshis, 1 BTC = 100,000,000 sats
83609
- - **connector** = remote = hosted tier = "claude.ai integration" = "use it without
83610
- installing" \u2192 \`guide connector\` (status: implemented, not yet publicly served)
83611
-
83612
- Context-dependent terms \u2014 DISAMBIGUATE, never flatten:
83613
- - **vault** \u2014 the position's BTC custody address. Its balance is your COLLATERAL, not
83614
- your loan. "How much is in my vault?" \u2192 collateral; "how much do I owe?" \u2192 debt.
83615
- - **balance** \u2014 ask which: vault BTC (collateral) or UCD debt? They move independently.
83616
- - **health** \u2014 collateral-value vs debt (\`indexedHealth\`, \`currentLtvBps\`): a SAFETY
83617
- measure against liquidation, not an account balance.
83618
- - **interest** \u2014 Diamond Hands charges FEES (origination/extension), not running
83619
- interest; see \`fees\`.
83620
-
83621
- Language: answer in the user's language, whatever it is. These mappings apply to meaning,
83622
- not to English words only \u2014 "pagar" \u2192 \`loan_pay\`, "retirar meu bitcoin" \u2192 \`loan_withdraw\`,
83623
- "emprestar/pedir emprestado" \u2192 \`loan_mint\`, and so on.`,
83624
- // Plan 16 C3: rendered from the ONE glossary source (boundary/field-glossary.ts) —
83625
- // the same entries the anchor test pins against the actually-serialized fields.
83626
- "reading-data": renderFieldGlossaryTopic()
83627
- };
83628
- var GUIDE_INDEX = `# Diamond Hands guide \u2014 topics
83629
-
83630
- - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
83631
- - first-setup \u2014 zero to ready by conversation (authorization choice included)
83632
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
83633
- - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
83634
- - fees \u2014 the two fee models, plainly
83635
- - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
83636
- - authorization \u2014 confirmation + signature: what protects every operation, which modes exist where
83637
- - safe \u2014 borrowing as a Safe smart-account (single or multi-owner), allowlisting, timing \u2014 PRACTICE-ONLY today
83638
- - delegation \u2014 one owner ceremony, then day-to-day solo: the agent, its cage, and what always stays with the owners \u2014 PRACTICE-ONLY today
83639
- - safety \u2014 liquidation, expiry, irreversible sends, decline-is-safe
83640
- - switch-network \u2014 moving this session between sepolia (practice) and mainnet (REAL MONEY): the card, what carries across (nothing), what stays gated
83641
- - connector \u2014 the hosted claude.ai tier (zero install, wallet = account): its six-trust ledger, signature cadence, what it can never do. Status: implemented, NOT yet publicly served
83642
- - troubleshooting \u2014 error codes in plain words, with the real remedies
83643
- - glossary \u2014 synonym map + disambiguations (use it to understand ANY user's vocabulary)
83644
- - reading-data \u2014 every payload field's exact meaning (consult before interpreting any number you are unsure of)
83645
-
83646
- Orientation: Diamond Hands = borrow UCD (dollar-pegged) against your own Bitcoin without
83647
- selling it. Everything fund-moving needs the user's confirmed:true AND their chosen
83648
- signature ceremony. Read boundary://info capabilities FIRST; state the money truth early
83649
- and always: mock = practice; real adapter on sepolia = real protocol, PRACTICE money;
83650
- only mainnet is real money.`;
83651
-
83652
- // src/tools/guide.ts
83653
- function registerGuideTool(server) {
83963
+ function registerGuideTool(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
83964
+ const content = buildGuideContent(deployment);
83965
+ const index = buildGuideIndex(deployment);
83654
83966
  registerBoundaryTool(
83655
83967
  server,
83656
83968
  "guide",
@@ -83664,26 +83976,31 @@ function registerGuideTool(server) {
83664
83976
  },
83665
83977
  async ({ topic }) => guarded(async () => {
83666
83978
  if (topic === void 0 || topic === "") {
83667
- return { content: [{ type: "text", text: GUIDE_INDEX }] };
83979
+ return { content: [{ type: "text", text: index }] };
83668
83980
  }
83669
83981
  if (!GUIDE_TOPICS.includes(topic)) {
83670
83982
  return validationFailed(`unknown guide topic '${topic}' \u2014 available: ${GUIDE_TOPICS.join(" | ")}`);
83671
83983
  }
83672
- return { content: [{ type: "text", text: GUIDE_CONTENT[topic] }] };
83984
+ return { content: [{ type: "text", text: content[topic] }] };
83673
83985
  })
83674
83986
  );
83675
83987
  }
83676
- function registerGuideResources(server) {
83988
+ function registerGuideResources(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
83989
+ const content = buildGuideContent(deployment);
83990
+ const index = buildGuideIndex(deployment);
83677
83991
  for (const topic of GUIDE_TOPICS) {
83678
83992
  server.resource(`guide-${topic}`, `guide://${topic}`, async () => ({
83679
- contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: GUIDE_CONTENT[topic] }]
83993
+ contents: [{ uri: `guide://${topic}`, mimeType: "text/markdown", text: content[topic] }]
83680
83994
  }));
83681
83995
  }
83682
83996
  server.resource("guide-index", "guide://index", async () => ({
83683
- contents: [{ uri: "guide://index", mimeType: "text/markdown", text: GUIDE_INDEX }]
83997
+ contents: [{ uri: "guide://index", mimeType: "text/markdown", text: index }]
83684
83998
  }));
83685
83999
  }
83686
- function registerGuidePrompts(server) {
84000
+ function onboardAuthorizationLine(deployment) {
84001
+ return deployment.signerModes.includes("keystore") ? "if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. " : "this build authorizes with MY OWN WALLET and nothing else, so offer the wallet walkthrough (guide 'connect-wallet') \u2014 never an automatic-signing alternative it does not have \u2014 and then help me open my first position. ";
84002
+ }
84003
+ function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
83687
84004
  server.prompt(
83688
84005
  "onboard-me",
83689
84006
  "Walk a brand-new user through Diamond Hands: what it is, practice-vs-real-money, choosing how to authorize, and their first position.",
@@ -83693,7 +84010,7 @@ function registerGuidePrompts(server) {
83693
84010
  role: "user",
83694
84011
  content: {
83695
84012
  type: "text",
83696
- text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; if external mode is available, offer the wallet walkthrough (guide 'connect-wallet') alongside the automatic keystore \u2014 my choice \u2014 and then help me open my first position. Ask before every operation; never assume confirmation."
84013
+ text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
83697
84014
  }
83698
84015
  }
83699
84016
  ]
@@ -83929,8 +84246,10 @@ function registerBoundaryInfoResource(server, getB) {
83929
84246
  );
83930
84247
  }
83931
84248
 
84249
+ // src/version.ts
84250
+ var SERVER_VERSION = "0.5.11";
84251
+
83932
84252
  // src/server.ts
83933
- var SERVER_VERSION = "0.5.3";
83934
84253
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
83935
84254
  var CONNECTOR_INSTRUCTIONS = SERVER_INSTRUCTIONS + " HOSTED CONNECTOR TIER: this server is the hosted claude.ai connector. Signer modes are external-wallet ONLY \u2014 keystore mode is ABSENT from this build (structurally, not disabled); the server never holds a key, and every fund-moving action needs a fresh signature from the user's own wallet. Each tenant's world is isolated by wallet identity; network_switch moves ONLY this tenant, within the networks this deployment serves (the refusal states the rollout truth). The login session lives in server memory only \u2014 a server restart or idle eviction means signing in again; that is the no-data-at-rest property, not a fault. Trust ledger and cadence: guide topic 'connector'.";
83936
84255
  function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
@@ -83950,9 +84269,9 @@ function createServer2(deps, instructions = SERVER_INSTRUCTIONS) {
83950
84269
  registerPositionResource(server, getB);
83951
84270
  registerProtocolResources(server, getB);
83952
84271
  registerBoundaryInfoResource(server, getB);
83953
- registerGuideTool(server);
83954
- registerGuideResources(server);
83955
- registerGuidePrompts(server);
84272
+ registerGuideTool(server, deps.deployment);
84273
+ registerGuideResources(server, deps.deployment);
84274
+ registerGuidePrompts(server, deps.deployment);
83956
84275
  if (deps.mockControl) {
83957
84276
  registerMockControlTool(server, deps.mockControl, deps.chainId);
83958
84277
  }