@gvnrdao/dh-mcp 0.5.12 → 0.5.14

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
@@ -41574,6 +41574,22 @@ var BoundaryCore = class {
41574
41574
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41575
41575
  return okEnvelope({ releasedSats: r.value.releasedSats }, r.source);
41576
41576
  }
41577
+ /** C-46. Unlike `recoverStaleSpend` this is NOT permissionless: re-running phase 2 signs
41578
+ * for the vault, so it takes the same borrower gate every fund-moving op takes. */
41579
+ async retryWithdrawExecute(p) {
41580
+ const auth = await this.requireBorrower();
41581
+ if (!auth.ok) return errEnvelope(auth.error);
41582
+ const r = await this.deps.plugin.ops.retryWithdrawExecute({
41583
+ positionId: p.positionId,
41584
+ networkFeeSats: p.networkFeeSats,
41585
+ borrower: auth.borrower
41586
+ });
41587
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
41588
+ return okEnvelope(
41589
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41590
+ r.source
41591
+ );
41592
+ }
41577
41593
  // ---- meta ----
41578
41594
  world() {
41579
41595
  return {
@@ -42397,6 +42413,78 @@ var World = class {
42397
42413
  c.authorizedSpends.splice(idx, 1);
42398
42414
  return { ok: true, value: { releasedSats: spend.satoshis } };
42399
42415
  }
42416
+ /**
42417
+ * C-46: re-run the withdrawal EXECUTE leg for reservations whose coins have not been
42418
+ * observed moving (`consumed === null`). This is the stranded shape: phase 1 committed
42419
+ * the reservation, phase 2's quantum-stamped signature expired, and the outpoint was
42420
+ * never spent.
42421
+ *
42422
+ * The retry BROADCASTS; it does not observe. `consumed` therefore stays null — that flag
42423
+ * means "seen consumed on Bitcoin", and only MockControl.confirmSpendConsumed (standing
42424
+ * in for the chain) may set it. Conflating the two would let a retry release collateral
42425
+ * against a transaction no one has confirmed, which is the mistake the whole
42426
+ * proof-of-consumption design exists to prevent. So a retry leaves the reservation
42427
+ * holding its balance exactly as before; what it produces is the txid that can LATER
42428
+ * become the invalidator — the proof the stranded state could never generate for itself.
42429
+ */
42430
+ retryWithdrawExecute(p) {
42431
+ const paused = this.pausedReason();
42432
+ if (paused) return { ok: false, reason: paused };
42433
+ const pos = this.state.positions[p.positionId];
42434
+ if (!pos) return { ok: false, reason: `position ${p.positionId} does not exist` };
42435
+ if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42436
+ return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42437
+ }
42438
+ const fee = BigInt(p.networkFeeSats);
42439
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
42440
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
42441
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
42442
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
42443
+ const { hash: txid } = this.nextId("btc-withdraw-retry");
42444
+ return {
42445
+ utxoIdentifier,
42446
+ ok: true,
42447
+ txid,
42448
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
42449
+ // the authorized amount, never added on top — the same semantics `withdraw` above
42450
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
42451
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
42452
+ // whether the fee was honoured at all.
42453
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
42454
+ destination: spend.targetAddress
42455
+ };
42456
+ });
42457
+ return { ok: true, value: { attempted: transfers.length, transfers } };
42458
+ }
42459
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
42460
+ pendingSpends(positionId) {
42461
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42462
+ }
42463
+ /**
42464
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
42465
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
42466
+ *
42467
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
42468
+ *
42469
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
42470
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
42471
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
42472
+ */
42473
+ retryFeeRefusal(spend, networkFeeSats) {
42474
+ const target = BigInt(spend.satoshis);
42475
+ if (BigInt(networkFeeSats) * 2n >= target) {
42476
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
42477
+ }
42478
+ return null;
42479
+ }
42480
+ /**
42481
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
42482
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
42483
+ * wallet is never opened — which is what the mock's ceremony gate reads.
42484
+ */
42485
+ retryExecutableCount(positionId, networkFeeSats) {
42486
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
42487
+ }
42400
42488
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42401
42489
  safesMap() {
42402
42490
  return this.state.safes;
@@ -43582,7 +43670,8 @@ var MockUpstreamPlugin = class {
43582
43670
  const r = this.world.recoverStaleSpend(p);
43583
43671
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43584
43672
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43585
- })
43673
+ }),
43674
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43586
43675
  };
43587
43676
  }
43588
43677
  indexer;
@@ -43857,6 +43946,46 @@ var MockUpstreamPlugin = class {
43857
43946
  );
43858
43947
  });
43859
43948
  }
