@gvnrdao/dh-mcp 0.5.21 → 0.5.22

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 = {
@@ -28308,7 +28308,7 @@ var require_lit_ops_module = __commonJS({
28308
28308
  async chipotleCreateWalletAndAddToGroup(accountApiKey) {
28309
28309
  const baseUrl = _LitOps.LIT_CORE_API_BASE;
28310
28310
  const createResp = await fetch(`${baseUrl}/create_wallet`, {
28311
- method: "GET",
28311
+ method: "POST",
28312
28312
  headers: {
28313
28313
  "X-Api-Key": accountApiKey
28314
28314
  }
@@ -40728,6 +40728,7 @@ __export(wc_transport_exports, {
40728
40728
  WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40729
40729
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
40730
40730
  WcTransport: () => WcTransport,
40731
+ guardRelayFatal: () => guardRelayFatal,
40731
40732
  newIsolatedCore: () => newIsolatedCore,
40732
40733
  wcSessionNamespaces: () => wcSessionNamespaces,
40733
40734
  withEip712DomainType: () => withEip712DomainType
@@ -40761,7 +40762,27 @@ function newIsolatedCore(cfg, label) {
40761
40762
  });
40762
40763
  return { core, scratch };
40763
40764
  }
40764
- var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40765
+ function guardRelayFatal(core, health, onFatal) {
40766
+ const relayer = core.relayer;
40767
+ const register = relayer.registerProviderListeners;
40768
+ if (typeof register !== "function") {
40769
+ throw new Error(
40770
+ "@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."
40771
+ );
40772
+ }
40773
+ const record = (e) => {
40774
+ if (health.fatal !== null) return;
40775
+ health.fatal = e.message;
40776
+ console.error(`[dh-mcp] WalletConnect relay failed fatally: ${e.message}`);
40777
+ onFatal(e.message);
40778
+ };
40779
+ relayer.on("relayer_error", record);
40780
+ relayer.registerProviderListeners = () => {
40781
+ register.call(relayer);
40782
+ relayer.provider.on("error", record);
40783
+ };
40784
+ }
40785
+ var import_core, import_sign_client, os, path3, import_node_fs, import_ethers50, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40765
40786
  var init_wc_transport = __esm({
40766
40787
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
40767
40788
  "use strict";
@@ -40770,6 +40791,7 @@ var init_wc_transport = __esm({
40770
40791
  os = __toESM(require("os"));
40771
40792
  path3 = __toESM(require("path"));
40772
40793
  import_node_fs = require("fs");
40794
+ import_ethers50 = require("ethers");
40773
40795
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
40774
40796
  WC_DAPP_METADATA = {
40775
40797
  name: "Diamond Hands MCP",
@@ -40779,11 +40801,14 @@ var init_wc_transport = __esm({
40779
40801
  };
40780
40802
  EVENTS = ["accountsChanged", "chainChanged"];
40781
40803
  WcTransport = class _WcTransport {
40782
- constructor(client, cfg, scratch) {
40804
+ constructor(client, cfg, scratch, health) {
40783
40805
  this.client = client;
40784
40806
  this.cfg = cfg;
40785
40807
  this.scratch = scratch;
40808
+ this.health = health;
40786
40809
  client.on("session_delete", ({ topic }) => {
40810
+ const pending = this.candidates.get(topic);
40811
+ if (pending) pending.deleted = true;
40787
40812
  if (this.session === null || this.session.topic !== topic) return;
40788
40813
  this.session = null;
40789
40814
  this.sessionListener?.(null);
@@ -40791,14 +40816,35 @@ var init_wc_transport = __esm({
40791
40816
  }
40792
40817
  session = null;
40793
40818
  sessionListener = null;
40819
+ /** Sessions announced but not yet adopted (awaiting a deferred verdict), by topic. */
40820
+ candidates = /* @__PURE__ */ new Map();
40794
40821
  static async create(cfg) {
40795
40822
  const { core, scratch } = newIsolatedCore(cfg, "dh-wc-dapp");
40823
+ const health = { fatal: null };
40824
+ let transport = null;
40825
+ guardRelayFatal(core, health, () => transport?.dropForFatal());
40796
40826
  const client = await import_sign_client.default.init({
40797
40827
  core,
40798
40828
  projectId: cfg.projectId,
40799
40829
  metadata: cfg.metadata ?? WC_DAPP_METADATA
40800
40830
  });
40801
- return new _WcTransport(client, cfg, scratch);
40831
+ transport = new _WcTransport(client, cfg, scratch, health);
40832
+ return transport;
40833
+ }
40834
+ /** The relay is gone for good: no adopted session may outlive it. Listeners hear a
40835
+ * disconnect, exactly as if the wallet had left. */
40836
+ dropForFatal() {
40837
+ if (this.session === null) return;
40838
+ this.session = null;
40839
+ void this.sessionListener?.(null);
40840
+ }
40841
+ /** Refuse to start new work over a relay that has failed fatally — naming why. */
40842
+ assertRelayHealthy() {
40843
+ if (this.health.fatal !== null) {
40844
+ throw new Error(
40845
+ `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`
40846
+ );
40847
+ }
40802
40848
  }
40803
40849
  /** Wallet-session state changes (connect/disconnect) — the bridge mirrors them. */
40804
40850
  onSession(cb) {
@@ -40809,6 +40855,7 @@ var init_wc_transport = __esm({
40809
40855
  }
40810
40856
  /** Create a pairing URI; resolves the session in the background when a wallet approves. */
40811
40857
  async createPairing() {
40858
+ this.assertRelayHealthy();
40812
40859
  const { uri, approval } = await this.client.connect({
40813
40860
  // sign-client 2.21 deprecates requiredNamespaces (auto-downgraded to optional).
40814
40861
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
@@ -40816,22 +40863,51 @@ var init_wc_transport = __esm({
40816
40863
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
40817
40864
  const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
40818
40865
  if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
40819
- void approval().then((session) => {
40866
+ let candidateTopic = null;
40867
+ void approval().then(async (session) => {
40820
40868
  const first = session.namespaces["eip155"]?.accounts[0];
40821
40869
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
40822
40870
  const [, chainIdStr, account] = first.split(":");
40871
+ candidateTopic = session.topic;
40872
+ const candidate = { topic: session.topic, account, chainId: Number(chainIdStr) };
40873
+ const prove = async (statement) => {
40874
+ this.assertRelayHealthy();
40875
+ return await this.client.request({
40876
+ topic: candidate.topic,
40877
+ chainId: `eip155:${candidate.chainId}`,
40878
+ request: { method: "personal_sign", params: [import_ethers50.ethers.hexlify(import_ethers50.ethers.toUtf8Bytes(statement)), candidate.account] }
40879
+ });
40880
+ };
40881
+ const state = { deleted: false };
40882
+ const live = () => !state.deleted && this.health.fatal === null;
40823
40883
  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) {
40884
+ this.session = candidate;
40885
+ this.candidates.set(candidate.topic, state);
40886
+ const verdict = this.sessionListener?.({ account: candidate.account, chainId: candidate.chainId, pairingId, prove, live });
40887
+ let adopted;
40888
+ if (verdict instanceof Promise) {
40827
40889
  this.session = previous;
40890
+ adopted = await verdict.finally(() => this.candidates.delete(candidate.topic)).then((v) => v !== false);
40891
+ if (adopted) this.session = candidate;
40892
+ } else {
40893
+ this.candidates.delete(candidate.topic);
40894
+ adopted = verdict !== false;
40895
+ if (!adopted) this.session = previous;
40896
+ }
40897
+ if (!adopted) {
40828
40898
  void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
40829
40899
  }
40830
- }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
40900
+ }).catch((e) => {
40901
+ console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`);
40902
+ if (candidateTopic !== null && this.session?.topic !== candidateTopic) {
40903
+ void this.client.disconnect({ topic: candidateTopic, reason: { code: 6e3, message: "session not adopted" } }).catch(() => void 0);
40904
+ }
40905
+ });
40831
40906
  return { uri, pairingId };
40832
40907
  }
40833
40908
  /** Route one wallet request over the active session. Throws on user rejection. */
40834
40909
  async request(method, params) {
40910
+ this.assertRelayHealthy();
40835
40911
  if (!this.session) throw new Error("no active WalletConnect session");
40836
40912
  return this.client.request({
40837
40913
  topic: this.session.topic,
@@ -41084,14 +41160,14 @@ function resolveRealConfig(env) {
41084
41160
 
41085
41161
  // src/boot.ts
41086
41162
  var fs6 = __toESM(require("fs"));
41087
- var import_ethers52 = require("ethers");
41163
+ var import_ethers53 = require("ethers");
41088
41164
 
41089
41165
  // src/boundary/index.ts
41090
41166
  var import_node_crypto8 = require("crypto");
41091
41167
  var fs5 = __toESM(require("fs"));
41092
41168
  var os2 = __toESM(require("os"));
41093
41169
  var path4 = __toESM(require("path"));
41094
- var import_ethers51 = require("ethers");
41170
+ var import_ethers52 = require("ethers");
41095
41171
 
41096
41172
  // src/boundary/envelope.ts
41097
41173
  function okEnvelope(data, source, warnings = []) {
@@ -83522,7 +83598,7 @@ var RealUpstreamPlugin = class {
83522
83598
  var fs4 = __toESM(require("fs"));
83523
83599
  var http3 = __toESM(require("http"));
83524
83600
  var import_node_crypto7 = require("crypto");
83525
- var import_ethers50 = require("ethers");
83601
+ var import_ethers51 = require("ethers");
83526
83602
 
83527
83603
  // src/util/brand-assets.ts
83528
83604
  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 +83723,7 @@ ${houseHeader("Diamond Hands \xB7 signature approval")}
83647
83723
  <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
83648
83724
  <div id="wc-qr" class="qr-plate hidden"></div>
83649
83725
  <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>
83726
+ <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
83727
  </div>
83652
83728
  </div>
83653
83729
  </main>
@@ -83994,7 +84070,7 @@ document.getElementById("wc-connect").onclick = async () => {
83994
84070
  qrEl.classList.remove("hidden");
83995
84071
  }
83996
84072
  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.");
84073
+ 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
84074
  };
83999
84075
 
84000
84076
  listen();
@@ -84106,7 +84182,6 @@ function htmlPageSecurityHeaders(extra) {
84106
84182
 
84107
84183
  // src/boundary/upstream/shared/external-bridge/bridge.ts
84108
84184
  var MAX_SESSIONS = 16;
84109
- var MAX_PENDING_PAIRINGS = 64;
84110
84185
  function presenceStatement(origin2, chainId, nonce) {
84111
84186
  return [
84112
84187
  "Diamond Hands approval page",
@@ -84116,6 +84191,13 @@ function presenceStatement(origin2, chainId, nonce) {
84116
84191
  `Session nonce: ${nonce}`
84117
84192
  ].join("\n");
84118
84193
  }
84194
+ function recoverPresenceSigner(statement, signature) {
84195
+ try {
84196
+ return import_ethers51.ethers.verifyMessage(statement, signature);
84197
+ } catch {
84198
+ return null;
84199
+ }
84200
+ }
84119
84201
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
84120
84202
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
84121
84203
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -84165,6 +84247,10 @@ var SignatureBridge = class {
84165
84247
  * "most recent asker" guess let a second session claim the credit for a QR the user's
84166
84248
  * phone scanned (Sentinel 2 PoC-B). */
84167
84249
  pairingOwners = /* @__PURE__ */ new Map();
84250
+ /** The page session the ADMITTED WalletConnect session's proof was made for — the one page
84251
+ * credited with `wcPaired`. The credit lasts exactly as long as that session: it moves when
84252
+ * another proven session replaces it and ends when the wallet disconnects. */
84253
+ wcCreditedSession = null;
84168
84254
  keystoreUnlock;
84169
84255
  unlockToken = null;
84170
84256
  unlockSession = null;
@@ -84653,46 +84739,16 @@ var SignatureBridge = class {
84653
84739
  const { WcTransport: WcTransport2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
84654
84740
  return WcTransport2.create(cfg);
84655
84741
  });
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
- });
84742
+ const transport = await factory2(this.wcConfig);
84743
+ this.wcTransport = transport;
84744
+ transport.onSession((info) => info === null ? this.onWcDisconnect() : this.admitWcSession(info, transport));
84687
84745
  }
84688
84746
  const { uri, pairingId } = await this.wcTransport.createPairing();
84689
84747
  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);
84748
+ for (const [pending, owner] of this.pairingOwners) {
84749
+ if (owner === askingSession || !this.sessions.has(owner)) this.pairingOwners.delete(pending);
84695
84750
  }
84751
+ this.pairingOwners.set(pairingId, askingSession);
84696
84752
  }
84697
84753
  const { default: qrcode } = await import("qrcode-generator");
84698
84754
  const qr = qrcode(0, "M");
@@ -84793,12 +84849,7 @@ var SignatureBridge = class {
84793
84849
  return;
84794
84850
  }
84795
84851
  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
- }
84852
+ const recovered = recoverPresenceSigner(statement, signature);
84802
84853
  if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
84803
84854
  this.deny(
84804
84855
  res,
@@ -84889,6 +84940,100 @@ var SignatureBridge = class {
84889
84940
  * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
84890
84941
  * false for them, and `unattendedReason` says plainly that the phone may already have
84891
84942
  * acted. */
84943
+ /**
84944
+ * C-47, the THIRD door: a wallet announced a WalletConnect session. `requestSignature`
84945
+ * PREFERS the WalletConnect wallet over the approval page (see the `wcActive` branch there),
84946
+ * so an account admitted here does not merely become the candidate — it becomes the SIGNER,
84947
+ * and the page that showed its QR becomes the page that sees every card.
84948
+ *
84949
+ * The account a WalletConnect session carries is the wallet's own UNSIGNED claim — the
84950
+ * protocol validates its format, never its ownership. Admitting on that claim let anyone
84951
+ * holding the approval link answer their own QR with a scripted wallet claiming the user's
84952
+ * public address: it took the signer seat, its page saw every card, and an extension-only
84953
+ * user's ceremonies were routed to it (Sentinel 2 PoC-D). So this door now asks for the same
84954
+ * proof `hello` does: the wallet signs the presence statement of the page whose QR it
84955
+ * answered, and the signature must recover to the account it claims.
84956
+ *
84957
+ * Resolves `false` to refuse — the transport then keeps what it held and drops the wallet. If
84958
+ * the wallet declines the proof (or the request fails) the promise rejects and the transport
84959
+ * ends the session unadopted; nothing here is adopted before the proof checks out.
84960
+ */
84961
+ async admitWcSession(info, transport) {
84962
+ const refusal = this.accountRefusal(info.account);
84963
+ if (refusal) return this.refuseWcSession(refusal);
84964
+ const ownerId = info.pairingId ? this.pairingOwners.get(info.pairingId) : void 0;
84965
+ if (info.pairingId) this.pairingOwners.delete(info.pairingId);
84966
+ const owner = ownerId ? this.sessions.get(ownerId) : void 0;
84967
+ if (!ownerId || !owner) {
84968
+ return this.refuseWcSession(
84969
+ "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"
84970
+ );
84971
+ }
84972
+ if (!info.prove || !info.live) {
84973
+ return this.refuseWcSession(
84974
+ "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"
84975
+ );
84976
+ }
84977
+ const statement = presenceStatement(this.publicOrigin(), info.chainId, owner.presenceNonce);
84978
+ const signature = await info.prove(statement);
84979
+ const recovered = recoverPresenceSigner(statement, signature);
84980
+ if (recovered === null || recovered.toLowerCase() !== info.account.toLowerCase()) {
84981
+ return this.refuseWcSession(
84982
+ `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`
84983
+ );
84984
+ }
84985
+ if (this.wcTransport !== transport) {
84986
+ return this.refuseWcSession("the bridge's WalletConnect connection was replaced while the wallet was proving its account");
84987
+ }
84988
+ if (!info.live()) {
84989
+ return this.refuseWcSession("the wallet's WalletConnect session ended (or the relay failed) while it was proving its account \u2014 scan the QR again");
84990
+ }
84991
+ const lateRefusal = this.accountRefusal(info.account);
84992
+ if (lateRefusal) return this.refuseWcSession(lateRefusal);
84993
+ const page = this.sessions.get(ownerId);
84994
+ if (!page || page.refused) {
84995
+ 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");
84996
+ }
84997
+ if (this.wcCreditedSession !== null && this.wcCreditedSession !== ownerId) {
84998
+ const previous = this.sessions.get(this.wcCreditedSession);
84999
+ if (previous) previous.wcPaired = false;
85000
+ }
85001
+ this.wcActive = true;
85002
+ this.wallet = { account: info.account, chainId: info.chainId };
85003
+ page.wcPaired = true;
85004
+ page.provenAccount = info.account;
85005
+ this.wcCreditedSession = ownerId;
85006
+ this.replayPending(page);
85007
+ return true;
85008
+ }
85009
+ /** Refuse a WalletConnect session — see `admitWcSession`. */
85010
+ refuseWcSession(reason) {
85011
+ if (!this.wcActive) {
85012
+ this.rebuildSharedWallet();
85013
+ this.demoteWcEntries();
85014
+ }
85015
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${reason}
85016
+ `);
85017
+ return false;
85018
+ }
85019
+ /** The admitted WalletConnect wallet went away. */
85020
+ onWcDisconnect() {
85021
+ this.wcActive = false;
85022
+ this.wallet = null;
85023
+ for (const entry of this.pending.values()) {
85024
+ if (!entry.settled && !entry.collect) {
85025
+ this.settle(entry, {
85026
+ status: "invalidated",
85027
+ 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"
85028
+ });
85029
+ }
85030
+ }
85031
+ if (this.wcCreditedSession !== null) {
85032
+ const credited = this.sessions.get(this.wcCreditedSession);
85033
+ if (credited) credited.wcPaired = false;
85034
+ this.wcCreditedSession = null;
85035
+ }
85036
+ }
84892
85037
  demoteWcEntries() {
84893
85038
  for (const entry of this.pending.values()) {
84894
85039
  if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
@@ -85397,7 +85542,7 @@ async function createRealBoundary(config, wallet, overrides) {
85397
85542
  const manager = new SignerManager({
85398
85543
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
85399
85544
  initialMode,
85400
- ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers51.ethers.getAddress(overrides.boundBorrower) } : {},
85545
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers52.ethers.getAddress(overrides.boundBorrower) } : {},
85401
85546
  candidate: () => bridge.walletState()?.account ?? null,
85402
85547
  pendingCeremonies: () => bridge.pendingCount(),
85403
85548
  keystore
@@ -85493,8 +85638,8 @@ async function buildBoundary(configResult, overrides) {
85493
85638
  );
85494
85639
  }
85495
85640
  try {
85496
- const decrypted = await import_ethers52.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85497
- if (!(decrypted instanceof import_ethers52.ethers.Wallet)) {
85641
+ const decrypted = await import_ethers53.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85642
+ if (!(decrypted instanceof import_ethers53.ethers.Wallet)) {
85498
85643
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
85499
85644
  }
85500
85645
  wallet = decrypted;
@@ -85974,7 +86119,7 @@ on the real adapter and the mock.
85974
86119
  **The walkthrough:**
85975
86120
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
85976
86121
  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) + "."}
86122
+ 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
86123
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
85979
86124
  login ceremony explicitly (one typed-data signature in the wallet).
85980
86125
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -86633,7 +86778,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
86633
86778
 
86634
86779
  // src/tools/loan.ts
86635
86780
  var import_zod = require("zod");
86636
- var import_ethers53 = require("ethers");
86781
+ var import_ethers54 = require("ethers");
86637
86782
 
86638
86783
  // src/util/format.ts
86639
86784
  function bigintReplacer(_key, value) {
@@ -86821,7 +86966,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86821
86966
  const b = getB();
86822
86967
  if (!b.ok) return renderError(b.error);
86823
86968
  return renderEnvelope(
86824
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers53.parseEther)(amountUcd.toString()).toString() })
86969
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers54.parseEther)(amountUcd.toString()).toString() })
86825
86970
  );
86826
86971
  })
86827
86972
  );
@@ -86859,7 +87004,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86859
87004
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
86860
87005
  amountUcdWei = detail.data.debtUcdWei;
86861
87006
  } else {
86862
- amountUcdWei = (0, import_ethers53.parseEther)(amountUcd.toString()).toString();
87007
+ amountUcdWei = (0, import_ethers54.parseEther)(amountUcd.toString()).toString();
86863
87008
  }
86864
87009
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
86865
87010
  })
@@ -87462,7 +87607,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
87462
87607
 
87463
87608
  // src/tools/signer.ts
87464
87609
  var import_zod6 = require("zod");
87465
- var import_ethers54 = require("ethers");
87610
+ var import_ethers55 = require("ethers");
87466
87611
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
87467
87612
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
87468
87613
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -87504,7 +87649,7 @@ function registerSignerTool(server, getRuntime, opts) {
87504
87649
  if (mode !== void 0 && !offeredModes.includes(mode)) {
87505
87650
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
87506
87651
  }
87507
- if (safeAddress !== void 0 && !import_ethers54.ethers.isAddress(safeAddress)) {
87652
+ if (safeAddress !== void 0 && !import_ethers55.ethers.isAddress(safeAddress)) {
87508
87653
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
87509
87654
  }
87510
87655
  if (action === "status") {
@@ -87920,7 +88065,7 @@ function registerBoundaryInfoResource(server, getB) {
87920
88065
  }
87921
88066
 
87922
88067
  // src/version.ts
87923
- var SERVER_VERSION = "0.5.21";
88068
+ var SERVER_VERSION = "0.5.22";
87924
88069
 
87925
88070
  // src/server.ts
87926
88071
  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.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gvnrdao/dh-mcp",
3
- "version": "0.5.21",
3
+ "version": "0.5.22",
4
4
  "description": "MCP server for the Diamond Hands protocol",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -55,7 +55,7 @@
55
55
  "devDependencies": {
56
56
  "@anthropic-ai/mcpb": "2.1.2",
57
57
  "@google-cloud/firestore": "9.3.1",
58
- "@gvnrdao/dh-sdk": "^0.0.344",
58
+ "@gvnrdao/dh-sdk": "^0.0.345",
59
59
  "@types/express": "5.0.3",
60
60
  "@types/jest": "29.5.12",
61
61
  "@types/node": "20.14.10",