@gvnrdao/dh-mcp 0.5.14 → 0.5.16

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
@@ -15440,9 +15440,9 @@ ${errorReport}`);
15440
15440
  var MAX_BTC_AMOUNT = 25e6 * 1e8;
15441
15441
  var UTXO_QUERY_MAX_RETRIES = 3;
15442
15442
  var UTXO_QUERY_RETRY_DELAY_MS = 500;
15443
- var QUANTUM_WINDOW_SECONDS3 = 60;
15443
+ var QUANTUM_WINDOW_SECONDS4 = 60;
15444
15444
  var DEAD_ZONE_SECONDS2 = 16;
15445
- var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS3 - DEAD_ZONE_SECONDS2;
15445
+ var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
15446
15446
  var SECONDS_PER_DAY = 86400;
15447
15447
  var DAYS_PER_MONTH = 30;
15448
15448
  var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
@@ -40498,6 +40498,7 @@ var require_dist3 = __commonJS({
40498
40498
  // src/boundary/upstream/shared/external-bridge/wc-transport.ts
40499
40499
  var wc_transport_exports = {};
40500
40500
  __export(wc_transport_exports, {
40501
+ WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40501
40502
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
40502
40503
  WcTransport: () => WcTransport,
40503
40504
  newIsolatedCore: () => newIsolatedCore,
@@ -40533,7 +40534,7 @@ function newIsolatedCore(cfg, label) {
40533
40534
  });
40534
40535
  return { core, scratch };
40535
40536
  }
40536
- var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
40537
+ var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40537
40538
  var init_wc_transport = __esm({
40538
40539
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
40539
40540
  "use strict";
@@ -40543,6 +40544,12 @@ var init_wc_transport = __esm({
40543
40544
  path3 = __toESM(require("path"));
40544
40545
  import_node_fs = require("fs");
40545
40546
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
40547
+ WC_DAPP_METADATA = {
40548
+ name: "Diamond Hands MCP",
40549
+ description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
40550
+ url: "https://app.diamondhands.credit",
40551
+ icons: []
40552
+ };
40546
40553
  EVENTS = ["accountsChanged", "chainChanged"];
40547
40554
  WcTransport = class _WcTransport {
40548
40555
  constructor(client, cfg, scratch) {
@@ -40561,12 +40568,7 @@ var init_wc_transport = __esm({
40561
40568
  const client = await import_sign_client.default.init({
40562
40569
  core,
40563
40570
  projectId: cfg.projectId,
40564
- metadata: {
40565
- name: "Diamond Hands MCP",
40566
- description: "Human approval for Diamond Hands operations",
40567
- url: "https://gvnr.xyz",
40568
- icons: []
40569
- }
40571
+ metadata: WC_DAPP_METADATA
40570
40572
  });
40571
40573
  return new _WcTransport(client, cfg, scratch);
40572
40574
  }
@@ -40628,6 +40630,27 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
40628
40630
  var ADAPTERS = ["mock", "real"];
40629
40631
  var LATENCIES = ["zero", "realistic"];
40630
40632
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
40633
+ var DEFAULT_WC_PROJECT_ID = "f93d3047a55f38275553a49b32ed5372";
40634
+ var WC_DISABLED = "off";
40635
+ function withLocalWcDefault(env) {
40636
+ const raw = env["DH_WC_PROJECT_ID"];
40637
+ if (raw !== void 0 && raw !== "") return env;
40638
+ return { ...env, DH_WC_PROJECT_ID: DEFAULT_WC_PROJECT_ID };
40639
+ }
40640
+ function wcEnabled(env) {
40641
+ return resolvedWcProjectId(env) !== void 0;
40642
+ }
40643
+ function resolvedWcProjectId(env) {
40644
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
40645
+ }
40646
+ function resolveWcProjectId(raw, problems) {
40647
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
40648
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
40649
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
40650
+ return void 0;
40651
+ }
40652
+ return raw;
40653
+ }
40631
40654
  var NETWORK_DEFAULTS = {
40632
40655
  sepolia: {
40633
40656
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -40702,10 +40725,7 @@ function resolveBoundaryConfig(env) {
40702
40725
  }
40703
40726
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
40704
40727
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
40705
- const wcProjectId = env["DH_WC_PROJECT_ID"];
40706
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
40707
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
40708
- }
40728
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
40709
40729
  let bridgeOpenBrowser;
40710
40730
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
40711
40731
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -40777,10 +40797,7 @@ function resolveRealConfig(env) {
40777
40797
  const stateDir = env["DH_STATE_DIR"];
40778
40798
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
40779
40799
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
40780
- const wcProjectId = env["DH_WC_PROJECT_ID"];
40781
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
40782
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
40783
- }
40800
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
40784
40801
  let bridgeOpenBrowser;
40785
40802
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
40786
40803
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41220,8 +41237,15 @@ var BoundaryCore = class {
41220
41237
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
41221
41238
  }
41222
41239
  // ---- PSM reads (plan 08 Part B Phase R) ----
41223
- async getPsmStatus() {
41224
- const r = await this.deps.plugin.chain.getPsmStatus();
41240
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
41241
+ * names the coin, and this is how they learn what they may name. */
41242
+ async listPsmStablecoins() {
41243
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
41244
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
41245
+ return okEnvelope(r.value, r.source);
41246
+ }
41247
+ async getPsmStatus(p) {
41248
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
41225
41249
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41226
41250
  return okEnvelope(this.psmStatusData(r.value), r.source);
41227
41251
  }
@@ -41232,7 +41256,7 @@ var BoundaryCore = class {
41232
41256
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
41233
41257
  * whenever `env.ok`. */
41234
41258
  async psmQuoteWithStatus(p) {
41235
- const statusR = await this.deps.plugin.chain.getPsmStatus();
41259
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
41236
41260
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
41237
41261
  const s = statusR.value;
41238
41262
  const toUcd = p.direction === "to-ucd";
@@ -41288,6 +41312,7 @@ var BoundaryCore = class {
41288
41312
  );
41289
41313
  }
41290
41314
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
41315
+ stablecoin: p.stablecoin,
41291
41316
  direction: toUcd ? "swap" : "redeem",
41292
41317
  amountIn: amountIn.toString()
41293
41318
  });
@@ -41354,6 +41379,7 @@ var BoundaryCore = class {
41354
41379
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
41355
41380
  if (floor === 0n) floor = 1n;
41356
41381
  const r = await this.deps.plugin.ops.psmSwap({
41382
+ stablecoin: p.stablecoin,
41357
41383
  direction: q.contractCall,
41358
41384
  amountIn: q.amountIn,
41359
41385
  minOut: floor.toString(),
@@ -41453,7 +41479,7 @@ var BoundaryCore = class {
41453
41479
  feeToken: "UCD",
41454
41480
  perBlockCap: s.maxSwapVolumePerBlock
41455
41481
  }),
41456
- toUsdc: direction({
41482
+ fromUcd: direction({
41457
41483
  minAmount: s.minRedeemAmount,
41458
41484
  maxAmount: s.maxRedeemAmount,
41459
41485
  amountUnit: ucdUnit,
@@ -43278,7 +43304,7 @@ var SINK_CONTRACTS = {
43278
43304
  PositionManager: sinkAddress("PositionManager"),
43279
43305
  UCDToken: sinkAddress("UCDToken"),
43280
43306
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
43281
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
43307
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
43282
43308
  SimplePSMV2: sinkAddress("SimplePSMV2"),
43283
43309
  UsdcToken: sinkAddress("UsdcToken"),
43284
43310
  UCDController: sinkAddress("UCDController")
@@ -43574,7 +43600,18 @@ var MockUpstreamPlugin = class {
43574
43600
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
43575
43601
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
43576
43602
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
43577
- getPsmStatus: () => this.read("mock-chain", () => {
43603
+ // The practice world models ONE stablecoin, and says so rather than implying a
43604
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
43605
+ // and naming anything but this one is refused the same way the real adapter refuses
43606
+ // an unsupported address — a mock that accepted any name would teach a habit the
43607
+ // real protocol punishes.
43608
+ listPsmStablecoins: () => this.read(
43609
+ "mock-chain",
43610
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
43611
+ ),
43612
+ getPsmStatus: (p) => this.read("mock-chain", () => {
43613
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43614
+ if (known) return known;
43578
43615
  const psm = this.world.psmSeed();
43579
43616
  return upOk(
43580
43617
  {
@@ -43599,6 +43636,8 @@ var MockUpstreamPlugin = class {
43599
43636
  );
43600
43637
  }),
43601
43638
  getPsmQuote: (p) => this.read("mock-chain", () => {
43639
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43640
+ if (known) return known;
43602
43641
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
43603
43642
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
43604
43643
  })
@@ -43723,6 +43762,19 @@ var MockUpstreamPlugin = class {
43723
43762
  return apply();
43724
43763
  }
43725
43764
  /** Mode `none`: every write answers with the conversational setup invitation. */
43765
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
43766
+ * refused with the same shape the real adapter uses for an address the chain does not
43767
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
43768
+ * instead of silently succeeding and teaching that any name works. */
43769
+ mockStablecoinRefusal(stablecoin) {
43770
+ const chosen = stablecoin.trim().toLowerCase();
43771
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
43772
+ return upFail({
43773
+ kind: "rejected",
43774
+ source: "mock-chain",
43775
+ message: `'${stablecoin}' is not a PSM-supported stablecoin in this practice world \u2014 it supports 'USDC' only. Read protocol://psm for the coins a deployment actually supports; there is no default coin on any tier.`
43776
+ });
43777
+ }
43726
43778
  noneRefusal() {
43727
43779
  if (this.signer && this.signer.manager.mode() === "none") {
43728
43780
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -78606,6 +78658,13 @@ function listPositionsQuery(f) {
78606
78658
  }
78607
78659
  return { document: LIST_POSITIONS, variables: { first, skip } };
78608
78660
  }
78661
+ var SUPPORTED_STABLECOINS = `
78662
+ query GetSupportedStablecoins {
78663
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
78664
+ id address isSupported exchangeRate entryFee exitFee reserves decimals
78665
+ totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
78666
+ }
78667
+ }`;
78609
78668
 
78610
78669
  // src/boundary/upstream/real/psm-calls.ts
78611
78670
  var import_ethers31 = require("ethers");
@@ -78745,6 +78804,11 @@ var PsmCalls = class {
78745
78804
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78746
78805
  });
