@gvnrdao/dh-mcp 0.5.21 → 0.5.23

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
@@ -15463,7 +15463,7 @@ ${errorReport}`);
15463
15463
  }
15464
15464
  init_debug_logger();
15465
15465
  init_session_signature_cache();
15466
- var import_ethers55 = require("ethers");
15466
+ var import_ethers56 = require("ethers");
15467
15467
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15468
15468
  var GRACE_PERIOD_DAYS = 30;
15469
15469
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -18459,12 +18459,12 @@ ${auth.clientId}`;
18459
18459
  }
18460
18460
  async function executeVaultSnapshot(params) {
18461
18461
  global.ethers = {
18462
- ...import_ethers55.ethers,
18462
+ ...import_ethers56.ethers,
18463
18463
  providers: {
18464
- StaticJsonRpcProvider: import_ethers55.ethers.JsonRpcProvider
18464
+ StaticJsonRpcProvider: import_ethers56.ethers.JsonRpcProvider
18465
18465
  },
18466
- Contract: import_ethers55.ethers.Contract,
18467
- utils: import_ethers55.ethers
18466
+ Contract: import_ethers56.ethers.Contract,
18467
+ utils: import_ethers56.ethers
18468
18468
  // v6 moved utils to top level
18469
18469
  };
18470
18470
  global.Lit = {
@@ -27397,7 +27397,7 @@ var require_lit_ops_module = __commonJS({
27397
27397
  litActionParams.rpcUrl = request.rpcUrl;
27398
27398
  litActionParams.customRpcUrl = request.rpcUrl;
27399
27399
  if (this.config.debug) {
27400
- console.log(" RPC URL override:", request.rpcUrl);
27400
+ console.log(" RPC URL override host:", new URL(request.rpcUrl).host);
27401
27401
  }
27402
27402
  }
27403
27403
  if (this.config.network === "chipotle") {
@@ -27573,7 +27573,7 @@ var require_lit_ops_module = __commonJS({
27573
27573
  litActionParams.rpcUrl = request.rpcUrl;
27574
27574
  litActionParams.customRpcUrl = request.rpcUrl;
27575
27575
  if (this.config.debug) {
27576
- console.log(" RPC URL override:", request.rpcUrl);
27576
+ console.log(" RPC URL override host:", new URL(request.rpcUrl).host);
27577
27577
  }
27578
27578
  }
27579
27579
  if (this.config.network === "chipotle") {
@@ -27911,7 +27911,7 @@ var require_lit_ops_module = __commonJS({
27911
27911
  litActionParams.rpcUrl = request.rpcUrl;
27912
27912
  litActionParams.customRpcUrl = request.rpcUrl;
27913
27913
  if (this.config.debug) {
27914
- console.log(" RPC URL override:", request.rpcUrl);
27914
+ console.log(" RPC URL override host:", new URL(request.rpcUrl).host);
27915
27915
  }
27916
27916
  }
27917
27917
  if (this.config.network === "chipotle") {
@@ -28127,7 +28127,7 @@ var require_lit_ops_module = __commonJS({
28127
28127
  litActionParams.rpcUrl = request.rpcUrl;
28128
28128
  litActionParams.customRpcUrl = request.rpcUrl;
28129
28129
  if (this.config.debug) {
28130
- console.log(" EVM RPC URL override:", request.rpcUrl);
28130
+ console.log(" EVM RPC URL override host:", new URL(request.rpcUrl).host);
28131
28131
  }
28132
28132
  }
28133
28133
  if (this.config.debug) {
@@ -28257,7 +28257,12 @@ var require_lit_ops_module = __commonJS({
28257
28257
  if (!moduleAddress || !provisionerPk || !baseRpc) {
28258
28258
  throw new Error("LIT_VAULT_PROVISION_MODE=module requires LIT_ONCHAIN_VAULT_MODULE_ADDRESS, LIT_ONCHAIN_PROVISIONER_PRIVATE_KEY, BASE_RPC_URL");
28259
28259
  }
28260
- const provider = new ethers_1.JsonRpcProvider(baseRpc);
28260
+ const baseRequest = new ethers_1.FetchRequest(baseRpc);
28261
+ const drpcKey = process.env.DRPC_API_KEY;
28262
+ if (drpcKey && /(^|\.)drpc\.(org|live)$/.test(new URL(baseRpc).hostname)) {
28263
+ baseRequest.setHeader("Drpc-Key", drpcKey);
28264
+ }
28265
+ const provider = new ethers_1.JsonRpcProvider(baseRequest);
28261
28266
  const signer = new ethers_1.Wallet(provisionerPk, provider);
28262
28267
  const chainId = Number(process.env.BASE_CHAIN_ID || "8453");
28263
28268
  const issuedAt = Math.floor(Date.now() / 1e3);
@@ -28308,7 +28313,7 @@ var require_lit_ops_module = __commonJS({
28308
28313
  async chipotleCreateWalletAndAddToGroup(accountApiKey) {
28309
28314
  const baseUrl = _LitOps.LIT_CORE_API_BASE;
28310
28315
  const createResp = await fetch(`${baseUrl}/create_wallet`, {
28311
- method: "GET",
28316
+ method: "POST",
28312
28317
  headers: {
28313
28318
  "X-Api-Key": accountApiKey
28314
28319
  }
@@ -40728,6 +40733,7 @@ __export(wc_transport_exports, {
40728
40733
  WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40729
40734
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
40730
40735
  WcTransport: () => WcTransport,
40736
+ guardRelayFatal: () => guardRelayFatal,
40731
40737
  newIsolatedCore: () => newIsolatedCore,
40732
40738
  wcSessionNamespaces: () => wcSessionNamespaces,
40733
40739
  withEip712DomainType: () => withEip712DomainType
@@ -40761,7 +40767,27 @@ function newIsolatedCore(cfg, label) {
40761
40767
  });
40762
40768
  return { core, scratch };
40763
40769
  }
40764
- var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40770
+ function guardRelayFatal(core, health, onFatal) {
40771
+ const relayer = core.relayer;
40772
+ const register = relayer.registerProviderListeners;
40773
+ if (typeof register !== "function") {
40774
+ throw new Error(
40775
+ "@walletconnect/core no longer exposes relayer.registerProviderListeners \u2014 the fatal-close guard (D-4) cannot be installed. Re-verify the relay error path for this WalletConnect version before shipping it."
40776
+ );
40777
+ }
40778
+ const record = (e) => {
40779
+ if (health.fatal !== null) return;
40780
+ health.fatal = e.message;
40781
+ console.error(`[dh-mcp] WalletConnect relay failed fatally: ${e.message}`);
40782
+ onFatal(e.message);
40783
+ };
40784
+ relayer.on("relayer_error", record);
40785
+ relayer.registerProviderListeners = () => {
40786
+ register.call(relayer);
40787
+ relayer.provider.on("error", record);
40788
+ };
40789
+ }
40790
+ var import_core, import_sign_client, os, path3, import_node_fs, import_ethers50, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40765
40791
  var init_wc_transport = __esm({
40766
40792
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
40767
40793
  "use strict";
@@ -40770,6 +40796,7 @@ var init_wc_transport = __esm({
40770
40796
  os = __toESM(require("os"));
40771
40797
  path3 = __toESM(require("path"));
40772
40798
  import_node_fs = require("fs");
40799
+ import_ethers50 = require("ethers");
40773
40800
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
40774
40801
  WC_DAPP_METADATA = {
40775
40802
  name: "Diamond Hands MCP",
@@ -40779,11 +40806,14 @@ var init_wc_transport = __esm({
40779
40806
  };
40780
40807
  EVENTS = ["accountsChanged", "chainChanged"];
40781
40808
  WcTransport = class _WcTransport {
40782
- constructor(client, cfg, scratch) {
40809
+ constructor(client, cfg, scratch, health) {
40783
40810
  this.client = client;
40784
40811
  this.cfg = cfg;
40785
40812
  this.scratch = scratch;
40813
+ this.health = health;
40786
40814
  client.on("session_delete", ({ topic }) => {
40815
+ const pending = this.candidates.get(topic);
40816
+ if (pending) pending.deleted = true;
40787
40817
  if (this.session === null || this.session.topic !== topic) return;
40788
40818
  this.session = null;
40789
40819
  this.sessionListener?.(null);
@@ -40791,14 +40821,35 @@ var init_wc_transport = __esm({
40791
40821
  }
40792
40822
  session = null;
40793
40823
  sessionListener = null;
40824
+ /** Sessions announced but not yet adopted (awaiting a deferred verdict), by topic. */
40825
+ candidates = /* @__PURE__ */ new Map();
40794
40826
  static async create(cfg) {
40795
40827
  const { core, scratch } = newIsolatedCore(cfg, "dh-wc-dapp");
40828
+ const health = { fatal: null };
40829
+ let transport = null;
40830
+ guardRelayFatal(core, health, () => transport?.dropForFatal());
40796
40831
  const client = await import_sign_client.default.init({
40797
40832
  core,
40798
40833
  projectId: cfg.projectId,
40799
40834
  metadata: cfg.metadata ?? WC_DAPP_METADATA
40800
40835
  });
40801
- return new _WcTransport(client, cfg, scratch);
40836
+ transport = new _WcTransport(client, cfg, scratch, health);
40837
+ return transport;
40838
+ }
40839
+ /** The relay is gone for good: no adopted session may outlive it. Listeners hear a
40840
+ * disconnect, exactly as if the wallet had left. */
40841
+ dropForFatal() {
40842
+ if (this.session === null) return;
40843
+ this.session = null;
40844
+ void this.sessionListener?.(null);
40845
+ }
40846
+ /** Refuse to start new work over a relay that has failed fatally — naming why. */
40847
+ assertRelayHealthy() {
40848
+ if (this.health.fatal !== null) {
40849
+ throw new Error(
40850
+ `the WalletConnect relay refused this connector (${this.health.fatal}) \u2014 mobile-wallet signing is unavailable until the relay accepts its project id (DH_WC_PROJECT_ID); use the browser-wallet approval page instead`
40851
+ );
40852
+ }
40802
40853
  }
40803
40854
  /** Wallet-session state changes (connect/disconnect) — the bridge mirrors them. */
40804
40855
  onSession(cb) {
@@ -40809,6 +40860,7 @@ var init_wc_transport = __esm({
40809
40860
  }
40810
40861
  /** Create a pairing URI; resolves the session in the background when a wallet approves. */
40811
40862
  async createPairing() {
40863
+ this.assertRelayHealthy();
40812
40864
  const { uri, approval } = await this.client.connect({
40813
40865
  // sign-client 2.21 deprecates requiredNamespaces (auto-downgraded to optional).
40814
40866
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
@@ -40816,22 +40868,51 @@ var init_wc_transport = __esm({
40816
40868
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
40817
40869
  const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
40818
40870
  if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
40819
- void approval().then((session) => {
40871
+ let candidateTopic = null;
40872
+ void approval().then(async (session) => {
40820
40873
  const first = session.namespaces["eip155"]?.accounts[0];
40821
40874
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
40822
40875
  const [, chainIdStr, account] = first.split(":");
40876
+ candidateTopic = session.topic;
40877
+ const candidate = { topic: session.topic, account, chainId: Number(chainIdStr) };
40878
+ const prove = async (statement) => {
40879
+ this.assertRelayHealthy();
40880
+ return await this.client.request({
40881
+ topic: candidate.topic,
40882
+ chainId: `eip155:${candidate.chainId}`,
40883
+ request: { method: "personal_sign", params: [import_ethers50.ethers.hexlify(import_ethers50.ethers.toUtf8Bytes(statement)), candidate.account] }
40884
+ });
40885
+ };
40886
+ const state = { deleted: false };
40887
+ const live = () => !state.deleted && this.health.fatal === null;
40823
40888
  const previous = this.session;
40824
- this.session = { topic: session.topic, account, chainId: Number(chainIdStr) };
40825
- const verdict = this.sessionListener?.({ ...this.active(), pairingId });
40826
- if (verdict === false) {
40889
+ this.session = candidate;
40890
+ this.candidates.set(candidate.topic, state);
40891
+ const verdict = this.sessionListener?.({ account: candidate.account, chainId: candidate.chainId, pairingId, prove, live });
40892
+ let adopted;
40893
+ if (verdict instanceof Promise) {
40827
40894
  this.session = previous;
40895
+ adopted = await verdict.finally(() => this.candidates.delete(candidate.topic)).then((v) => v !== false);
40896
+ if (adopted) this.session = candidate;
40897
+ } else {
40898
+ this.candidates.delete(candidate.topic);
40899
+ adopted = verdict !== false;
40900
+ if (!adopted) this.session = previous;
40901
+ }
40902
+ if (!adopted) {
40828
40903
  void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
40829
40904
  }
40830
- }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
40905
+ }).catch((e) => {
40906
+ console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`);
40907
+ if (candidateTopic !== null && this.session?.topic !== candidateTopic) {
40908
+ void this.client.disconnect({ topic: candidateTopic, reason: { code: 6e3, message: "session not adopted" } }).catch(() => void 0);
40909
+ }
40910
+ });
40831
40911
  return { uri, pairingId };
40832
40912
  }
40833
40913
  /** Route one wallet request over the active session. Throws on user rejection. */
40834
40914
  async request(method, params) {
40915
+ this.assertRelayHealthy();
40835
40916
  if (!this.session) throw new Error("no active WalletConnect session");
40836
40917
  return this.client.request({
40837
40918
  topic: this.session.topic,
@@ -40888,6 +40969,11 @@ function resolveWcProjectId(raw, problems) {
40888
40969
  }
40889
40970
  var RPC_PROXY_ORIGIN = "https://api.gvnr.xyz";
40890
40971
  var rpcProxy = (chainId) => `${RPC_PROXY_ORIGIN}/v1/proxy/rpc/${chainId}`;
40972
+ var publicRpcUrl = rpcProxy;
40973
+ var DRPC_ENDPOINT = {
40974
+ mainnet: "https://lb.drpc.live/ethereum",
40975
+ sepolia: "https://lb.drpc.live/sepolia"
40976
+ };
40891
40977
  var NETWORK_DEFAULTS = {
40892
40978
  sepolia: {
40893
40979
  rpcUrl: rpcProxy(11155111),
@@ -41020,7 +41106,11 @@ function resolveRealConfig(env) {
41020
41106
  problems.push(`DH_NETWORK='${network}' is not supported. Allowed: ${Object.keys(NETWORKS).join(" | ")}.`);
41021
41107
  }
41022
41108
  const defaults2 = NETWORK_DEFAULTS[network] ?? NETWORK_DEFAULTS.mainnet;
41023
- const rpcUrl = env["ETH_RPC_URL"] || defaults2.rpcUrl;
41109
+ const rpcDrpcKey = env["DRPC_API_KEY"] || void 0;
41110
+ if (rpcDrpcKey !== void 0 && env["ETH_RPC_URL"]) {
41111
+ problems.push("DRPC_API_KEY and ETH_RPC_URL are both set \u2014 set one: DRPC_API_KEY (dRPC, key sent as a header) or ETH_RPC_URL (your own endpoint).");
41112
+ }
41113
+ const rpcUrl = rpcDrpcKey !== void 0 ? DRPC_ENDPOINT[network] ?? DRPC_ENDPOINT.mainnet : env["ETH_RPC_URL"] || defaults2.rpcUrl;
41024
41114
  const serviceEndpoint = env["DH_SERVICE_ENDPOINT"] || defaults2.serviceEndpoint;
41025
41115
  if (!/^https:\/\//.test(serviceEndpoint) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(serviceEndpoint)) {
41026
41116
  problems.push(`DH_SERVICE_ENDPOINT='${serviceEndpoint}' must be https:// (or http:// on loopback).`);
@@ -41069,6 +41159,7 @@ function resolveRealConfig(env) {
41069
41159
  network,
41070
41160
  chainId: NETWORKS[network],
41071
41161
  rpcUrl,
41162
+ ...rpcDrpcKey !== void 0 ? { rpcDrpcKey } : {},
41072
41163
  serviceEndpoint,
41073
41164
  litNetwork,
41074
41165
  ...keystorePath && keystorePassword ? { keystorePath, keystorePassword } : {},
@@ -41084,14 +41175,14 @@ function resolveRealConfig(env) {
41084
41175
 
41085
41176
  // src/boot.ts
41086
41177
  var fs6 = __toESM(require("fs"));
41087
- var import_ethers52 = require("ethers");
41178
+ var import_ethers53 = require("ethers");
41088
41179
 
41089
41180
  // src/boundary/index.ts
41090
41181
  var import_node_crypto8 = require("crypto");
41091
41182
  var fs5 = __toESM(require("fs"));
41092
41183
  var os2 = __toESM(require("os"));
41093
41184
  var path4 = __toESM(require("path"));
41094
- var import_ethers51 = require("ethers");
41185
+ var import_ethers52 = require("ethers");
41095
41186
 
41096
41187
  // src/boundary/envelope.ts
41097
41188
  function okEnvelope(data, source, warnings = []) {
@@ -41150,6 +41241,16 @@ function checkBtcAddress(addr, expected) {
41150
41241
  }
41151
41242
  }
41152
41243
 
41244
+ // src/util/redact-url.ts
41245
+ var URL_PATTERN = /\b((?:https?|wss?):\/\/)([^\s/?#"'`<>\\]+)([^\s"'`<>\\]*)/gi;
41246
+ function redactUrls(text) {
41247
+ return text.replace(URL_PATTERN, (_whole, scheme, authority, rest) => {
41248
+ const host = authority.includes("@") ? authority.slice(authority.lastIndexOf("@") + 1) : authority;
41249
+ const cut = rest.length > 0 || host !== authority;
41250
+ return `${scheme}${host}${cut ? "/\u2026" : ""}`;
41251
+ });
41252
+ }
41253
+
41153
41254
  // src/boundary/math.ts
41154
41255
  function collateralValueUcdWei(sats, priceUsd8) {
41155
41256
  return sats * priceUsd8 * 100n;
@@ -41182,10 +41283,11 @@ function stablecoinKindFor(network, stablecoinAddress) {
41182
41283
  }
41183
41284
  function failureToError(f) {
41184
41285
  const code = f.kind === "signer-missing" ? "SIGNER_UNAVAILABLE" : f.kind === "unavailable" ? "UPSTREAM_UNAVAILABLE" : f.kind === "unsupported" ? "NOT_IMPLEMENTED" : f.kind === "not-found" ? "NOT_FOUND" : "UPSTREAM_REJECTED";
41185
- const message = f.kind === "malformed" ? `${f.message} (upstream response failed integrity checks)` : f.message;
41286
+ const text = redactUrls(f.message);
41287
+ const message = f.kind === "malformed" ? `${text} (upstream response failed integrity checks)` : text;
41186
41288
  return boundaryError(code, message, {
41187
41289
  source: f.source,
41188
- ...f.raw ? { details: { upstreamMessage: f.raw } } : {}
41290
+ ...f.raw ? { details: { upstreamMessage: redactUrls(f.raw) } } : {}
41189
41291
  });
41190
41292
  }
41191
41293
  var BoundaryCore = class {
@@ -82519,7 +82621,9 @@ var MIN_CONFIRMATIONS = { mainnet: 6, sepolia: 1 };
82519
82621
  var RealUpstreamPlugin = class {
82520
82622
  constructor(config, wallet, runtime) {
82521
82623
  this.config = config;
82522
- this.provider = new import_ethers49.ethers.JsonRpcProvider(config.rpcUrl, config.chainId);
82624
+ const rpc = new import_ethers49.ethers.FetchRequest(config.rpcUrl);
82625
+ if (config.rpcDrpcKey !== void 0) rpc.setHeader("Drpc-Key", config.rpcDrpcKey);
82626
+ this.provider = new import_ethers49.ethers.JsonRpcProvider(rpc, config.chainId);
82523
82627
  this.wallet = wallet ?? null;
82524
82628
  this.runtime = runtime ?? null;
82525
82629
  this.session = wallet ? new LitOpsSession(wallet.connect(this.provider), config.serviceEndpoint, config.chainId) : null;
@@ -83460,8 +83564,9 @@ var RealUpstreamPlugin = class {
83460
83564
  }
83461
83565
  /** Chain read → mapped value, failures typed. F-PUB-5 (protocol 106): the SPECIFIC
83462
83566
  * thrown cause is rendered — a blanket rewrite to a generic message masked the
83463
- * deliberate `readPendingWithdrawals` gap as an RPC outage. No secrets transit here
83464
- * (provider errors carry method/params, never keys). */
83567
+ * deliberate `readPendingWithdrawals` gap as an RPC outage. Provider errors DO carry
83568
+ * the request URL (ethers' `info.requestUrl`); the server's URL holds no key (it is in
83569
+ * the `Drpc-Key` header) and failureToError redacts every URL regardless. */
83465
83570
  async chainRead(fn) {
83466
83571
  try {
83467
83572
  return upOk(await fn(), this.src("chain-rpc"));
@@ -83522,7 +83627,7 @@ var RealUpstreamPlugin = class {
83522
83627
  var fs4 = __toESM(require("fs"));
83523
83628
  var http3 = __toESM(require("http"));
83524
83629
  var import_node_crypto7 = require("crypto");
83525
- var import_ethers50 = require("ethers");
83630
+ var import_ethers51 = require("ethers");
83526
83631
 
83527
83632
  // src/util/brand-assets.ts
83528
83633
  var FAVICON_SVG = `<svg width="512" height="512" viewBox="-6 -11 88 88" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Diamond Hands"><path d="M1.08325 20.7041L37.9038 64.4967L74.2886 20.7041L61.8699 0.877686H13.502L1.08325 20.7041Z" fill="#C9F284" stroke="#34440E" stroke-width="1.75559"/><path d="M13.9385 0.877441L37.9045 64.2785" stroke="#34440E" stroke-width="1.75559"/><path d="M61.6553 0.877441L37.9071 64.4964" stroke="#34440E" stroke-width="1.75559"/><path d="M1.08276 20.7029H74.2882" stroke="#34440E" stroke-width="1.75559"/></svg>`;
@@ -83647,7 +83752,7 @@ ${houseHeader("Diamond Hands \xB7 signature approval")}
83647
83752
  <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
83648
83753
  <div id="wc-qr" class="qr-plate hidden"></div>
83649
83754
  <div id="wc-uri" class="card hidden"></div>
83650
- <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Approvals then happen on your phone.</div>
83755
+ <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Your wallet first asks you to sign a short statement proving the wallet is yours \u2014 it moves no funds. Approvals then happen on your phone.</div>
83651
83756
  </div>
83652
83757
  </div>
83653
83758
  </main>
@@ -83994,7 +84099,7 @@ document.getElementById("wc-connect").onclick = async () => {
83994
84099
  qrEl.classList.remove("hidden");
83995
84100
  }
83996
84101
  document.getElementById("wc-hint").classList.remove("hidden");
83997
- showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
84102
+ showIdleStatus("Scan the QR (or paste the code) in your mobile wallet, then sign the short statement it shows (it proves the wallet is yours and moves no funds) \u2014 it then becomes the signing wallet.");
83998
84103
  };
83999
84104
 
84000
84105
  listen();
@@ -84106,7 +84211,6 @@ function htmlPageSecurityHeaders(extra) {
84106
84211
 
84107
84212
  // src/boundary/upstream/shared/external-bridge/bridge.ts
84108
84213
  var MAX_SESSIONS = 16;
84109
- var MAX_PENDING_PAIRINGS = 64;
84110
84214
  function presenceStatement(origin2, chainId, nonce) {
84111
84215
  return [
84112
84216
  "Diamond Hands approval page",
@@ -84116,6 +84220,13 @@ function presenceStatement(origin2, chainId, nonce) {
84116
84220
  `Session nonce: ${nonce}`
84117
84221
  ].join("\n");
84118
84222
  }
84223
+ function recoverPresenceSigner(statement, signature) {
84224
+ try {
84225
+ return import_ethers51.ethers.verifyMessage(statement, signature);
84226
+ } catch {
84227
+ return null;
84228
+ }
84229
+ }
84119
84230
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
84120
84231
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
84121
84232
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -84165,6 +84276,10 @@ var SignatureBridge = class {
84165
84276
  * "most recent asker" guess let a second session claim the credit for a QR the user's
84166
84277
  * phone scanned (Sentinel 2 PoC-B). */
84167
84278
  pairingOwners = /* @__PURE__ */ new Map();
84279
+ /** The page session the ADMITTED WalletConnect session's proof was made for — the one page
84280
+ * credited with `wcPaired`. The credit lasts exactly as long as that session: it moves when
84281
+ * another proven session replaces it and ends when the wallet disconnects. */
84282
+ wcCreditedSession = null;
84168
84283
  keystoreUnlock;
84169
84284
  unlockToken = null;
84170
84285
  unlockSession = null;
@@ -84653,46 +84768,16 @@ var SignatureBridge = class {
84653
84768
  const { WcTransport: WcTransport2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
84654
84769
  return WcTransport2.create(cfg);
84655
84770
  });
84656
- this.wcTransport = await factory2(this.wcConfig);
84657
- this.wcTransport.onSession((info) => {
84658
- const refusal = info ? this.accountRefusal(info.account) : null;
84659
- if (info && refusal) {
84660
- if (!this.wcActive) {
84661
- this.rebuildSharedWallet();
84662
- this.demoteWcEntries();
84663
- }
84664
- process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
84665
- `);
84666
- return false;
84667
- }
84668
- this.wcActive = info !== null;
84669
- this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
84670
- if (info?.pairingId) {
84671
- const owner = this.pairingOwners.get(info.pairingId);
84672
- this.pairingOwners.delete(info.pairingId);
84673
- const paired = owner ? this.sessions.get(owner) : void 0;
84674
- if (paired) paired.wcPaired = true;
84675
- }
84676
- if (info === null) {
84677
- for (const entry of this.pending.values()) {
84678
- if (!entry.settled && !entry.collect) {
84679
- this.settle(entry, {
84680
- status: "invalidated",
84681
- reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
84682
- });
84683
- }
84684
- }
84685
- }
84686
- });
84771
+ const transport = await factory2(this.wcConfig);
84772
+ this.wcTransport = transport;
84773
+ transport.onSession((info) => info === null ? this.onWcDisconnect() : this.admitWcSession(info, transport));
84687
84774
  }
84688
84775
  const { uri, pairingId } = await this.wcTransport.createPairing();
84689
84776
  if (pairingId) {
84690
- this.pairingOwners.set(pairingId, askingSession);
84691
- while (this.pairingOwners.size > MAX_PENDING_PAIRINGS) {
84692
- const oldest = this.pairingOwners.keys().next();
84693
- if (oldest.done) break;
84694
- this.pairingOwners.delete(oldest.value);
84777
+ for (const [pending, owner] of this.pairingOwners) {
84778
+ if (owner === askingSession || !this.sessions.has(owner)) this.pairingOwners.delete(pending);
84695
84779
  }
84780
+ this.pairingOwners.set(pairingId, askingSession);
84696
84781
  }
84697
84782
  const { default: qrcode } = await import("qrcode-generator");
84698
84783
  const qr = qrcode(0, "M");
@@ -84793,12 +84878,7 @@ var SignatureBridge = class {
84793
84878
  return;
84794
84879
  }
84795
84880
  const statement = presenceStatement(this.publicOrigin(), chainId, session.presenceNonce);
84796
- let recovered = null;
84797
- try {
84798
- recovered = import_ethers50.ethers.verifyMessage(statement, signature);
84799
- } catch {
84800
- recovered = null;
84801
- }
84881
+ const recovered = recoverPresenceSigner(statement, signature);
84802
84882
  if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
84803
84883
  this.deny(
84804
84884
  res,
@@ -84889,6 +84969,100 @@ var SignatureBridge = class {
84889
84969
  * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
84890
84970
  * false for them, and `unattendedReason` says plainly that the phone may already have
84891
84971
  * acted. */
84972
+ /**
84973
+ * C-47, the THIRD door: a wallet announced a WalletConnect session. `requestSignature`
84974
+ * PREFERS the WalletConnect wallet over the approval page (see the `wcActive` branch there),
84975
+ * so an account admitted here does not merely become the candidate — it becomes the SIGNER,
84976
+ * and the page that showed its QR becomes the page that sees every card.
84977
+ *
84978
+ * The account a WalletConnect session carries is the wallet's own UNSIGNED claim — the
84979
+ * protocol validates its format, never its ownership. Admitting on that claim let anyone
84980
+ * holding the approval link answer their own QR with a scripted wallet claiming the user's
84981
+ * public address: it took the signer seat, its page saw every card, and an extension-only
84982
+ * user's ceremonies were routed to it (Sentinel 2 PoC-D). So this door now asks for the same
84983
+ * proof `hello` does: the wallet signs the presence statement of the page whose QR it
84984
+ * answered, and the signature must recover to the account it claims.
84985
+ *
84986
+ * Resolves `false` to refuse — the transport then keeps what it held and drops the wallet. If
84987
+ * the wallet declines the proof (or the request fails) the promise rejects and the transport
84988
+ * ends the session unadopted; nothing here is adopted before the proof checks out.
84989
+ */
84990
+ async admitWcSession(info, transport) {
84991
+ const refusal = this.accountRefusal(info.account);
84992
+ if (refusal) return this.refuseWcSession(refusal);
84993
+ const ownerId = info.pairingId ? this.pairingOwners.get(info.pairingId) : void 0;
84994
+ if (info.pairingId) this.pairingOwners.delete(info.pairingId);
84995
+ const owner = ownerId ? this.sessions.get(ownerId) : void 0;
84996
+ if (!ownerId || !owner) {
84997
+ return this.refuseWcSession(
84998
+ "the wallet answered no QR code that an open approval page of this bridge showed \u2014 open the approval page and scan the QR code it shows"
84999
+ );
85000
+ }
85001
+ if (!info.prove || !info.live) {
85002
+ return this.refuseWcSession(
85003
+ "this WalletConnect transport cannot ask the wallet to prove its account (or report whether its session is still live), so no session can be admitted"
85004
+ );
85005
+ }
85006
+ const statement = presenceStatement(this.publicOrigin(), info.chainId, owner.presenceNonce);
85007
+ const signature = await info.prove(statement);
85008
+ const recovered = recoverPresenceSigner(statement, signature);
85009
+ if (recovered === null || recovered.toLowerCase() !== info.account.toLowerCase()) {
85010
+ return this.refuseWcSession(
85011
+ `the wallet claimed ${info.account} but ${recovered === null ? "returned no valid signature" : `signed with ${recovered}`} for the approval page's presence statement \u2014 an address alone proves nothing`
85012
+ );
85013
+ }
85014
+ if (this.wcTransport !== transport) {
85015
+ return this.refuseWcSession("the bridge's WalletConnect connection was replaced while the wallet was proving its account");
85016
+ }
85017
+ if (!info.live()) {
85018
+ return this.refuseWcSession("the wallet's WalletConnect session ended (or the relay failed) while it was proving its account \u2014 scan the QR again");
85019
+ }
85020
+ const lateRefusal = this.accountRefusal(info.account);
85021
+ if (lateRefusal) return this.refuseWcSession(lateRefusal);
85022
+ const page = this.sessions.get(ownerId);
85023
+ if (!page || page.refused) {
85024
+ return this.refuseWcSession("the approval page that showed this QR code closed while the wallet was proving its account \u2014 reopen it and scan again");
85025
+ }
85026
+ if (this.wcCreditedSession !== null && this.wcCreditedSession !== ownerId) {
85027
+ const previous = this.sessions.get(this.wcCreditedSession);
85028
+ if (previous) previous.wcPaired = false;
85029
+ }
85030
+ this.wcActive = true;
85031
+ this.wallet = { account: info.account, chainId: info.chainId };
85032
+ page.wcPaired = true;
85033
+ page.provenAccount = info.account;
85034
+ this.wcCreditedSession = ownerId;
85035
+ this.replayPending(page);
85036
+ return true;
85037
+ }
85038
+ /** Refuse a WalletConnect session — see `admitWcSession`. */
85039
+ refuseWcSession(reason) {
85040
+ if (!this.wcActive) {
85041
+ this.rebuildSharedWallet();
85042
+ this.demoteWcEntries();
85043
+ }
85044
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${reason}
85045
+ `);
85046
+ return false;
85047
+ }
85048
+ /** The admitted WalletConnect wallet went away. */
85049
+ onWcDisconnect() {
85050
+ this.wcActive = false;
85051
+ this.wallet = null;
85052
+ for (const entry of this.pending.values()) {
85053
+ if (!entry.settled && !entry.collect) {
85054
+ this.settle(entry, {
85055
+ status: "invalidated",
85056
+ reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
85057
+ });
85058
+ }
85059
+ }
85060
+ if (this.wcCreditedSession !== null) {
85061
+ const credited = this.sessions.get(this.wcCreditedSession);
85062
+ if (credited) credited.wcPaired = false;
85063
+ this.wcCreditedSession = null;
85064
+ }
85065
+ }
84892
85066
  demoteWcEntries() {
84893
85067
  for (const entry of this.pending.values()) {
84894
85068
  if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
@@ -85372,7 +85546,10 @@ async function createRealBoundary(config, wallet, overrides) {
85372
85546
  const chainName = config.network === "mainnet" ? "Ethereum Mainnet" : "Sepolia";
85373
85547
  const bridge = new SignatureBridge({
85374
85548
  ...config.bridgeUrlFile ? { urlFile: config.bridgeUrlFile } : {},
85375
- network: { chainId: config.chainId, chainName, rpcUrl: config.rpcUrl },
85549
+ // The page's wallet_addEthereumChain gets the PUBLIC proxy, never config.rpcUrl: the
85550
+ // server's endpoint is a server credential, and the page would save it into the
85551
+ // user's wallet.
85552
+ network: { chainId: config.chainId, chainName, rpcUrl: publicRpcUrl(config.chainId) },
85376
85553
  ...config.wcProjectId ? { wc: { projectId: config.wcProjectId, chainId: config.chainId } } : {},
85377
85554
  // Plan 17 E2 (SVC-OPS-08): the HOSTED tier caps ceremonies at concurrent-1 per
85378
85555
  // tenant — one bridge per tenant world, so the bridge cap IS the tenant cap. The
@@ -85397,7 +85574,7 @@ async function createRealBoundary(config, wallet, overrides) {
85397
85574
  const manager = new SignerManager({
85398
85575
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
85399
85576
  initialMode,
85400
- ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers51.ethers.getAddress(overrides.boundBorrower) } : {},
85577
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers52.ethers.getAddress(overrides.boundBorrower) } : {},
85401
85578
  candidate: () => bridge.walletState()?.account ?? null,
85402
85579
  pendingCeremonies: () => bridge.pendingCount(),
85403
85580
  keystore
@@ -85493,8 +85670,8 @@ async function buildBoundary(configResult, overrides) {
85493
85670
  );
85494
85671
  }
85495
85672
  try {
85496
- const decrypted = await import_ethers52.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85497
- if (!(decrypted instanceof import_ethers52.ethers.Wallet)) {
85673
+ const decrypted = await import_ethers53.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85674
+ if (!(decrypted instanceof import_ethers53.ethers.Wallet)) {
85498
85675
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
85499
85676
  }
85500
85677
  wallet = decrypted;
@@ -85974,7 +86151,7 @@ on the real adapter and the mock.
85974
86151
  **The walkthrough:**
85975
86152
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
85976
86153
  desktop browser; ${approvalPageLocation(d)}
85977
- 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THAT APPROVAL PAGE OPEN \u2014 the one\n whose QR you scanned: while a phone wallet is connected it is the READ-ONLY reader for\n every ceremony \u2014 it shows the full card, the phone shows only what a wallet can render,\n and you approve or decline in the phone. (Cancel still works from the page.) With no\n such page open, the phone is NOT asked to sign the opaque 32-byte hashes (loan and withdrawal\n envelopes) \u2014 those refuse, because a wallet shows them as a bare hash. Plain transactions and\n typed-data are not gated: the wallet decodes those itself." : ". " + phoneWalletOffer(d) + "."}
86154
+ 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code, then sign the short statement the wallet\n shows: it proves the wallet holds the address it reports, approves nothing and moves no\n funds, and without it the phone is not accepted. The proof needs an ordinary wallet account\n (EOA): a smart-contract or smart-account wallet cannot produce it, so it cannot connect\n here. KEEP THAT APPROVAL PAGE OPEN \u2014 the one\n whose QR you scanned: while a phone wallet is connected it is the READ-ONLY reader for\n every ceremony \u2014 it shows the full card, the phone shows only what a wallet can render,\n and you approve or decline in the phone. (Cancel still works from the page.) With no\n such page open, the phone is NOT asked to sign the opaque 32-byte hashes (loan and withdrawal\n envelopes) \u2014 those refuse, because a wallet shows them as a bare hash. Plain transactions and\n typed-data are not gated: the wallet decodes those itself." : ". " + phoneWalletOffer(d) + "."}
85978
86155
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
85979
86156
  login ceremony explicitly (one typed-data signature in the wallet).
85980
86157
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -86633,7 +86810,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
86633
86810
 
86634
86811
  // src/tools/loan.ts
86635
86812
  var import_zod = require("zod");
86636
- var import_ethers53 = require("ethers");
86813
+ var import_ethers54 = require("ethers");
86637
86814
 
86638
86815
  // src/util/format.ts
86639
86816
  function bigintReplacer(_key, value) {
@@ -86821,7 +86998,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86821
86998
  const b = getB();
86822
86999
  if (!b.ok) return renderError(b.error);
86823
87000
  return renderEnvelope(
86824
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers53.parseEther)(amountUcd.toString()).toString() })
87001
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers54.parseEther)(amountUcd.toString()).toString() })
86825
87002
  );
86826
87003
  })
86827
87004
  );
@@ -86859,7 +87036,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86859
87036
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
86860
87037
  amountUcdWei = detail.data.debtUcdWei;
86861
87038
  } else {
86862
- amountUcdWei = (0, import_ethers53.parseEther)(amountUcd.toString()).toString();
87039
+ amountUcdWei = (0, import_ethers54.parseEther)(amountUcd.toString()).toString();
86863
87040
  }
86864
87041
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
86865
87042
  })
@@ -87462,7 +87639,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
87462
87639
 
87463
87640
  // src/tools/signer.ts
87464
87641
  var import_zod6 = require("zod");
87465
- var import_ethers54 = require("ethers");
87642
+ var import_ethers55 = require("ethers");
87466
87643
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
87467
87644
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
87468
87645
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -87504,7 +87681,7 @@ function registerSignerTool(server, getRuntime, opts) {
87504
87681
  if (mode !== void 0 && !offeredModes.includes(mode)) {
87505
87682
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
87506
87683
  }
87507
- if (safeAddress !== void 0 && !import_ethers54.ethers.isAddress(safeAddress)) {
87684
+ if (safeAddress !== void 0 && !import_ethers55.ethers.isAddress(safeAddress)) {
87508
87685
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
87509
87686
  }
87510
87687
  if (action === "status") {
@@ -87920,7 +88097,7 @@ function registerBoundaryInfoResource(server, getB) {
87920
88097
  }
87921
88098
 
87922
88099
  // src/version.ts
87923
- var SERVER_VERSION = "0.5.21";
88100
+ var SERVER_VERSION = "0.5.23";
87924
88101
 
87925
88102
  // src/server.ts
87926
88103
  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.";