43949
+ /**
43950
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
43951
+ *
43952
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
43953
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
43954
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
43955
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
43956
+ * passing requests the real protocol would refuse, which is the one thing a practice world
43957
+ * must never do.
43958
+ *
43959
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
43960
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
43961
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
43962
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
43963
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
43964
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
43965
+ */
43966
+ async opRetryWithdrawExecute(p) {
43967
+ const none = this.noneRefusal();
43968
+ if (none) return none;
43969
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
43970
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
43971
+ const cer = executable > 0 ? this.ceremonyNow() : null;
43972
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
43973
+ if (auth && !auth.ok) return auth.failure;
43974
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
43975
+ return this.write("retryWithdrawExecute", () => {
43976
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
43977
+ if (sig && !sig.ok) return sig.failure;
43978
+ const r = this.applyAuthorized(
43979
+ sig ? sig.authorization : void 0,
43980
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
43981
+ );
43982
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43983
+ return upOk(
43984
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
43985
+ this.src("mock-ops")
43986
+ );
43987
+ });
43988
+ }
43860
43989
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43861
43990
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43862
43991
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -51821,13 +51950,13 @@ var init_deployment_addresses = __esm2({
51821
51950
  block: 25472956
51822
51951
  },
51823
51952
  BTCSpendAuthorizer: {
51824
- previousImplementation: "0xb003ed89F695E8819a85513fE17260b805B3c478",
51825
- newImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51826
- upgradedAt: "2026-07-06T10:40:59.000Z",
51827
- upgradedBy: "AdminModule/Safe audit-batch upgradeToAndCall; executed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f in tx 0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281 (block 25472957)",
51828
- reason: "Reconciled from chain \u2014 mainnet audit rollout batch (cross-ref onchain-auth/.safe-batches/mainnet-audit-execute.json)",
51829
- executeTx: "0xe1b1884a7e76c7fd569522545a04e49d5128d83d27b3892cda59f143b53b5281",
51830
- block: 25472957
51953
+ previousImplementation: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
51954
+ newImplementation: "0x00D7a47798E8ff169104b748131703B78f23390C",
51955
+ upgradedAt: "2026-09-09T12:05:35.000Z",
51956
+ upgradedBy: "AdminModule generic op 0xc0214ff38bb454864a34f6482dcd03570b3fd04171c84be2c20184afb1a2e161 (bsa-1-7-0 ceremony: proposed by seat 0x3030C0414B6d95aA9d5A57269E51a347fCBaB472 2026-09-08T11:35:23Z, 3/3 seat signatures, 24h timelock); executeGenericAdminOperation sent by 0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6 in tx 0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c (block 25939703)",
51957
+ reason: "BTCSpendAuthorizer 1.6.0 -> 1.7.0: allow a full-vault sweep (targetAmount == satoshis); TargetMustLeaveFeeRoom -> TargetExceedsInputValue (PR #849; mainnet incidents 2026-09-04 and 2026-09-07). Impl deployed by 0xEba7BfAeB35ee18408b424Ee0BB45AdDf776589f at nonce 430 from source 0a7c535a1 (contracts/src identical to main 99b335f77). Cross-ref onchain-auth/.safe-batches/mainnet-bsa-1-7-0-{propose,sign,execute}.json and docs/mainnet-bsa-1-7-0-ceremony-2026-09-08.md",
51958
+ executeTx: "0x77cd231966c546177bd8f1a07bd4e705afd5c2dfbd110b096836401679c0c69c",
51959
+ block: 25939703
51831
51960
  },
51832
51961
  PositionManager: {
51833
51962
  previousImplementation: "0x600Dc0D1C2c0F94882B6Bc09172f8650047Ad5B1",
@@ -51930,7 +52059,7 @@ var init_deployment_addresses = __esm2({
51930
52059
  ADMIN_MODULE: "0x0023B71B586795eE5fa4E83E384345C1EC8Bb946",
51931
52060
  ADMIN_MODULE_IMPL: "0xb4C5C7E051A1e672F014B25CB5D55B225Aa0D512",
51932
52061
  BTC_SPEND_AUTHORIZER: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
51933
- BTC_SPEND_AUTHORIZER_IMPL: "0x40c9e8C46C65E0A57BB63da5368868A9E8Df81A5",
52062
+ BTC_SPEND_AUTHORIZER_IMPL: "0x00D7a47798E8ff169104b748131703B78f23390C",
51934
52063
  POSITION_MANAGER_VIEWS: "0x8B57954eA338c6A6bfF1457f71080e25baFF3937",
51935
52064
  POSITION_MANAGER_VIEWS_IMPL: "0xE68DC096A65Ecddbc6A9b5c6e5f878e2CE143Bfe",
51936
52065
  POSITION_MANAGER: "0x12A1836e56139ccaD8722B89519d84233efc224B",
@@ -58000,9 +58129,27 @@ var LOGIN_TYPES_WITH_AUDIENCE2 = {
58000
58129
  { name: "audience", type: "string" }
58001
58130
  ]
58002
58131
  };
58003
- async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
58132
+ var LOGIN_TYPES_WITH_STATEMENT = {
58133
+ DiamondHands: [
58134
+ { name: "statement", type: "string" },
58135
+ { name: "address", type: "address" },
58136
+ { name: "issuedAt", type: "uint256" },
58137
+ { name: "nonce", type: "bytes32" },
58138
+ { name: "audience", type: "string" }
58139
+ ]
58140
+ };
58141
+ var LOGIN_STATEMENT_TEMPLATE = "{host} is verifying you own this wallet. Signing proves control of the address so we can show your loans and positions. It authorizes no transaction, moves no funds, and costs no gas.";
58142
+ function canonicalLoginStatement(audience) {
58143
+ const host = /^https?:\/\/([^/?#]+)/i.exec(audience)?.[1];
58144
+ if (!host)
58145
+ return null;
58146
+ return LOGIN_STATEMENT_TEMPLATE.replace("{host}", host);
58147
+ }
58148
+ async function buildSignedLoginPayload(signer, chainId, audience, reuse, withStatement = false) {
58004
58149
  const address = await signer.getAddress();
58150
+ const statement = withStatement && audience ? canonicalLoginStatement(audience) : null;
58005
58151
  const message = {
58152
+ ...statement ? { statement } : {},
58006
58153
  address,
58007
58154
  issuedAt: reuse?.issuedAt ?? Math.floor(Date.now() / 1e3),
58008
58155
  nonce: reuse?.nonce ?? (0, import_ethers17.hexlify)((0, import_ethers17.randomBytes)(32)),
@@ -58010,7 +58157,7 @@ async function buildSignedLoginPayload(signer, chainId, audience, reuse) {
58010
58157
  };
58011
58158
  const signature = await signer.signTypedData(
58012
58159
  buildLoginDomain(chainId),
58013
- audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
58160
+ statement ? LOGIN_TYPES_WITH_STATEMENT : audience ? LOGIN_TYPES_WITH_AUDIENCE2 : LOGIN_TYPES2,
58014
58161
  message
58015
58162
  );
58016
58163
  return { chainId, message, signature };
@@ -58179,6 +58326,8 @@ var ServerSession = class {
58179
58326
  signer;
58180
58327
  serviceEndpoint;
58181
58328
  loginAudience;
58329
+ /** Whether this session's login carries the human-readable statement. */
58330
+ withStatement;
58182
58331
  chainId;
58183
58332
  store;
58184
58333
  onSignaturePrompt;
@@ -58220,6 +58369,13 @@ var ServerSession = class {
58220
58369
  /\/+$/,
58221
58370
  ""
58222
58371
  );
58372
+ const explicitAudience = typeof opts.loginAudience === "string" && opts.loginAudience.length > 0;
58373
+ this.withStatement = opts.withStatement === true && explicitAudience;
58374
+ if (opts.withStatement === true && !explicitAudience) {
58375
+ console.warn(
58376
+ "[dh-sdk] withStatement ignored: it requires an explicit loginAudience, since the servers rebuild the expected sentence from the audience host"
58377
+ );
58378
+ }
58223
58379
  this.chainId = opts.chainId;
58224
58380
  this.store = opts.persistSession === false ? null : opts.sessionStore ?? createDefaultSessionStore();
58225
58381
  this.onSignaturePrompt = opts.onSignaturePrompt;
@@ -58473,12 +58629,16 @@ var ServerSession = class {
58473
58629
  this.signer,
58474
58630
  this.chainId,
58475
58631
  this.loginAudience,
58476
- reuse
58632
+ reuse,
58633
+ reuse ? reuse.withStatement === true : this.withStatement
58477
58634
  );
58478
58635
  if (storeKey && !reuse) {
58479
58636
  store.savePending?.(storeKey, {
58480
58637
  issuedAt: payload.message.issuedAt,
58481
- nonce: payload.message.nonce
58638
+ nonce: payload.message.nonce,
58639
+ // Recorded so a resume reproduces this digest even if the
58640
+ // capability flag changes before the owners finish signing.
58641
+ withStatement: this.withStatement
58482
58642
  });
58483
58643
  }
58484
58644
  session = await this.login(payload);
@@ -70689,6 +70849,9 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
70689
70849
  signer: config.authSigner ?? config.contractSigner,
70690
70850
  serviceEndpoint: config.serviceEndpoint,
70691
70851
  loginAudience: config.loginAudience,
70852
+ // Only meaningful alongside an audience; the servers derive the expected
70853
+ // sentence from its host. Defaults off so Node callers are untouched.
70854
+ withStatement: config.loginStatement === true,
70692
70855
  chainId: config.chainId,
70693
70856
  persistSession: config.sessionPersistence?.enabled,
70694
70857
  sessionStore: config.sessionPersistence?.store,
@@ -79534,7 +79697,33 @@ function buildWriteOps(deps) {
79534
79697
  kind: "unavailable",
79535
79698
  source: SOURCE5,
79536
79699
  message: "recoverStaleSpend is not wired in this delivery (permissionless recovery \u2014 planned follow-up)."
79537
- })
79700
+ }),
79701
+ retryWithdrawExecute: async (p) => {
79702
+ const sdk = deps.getWriteSdk();
79703
+ if (!sdk) return upFail({ kind: "unavailable", source: SOURCE5, message: "write SDK is not initialized (its boot-time construction failed)" });
79704
+ let rows;
79705
+ try {
79706
+ rows = await sdk.executePendingBtcTransfers(p.positionId, p.networkFeeSats);
79707
+ } catch (e) {
79708
+ return failed("retryWithdrawExecute", e);
79709
+ }
79710
+ const gate = rows.find((r) => !r.success && !r.utxoIdentifier);
79711
+ if (gate) return declined("retryWithdrawExecute", gate.error ?? "pending-transfer execution refused before any reservation was attempted");
79712
+ return upOk(
79713
+ {
79714
+ attempted: rows.length,
79715
+ transfers: rows.map((r) => ({
79716
+ utxoIdentifier: r.utxoIdentifier ?? "",
79717
+ ok: r.success,
79718
+ ...r.txid ? { txid: r.txid } : {},
79719
+ ...r.amountSent !== void 0 ? { amountSentSats: String(r.amountSent) } : {},
79720
+ ...r.destination ? { destination: r.destination } : {},
79721
+ ...r.error ? { error: r.error } : {}
79722
+ }))
79723
+ },
79724
+ { id: SOURCE5, kind: "lit-ops", fetchedAt: (/* @__PURE__ */ new Date()).toISOString() }
79725
+ );
79726
+ }
79538
79727
  };
79539
79728
  }
79540
79729
 
@@ -80059,7 +80248,8 @@ var RealUpstreamPlugin = class {
80059
80248
  message: "no signer configured \u2014 psmSwap signs two on-chain transactions (exact-amount approve, then swap/redeem) with the keystore signer. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
80060
80249
  })
80061
80250
  ),
80062
- recoverStaleSpend: () => readOnly("recoverStaleSpend")
80251
+ recoverStaleSpend: () => readOnly("recoverStaleSpend"),
80252
+ retryWithdrawExecute: () => readOnly("retryWithdrawExecute")
80063
80253
  };