78747
78806
  }
78807
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
78808
+ * so it must come from the token rather than from a per-network assumption. */
78809
+ symbol() {
78810
+ return this.deps.stablecoinSymbol;
78811
+ }
78748
78812
  async status() {
78749
78813
  return this.call(async () => {
78750
78814
  const s = this.deps.stablecoinAddress;
@@ -79204,13 +79268,6 @@ function buildValidationContext(network, chainId) {
79204
79268
  }
79205
79269
 
79206
79270
  // src/boundary/upstream/real/write-ops.ts
79207
- function psmMainnetWriteRefusal(network, chainId) {
79208
- return {
79209
- kind: "rejected",
79210
- source: SOURCE5,
79211
- message: `psmSwap is refused (MAINNET_WRITES_DISABLED): PSM writes are enabled on sepolia ONLY, and this process is configured for network '${network}' (chainId ${chainId}) \u2014 the PSM-specific sepolia-only anchor; mainnet PSM operations await their dedicated security review. No ceremony was started and no signer was touched. PSM reads (psm_quote, protocol://psm) remain available. Loan operations are NOT affected by this gate.`
79212
- };
79213
- }
79214
79271
  var SOURCE5 = "real-ops";
79215
79272
  var OP_LAYOUT = "dh-op-envelope-v1";
79216
79273
  function randomNonceHex() {
@@ -79558,8 +79615,7 @@ function buildWriteOps(deps) {
79558
79615
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79559
79616
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
79560
79617
  psmSwap: async (p) => {
79561
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
79562
- const pr = deps.psm();
79618
+ const pr = await deps.psm(p.stablecoin);
79563
79619
  if (!pr.ok) return upFail(pr.failure);
79564
79620
  const calls = pr.calls;
79565
79621
  const addr = calls.addresses();
@@ -79577,7 +79633,7 @@ function buildWriteOps(deps) {
79577
79633
  const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
79578
79634
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
79579
79635
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
79580
- const tokenSymbol = isSwap ? "USDC" : "UCD";
79636
+ const tokenSymbol = isSwap ? calls.symbol() : "UCD";
79581
79637
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
79582
79638
  if (!quoteR.ok) return upFail(quoteR.failure);
79583
79639
  const broadcast = async (leg, action, tx2) => {
@@ -79617,7 +79673,7 @@ function buildWriteOps(deps) {
79617
79673
  } catch (e) {
79618
79674
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
79619
79675
  }
79620
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? "USDC smallest units" : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
79676
+ const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
79621
79677
  const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
79622
79678
  if (!execHashR.ok) {
79623
79679
  const f = execHashR.failure;
@@ -79940,6 +79996,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79940
79996
  );
79941
79997
  }
79942
79998
  const hashHex = import_ethers37.ethers.hexlify(bytes).toLowerCase();
79999
+ const nowMs = (this.deps.clock ?? Date.now)();
80000
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80001
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
79943
80002
  const outcome = await this.deps.bridge.requestSignature({
79944
80003
  id: (0, import_node_crypto5.randomUUID)(),
79945
80004
  kind: "personal-sign",
@@ -79951,15 +80010,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79951
80010
  "(identical to how diamondhands.credit signs withdrawals).",
79952
80011
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79953
80012
  "",
79954
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
79955
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
79956
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
79957
- "itself allows. If it expires the signature is refused, the withdrawal does not",
79958
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
79959
- "start again rather than signing something you have not finished reading."
80013
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80014
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80015
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80016
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80017
+ "stay reserved until that is cleared. If the number above is already small, decline",
80018
+ "and start again rather than signing something you have not finished reading."
79960
80019
  ],
79961
80020
  expectedSigner: this.deps.borrower,
79962
80021
  chainId: this.deps.chainId,
80022
+ expiresAtSec,
79963
80023
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
79964
80024
  });
79965
80025
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -80163,13 +80223,18 @@ var RealUpstreamPlugin = class {
80163
80223
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
80164
80224
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
80165
80225
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
80166
- getPsmStatus: () => {
80167
- const r = this.psmCalls();
80168
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
80169
- },
80170
- getPsmQuote: (p) => {
80171
- const r = this.psmCalls();
80172
- if (!r.ok) return Promise.resolve(upFail(r.failure));
80226
+ listPsmStablecoins: async () => {
80227
+ const verified = await this.verifiedStablecoins();
80228
+ if (!verified.ok) return upFail(verified.failure);
80229
+ return upOk(verified.rows, this.src("subgraph"));
80230
+ },
80231
+ getPsmStatus: async (p) => {
80232
+ const r = await this.psmCallsForChoice(p.stablecoin);
80233
+ return r.ok ? r.calls.status() : upFail(r.failure);
80234
+ },
80235
+ getPsmQuote: async (p) => {
80236
+ const r = await this.psmCallsForChoice(p.stablecoin);
80237
+ if (!r.ok) return upFail(r.failure);
80173
80238
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
80174
80239
  }
80175
80240
  };
@@ -80237,12 +80302,13 @@ var RealUpstreamPlugin = class {
80237
80302
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
80238
80303
  delegationSetup: () => readOnly("delegationSetup"),
80239
80304
  delegationGrant: () => readOnly("delegationGrant"),
80240
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
80241
- // any non-sepolia network refuses typed — naming the network gate truthfully —
80242
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
80243
- // missing signer instead (the honest reason on that path).
80305
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
80306
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
80307
+ // signerless boot the honest refusal was always the missing signer; the network
80308
+ // gate sat in front of it and answered first. Now there is one reason left, and it
80309
+ // is the true one on this path.
80244
80310
  psmSwap: () => Promise.resolve(
80245
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
80311
+ upFail({
80246
80312
  kind: "signer-missing",
80247
80313
  source: "real-ops",
80248
80314
  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."
@@ -80359,7 +80425,7 @@ var RealUpstreamPlugin = class {
80359
80425
  session,
80360
80426
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80361
80427
  readDetails: (id) => this.readPositionDetails(id),
80362
- psm: () => this.psmCalls(),
80428
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80363
80429
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80364
80430
  });
80365
80431
  }
@@ -80493,7 +80559,7 @@ var RealUpstreamPlugin = class {
80493
80559
  session,
80494
80560
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80495
80561
  readDetails: (id) => this.readPositionDetails(id),
80496
- psm: () => this.psmCalls(),
80562
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80497
80563
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80498
80564
  });
80499
80565
  this.opsGatewayCache.set(key, gateway);
@@ -80639,35 +80705,200 @@ var RealUpstreamPlugin = class {
80639
80705
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
80640
80706
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
80641
80707
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
80642
- psmWrapper = null;
80643
- psmCalls() {
80644
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
80708
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
80709
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
80710
+ psmWrappers = /* @__PURE__ */ new Map();
80711
+ /**
80712
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
80713
+ *
80714
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
80715
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
80716
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
80717
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
80718
+ * `getPSMStablecoins` reads the index for the same reason.
80719
+ */
80720
+ async listSupportedStablecoins() {
80721
+ const r = await this.graphProxy(
80722
+ SUPPORTED_STABLECOINS,
80723
+ {}
80724
+ );
80725
+ if (!r.ok) return r;
80726
+ const raw = r.value.data.supportedStablecoins ?? [];
80727
+ const bad = raw.find((x) => !import_ethers38.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
80728
+ if (bad) {
80729
+ return {
80730
+ ok: false,
80731
+ failure: {
80732
+ kind: "malformed",
80733
+ source: "subgraph",
80734
+ message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
80735
+ }
80736
+ };
80737
+ }
80738
+ const rows = raw.map((x) => ({
80739
+ address: String(x.address).toLowerCase(),
80740
+ decimals: Number(x.decimals)
80741
+ }));
80742
+ if (rows.length === 0) {
80743
+ return {
80744
+ ok: false,
80745
+ failure: {
80746
+ kind: "unavailable",
80747
+ source: "subgraph",
80748
+ message: `the indexer lists NO supported stablecoins for the PSM on ${this.config.network}. Either the subgraph has not indexed the StablecoinAdded events yet (check its start block against the block the coins were added at), or governance has removed every coin. PSM exchange is unavailable here until one of those is resolved \u2014 this is NOT "the PSM supports nothing".`
80749
+ }
80750
+ };
80751
+ }
80752
+ return { ok: true, rows };
80753
+ }
80754
+ /**
80755
+ * The supported set, verified — index rows each re-checked on-chain, carrying the symbol
80756
+ * read from the token itself. This is what `protocol://psm` lists and what a caller's
80757
+ * SYMBOL is resolved against.
80758
+ *
80759
+ * Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
80760
+ * the chain no longer supports (index lag behind a governance removal). Any OTHER failure
80761
+ * — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
80762
+ * chain is unreachable is the same silent-failure shape as the empty list above. If
80763
+ * nothing survives verification, that is a refusal too, and it says which side disagreed.
80764
+ */
80765
+ async verifiedStablecoins() {
80766
+ const listed = await this.listSupportedStablecoins();
80767
+ if (!listed.ok) return listed;
80768
+ const checked = await Promise.all(
80769
+ listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
80770
+ );
80771
+ const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
80772
+ if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
80773
+ const rows = checked.flatMap(
80774
+ ({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
80775
+ );
80776
+ if (rows.length === 0) {
80777
+ return {
80778
+ ok: false,
80779
+ failure: {
80780
+ kind: "unavailable",
80781
+ source: "chain-rpc",
80782
+ message: `the indexer lists ${listed.rows.length} PSM stablecoin(s) on ${this.config.network}, and the PSM contract confirms none of them. The index is behind a governance removal, or it is indexing a different PSM than the one in this build's deployment table \u2014 verify before exchanging anything.`
80783
+ }
80784
+ };
80785
+ }
80786
+ return { ok: true, rows };
80787
+ }
80788
+ /**
80789
+ * Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
80790
+ *
80791
+ * The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
80792
+ * and the mock world accepts exactly that. The real adapter accepted only the address:
80793
+ * a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
80794
+ * throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
80795
+ * tells the model is "usually transient; retry once". So the documented input produced a
80796
+ * retry loop on the one deployment that moves real money, and a developer practising
80797
+ * against the mock never met it. Both halves are fixed here: the symbol resolves, and a
80798
+ * name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
80799
+ * (our upstream).
80800
+ */
80801
+ async psmCallsForChoice(chosen) {
80802
+ const raw = chosen.trim();
80803
+ if (raw.length === 0) {
80804
+ return {
80805
+ ok: false,
80806
+ failure: { kind: "rejected", source: "chain-rpc", message: "no stablecoin named \u2014 name one by symbol (e.g. 'USDC') or by 0x address; there is no default coin." }
80807
+ };
80808
+ }
80809
+ const symbol = raw.toLowerCase();
80810
+ if (import_ethers38.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
80811
+ const verified = await this.verifiedStablecoins();
80812
+ if (!verified.ok) return { ok: false, failure: verified.failure };
80813
+ const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
80814
+ if (hits.length > 1) {
80815
+ return {
80816
+ ok: false,
80817
+ failure: {
80818
+ kind: "rejected",
80819
+ source: "chain-rpc",
80820
+ message: `'${raw}' names ${hits.length} different coins this PSM supports \u2014 ${hits.map((r) => r.address).join(", ")}. Symbols are self-declared and not unique, so this one cannot be resolved for you: name the 0x address of the one you mean.`
80821
+ }
80822
+ };
80823
+ }
80824
+ const hit = hits[0];
80825
+ if (!hit) {
80826
+ const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
80827
+ return {
80828
+ ok: false,
80829
+ failure: {
80830
+ kind: "rejected",
80831
+ source: "chain-rpc",
80832
+ message: `'${raw}' is not a coin this PSM supports on ${this.config.network} \u2014 it supports ${names}. Name one of those by symbol or address. \`protocol://psm\` carries each one's fees, limits and reserves.`
80833
+ }
80834
+ };
80835
+ }
80836
+ return this.psmCallsFor(hit.address);
80837
+ }
80838
+ /**
80839
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
80840
+ *
80841
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
80842
+ * indexer is how the list is discovered and is not authority over it: it can lag a
80843
+ * governance removal, and acting on a stale list would build a swap the contract reverts
80844
+ * — after the user has approved it in their wallet. List from the index, verify on the
80845
+ * chain, then sign.
80846
+ */
80847
+ async psmCallsFor(stablecoinAddress) {
80848
+ if (!import_ethers38.ethers.isAddress(stablecoinAddress)) {
80849
+ throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
80850
+ }
80851
+ const key = stablecoinAddress.toLowerCase();
80852
+ const cached = this.psmWrappers.get(key);
80853
+ if (cached) return { ok: true, calls: cached };
80645
80854
  const psmAddress = this.contracts["SimplePSMV2"];
80646
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
80647
- if (!psmAddress || !stablecoinAddress) {
80648
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
80855
+ if (!psmAddress) {
80649
80856
  return {
80650
80857
  ok: false,
80651
80858
  failure: {
80652
80859
  kind: "unavailable",
80653
80860
  source: "chain-rpc",
80654
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
80861
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
80862
+ }
80863
+ };
80864
+ }
80865
+ let supported;
80866
+ let symbol;
80867
+ try {
80868
+ const psm = new import_ethers38.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
80869
+ supported = await psm["supportedStablecoins"](key);
80870
+ const erc20 = new import_ethers38.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
80871
+ symbol = await erc20["symbol"]();
80872
+ } catch (e) {
80873
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
80874
+ }
80875
+ if (!supported) {
80876
+ return {
80877
+ ok: false,
80878
+ failure: {
80879
+ kind: "rejected",
80880
+ source: "chain-rpc",
80881
+ message: `${key} is not a PSM-supported stablecoin on ${this.config.network} (checked on-chain against SimplePSMV2.supportedStablecoins). Read protocol://psm for the coins this deployment actually supports.`
80655
80882
  }
80656
80883
  };
80657
80884
  }
80885
+ const stablecoinAddress2 = key;
80658
80886
  const ucdTokenAddress = this.contracts["UCDToken"];
80659
80887
  const ucdControllerAddress = this.contracts["UCDController"];
80660
- this.psmWrapper = new PsmCalls({
80888
+ const built = new PsmCalls({
80661
80889
  provider: this.provider,
80662
80890
  psmAddress,
80663
- stablecoinAddress,
80664
- stablecoinSymbol: "USDC",
80891
+ stablecoinAddress: stablecoinAddress2,
80892
+ // Read from the token, never assumed. The old value was the literal "USDC", which
80893
+ // stops being true the moment a second coin is supported.
80894
+ stablecoinSymbol: symbol,
80665
80895
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
80666
80896
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
80667
80897
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
80668
80898
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
80669
80899
  });
80670
- return { ok: true, calls: this.psmWrapper };
80900
+ this.psmWrappers.set(key, built);
80901
+ return { ok: true, calls: built };
80671
80902
  }
80672
80903
  src(id) {
80673
80904
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -80930,6 +81161,7 @@ function renderApprovalPage(sessionId, nonce) {
80930
81161
  <div id="request" class="hidden">
80931
81162
  <div id="action" class="action"></div>
80932
81163
  <div id="card" class="card"></div>
81164
+ <div id="deadline" class="status hidden"></div>
80933
81165
  <button id="approve">Approve in wallet</button>
80934
81166
  <button id="reject">Reject</button>
80935
81167
  </div>
@@ -80962,10 +81194,19 @@ const statusEl = document.getElementById("status");
80962
81194
  const requestEl = document.getElementById("request");
80963
81195
  const actionEl = document.getElementById("action");
80964
81196
  const cardEl = document.getElementById("card");
81197
+ const approveEl = document.getElementById("approve");
81198
+ const rejectEl = document.getElementById("reject");
81199
+ const deadlineEl = document.getElementById("deadline");
81200
+ let deadlineTimer = null;
80965
81201
  const walletEl = document.getElementById("wallet");
80966
81202
  let account = null;
80967
81203
  let chainId = null;
80968
81204
  let current = null;
81205
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
81206
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
81207
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
81208
+ // card the page never renders is one the human can neither read nor reject.
81209
+ const pending = new Map();
80969
81210
 
80970
81211
  function post(path, body) {
80971
81212
  return fetch(path, {
@@ -81028,43 +81269,135 @@ async function onAccountsChanged(accounts) {
81028
81269
  account = (accounts && accounts[0]) || null;
81029
81270
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81030
81271
  showWallet();
81031
- clearRequest("Wallet changed \u2014 pending request invalidated.");
81272
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81032
81273
  }
81033
81274
 
81034
81275
  async function onChainChanged(cid) {
81035
81276
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81036
81277
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81037
81278
  showWallet();
81038
- clearRequest("Network changed \u2014 pending request invalidated.");
81279
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81039
81280
  }
81040
81281
 
81041
81282
  function listen() {
81042
81283
  const es = new EventSource(BASE + "events?s=" + SESSION);
81043
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
81284
+ es.onmessage = (ev) => {
81285
+ const next = JSON.parse(ev.data);
81286
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
81287
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
81288
+ pending.set(next.id, next);
81289
+ showPending();
81290
+ };
81044
81291
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81045
81292
  }
81046
81293
 
81294
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
81295
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
81296
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
81297
+ // gets approved.
81298
+ function pickPending() {
81299
+ const held = current ? pending.get(current.id) : undefined;
81300
+ if (held && held.mirror !== true) return held;
81301
+ let best = held || null;
81302
+ pending.forEach((frame) => {
81303
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
81304
+ });
81305
+ return best;
81306
+ }
81307
+
81308
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
81309
+ function showPending(emptyText) {
81310
+ const next = pickPending();
81311
+ if (!next) {
81312
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
81313
+ // an expiry for a ceremony that is already decided.
81314
+ stopDeadline();
81315
+ current = null;
81316
+ requestEl.classList.add("hidden");
81317
+ if (emptyText) showStatus(emptyText);
81318
+ return;
81319
+ }
81320
+ current = next;
81321
+ renderRequest();
81322
+ }
81323
+
81047
81324
  function renderRequest() {
81048
81325
  actionEl.textContent = current.action;
81049
81326
  cardEl.textContent = current.card.join("\\n");
81327
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
81328
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
81329
+ // server-side, which is the actual boundary.
81330
+ const mirrored = current.mirror === true;
81331
+ approveEl.classList.toggle("hidden", mirrored);
81332
+ rejectEl.classList.remove("hidden");
81050
81333
  requestEl.classList.remove("hidden");
81051
- showStatus("Review the operation below. Nothing signs without your approval.");
81334
+ showStatus(mirrored
81335
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
81336
+ : "Review the operation below. Nothing signs without your approval.");
81337
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
81338
+ // card promoted after another settles gets its own clock, not the previous one's.
81339
+ startDeadline();
81340
+ }
81341
+
81342
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
81343
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
81344
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
81345
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
81346
+ // honest without it needing to know anything about quantum windows.
81347
+ function stopDeadline() {
81348
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81349
+ deadlineEl.classList.add("hidden");
81052
81350
  }
81053
81351
 
81352
+ function startDeadline() {
81353
+ stopDeadline();
81354
+ if (!current || typeof current.expiresAtSec !== "number") return;
81355
+ const tick = () => {
81356
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
81357
+ if (left > 0) {
81358
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
81359
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
81360
+ } else {
81361
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
81362
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
81363
+ // after. The button is deliberately left enabled \u2014 declining is still the right
81364
+ // action and the page must not trap them.
81365
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
81366
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81367
+ }
81368
+ deadlineEl.classList.remove("hidden");
81369
+ };
81370
+ tick();
81371
+ deadlineTimer = setInterval(tick, 1000);
81372
+ }
81373
+
81374
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
81375
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
81376
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81054
81377
  function clearRequest(text) {
81055
- current = null;
81056
- requestEl.classList.add("hidden");
81057
- showStatus(text);
81378
+ if (current) pending.delete(current.id);
81379
+ showPending(text);
81058
81380
  }
81059
81381
 
81060
- document.getElementById("reject").onclick = async () => {
81382
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
81383
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
81384
+ // stays readable and rejectable.
81385
+ function invalidatePageRequests(text) {
81386
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
81387
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
81388
+ }
81389
+
81390
+ rejectEl.onclick = async () => {
81061
81391
  if (!current) return;
81062
81392
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81063
81393
  clearRequest("Rejected. Waiting for the next request\u2026");
81064
81394
  };
81065
81395
 
81066
- document.getElementById("approve").onclick = async () => {
81396
+ approveEl.onclick = async () => {
81067
81397
  if (!current) return;
81398
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
81399
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
81400
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81068
81401
  const req = current;
81069
81402
  try {
81070
81403
  if (req.kind === "transaction") {
@@ -81081,7 +81414,10 @@ document.getElementById("approve").onclick = async () => {
81081
81414
  const fbody = await fr.json();
81082
81415
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
81083
81416
  const fresh = fbody.request;
81084
- // \u2026re-render what will actually sign\u2026
81417
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
81418
+ // another card arriving while the wallet popup is open re-picks from there, and the
81419
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
81420
+ pending.set(fresh.id, fresh);
81085
81421
  current = fresh; renderRequest();
81086
81422
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
81087
81423
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -81264,9 +81600,6 @@ var SignatureBridge = class {
81264
81600
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81265
81601
  maxPending;
81266
81602
  attachGraceMs;
81267
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
81268
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
81269
- lastAttachedMs = 0;
81270
81603
  server = null;
81271
81604
  port = 0;
81272
81605
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -81417,13 +81750,16 @@ var SignatureBridge = class {
81417
81750
  enqueuedMs: now,
81418
81751
  resolve,
81419
81752
  settled: false,
81420
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
81753
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
81754
+ owner: this.wcActive ? "wc" : "page",
81755
+ dispatched: false,
81756
+ lastAttachedMs: now
81421
81757
  };
81422
81758
  this.pending.set(request.id, entry);
81423
- if (this.wcActive) {
81759
+ if (entry.owner === "wc") {
81424
81760
  void this.driveWc(entry);
81425
81761
  } else {
81426
- this.push(request);
81762
+ this.pushEntry(entry);
81427
81763
  }
81428
81764
  });
81429
81765
  }
@@ -81444,10 +81780,16 @@ var SignatureBridge = class {
81444
81780
  enqueuedMs: now,
81445
81781
  resolve,
81446
81782
  settled: false,
81447
- collect
81783
+ collect,
81784
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
81785
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
81786
+ // ceremony could not reach quorum through the very pages it is broadcast to.
81787
+ owner: "both",
81788
+ dispatched: false,
81789
+ lastAttachedMs: now
81448
81790
  };
81449
81791
  this.pending.set(request.id, entry);
81450
- this.push(request);
81792
+ this.pushEntry(entry);
81451
81793
  if (this.wcActive) void this.driveWcCollection(entry);
81452
81794
  });
81453
81795
  }
@@ -81486,7 +81828,9 @@ var SignatureBridge = class {
81486
81828
  }
81487
81829
  try {
81488
81830
  if (req.kind === "transaction") {
81831
+ this.pushEntry(entry);
81489
81832
  const tx2 = req.tx;
81833
+ entry.dispatched = true;
81490
81834
  const txHash = await transport.request("eth_sendTransaction", [
81491
81835
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
81492
81836
  ]);
@@ -81498,11 +81842,22 @@ var SignatureBridge = class {
81498
81842
  req.card = fresh.card;
81499
81843
  }
81500
81844
  const ps = req.personalSign;
81845
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
81846
+ this.settle(entry, {
81847
+ status: "invalidated",
81848
+ reason: `this step signs a 32-byte hash your wallet cannot decode, and no approval page is open to show you what it authorizes \u2014 open ${this.url()} and re-run the withdrawal with loan_withdraw_retry (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`
81849
+ });
81850
+ return;
81851
+ }
81852
+ this.pushEntry(entry);
81853
+ entry.dispatched = true;
81501
81854
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
81502
81855
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81503
81856
  } else {
81857
+ this.pushEntry(entry);
81504
81858
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
81505
81859
  const payload = withEip712DomainType2(req.typedData);
81860
+ entry.dispatched = true;
81506
81861
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
81507
81862
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81508
81863
  }
@@ -81522,29 +81877,54 @@ var SignatureBridge = class {
81522
81877
  * with a live attachment is in use and must never be evicted. */
81523
81878
  attachedNow() {
81524
81879
  if (this.wcActive) return true;
81525
- for (const s of this.sessions.values()) if (s.sse) return true;
81880
+ return this.pageAttached();
81881
+ }
81882
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
81883
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
81884
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
81885
+ * WalletConnect and must stay global for the connector's eviction predicate. */
81886
+ pageAttached() {
81887
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
81526
81888
  return false;
81527
81889
  }
81890
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
81891
+ * predicate said "a WC session is attached", which is true but irrelevant to a
81892
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
81893
+ * out the full expiry instead of failing fast at the grace. */
81894
+ attachedFor(entry) {
81895
+ if (entry.owner === "wc") return this.wcActive;
81896
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
81897
+ return this.pageAttached();
81898
+ }
81528
81899
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
81529
81900
  * interval; tests call it directly with the injected clock advanced. Order matters:
81530
81901
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
81531
81902
  sweep() {
81532
81903
  const now = this.clock();
81533
- const attached = this.attachedNow();
81534
- if (attached) this.lastAttachedMs = now;
81535
81904
  for (const entry of this.pending.values()) {
81536
81905
  if (entry.settled) continue;
81537
81906
  if (now >= entry.deadlineMs) {
81538
81907
  this.settle(entry, { status: "expired" });
81539
81908
  continue;
81540
81909
  }
81541
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
81542
- this.settle(entry, {
81543
- status: "invalidated",
81544
- reason: `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`
81545
- });
81910
+ if (this.attachedFor(entry)) {
81911
+ entry.lastAttachedMs = now;
81912
+ continue;
81546
81913
  }
81914
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
81915
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
81916
+ }
81917
+ }
81918
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
81919
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
81920
+ unattendedReason(entry) {
81921
+ if (entry.dispatched && entry.request.kind === "transaction") {
81922
+ return "the mobile wallet holding this transaction went away before answering, but it was already asked to send it \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice.";
81547
81923
  }
81924
+ if (entry.owner === "wc") {
81925
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
81926
+ }
81927
+ return `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`;
81548
81928
  }
81549
81929
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
81550
81930
  walletConnectActive() {
@@ -81669,6 +82049,7 @@ var SignatureBridge = class {
81669
82049
  if (info && refusal) {
81670
82050
  this.wcActive = false;
81671
82051
  this.rebuildSharedWallet();
82052
+ this.demoteWcEntries();
81672
82053
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81673
82054
  `);
81674
82055
  return;
@@ -81678,7 +82059,10 @@ var SignatureBridge = class {
81678
82059
  if (info === null) {
81679
82060
  for (const entry of this.pending.values()) {
81680
82061
  if (!entry.settled && !entry.collect) {
81681
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82062
+ this.settle(entry, {
82063
+ status: "invalidated",
82064
+ 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"
82065
+ });
81682
82066
  }
81683
82067
  }
81684
82068
  }
@@ -81750,9 +82134,7 @@ var SignatureBridge = class {
81750
82134
  session.sse?.end();
81751
82135
  session.sse = res;
81752
82136
  for (const entry of this.pending.values()) {
81753
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
81754
-
81755
- `);
82137
+ if (!entry.settled) res.write(this.wireFor(entry));
81756
82138
  }
81757
82139
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
81758
82140
  keepAlive.unref();
@@ -81828,10 +82210,36 @@ var SignatureBridge = class {
81828
82210
  }
81829
82211
  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";
81830
82212
  for (const entry of this.pending.values()) {
81831
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
82213
+ if (entry.settled || entry.collect) continue;
82214
+ if (this.ownedByWc(entry)) continue;
82215
+ this.settle(entry, { status: "invalidated", reason });
81832
82216
  }
81833
82217
  this.ok(res);
81834
82218
  }
82219
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
82220
+ * session hands the request back to the page rather than stranding it. */
82221
+ ownedByWc(entry) {
82222
+ if (entry.owner !== "wc") return false;
82223
+ return this.wcActive || entry.dispatched;
82224
+ }
82225
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
82226
+ * them so the card stops rendering read-only. Collections are already `both`.
82227
+ *
82228
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
82229
+ * phone is still holding does not replace one wallet with another, it adds a second: the
82230
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
82231
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
82232
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
82233
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
82234
+ * false for them, and `unattendedReason` says plainly that the phone may already have
82235
+ * acted. */
82236
+ demoteWcEntries() {
82237
+ for (const entry of this.pending.values()) {
82238
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
82239
+ entry.owner = "page";
82240
+ this.pushEntry(entry);
82241
+ }
82242
+ }
81835
82243
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
81836
82244
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
81837
82245
  async onFinalize(body, res) {
@@ -81845,6 +82253,10 @@ var SignatureBridge = class {
81845
82253
  this.deny(res, 400, "finalize applies only to personal-sign requests");
81846
82254
  return;
81847
82255
  }
82256
+ if (this.ownedByWc(entry)) {
82257
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
82258
+ return;
82259
+ }
81848
82260
  if (entry.finalize) {
81849
82261
  let fresh;
81850
82262
  try {
@@ -81871,10 +82283,22 @@ var SignatureBridge = class {
81871
82283
  return;
81872
82284
  }
81873
82285
  if (body["approved"] !== true) {
82286
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
82287
+ this.settle(entry, {
82288
+ status: "invalidated",
82289
+ reason: "cancelled on the approval page, but a mobile wallet was already asked to send this transaction \u2014 it may have broadcast already. Check the chain (or your wallet's activity) before retrying, or you may pay twice."
82290
+ });
82291
+ this.ok(res);
82292
+ return;
82293
+ }
81874
82294
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
81875
82295
  this.ok(res);
81876
82296
  return;
81877
82297
  }
82298
+ if (this.ownedByWc(entry)) {
82299
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
82300
+ return;
82301
+ }
81878
82302
  const account = String(body["account"] ?? "");
81879
82303
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
81880
82304
  this.deny(res, 400, "approved result requires the signing account");
@@ -81911,11 +82335,20 @@ var SignatureBridge = class {
81911
82335
  this.pending.delete(entry.request.id);
81912
82336
  entry.resolve(outcome);
81913
82337
  }
81914
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
81915
- push(request) {
81916
- const data = `data: ${JSON.stringify(request)}
82338
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
82339
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
82340
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
82341
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
82342
+ * a permanently read-only card that nobody is allowed to decide. */
82343
+ wireFor(entry) {
82344
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
82345
+ return `data: ${JSON.stringify(payload)}
81917
82346
 
81918
82347
  `;
82348
+ }
82349
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
82350
+ pushEntry(entry) {
82351
+ const data = this.wireFor(entry);
81919
82352
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81920
82353
  }
81921
82354
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -82398,7 +82831,7 @@ var FIELD_GLOSSARY = {
82398
82831
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
82399
82832
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
82400
82833
  // ---- psm quote ----
82401
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
82834
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
82402
82835
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
82403
82836
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
82404
82837
  amountInToken: "the token you pay with",
@@ -82465,6 +82898,17 @@ function signerModeSourceClause(d) {
82465
82898
  function phoneWalletOffer(d) {
82466
82899
  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
82900
  }
82901
+ function worldAxes(d) {
82902
+ const axes = [];
82903
+ axes.push(
82904
+ offers(d, "mock-simulated") ? "practice (mock) or real adapter" : "the REAL adapter \u2014 there is no practice (mock) world on this deployment"
82905
+ );
82906
+ axes.push(
82907
+ d.networks.length > 1 ? "sepolia (practice money) or mainnet (real money)" : d.networks.includes("mainnet") ? "MAINNET only, so every fund movement here is real money" : "sepolia only, so the ceremonies are real and the money is practice"
82908
+ );
82909
+ axes.push("that writes are enabled, and what actually gates one is whether a signing identity is connected");
82910
+ return axes.join("; ");
82911
+ }
82468
82912
  function moneyTruth(d) {
82469
82913
  const practice = offers(d, "mock-simulated");
82470
82914
  const sepolia = d.networks.includes("sepolia");
@@ -82496,11 +82940,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
82496
82940
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
82497
82941
  // on the real adapter these modes refuse") carry the narrower adapter axis.
82498
82942
  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).
82943
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
82944
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
82945
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
82946
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
82947
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
82948
+ // nobody supplied a deployment at all, and understating a capability there is the safe
82949
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
82950
+ // overclaim C-44 is about — promising a QR the build cannot show.
82504
82951
  walletConnect: false
82505
82952
  };
82506
82953
  function servedNetworks(d) {
@@ -82511,7 +82958,7 @@ function servedNetworks(d) {
82511
82958
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
82512
82959
  }
82513
82960
  if (mainnet) {
82514
- return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
82961
+ return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing; PSM swaps are NOT an exception \u2014 they execute here and move real funds), and there is no practice network on this deployment to fall back to";
82515
82962
  }
82516
82963
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
82517
82964
  }
@@ -82590,13 +83037,14 @@ function switchNetworkRules(d) {
82590
83037
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
82591
83038
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
82592
83039
  A sepolia position does not exist on mainnet and vice versa.
82593
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
82594
- and every one still requires the user's explicit confirmation plus the signer
82595
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83040
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83041
+ mainnet they move REAL money, and every one still requires the user's explicit
83042
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83043
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83044
+ signed.`;
82596
83045
  }
82597
83046
  const only = d.networks[0];
82598
83047
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82599
- const psm = d.networks.includes("mainnet") ? "The exception is PSM swaps \u2014 the write port refuses them here." : "PSM swaps run here, and are refused on every other network.";
82600
83048
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
82601
83049
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
82602
83050
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -82605,7 +83053,9 @@ function switchNetworkRules(d) {
82605
83053
  belong to ${only} and would not exist anywhere else.
82606
83054
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
82607
83055
  confirmation plus the signer ceremony.
82608
- - ${psm}`;
83056
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83057
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83058
+ anything is signed.`;
82609
83059
  }
82610
83060
  function wrongNetworkTroubleshootingRow(d) {
82611
83061
  if (d.networks.length > 1) {
@@ -82625,20 +83075,23 @@ function switchNetworkIndexLine(d) {
82625
83075
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82626
83076
  return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
82627
83077
  }
82628
- function psmAvailabilityNote(d) {
82629
- if (d.networks.includes("sepolia")) return "";
82630
- return `**Not executable on this deployment.** The PSM write port refuses on every network
82631
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
82632
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
82633
- the mechanism, not an offer: say so before a user plans around it.
82634
-
82635
- `;
83078
+ function psmStablecoinRealityNote(d) {
83079
+ if (d.networks.includes("sepolia")) {
83080
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83081
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83082
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83083
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83084
+ }
83085
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83086
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83087
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83088
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83089
+ have to guess whether the money is real.`;
82636
83090
  }
82637
83091
  function authorizationModeBullets(d) {
82638
83092
  const bullets = [];
82639
83093
  if (offers(d, "external")) {
82640
- bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
82641
- mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
83094
+ bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup${d.walletConnect ? ", or WalletConnect\n mobile via QR/paste-code" : " \u2014 this build has no WalletConnect\n mobile leg"}). Real adapter and mock. For TRANSACTIONS the approval card
82642
83095
  is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
82643
83096
  The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
82644
83097
  approval page states plainly it CANNOT decode. Never extend the card promise over
@@ -82701,8 +83154,7 @@ install matrix. ${connectorInstallNote(d)}
82701
83154
  Nothing needs a config file. Three steps:
82702
83155
 
82703
83156
  **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
82704
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
82705
- (practice money) or mainnet (real money); whether writes are enabled here and which
83157
+ \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
82706
83158
  signer modes exist; current terms (\`protocol_terms\`).
82707
83159
 
82708
83160
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
@@ -82746,7 +83198,7 @@ on the real adapter and the mock.
82746
83198
  **The walkthrough:**
82747
83199
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
82748
83200
  desktop browser; ${approvalPageLocation(d)}
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) + "."}
83201
+ 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 THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
82750
83202
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
82751
83203
  login ceremony explicitly (one typed-data signature in the wallet).
82752
83204
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -82785,7 +83237,14 @@ on the real adapter and the mock.
82785
83237
  hash the SDK builds internally, which the approval page shows bare and says plainly it
82786
83238
  cannot decode (the production web app signs the same way). Tell the user before that
82787
83239
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
82788
- expect an unreadable card and click through the readable one.
83240
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
83241
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
83242
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
83243
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
83244
+ on the card, and the page is the only surface that shows it. With no page attached the
83245
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
83246
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
83247
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
82789
83248
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
82790
83249
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
82791
83250
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
@@ -82804,8 +83263,7 @@ on the real adapter and the mock.
82804
83263
  10 UCD.
82805
83264
 
82806
83265
  **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
82807
- \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
82808
- WalletConnect session (pending approvals are cancelled loudly), discards the login
83266
+ \`disconnect\`):** the FULL wallet flush. It ends every approval-page session${d.walletConnect ? " and any\nWalletConnect session" : ""} (pending approvals are cancelled loudly), discards the login
82809
83267
  token from server memory AND revokes it at the service, and unbinds the borrower
82810
83268
  identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
82811
83269
  a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
@@ -82866,9 +83324,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
82866
83324
 
82867
83325
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
82868
83326
  signed, amounts included. Read it back when the user asks what happened.`,
82869
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83327
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
82870
83328
 
82871
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83329
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
82872
83330
  directions, in user words:
82873
83331
 
82874
83332
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -82876,20 +83334,27 @@ directions, in user words:
82876
83334
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
82877
83335
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
82878
83336
  and you receive 99 UCD.
82879
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
82880
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
82881
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
82882
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
82883
- shortfall refuses with both figures (available vs required).
83337
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
83338
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
83339
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
83340
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
83341
+ reserves, and a shortfall refuses with both figures (available vs required).
83342
+
83343
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
83344
+ default and that is deliberate: the PSM can carry several coins, each with its own
83345
+ reserves, fees and limits, so picking one silently would move someone's money through a
83346
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
83347
+ there rather than guessing one.
82884
83348
 
82885
83349
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
82886
83350
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
82887
83351
  1e18 = 1:1) and can be changed by protocol governance.
82888
83352
 
82889
83353
  **Limits and switches** (all visible in \`protocol://psm\`):
82890
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
82891
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
82892
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
83354
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
83355
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
83356
+ direction is DISABLED.
83357
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
82893
83358
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
82894
83359
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
82895
83360
 
@@ -82898,23 +83363,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
82898
83363
  change between your quote and execution; the floor makes a drifted execution REFUSE
82899
83364
  rather than silently deliver less than quoted.
82900
83365
 
82901
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
82902
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
82903
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
82904
- the money is real. On mainnet the stablecoin is real Circle USDC.
83366
+ ${psmStablecoinRealityNote(d)}
82905
83367
 
82906
83368
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
82907
83369
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
82908
83370
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
82909
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
82910
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
82911
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83371
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
83372
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
83373
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
82912
83374
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
82913
83375
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
82914
83376
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
82915
83377
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
82916
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
82917
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
83378
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
83379
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
83380
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
83381
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
83382
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
83383
+ per-operation and per-block limits,
83384
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
83385
+ mainnet swap, not after.`,
82918
83386
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
82919
83387
 
82920
83388
  Every fund-moving operation needs TWO things, always in this order:
@@ -83173,9 +83641,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
83173
83641
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83174
83642
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83175
83643
  the same way \u2014 reconnect on the user's word.`}
83176
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83177
- not a bug); loan operations work on mainnet. Reads keep working everywhere.` : `- **PSM write refused** \u2014 the PSM write port answers on sepolia alone (a deliberate
83178
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
83644
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
83645
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
83646
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
83647
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
83648
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
83179
83649
  ${wrongNetworkTroubleshootingRow(d)}
83180
83650
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
83181
83651
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -83251,7 +83721,7 @@ function renderGuideIndex(deployment) {
83251
83721
 
83252
83722
  - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
83253
83723
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
83254
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
83724
+ - connect-wallet \u2014 external-wallet walkthrough: approval page, ${deployment.walletConnect ? "extension or WalletConnect QR" : "browser extension (no WalletConnect leg here)"}, popup cadence, login honesty, disconnect/log-out
83255
83725
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
83256
83726
  - fees \u2014 the two fee models, plainly
83257
83727
  - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
@@ -83333,12 +83803,13 @@ function guideDeployment(overrides, env) {
83333
83803
  tier: overrides?.bridgeMount ? "hosted" : "local",
83334
83804
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83335
83805
  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"])
83806
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
83807
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
83808
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
83809
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
83810
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
83811
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
83812
+ walletConnect: wcEnabled(env)
83342
83813
  };
83343
83814
  }
83344
83815
  function assembleWorld(opts) {
@@ -83978,39 +84449,45 @@ function registerPsmTools(server, getB) {
83978
84449
  server,
83979
84450
  "psm_quote",
83980
84451
  {
83981
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
83982
- description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
84452
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
84453
+ description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay the stablecoin, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'from-ucd' = pay UCD, receive the stablecoin back from the PSM's reserves; the EXIT fee is charged IN that stablecoin and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). The result names both amounts, the fee WITH its token, and (from-ucd) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
83983
84454
  inputSchema: {
83984
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = get UCD for USDC (contract swap); 'to-usdc' = get USDC back for UCD (contract redeem)"),
83985
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
84455
+ stablecoin: import_zod4.z.string().min(1).describe(
84456
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
84457
+ ),
84458
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
84459
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals.")
83986
84460
  },
83987
84461
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
83988
84462
  },
83989
- async ({ direction, amount }) => guarded(async () => {
83990
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
84463
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
84464
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
83991
84465
  const problem = checkUcdAmount(amount, label);
83992
84466
  if (problem) return validationFailed(problem);
83993
84467
  const b = getB();
83994
84468
  if (!b.ok) return renderError(b.error);
83995
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
84469
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
83996
84470
  })
83997
84471
  );
83998
84472
  registerBoundaryTool(
83999
84473
  server,
84000
84474
  "psm_swap",
84001
84475
  {
84002
- title: "Exchange UCD \u2194 USDC through the PSM",
84003
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
84476
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
84477
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
84004
84478
  inputSchema: {
84005
- direction: import_zod4.z.enum(["to-ucd", "to-usdc"]).describe("'to-ucd' = pay USDC, get UCD (contract swap); 'to-usdc' = pay UCD, get USDC back (contract redeem)"),
84006
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
84479
+ stablecoin: import_zod4.z.string().min(1).describe(
84480
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
84481
+ ),
84482
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
84483
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals."),
84007
84484
  confirmed: confirmedSchema2
84008
84485
  },
84009
84486
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84010
84487
  },
84011
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84012
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84013
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
84488
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
84489
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
84490
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84014
84491
  const gate = requireConfirmation(
84015
84492
  confirmed,
84016
84493
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84020,7 +84497,7 @@ function registerPsmTools(server, getB) {
84020
84497
  if (problem) return validationFailed(problem);
84021
84498
  const b = getB();
84022
84499
  if (!b.ok) return renderError(b.error);
84023
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
84500
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84024
84501
  })
84025
84502
  );
84026
84503
  }
@@ -84466,7 +84943,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
84466
84943
  "network_switch",
84467
84944
  {
84468
84945
  title: "Show or switch the active network",
84469
- description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks (on mainnet they move REAL money; PSM swaps stay sepolia-only). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
84946
+ description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks \u2014 loan operations and PSM swaps alike (on mainnet they move REAL money). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
84470
84947
  inputSchema: {
84471
84948
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
84472
84949
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -84484,7 +84961,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
84484
84961
  lines.push(
84485
84962
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
84486
84963
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
84487
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
84964
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
84488
84965
  "Session-scoped: the configured default network returns when the server restarts."
84489
84966
  );
84490
84967
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -84590,13 +85067,26 @@ function registerProtocolResources(server, getB) {
84590
85067
  "protocol://psm",
84591
85068
  {
84592
85069
  title: "PSM status (UCD \u2194 USDC exchange)",
84593
- description: "Live SimplePSMV2 state as {data, warnings, source}: network + chainId + addresses (the money surface names its chain), stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in USDC smallest units, to-usdc caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0).",
85070
+ description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
84594
85071
  mimeType: "application/json"
84595
85072
  },
84596
85073
  async (uri) => {
84597
85074
  const b = getB();
84598
85075
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
84599
- const env = await b.boundary.getPsmStatus();
85076
+ const listed = await b.boundary.listPsmStablecoins();
85077
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85078
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85079
+ const failed = perCoin.find((s) => !s.ok);
85080
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85081
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85082
+ const head = coins[0];
85083
+ const env = {
85084
+ ...listed,
85085
+ data: {
85086
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85087
+ stablecoins: coins
85088
+ }
85089
+ };
84600
85090
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
84601
85091
  }
84602
85092
  );
@@ -84639,7 +85129,7 @@ function registerBoundaryInfoResource(server, getB) {
84639
85129
  }
84640
85130
 
84641
85131
  // src/version.ts
84642
- var SERVER_VERSION = "0.5.14";
85132
+ var SERVER_VERSION = "0.5.16";
84643
85133
 
84644
85134
  // src/server.ts
84645
85135
  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.";
@@ -84684,14 +85174,17 @@ if (process.argv.includes("--version")) {
84684
85174
  process.exit(0);
84685
85175
  }
84686
85176
  async function main() {
84687
- const configResult = resolveBoundaryConfig(process.env);
85177
+ const localEnv = withLocalWcDefault(process.env);
85178
+ const configResult = resolveBoundaryConfig(localEnv);
84688
85179
  let boot = await buildBoundary(configResult);
84689
85180
  if (!boot.boundaryResult.ok) {
84690
85181
  process.stderr.write(`[dh-mcp] boundary not available: ${boot.boundaryResult.error.message}
84691
85182
  `);
84692
85183
  }
84693
85184
  const world = assembleWorld({
84694
- env: process.env,
85185
+ // The SAME resolved env the boundary booted from, so a `network_switch` rebuild does
85186
+ // not silently drop the phone-wallet leg the user started the session with.
85187
+ env: localEnv,
84695
85188
  configResult,
84696
85189
  boot,
84697
85190
  log: (line) => process.stderr.write(`[dh-mcp] ${line}