80064
80254
  }
80065
80255
  }
@@ -80227,7 +80417,8 @@ var RealUpstreamPlugin = class {
80227
80417
  psmSwap: call("psmSwap"),
80228
80418
  delegationSetup: call("delegationSetup"),
80229
80419
  delegationGrant: call("delegationGrant"),
80230
- recoverStaleSpend: call("recoverStaleSpend")
80420
+ recoverStaleSpend: call("recoverStaleSpend"),
80421
+ retryWithdrawExecute: call("retryWithdrawExecute")
80231
80422
  };
80232
80423
  }
80233
80424
  async resolveOpsGateway() {
@@ -81066,6 +81257,9 @@ function wcDeclineOrFault(e) {
81066
81257
  }
81067
81258
  var SignatureBridge = class {
81068
81259
  clock;
81260
+ /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
81261
+ * differs between what SIWE signs and what a wallet reports for the SAME address. */
81262
+ boundAccount;
81069
81263
  expiryMs;
81070
81264
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81071
81265
  maxPending;
@@ -81101,6 +81295,7 @@ var SignatureBridge = class {
81101
81295
  unlockSession = null;
81102
81296
  constructor(opts) {
81103
81297
  this.clock = opts?.clock ?? Date.now;
81298
+ this.boundAccount = opts?.boundAccount?.toLowerCase();
81104
81299
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
81105
81300
  this.maxPending = opts?.maxPending ?? null;
81106
81301
  this.attachGraceMs = opts?.attachGraceMs ?? (opts?.mount ? DEFAULT_HOSTED_ATTACH_GRACE_MS : DEFAULT_ATTACH_GRACE_MS);
@@ -81182,7 +81377,7 @@ var SignatureBridge = class {
81182
81377
  connectedAccounts() {
81183
81378
  const seen = /* @__PURE__ */ new Map();
81184
81379
  for (const s of this.sessions.values()) {
81185
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81380
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81186
81381
  }
81187
81382
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
81188
81383
  return [...seen.values()];
@@ -81443,7 +81638,7 @@ var SignatureBridge = class {
81443
81638
  return;
81444
81639
  }
81445
81640
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81446
- this.sessions.set(sessionId, { wallet: null, sse: null });
81641
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81447
81642
  const page = htmlPageSecurityHeaders();
81448
81643
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81449
81644
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81470,6 +81665,14 @@ var SignatureBridge = class {
81470
81665
  });
81471
81666
  this.wcTransport = await factory2(this.wcConfig);
81472
81667
  this.wcTransport.onSession((info) => {
81668
+ const refusal = info ? this.accountRefusal(info.account) : null;
81669
+ if (info && refusal) {
81670
+ this.wcActive = false;
81671
+ this.rebuildSharedWallet();
81672
+ process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81673
+ `);
81674
+ return;
81675
+ }
81473
81676
  this.wcActive = info !== null;
81474
81677
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
81475
81678
  if (info === null) {
@@ -81567,10 +81770,37 @@ var SignatureBridge = class {
81567
81770
  this.deny(res, 400, "hello requires account (0x address) and integer chainId");
81568
81771
  return;
81569
81772
  }
81773
+ const refusal = this.accountRefusal(account);
81774
+ if (refusal) {
81775
+ this.quarantine(session, refusal);
81776
+ this.deny(res, 403, refusal);
81777
+ return;
81778
+ }
81570
81779
  session.wallet = { account, chainId };
81571
81780
  this.wallet = { account, chainId };
81572
81781
  this.ok(res);
81573
81782
  }
81783
+ /** C-47: the single predicate every wallet account is admitted through. There are THREE
81784
+ * doors into the account this bridge will sign with — `hello`, `accountsChanged`, and the
81785
+ * WalletConnect `onSession` callback — and all three call this. The first version of this
81786
+ * fix guarded only the first two while this docstring already claimed to be "the single
81787
+ * place", which is how the WC door survived a green suite: the claim was in prose, not in a
81788
+ * test. T-EXT-BIND-01/02/04 now pin one door each, so adding a fourth writer of
81789
+ * `this.wallet` without coming through here fails a test rather than a review.
81790
+ *
81791
+ * Returns the refusal reason, or
81792
+ * null when the account may be adopted.
81793
+ *
81794
+ * Both addresses are named because the pre-fix failure surfaced much later as an opaque
81795
+ * signature-recovery error (`external-eoa.ts:230-233`) that named neither and read as a
81796
+ * wallet fault. A user with several accounts in one wallet extension hits this by
81797
+ * accident far more often than any attacker does, and "wrong account" is only actionable
81798
+ * if it says WHICH. */
81799
+ accountRefusal(account) {
81800
+ if (!this.boundAccount) return null;
81801
+ if (account.toLowerCase() === this.boundAccount) return null;
81802
+ return `this session is signed in as ${this.boundAccount} but the wallet offered ${account.toLowerCase()} \u2014 the account that signs must be the account that signed in. Switch your wallet to the signed-in account, or start a new session with this one.`;
81803
+ }
81574
81804
  /** accountsChanged / chainChanged: a wallet-state CHANGE mid-request invalidates every
81575
81805
  * pending request — what the human saw approved is no longer what would sign. Wallets
81576
81806
  * also deliver late no-op echoes of these events; an unchanged state invalidates nothing. */
@@ -81580,16 +81810,23 @@ var SignatureBridge = class {
81580
81810
  const account = String(body["account"] ?? "");
81581
81811
  const chainId = Number(body["chainId"]);
81582
81812
  const prev = session.wallet;
81583
- session.wallet = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81584
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81585
- this.wallet = session.wallet;
81813
+ const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81814
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
81815
+ const refusedSwitch = switchRefusal !== null;
81816
+ if (refusedSwitch) {
81817
+ this.quarantine(session, switchRefusal);
81818
+ } else {
81819
+ session.wallet = offered;
81820
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81821
+ this.wallet = session.wallet;
81822
+ }
81586
81823
  }
81587
81824
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81588
81825
  if (unchanged) {
81589
81826
  this.ok(res);
81590
81827
  return;
81591
81828
  }
81592
- const reason = prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
81829
+ const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
81593
81830
  for (const entry of this.pending.values()) {
81594
81831
  if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
81595
81832
  }
@@ -81679,7 +81916,7 @@ var SignatureBridge = class {
81679
81916
  const data = `data: ${JSON.stringify(request)}
81680
81917
 
81681
81918
  `;
81682
- for (const s of this.sessions.values()) s.sse?.write(data);
81919
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81683
81920
  }
81684
81921
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81685
81922
  pushProgress(payload) {
@@ -81687,7 +81924,48 @@ var SignatureBridge = class {
81687
81924
  data: ${JSON.stringify(payload)}
81688
81925
 
81689
81926
  `;
81690
- for (const s of this.sessions.values()) s.sse?.write(data);
81927
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81928
+ }
81929
+ /**
81930
+ * C-47: `this.wallet` is DERIVED, never guessed.
81931
+ *
81932
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
81933
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
81934
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
81935
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
81936
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
81937
+ * wrong account into a disconnect for the legitimate user.
81938
+ *
81939
+ * Deriving it from live state removes the guess. Preference order matches
81940
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
81941
+ */
81942
+ rebuildSharedWallet() {
81943
+ if (this.wcActive && this.wcTransport) {
81944
+ const wc = this.wcTransport.active();
81945
+ if (wc && !this.accountRefusal(wc.account)) {
81946
+ this.wallet = { account: wc.account, chainId: wc.chainId };
81947
+ return;
81948
+ }
81949
+ }
81950
+ let latest = null;
81951
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
81952
+ this.wallet = latest;
81953
+ }
81954
+ /**
81955
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
81956
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
81957
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
81958
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
81959
+ * stream, and re-derive the shared view without it.
81960
+ */
81961
+ quarantine(session, reason) {
81962
+ session.refused = reason;
81963
+ session.wallet = null;
81964
+ if (session.sse) {
81965
+ session.sse.end();
81966
+ session.sse = null;
81967
+ }
81968
+ this.rebuildSharedWallet();
81691
81969
  }
81692
81970
  sessionOf(candidate, res) {
81693
81971
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81695,6 +81973,10 @@ data: ${JSON.stringify(payload)}
81695
81973
  this.deny(res, 403, "missing or wrong session");
81696
81974
  return null;
81697
81975
  }
81976
+ if (session.refused) {
81977
+ this.deny(res, 403, session.refused);
81978
+ return null;
81979
+ }
81698
81980
  return session;
81699
81981
  }
81700
81982
  checkSession(candidate, res) {
@@ -81899,6 +82181,11 @@ async function createRealBoundary(config, wallet, overrides) {
81899
82181
  // tenant — one bridge per tenant world, so the bridge cap IS the tenant cap. The
81900
82182
  // loopback tier keeps its unbounded pending (multi-owner Safe pages need it).
81901
82183
  ...overrides?.bridgeMount ? { mount: overrides.bridgeMount(config.network), maxPending: 1 } : {},
82184
+ // C-47: the authenticated identity governs the write path. Passed separately from
82185
+ // `bridgeMount` although the hosted tier sets both — they answer different questions
82186
+ // ("where does the page live" vs "whose wallet may sign"), and fusing them would make
82187
+ // an unbound hosted bridge impossible to express in a test.
82188
+ ...overrides?.boundBorrower ? { boundAccount: overrides.boundBorrower } : {},
81902
82189
  // M12-12: no unlock closures without a provider — the unlock endpoints answer with
81903
82190
  // their loud not-wired refusal instead of ever touching key material.
81904
82191
  ...keystore ? {
@@ -82175,6 +82462,32 @@ function offers(d, mode) {
82175
82462
  function signerModeSourceClause(d) {
82176
82463
  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`";
82177
82464
  }
82465
+ function phoneWalletOffer(d) {
82466
+ return d.walletConnect ? "or scan the WalletConnect QR (or paste the pairing code) to approve on a phone wallet" : "This deployment does NOT offer the WalletConnect phone-wallet leg \u2014 there is no QR to scan and `/wc-pairing` answers 404; a browser-extension wallet is the only path here";
82467
+ }
82468
+ function moneyTruth(d) {
82469
+ const practice = offers(d, "mock-simulated");
82470
+ const sepolia = d.networks.includes("sepolia");
82471
+ const mainnet = d.networks.includes("mainnet");
82472
+ const cases = [];
82473
+ if (practice) cases.push("- Adapter `mock` \u2014 a PRACTICE sandbox. No real money anywhere.");
82474
+ if (sepolia) {
82475
+ cases.push(
82476
+ "- Adapter `real` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on\n the test network: real ceremonies and signatures, PRACTICE money (test funds)."
82477
+ );
82478
+ }
82479
+ if (mainnet) cases.push("- Adapter `real` on MAINNET \u2014 REAL MONEY.");
82480
+ const gate = "Writes are enabled on every build; what stops one is having no signing identity connected\nyet \u2014 `signer_setup` is how that is fixed, and every fund movement still needs the user's\nown wallet signature AND `confirmed: true`.";
82481
+ if (cases.length === 1) {
82482
+ const only = mainnet && !sepolia && !practice ? "This deployment serves MAINNET ONLY \u2014 every fund-moving operation here spends REAL MONEY,\nand there is no practice network on it to fall back to." : `This deployment serves exactly one world:
82483
+ ${cases[0]}`;
82484
+ return `${only}
82485
+ ${gate}`;
82486
+ }
82487
+ return `The money truth on this deployment has ${cases.length === 2 ? "TWO" : "THREE"} cases:
82488
+ ${cases.join("\n")}
82489
+ ${gate}`;
82490
+ }
82178
82491
  var LOCAL_GUIDE_DEPLOYMENT = {
82179
82492
  tier: "local",
82180
82493
  networks: ["sepolia", "mainnet"],
@@ -82182,7 +82495,13 @@ var LOCAL_GUIDE_DEPLOYMENT = {
82182
82495
  // external+keystore and the mock sandbox adds the practice ceremonies, so the guide may
82183
82496
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
82184
82497
  // on the real adapter these modes refuse") carry the narrower adapter axis.
82185
- signerModes: GUIDE_SIGNER_MODES
82498
+ signerModes: GUIDE_SIGNER_MODES,
82499
+ // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
82500
+ // leg genuinely is not there until an operator configures it. The first draft of this line
82501
+ // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
82502
+ // about — the default rendering would have promised a QR that most installs cannot show.
82503
+ // A live boot derives this from env either way (network-switch.ts).
82504
+ walletConnect: false
82186
82505
  };
82187
82506
  function servedNetworks(d) {
82188
82507
  if (d.networks.length === 0) throw new Error("guide: a deployment must serve at least one network");
@@ -82354,7 +82673,7 @@ function keystoreAbsenceBullet() {
82354
82673
  never ask for a password.`;
82355
82674
  }
82356
82675
  var GUIDE_TOPIC_SOURCES = {
82357
- "getting-started": `# Diamond Hands \u2014 what this is
82676
+ "getting-started": (d) => `# Diamond Hands \u2014 what this is
82358
82677
 
82359
82678
  Diamond Hands lets you BORROW a dollar-pegged token (UCD) against your own BITCOIN,
82360
82679
  without selling it. Your BTC sits in a custody vault tied to your position; you mint UCD
@@ -82362,14 +82681,9 @@ against it, pay it back whenever you like, and take your BTC out again.
82362
82681
 
82363
82682
  **Agent instructions:** answer in the USER'S language, map their words via the \`glossary\`
82364
82683
  topic, and always say plainly whether this session is PRACTICE or REAL MONEY. Read the
82365
- \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, whether writes
82366
- are enabled (and the true reason when not), and which signer modes this build offers;
82367
- never promise a capability it does not list. The money truth has THREE cases:
82368
- - Adapter \`mock\` \u2014 a PRACTICE sandbox. No real money anywhere.
82369
- - Adapter \`real\` on SEPOLIA (the zero-config default) \u2014 the REAL protocol contracts on
82370
- the test network: real ceremonies and signatures, PRACTICE money (test funds).
82371
- - Adapter \`real\` on MAINNET \u2014 REAL MONEY. Writes are disabled unless the operator
82372
- explicitly arms them; the capabilities block states which applies.
82684
+ \`capabilities\` block in \`boundary://info\` FIRST \u2014 it states the network, which signer
82685
+ modes this build offers, and which mode is active; never promise a capability it does not
82686
+ list. ${moneyTruth(d)}
82373
82687
  SAY THIS EARLY AND UNPROMPTED \u2014 users must never wonder whether money is real.
82374
82688
 
82375
82689
  A first conversation usually goes: explain this page \u2192 \`guide first-setup\` (choose how to
@@ -82394,8 +82708,8 @@ signer modes exist; current terms (\`protocol_terms\`).
82394
82708
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
82395
82709
  - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
82396
82710
  on the real adapter and the mock. The approval page auto-opens in the browser (its URL
82397
- is ALSO in the tool result); the user connects MetaMask \u2014 or scans the WalletConnect QR
82398
- / pastes the pairing code for a mobile wallet \u2014 and then APPROVES EACH OPERATION in
82711
+ is ALSO in the tool result); the user connects MetaMask \u2014 ${phoneWalletOffer(d)} \u2014 and
82712
+ then APPROVES EACH OPERATION in
82399
82713
  their own wallet. The first verified signature binds their wallet address as the
82400
82714
  borrower. Full walkthrough: \`guide connect-wallet\`.
82401
82715
  ${offers(d, "keystore") ? `- **"Sign automatically / no popups"** \u2192 mode \`keystore\`. A local encrypted keystore
@@ -82426,14 +82740,13 @@ The user can switch authorization modes at ANY time by saying so \u2014 repeat s
82426
82740
  "connect-wallet": (d) => `# Connect your wallet \u2014 the external-signer walkthrough
82427
82741
 
82428
82742
  External mode means the user approves every operation in their OWN wallet \u2014 a browser
82429
- extension (MetaMask) or a WalletConnect mobile wallet. It works on the real adapter and
82430
- the mock.
82743
+ extension (MetaMask)${d.walletConnect ? " or a WalletConnect mobile wallet" : ""}. It works
82744
+ on the real adapter and the mock.
82431
82745
 
82432
82746
  **The walkthrough:**
82433
82747
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
82434
82748
  desktop browser; ${approvalPageLocation(d)}
82435
- 2. On the page: connect the browser extension, or \u2014 for a mobile wallet \u2014 scan the
82436
- WalletConnect QR code or paste the pairing code.
82749
+ 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." : ". " + phoneWalletOffer(d) + "."}
82437
82750
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
82438
82751
  login ceremony explicitly (one typed-data signature in the wallet).
82439
82752
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -82478,7 +82791,11 @@ the mock.
82478
82791
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
82479
82792
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
82480
82793
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
82481
- signature. The blind execute popup happens once.
82794
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
82795
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
82796
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
82797
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
82798
+ typed-data card. Promise the unreadable one only where it is real.
82482
82799
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
82483
82800
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
82484
82801
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -82514,6 +82831,21 @@ Connections / Connected sites).`,
82514
82831
  6. **Withdraw BTC** \u2014 \`loan_withdraw {positionId, btcAddress, amountSats, confirmed:true}\`.
82515
82832
  BTC sends are IRREVERSIBLE \u2014 read the address back to the user before confirming.
82516
82833
  amountSats is gross (fee comes out of it) and may be the whole available balance.
82834
+ The SECOND wallet popup is on a clock of well under a minute; if the user misses it the
82835
+ withdrawal fails with the reservation already committed and their coins still in the
82836
+ vault. That does NOT clear itself and it is not a stale spend \u2014 \`loan_recover_stale_spend\`
82837
+ needs the coins to have MOVED, which is exactly what did not happen. The way out is
82838
+ \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
82839
+ fresh stamp using the destination and amount the CHAIN already holds. Check
82840
+ \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
82841
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
82842
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
82843
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
82844
+ Say which one before they open the page, not after the popup surprises them.
82845
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
82846
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
82847
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
82848
+ the original withdrawal authorized.
82517
82849
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
82518
82850
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
82519
82851
 
@@ -82776,8 +83108,7 @@ ${connectorStatusTruth(d)}
82776
83108
  **What it is:** instead of installing anything, the user adds Diamond Hands to
82777
83109
  claude.ai as a connector (paste a URL \u2014 zero install, zero Node, zero config files).
82778
83110
  Sign-in IS the wallet: one Sign-In-with-Ethereum signature proves address ownership \u2014
82779
- no password, no email, no account beyond the wallet address. The sign-in page offers a
82780
- WalletConnect QR too, so a phone wallet works without any browser extension.
83111
+ no password, no email, no account beyond the wallet address.${d.walletConnect ? " The sign-in\npage offers a WalletConnect QR too, so a phone wallet works without any browser extension." : "\n" + phoneWalletOffer(d) + "."}
82781
83112
 
82782
83113
  **Signature cadence, plainly:** the FIRST connect costs one SIWE signature (sign-in)
82783
83114
  plus one lit-ops login signature (read access). After that, every operation that moves
@@ -82798,17 +83129,19 @@ honestly when asked "is this safe"):
82798
83129
  is never written to disk. A breach here is privacy-class, never money-class.
82799
83130
  3. **What the assistant narrates.** Tool results shape what the assistant tells you \u2014
82800
83131
  a security concern is filed and audited for exactly this channel.
82801
- 4. **Tenant separation \u2014 and the one binding it does NOT make.** Each signed-in wallet
82802
- gets its own world: its own boundary, its own signer state, its own approval-page
82803
- mount, keyed by that address. What is NOT bound is the mount to that address \u2014 the
82804
- world's borrower is whichever wallet CONNECTS at the mount, so a leaked mount link
82805
- plus an earlier connection would make a different wallet this session's signer. That
82806
- is signing-class, not merely privacy-class; do not tell a user it cannot be. What
82807
- contains it: the mount id is freshly random per world and travels only in the user's
82808
- own tool result (treat the link as a secret), and EVERY fund movement verifies the
82809
- signature against that bound borrower \u2014 no key material exists server-side, so
82810
- whoever reaches the page still cannot sign for anyone else. The gap is filed and
82811
- audited; state it this way rather than claiming a binding that isn't there.
83132
+ 4. **Tenant separation, and what the mount binding does and does not cover.** Each
83133
+ signed-in wallet gets its own world: its own boundary, its own signer state, its own
83134
+ approval-page mount, keyed by that address. The wallet that connects at the mount
83135
+ must BE that address \u2014 a wallet offering any other account is refused at connect
83136
+ time, and switching accounts afterwards is refused the same way rather than silently
83137
+ becoming the new signer. So the account that signs is the account that signed in.
83138
+ None of that makes the mount link safe to pass around: whoever holds it can still
83139
+ load the page and observe or disrupt a pending ceremony, so treat the link as a
83140
+ secret \u2014 it is freshly random per world and travels only in the user's own tool
83141
+ result. What the binding does mean is that a holder cannot become this session's
83142
+ signer. Alongside that,
83143
+ EVERY fund movement still verifies the signature against the bound borrower, and no
83144
+ key material exists server-side.
82812
83145
  5. **Availability and deploy honesty.** Hosted code changes under you: deploys are
82813
83146
  version-pinned, the page bundle is open-source, and \`boundary://info\` capabilities
82814
83147
  reports the exact server version.
@@ -82995,11 +83328,17 @@ function createNetworkSwitchRuntime(opts) {
82995
83328
  }
82996
83329
  };
82997
83330
  }
82998
- function guideDeployment(overrides) {
83331
+ function guideDeployment(overrides, env) {
82999
83332
  return {
83000
83333
  tier: overrides?.bridgeMount ? "hosted" : "local",
83001
83334
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83002
- signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes
83335
+ signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
83336
+ // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
83337
+ // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
83338
+ // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
83339
+ // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
83340
+ // about the same server, which is exactly what they did before this line existed.
83341
+ walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
83003
83342
  };
83004
83343
  }
83005
83344
  function assembleWorld(opts) {
@@ -83009,7 +83348,7 @@ function assembleWorld(opts) {
83009
83348
  ...boot.mockControl ? { mockControl: boot.mockControl } : {},
83010
83349
  ...boot.signer ? { signer: boot.signer } : {},
83011
83350
  ...opts.overrides?.externalOnly ? { externalOnly: true } : {},
83012
- deployment: guideDeployment(opts.overrides),
83351
+ deployment: guideDeployment(opts.overrides, opts.env),
83013
83352
  ...opts.configResult.ok && opts.configResult.config.adapter === "mock" && opts.configResult.config.chainId ? { chainId: opts.configResult.config.chainId } : {}
83014
83353
  };
83015
83354
  if ((opts.env["DH_ADAPTER"] ?? "real") !== "mock") {
@@ -83321,6 +83660,32 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83321
83660
  return renderEnvelope(await b.boundary.withdrawBtc({ positionId, btcAddress: btcAddress2, amountSats, networkFeeSats }));
83322
83661
  })
83323
83662
  );
83663
+ registerBoundaryTool(
83664
+ server,
83665
+ "loan_withdraw_retry",
83666
+ {
83667
+ title: "Re-run a stalled BTC withdrawal's execute step",
83668
+ description: `Finish a withdrawal that authorized but never broadcast. loan_withdraw has two steps: the first commits the reservation on-chain, the second signs a time-stamped hash whose window is under a minute \u2014 often nearer twenty seconds. If that second signature is not given in time the withdrawal fails with the reservation ALREADY committed and the coins still in the vault, and it does not clear itself: loan_recover_stale_spend needs the coins to have MOVED, which is exactly what did not happen. This re-runs the second step alone with a fresh stamp. Destination and amount come from the on-chain record, not from you \u2014 the only figure you supply is the network fee, which is taken OUT of the already-authorized amount and cannot increase what leaves the vault. Use position_pending_withdrawals to see what is outstanding first. Sends real BTC. ${LATENCY_NOTE} Requires human confirmation (confirmed: true).`,
83669
+ inputSchema: {
83670
+ positionId: positionIdSchema,
83671
+ networkFeeSats: import_zod.z.number().int().positive().default(1e3).describe("BTC network fee in sats (declared default 1000); taken FROM the authorized amount, not added on top"),
83672
+ confirmed: confirmedSchema
83673
+ },
83674
+ annotations: DESTRUCTIVE_WRITE_ANNOTATIONS
83675
+ },
83676
+ async ({ positionId, networkFeeSats, confirmed }) => guardedWrite(getB, async () => {
83677
+ const gate = requireConfirmation(
83678
+ confirmed,
83679
+ `re-run the execute step for every outstanding BTC withdrawal reservation on position ${positionId} (this BROADCASTS real BTC to the destination each reservation already authorizes)`
83680
+ );
83681
+ if (gate) return gate;
83682
+ const problem = checkPositionIdHex(positionId) ?? checkSatsAmount(networkFeeSats, "Network fee");
83683
+ if (problem) return validationFailed(problem);
83684
+ const b = getB();
83685
+ if (!b.ok) return renderError(b.error);
83686
+ return renderEnvelope(await b.boundary.retryWithdrawExecute({ positionId, networkFeeSats }));
83687
+ })
83688
+ );
83324
83689
  registerBoundaryTool(
83325
83690
  server,
83326
83691
  "loan_allowlist_destination",
@@ -83346,7 +83711,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83346
83711
  "loan_delegation_setup",
83347
83712
  {
83348
83713
  title: "Install delegation on the Safe (one owner ceremony)",
83349
- 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).`,
83714
+ description: `NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'). It runs on the practice (mock) adapter only. Say so before a user plans around it. 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).`,
83350
83715
  inputSchema: {
83351
83716
  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)"),
83352
83717
  confirmed: confirmedSchema
@@ -83366,7 +83731,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83366
83731
  "loan_delegation_grant",
83367
83732
  {
83368
83733
  title: "Grant the agent per-position scopes (owners sign)",
83369
- 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).`,
83734
+ description: `NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'). It runs on the practice (mock) adapter only. Say so before a user plans around it. 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).`,
83370
83735
  inputSchema: {
83371
83736
  positionId: positionIdSchema,
83372
83737
  renew: import_zod.z.boolean().optional().describe("Allow the agent to extend/renew this position"),
@@ -83396,7 +83761,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
83396
83761
  "loan_recover_stale_spend",
83397
83762
  {
83398
83763
  title: "Recover a stale BTC reservation via LIT-attested proof",
83399
- 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.",
83764
+ description: "NOT AVAILABLE on the real protocol in this build \u2014 the real adapter answers UPSTREAM_UNAVAILABLE ('not wired in this delivery'); it runs on the practice (mock) adapter only. For a withdrawal that authorized but never broadcast, loan_withdraw_retry is the working path. 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.",
83400
83765
  inputSchema: {
83401
83766
  positionId: positionIdSchema,
83402
83767
  utxoTxid: import_zod.z.string().describe("The original authorized UTXO's txid"),
@@ -84274,7 +84639,7 @@ function registerBoundaryInfoResource(server, getB) {
84274
84639
  }
84275
84640
 
84276
84641
  // src/version.ts
84277
- var SERVER_VERSION = "0.5.12";
84642
+ var SERVER_VERSION = "0.5.14";
84278
84643
 
84279
84644
  // src/server.ts
84280
84645
  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.";