@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.
@@ -37,6 +37,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
37
37
  // src/boundary/upstream/shared/external-bridge/wc-transport.ts
38
38
  var wc_transport_exports = {};
39
39
  __export(wc_transport_exports, {
40
+ WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40
41
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
41
42
  WcTransport: () => WcTransport,
42
43
  newIsolatedCore: () => newIsolatedCore,
@@ -72,7 +73,7 @@ function newIsolatedCore(cfg, label) {
72
73
  });
73
74
  return { core, scratch };
74
75
  }
75
- var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
76
+ var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
76
77
  var init_wc_transport = __esm({
77
78
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
78
79
  "use strict";
@@ -82,6 +83,12 @@ var init_wc_transport = __esm({
82
83
  path = __toESM(require("path"));
83
84
  import_node_fs = require("fs");
84
85
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
86
+ WC_DAPP_METADATA = {
87
+ name: "Diamond Hands MCP",
88
+ description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
89
+ url: "https://app.diamondhands.credit",
90
+ icons: []
91
+ };
85
92
  EVENTS = ["accountsChanged", "chainChanged"];
86
93
  WcTransport = class _WcTransport {
87
94
  constructor(client, cfg, scratch) {
@@ -100,12 +107,7 @@ var init_wc_transport = __esm({
100
107
  const client = await import_sign_client.default.init({
101
108
  core,
102
109
  projectId: cfg.projectId,
103
- metadata: {
104
- name: "Diamond Hands MCP",
105
- description: "Human approval for Diamond Hands operations",
106
- url: "https://gvnr.xyz",
107
- icons: []
108
- }
110
+ metadata: WC_DAPP_METADATA
109
111
  });
110
112
  return new _WcTransport(client, cfg, scratch);
111
113
  }
@@ -15559,9 +15561,9 @@ ${errorReport}`);
15559
15561
  var MAX_BTC_AMOUNT = 25e6 * 1e8;
15560
15562
  var UTXO_QUERY_MAX_RETRIES = 3;
15561
15563
  var UTXO_QUERY_RETRY_DELAY_MS = 500;
15562
- var QUANTUM_WINDOW_SECONDS3 = 60;
15564
+ var QUANTUM_WINDOW_SECONDS4 = 60;
15563
15565
  var DEAD_ZONE_SECONDS2 = 16;
15564
- var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS3 - DEAD_ZONE_SECONDS2;
15566
+ var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
15565
15567
  var SECONDS_PER_DAY = 86400;
15566
15568
  var DAYS_PER_MONTH = 30;
15567
15569
  var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
@@ -41036,7 +41038,7 @@ function htmlPageSecurityHeaders(extra) {
41036
41038
  }
41037
41039
 
41038
41040
  // src/version.ts
41039
- var SERVER_VERSION = "0.5.14";
41041
+ var SERVER_VERSION = "0.5.16";
41040
41042
 
41041
41043
  // src/connector/siwe-oauth.ts
41042
41044
  var import_node_crypto2 = require("crypto");
@@ -41543,6 +41545,21 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
41543
41545
  var ADAPTERS = ["mock", "real"];
41544
41546
  var LATENCIES = ["zero", "realistic"];
41545
41547
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
41548
+ var WC_DISABLED = "off";
41549
+ function wcEnabled(env) {
41550
+ return resolvedWcProjectId(env) !== void 0;
41551
+ }
41552
+ function resolvedWcProjectId(env) {
41553
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
41554
+ }
41555
+ function resolveWcProjectId(raw, problems) {
41556
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
41557
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
41558
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
41559
+ return void 0;
41560
+ }
41561
+ return raw;
41562
+ }
41546
41563
  var NETWORK_DEFAULTS = {
41547
41564
  sepolia: {
41548
41565
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -41617,10 +41634,7 @@ function resolveBoundaryConfig(env) {
41617
41634
  }
41618
41635
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41619
41636
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41620
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41621
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41622
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41623
- }
41637
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41624
41638
  let bridgeOpenBrowser;
41625
41639
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41626
41640
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41692,10 +41706,7 @@ function resolveRealConfig(env) {
41692
41706
  const stateDir = env["DH_STATE_DIR"];
41693
41707
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41694
41708
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41695
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41696
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41697
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41698
- }
41709
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41699
41710
  let bridgeOpenBrowser;
41700
41711
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41701
41712
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -42135,8 +42146,15 @@ var BoundaryCore = class {
42135
42146
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
42136
42147
  }
42137
42148
  // ---- PSM reads (plan 08 Part B Phase R) ----
42138
- async getPsmStatus() {
42139
- const r = await this.deps.plugin.chain.getPsmStatus();
42149
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
42150
+ * names the coin, and this is how they learn what they may name. */
42151
+ async listPsmStablecoins() {
42152
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
42153
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
42154
+ return okEnvelope(r.value, r.source);
42155
+ }
42156
+ async getPsmStatus(p) {
42157
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
42140
42158
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42141
42159
  return okEnvelope(this.psmStatusData(r.value), r.source);
42142
42160
  }
@@ -42147,7 +42165,7 @@ var BoundaryCore = class {
42147
42165
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
42148
42166
  * whenever `env.ok`. */
42149
42167
  async psmQuoteWithStatus(p) {
42150
- const statusR = await this.deps.plugin.chain.getPsmStatus();
42168
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
42151
42169
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
42152
42170
  const s = statusR.value;
42153
42171
  const toUcd = p.direction === "to-ucd";
@@ -42203,6 +42221,7 @@ var BoundaryCore = class {
42203
42221
  );
42204
42222
  }
42205
42223
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
42224
+ stablecoin: p.stablecoin,
42206
42225
  direction: toUcd ? "swap" : "redeem",
42207
42226
  amountIn: amountIn.toString()
42208
42227
  });
@@ -42269,6 +42288,7 @@ var BoundaryCore = class {
42269
42288
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
42270
42289
  if (floor === 0n) floor = 1n;
42271
42290
  const r = await this.deps.plugin.ops.psmSwap({
42291
+ stablecoin: p.stablecoin,
42272
42292
  direction: q.contractCall,
42273
42293
  amountIn: q.amountIn,
42274
42294
  minOut: floor.toString(),
@@ -42368,7 +42388,7 @@ var BoundaryCore = class {
42368
42388
  feeToken: "UCD",
42369
42389
  perBlockCap: s.maxSwapVolumePerBlock
42370
42390
  }),
42371
- toUsdc: direction({
42391
+ fromUcd: direction({
42372
42392
  minAmount: s.minRedeemAmount,
42373
42393
  maxAmount: s.maxRedeemAmount,
42374
42394
  amountUnit: ucdUnit,
@@ -44193,7 +44213,7 @@ var SINK_CONTRACTS = {
44193
44213
  PositionManager: sinkAddress("PositionManager"),
44194
44214
  UCDToken: sinkAddress("UCDToken"),
44195
44215
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
44196
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
44216
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
44197
44217
  SimplePSMV2: sinkAddress("SimplePSMV2"),
44198
44218
  UsdcToken: sinkAddress("UsdcToken"),
44199
44219
  UCDController: sinkAddress("UCDController")
@@ -44498,7 +44518,18 @@ var MockUpstreamPlugin = class {
44498
44518
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
44499
44519
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
44500
44520
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
44501
- getPsmStatus: () => this.read("mock-chain", () => {
44521
+ // The practice world models ONE stablecoin, and says so rather than implying a
44522
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
44523
+ // and naming anything but this one is refused the same way the real adapter refuses
44524
+ // an unsupported address — a mock that accepted any name would teach a habit the
44525
+ // real protocol punishes.
44526
+ listPsmStablecoins: () => this.read(
44527
+ "mock-chain",
44528
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
44529
+ ),
44530
+ getPsmStatus: (p) => this.read("mock-chain", () => {
44531
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44532
+ if (known) return known;
44502
44533
  const psm = this.world.psmSeed();
44503
44534
  return upOk(
44504
44535
  {
@@ -44523,6 +44554,8 @@ var MockUpstreamPlugin = class {
44523
44554
  );
44524
44555
  }),
44525
44556
  getPsmQuote: (p) => this.read("mock-chain", () => {
44557
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44558
+ if (known) return known;
44526
44559
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
44527
44560
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
44528
44561
  })
@@ -44647,6 +44680,19 @@ var MockUpstreamPlugin = class {
44647
44680
  return apply();
44648
44681
  }
44649
44682
  /** Mode `none`: every write answers with the conversational setup invitation. */
44683
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
44684
+ * refused with the same shape the real adapter uses for an address the chain does not
44685
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
44686
+ * instead of silently succeeding and teaching that any name works. */
44687
+ mockStablecoinRefusal(stablecoin) {
44688
+ const chosen = stablecoin.trim().toLowerCase();
44689
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
44690
+ return upFail({
44691
+ kind: "rejected",
44692
+ source: "mock-chain",
44693
+ 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.`
44694
+ });
44695
+ }
44650
44696
  noneRefusal() {
44651
44697
  if (this.signer && this.signer.manager.mode() === "none") {
44652
44698
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -79530,6 +79576,13 @@ function listPositionsQuery(f) {
79530
79576
  }
79531
79577
  return { document: LIST_POSITIONS, variables: { first, skip } };
79532
79578
  }
79579
+ var SUPPORTED_STABLECOINS = `
79580
+ query GetSupportedStablecoins {
79581
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79582
+ id address isSupported exchangeRate entryFee exitFee reserves decimals
79583
+ totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
79584
+ }
79585
+ }`;
79533
79586
 
79534
79587
  // src/boundary/upstream/real/psm-calls.ts
79535
79588
  var import_ethers32 = require("ethers");
@@ -79669,6 +79722,11 @@ var PsmCalls = class {
79669
79722
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79670
79723
  });
79671
79724
  }
79725
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
79726
+ * so it must come from the token rather than from a per-network assumption. */
79727
+ symbol() {
79728
+ return this.deps.stablecoinSymbol;
79729
+ }
79672
79730
  async status() {
79673
79731
  return this.call(async () => {
79674
79732
  const s = this.deps.stablecoinAddress;
@@ -80128,13 +80186,6 @@ function buildValidationContext(network, chainId) {
80128
80186
  }
80129
80187
 
80130
80188
  // src/boundary/upstream/real/write-ops.ts
80131
- function psmMainnetWriteRefusal(network, chainId) {
80132
- return {
80133
- kind: "rejected",
80134
- source: SOURCE5,
80135
- 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.`
80136
- };
80137
- }
80138
80189
  var SOURCE5 = "real-ops";
80139
80190
  var OP_LAYOUT = "dh-op-envelope-v1";
80140
80191
  function randomNonceHex() {
@@ -80482,8 +80533,7 @@ function buildWriteOps(deps) {
80482
80533
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80483
80534
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
80484
80535
  psmSwap: async (p) => {
80485
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
80486
- const pr = deps.psm();
80536
+ const pr = await deps.psm(p.stablecoin);
80487
80537
  if (!pr.ok) return upFail(pr.failure);
80488
80538
  const calls = pr.calls;
80489
80539
  const addr = calls.addresses();
@@ -80501,7 +80551,7 @@ function buildWriteOps(deps) {
80501
80551
  const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
80502
80552
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
80503
80553
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
80504
- const tokenSymbol = isSwap ? "USDC" : "UCD";
80554
+ const tokenSymbol = isSwap ? calls.symbol() : "UCD";
80505
80555
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
80506
80556
  if (!quoteR.ok) return upFail(quoteR.failure);
80507
80557
  const broadcast = async (leg, action, tx2) => {
@@ -80541,7 +80591,7 @@ function buildWriteOps(deps) {
80541
80591
  } catch (e) {
80542
80592
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
80543
80593
  }
80544
- 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}`;
80594
+ 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}`;
80545
80595
  const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
80546
80596
  if (!execHashR.ok) {
80547
80597
  const f = execHashR.failure;
@@ -80864,6 +80914,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80864
80914
  );
80865
80915
  }
80866
80916
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80917
+ const nowMs = (this.deps.clock ?? Date.now)();
80918
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80919
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
80867
80920
  const outcome = await this.deps.bridge.requestSignature({
80868
80921
  id: (0, import_node_crypto7.randomUUID)(),
80869
80922
  kind: "personal-sign",
@@ -80875,15 +80928,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80875
80928
  "(identical to how diamondhands.credit signs withdrawals).",
80876
80929
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80877
80930
  "",
80878
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80879
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80880
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80881
- "itself allows. If it expires the signature is refused, the withdrawal does not",
80882
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80883
- "start again rather than signing something you have not finished reading."
80931
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80932
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80933
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80934
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80935
+ "stay reserved until that is cleared. If the number above is already small, decline",
80936
+ "and start again rather than signing something you have not finished reading."
80884
80937
  ],
80885
80938
  expectedSigner: this.deps.borrower,
80886
80939
  chainId: this.deps.chainId,
80940
+ expiresAtSec,
80887
80941
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
80888
80942
  });
80889
80943
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -81087,13 +81141,18 @@ var RealUpstreamPlugin = class {
81087
81141
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
81088
81142
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81089
81143
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
81090
- getPsmStatus: () => {
81091
- const r = this.psmCalls();
81092
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
81093
- },
81094
- getPsmQuote: (p) => {
81095
- const r = this.psmCalls();
81096
- if (!r.ok) return Promise.resolve(upFail(r.failure));
81144
+ listPsmStablecoins: async () => {
81145
+ const verified = await this.verifiedStablecoins();
81146
+ if (!verified.ok) return upFail(verified.failure);
81147
+ return upOk(verified.rows, this.src("subgraph"));
81148
+ },
81149
+ getPsmStatus: async (p) => {
81150
+ const r = await this.psmCallsForChoice(p.stablecoin);
81151
+ return r.ok ? r.calls.status() : upFail(r.failure);
81152
+ },
81153
+ getPsmQuote: async (p) => {
81154
+ const r = await this.psmCallsForChoice(p.stablecoin);
81155
+ if (!r.ok) return upFail(r.failure);
81097
81156
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81098
81157
  }
81099
81158
  };
@@ -81161,12 +81220,13 @@ var RealUpstreamPlugin = class {
81161
81220
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
81162
81221
  delegationSetup: () => readOnly("delegationSetup"),
81163
81222
  delegationGrant: () => readOnly("delegationGrant"),
81164
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
81165
- // any non-sepolia network refuses typed — naming the network gate truthfully —
81166
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
81167
- // missing signer instead (the honest reason on that path).
81223
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
81224
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
81225
+ // signerless boot the honest refusal was always the missing signer; the network
81226
+ // gate sat in front of it and answered first. Now there is one reason left, and it
81227
+ // is the true one on this path.
81168
81228
  psmSwap: () => Promise.resolve(
81169
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
81229
+ upFail({
81170
81230
  kind: "signer-missing",
81171
81231
  source: "real-ops",
81172
81232
  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."
@@ -81283,7 +81343,7 @@ var RealUpstreamPlugin = class {
81283
81343
  session,
81284
81344
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81285
81345
  readDetails: (id) => this.readPositionDetails(id),
81286
- psm: () => this.psmCalls(),
81346
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81287
81347
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81288
81348
  });
81289
81349
  }
@@ -81417,7 +81477,7 @@ var RealUpstreamPlugin = class {
81417
81477
  session,
81418
81478
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81419
81479
  readDetails: (id) => this.readPositionDetails(id),
81420
- psm: () => this.psmCalls(),
81480
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
81421
81481
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81422
81482
  });
81423
81483
  this.opsGatewayCache.set(key, gateway);
@@ -81563,35 +81623,200 @@ var RealUpstreamPlugin = class {
81563
81623
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
81564
81624
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
81565
81625
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
81566
- psmWrapper = null;
81567
- psmCalls() {
81568
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
81626
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
81627
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
81628
+ psmWrappers = /* @__PURE__ */ new Map();
81629
+ /**
81630
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
81631
+ *
81632
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
81633
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
81634
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
81635
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
81636
+ * `getPSMStablecoins` reads the index for the same reason.
81637
+ */
81638
+ async listSupportedStablecoins() {
81639
+ const r = await this.graphProxy(
81640
+ SUPPORTED_STABLECOINS,
81641
+ {}
81642
+ );
81643
+ if (!r.ok) return r;
81644
+ const raw = r.value.data.supportedStablecoins ?? [];
81645
+ const bad = raw.find((x) => !import_ethers39.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
81646
+ if (bad) {
81647
+ return {
81648
+ ok: false,
81649
+ failure: {
81650
+ kind: "malformed",
81651
+ source: "subgraph",
81652
+ message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
81653
+ }
81654
+ };
81655
+ }
81656
+ const rows = raw.map((x) => ({
81657
+ address: String(x.address).toLowerCase(),
81658
+ decimals: Number(x.decimals)
81659
+ }));
81660
+ if (rows.length === 0) {
81661
+ return {
81662
+ ok: false,
81663
+ failure: {
81664
+ kind: "unavailable",
81665
+ source: "subgraph",
81666
+ 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".`
81667
+ }
81668
+ };
81669
+ }
81670
+ return { ok: true, rows };
81671
+ }
81672
+ /**
81673
+ * The supported set, verified — index rows each re-checked on-chain, carrying the symbol
81674
+ * read from the token itself. This is what `protocol://psm` lists and what a caller's
81675
+ * SYMBOL is resolved against.
81676
+ *
81677
+ * Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
81678
+ * the chain no longer supports (index lag behind a governance removal). Any OTHER failure
81679
+ * — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
81680
+ * chain is unreachable is the same silent-failure shape as the empty list above. If
81681
+ * nothing survives verification, that is a refusal too, and it says which side disagreed.
81682
+ */
81683
+ async verifiedStablecoins() {
81684
+ const listed = await this.listSupportedStablecoins();
81685
+ if (!listed.ok) return listed;
81686
+ const checked = await Promise.all(
81687
+ listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
81688
+ );
81689
+ const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
81690
+ if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
81691
+ const rows = checked.flatMap(
81692
+ ({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
81693
+ );
81694
+ if (rows.length === 0) {
81695
+ return {
81696
+ ok: false,
81697
+ failure: {
81698
+ kind: "unavailable",
81699
+ source: "chain-rpc",
81700
+ 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.`
81701
+ }
81702
+ };
81703
+ }
81704
+ return { ok: true, rows };
81705
+ }
81706
+ /**
81707
+ * Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
81708
+ *
81709
+ * The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
81710
+ * and the mock world accepts exactly that. The real adapter accepted only the address:
81711
+ * a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
81712
+ * throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
81713
+ * tells the model is "usually transient; retry once". So the documented input produced a
81714
+ * retry loop on the one deployment that moves real money, and a developer practising
81715
+ * against the mock never met it. Both halves are fixed here: the symbol resolves, and a
81716
+ * name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
81717
+ * (our upstream).
81718
+ */
81719
+ async psmCallsForChoice(chosen) {
81720
+ const raw = chosen.trim();
81721
+ if (raw.length === 0) {
81722
+ return {
81723
+ ok: false,
81724
+ 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." }
81725
+ };
81726
+ }
81727
+ const symbol = raw.toLowerCase();
81728
+ if (import_ethers39.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
81729
+ const verified = await this.verifiedStablecoins();
81730
+ if (!verified.ok) return { ok: false, failure: verified.failure };
81731
+ const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
81732
+ if (hits.length > 1) {
81733
+ return {
81734
+ ok: false,
81735
+ failure: {
81736
+ kind: "rejected",
81737
+ source: "chain-rpc",
81738
+ 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.`
81739
+ }
81740
+ };
81741
+ }
81742
+ const hit = hits[0];
81743
+ if (!hit) {
81744
+ const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
81745
+ return {
81746
+ ok: false,
81747
+ failure: {
81748
+ kind: "rejected",
81749
+ source: "chain-rpc",
81750
+ 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.`
81751
+ }
81752
+ };
81753
+ }
81754
+ return this.psmCallsFor(hit.address);
81755
+ }
81756
+ /**
81757
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
81758
+ *
81759
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
81760
+ * indexer is how the list is discovered and is not authority over it: it can lag a
81761
+ * governance removal, and acting on a stale list would build a swap the contract reverts
81762
+ * — after the user has approved it in their wallet. List from the index, verify on the
81763
+ * chain, then sign.
81764
+ */
81765
+ async psmCallsFor(stablecoinAddress) {
81766
+ if (!import_ethers39.ethers.isAddress(stablecoinAddress)) {
81767
+ throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
81768
+ }
81769
+ const key = stablecoinAddress.toLowerCase();
81770
+ const cached = this.psmWrappers.get(key);
81771
+ if (cached) return { ok: true, calls: cached };
81569
81772
  const psmAddress = this.contracts["SimplePSMV2"];
81570
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
81571
- if (!psmAddress || !stablecoinAddress) {
81572
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
81773
+ if (!psmAddress) {
81573
81774
  return {
81574
81775
  ok: false,
81575
81776
  failure: {
81576
81777
  kind: "unavailable",
81577
81778
  source: "chain-rpc",
81578
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
81779
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
81579
81780
  }
81580
81781
  };
81581
81782
  }
81783
+ let supported;
81784
+ let symbol;
81785
+ try {
81786
+ const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81787
+ supported = await psm["supportedStablecoins"](key);
81788
+ const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81789
+ symbol = await erc20["symbol"]();
81790
+ } catch (e) {
81791
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
81792
+ }
81793
+ if (!supported) {
81794
+ return {
81795
+ ok: false,
81796
+ failure: {
81797
+ kind: "rejected",
81798
+ source: "chain-rpc",
81799
+ 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.`
81800
+ }
81801
+ };
81802
+ }
81803
+ const stablecoinAddress2 = key;
81582
81804
  const ucdTokenAddress = this.contracts["UCDToken"];
81583
81805
  const ucdControllerAddress = this.contracts["UCDController"];
81584
- this.psmWrapper = new PsmCalls({
81806
+ const built = new PsmCalls({
81585
81807
  provider: this.provider,
81586
81808
  psmAddress,
81587
- stablecoinAddress,
81588
- stablecoinSymbol: "USDC",
81809
+ stablecoinAddress: stablecoinAddress2,
81810
+ // Read from the token, never assumed. The old value was the literal "USDC", which
81811
+ // stops being true the moment a second coin is supported.
81812
+ stablecoinSymbol: symbol,
81589
81813
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
81590
81814
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
81591
81815
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
81592
81816
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
81593
81817
  });
81594
- return { ok: true, calls: this.psmWrapper };
81818
+ this.psmWrappers.set(key, built);
81819
+ return { ok: true, calls: built };
81595
81820
  }
81596
81821
  src(id) {
81597
81822
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -81854,6 +82079,7 @@ function renderApprovalPage(sessionId, nonce) {
81854
82079
  <div id="request" class="hidden">
81855
82080
  <div id="action" class="action"></div>
81856
82081
  <div id="card" class="card"></div>
82082
+ <div id="deadline" class="status hidden"></div>
81857
82083
  <button id="approve">Approve in wallet</button>
81858
82084
  <button id="reject">Reject</button>
81859
82085
  </div>
@@ -81886,10 +82112,19 @@ const statusEl = document.getElementById("status");
81886
82112
  const requestEl = document.getElementById("request");
81887
82113
  const actionEl = document.getElementById("action");
81888
82114
  const cardEl = document.getElementById("card");
82115
+ const approveEl = document.getElementById("approve");
82116
+ const rejectEl = document.getElementById("reject");
82117
+ const deadlineEl = document.getElementById("deadline");
82118
+ let deadlineTimer = null;
81889
82119
  const walletEl = document.getElementById("wallet");
81890
82120
  let account = null;
81891
82121
  let chainId = null;
81892
82122
  let current = null;
82123
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
82124
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
82125
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
82126
+ // card the page never renders is one the human can neither read nor reject.
82127
+ const pending = new Map();
81893
82128
 
81894
82129
  function post(path, body) {
81895
82130
  return fetch(path, {
@@ -81952,43 +82187,135 @@ async function onAccountsChanged(accounts) {
81952
82187
  account = (accounts && accounts[0]) || null;
81953
82188
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81954
82189
  showWallet();
81955
- clearRequest("Wallet changed \u2014 pending request invalidated.");
82190
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81956
82191
  }
81957
82192
 
81958
82193
  async function onChainChanged(cid) {
81959
82194
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81960
82195
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81961
82196
  showWallet();
81962
- clearRequest("Network changed \u2014 pending request invalidated.");
82197
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81963
82198
  }
81964
82199
 
81965
82200
  function listen() {
81966
82201
  const es = new EventSource(BASE + "events?s=" + SESSION);
81967
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
82202
+ es.onmessage = (ev) => {
82203
+ const next = JSON.parse(ev.data);
82204
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
82205
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
82206
+ pending.set(next.id, next);
82207
+ showPending();
82208
+ };
81968
82209
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81969
82210
  }
81970
82211
 
82212
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
82213
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
82214
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
82215
+ // gets approved.
82216
+ function pickPending() {
82217
+ const held = current ? pending.get(current.id) : undefined;
82218
+ if (held && held.mirror !== true) return held;
82219
+ let best = held || null;
82220
+ pending.forEach((frame) => {
82221
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
82222
+ });
82223
+ return best;
82224
+ }
82225
+
82226
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
82227
+ function showPending(emptyText) {
82228
+ const next = pickPending();
82229
+ if (!next) {
82230
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
82231
+ // an expiry for a ceremony that is already decided.
82232
+ stopDeadline();
82233
+ current = null;
82234
+ requestEl.classList.add("hidden");
82235
+ if (emptyText) showStatus(emptyText);
82236
+ return;
82237
+ }
82238
+ current = next;
82239
+ renderRequest();
82240
+ }
82241
+
81971
82242
  function renderRequest() {
81972
82243
  actionEl.textContent = current.action;
81973
82244
  cardEl.textContent = current.card.join("\\n");
82245
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
82246
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
82247
+ // server-side, which is the actual boundary.
82248
+ const mirrored = current.mirror === true;
82249
+ approveEl.classList.toggle("hidden", mirrored);
82250
+ rejectEl.classList.remove("hidden");
81974
82251
  requestEl.classList.remove("hidden");
81975
- showStatus("Review the operation below. Nothing signs without your approval.");
82252
+ showStatus(mirrored
82253
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
82254
+ : "Review the operation below. Nothing signs without your approval.");
82255
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
82256
+ // card promoted after another settles gets its own clock, not the previous one's.
82257
+ startDeadline();
81976
82258
  }
81977
82259
 
82260
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
82261
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
82262
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
82263
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
82264
+ // honest without it needing to know anything about quantum windows.
82265
+ function stopDeadline() {
82266
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82267
+ deadlineEl.classList.add("hidden");
82268
+ }
82269
+
82270
+ function startDeadline() {
82271
+ stopDeadline();
82272
+ if (!current || typeof current.expiresAtSec !== "number") return;
82273
+ const tick = () => {
82274
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
82275
+ if (left > 0) {
82276
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
82277
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
82278
+ } else {
82279
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
82280
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
82281
+ // after. The button is deliberately left enabled \u2014 declining is still the right
82282
+ // action and the page must not trap them.
82283
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
82284
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82285
+ }
82286
+ deadlineEl.classList.remove("hidden");
82287
+ };
82288
+ tick();
82289
+ deadlineTimer = setInterval(tick, 1000);
82290
+ }
82291
+
82292
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
82293
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
82294
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81978
82295
  function clearRequest(text) {
81979
- current = null;
81980
- requestEl.classList.add("hidden");
81981
- showStatus(text);
82296
+ if (current) pending.delete(current.id);
82297
+ showPending(text);
82298
+ }
82299
+
82300
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
82301
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
82302
+ // stays readable and rejectable.
82303
+ function invalidatePageRequests(text) {
82304
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
82305
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
81982
82306
  }
81983
82307
 
81984
- document.getElementById("reject").onclick = async () => {
82308
+ rejectEl.onclick = async () => {
81985
82309
  if (!current) return;
81986
82310
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81987
82311
  clearRequest("Rejected. Waiting for the next request\u2026");
81988
82312
  };
81989
82313
 
81990
- document.getElementById("approve").onclick = async () => {
82314
+ approveEl.onclick = async () => {
81991
82315
  if (!current) return;
82316
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
82317
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
82318
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81992
82319
  const req = current;
81993
82320
  try {
81994
82321
  if (req.kind === "transaction") {
@@ -82005,7 +82332,10 @@ document.getElementById("approve").onclick = async () => {
82005
82332
  const fbody = await fr.json();
82006
82333
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
82007
82334
  const fresh = fbody.request;
82008
- // \u2026re-render what will actually sign\u2026
82335
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
82336
+ // another card arriving while the wallet popup is open re-picks from there, and the
82337
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
82338
+ pending.set(fresh.id, fresh);
82009
82339
  current = fresh; renderRequest();
82010
82340
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
82011
82341
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -82160,9 +82490,6 @@ var SignatureBridge = class {
82160
82490
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
82161
82491
  maxPending;
82162
82492
  attachGraceMs;
82163
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
82164
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
82165
- lastAttachedMs = 0;
82166
82493
  server = null;
82167
82494
  port = 0;
82168
82495
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -82313,13 +82640,16 @@ var SignatureBridge = class {
82313
82640
  enqueuedMs: now,
82314
82641
  resolve,
82315
82642
  settled: false,
82316
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
82643
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
82644
+ owner: this.wcActive ? "wc" : "page",
82645
+ dispatched: false,
82646
+ lastAttachedMs: now
82317
82647
  };
82318
82648
  this.pending.set(request.id, entry);
82319
- if (this.wcActive) {
82649
+ if (entry.owner === "wc") {
82320
82650
  void this.driveWc(entry);
82321
82651
  } else {
82322
- this.push(request);
82652
+ this.pushEntry(entry);
82323
82653
  }
82324
82654
  });
82325
82655
  }
@@ -82340,10 +82670,16 @@ var SignatureBridge = class {
82340
82670
  enqueuedMs: now,
82341
82671
  resolve,
82342
82672
  settled: false,
82343
- collect
82673
+ collect,
82674
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
82675
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
82676
+ // ceremony could not reach quorum through the very pages it is broadcast to.
82677
+ owner: "both",
82678
+ dispatched: false,
82679
+ lastAttachedMs: now
82344
82680
  };
82345
82681
  this.pending.set(request.id, entry);
82346
- this.push(request);
82682
+ this.pushEntry(entry);
82347
82683
  if (this.wcActive) void this.driveWcCollection(entry);
82348
82684
  });
82349
82685
  }
@@ -82382,7 +82718,9 @@ var SignatureBridge = class {
82382
82718
  }
82383
82719
  try {
82384
82720
  if (req.kind === "transaction") {
82721
+ this.pushEntry(entry);
82385
82722
  const tx2 = req.tx;
82723
+ entry.dispatched = true;
82386
82724
  const txHash = await transport.request("eth_sendTransaction", [
82387
82725
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
82388
82726
  ]);
@@ -82394,11 +82732,22 @@ var SignatureBridge = class {
82394
82732
  req.card = fresh.card;
82395
82733
  }
82396
82734
  const ps = req.personalSign;
82735
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
82736
+ this.settle(entry, {
82737
+ status: "invalidated",
82738
+ 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)`
82739
+ });
82740
+ return;
82741
+ }
82742
+ this.pushEntry(entry);
82743
+ entry.dispatched = true;
82397
82744
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
82398
82745
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82399
82746
  } else {
82747
+ this.pushEntry(entry);
82400
82748
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
82401
82749
  const payload = withEip712DomainType2(req.typedData);
82750
+ entry.dispatched = true;
82402
82751
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
82403
82752
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82404
82753
  }
@@ -82418,30 +82767,55 @@ var SignatureBridge = class {
82418
82767
  * with a live attachment is in use and must never be evicted. */
82419
82768
  attachedNow() {
82420
82769
  if (this.wcActive) return true;
82421
- for (const s of this.sessions.values()) if (s.sse) return true;
82770
+ return this.pageAttached();
82771
+ }
82772
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
82773
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
82774
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
82775
+ * WalletConnect and must stay global for the connector's eviction predicate. */
82776
+ pageAttached() {
82777
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
82422
82778
  return false;
82423
82779
  }
82780
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
82781
+ * predicate said "a WC session is attached", which is true but irrelevant to a
82782
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
82783
+ * out the full expiry instead of failing fast at the grace. */
82784
+ attachedFor(entry) {
82785
+ if (entry.owner === "wc") return this.wcActive;
82786
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
82787
+ return this.pageAttached();
82788
+ }
82424
82789
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
82425
82790
  * interval; tests call it directly with the injected clock advanced. Order matters:
82426
82791
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
82427
82792
  sweep() {
82428
82793
  const now = this.clock();
82429
- const attached = this.attachedNow();
82430
- if (attached) this.lastAttachedMs = now;
82431
82794
  for (const entry of this.pending.values()) {
82432
82795
  if (entry.settled) continue;
82433
82796
  if (now >= entry.deadlineMs) {
82434
82797
  this.settle(entry, { status: "expired" });
82435
82798
  continue;
82436
82799
  }
82437
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
82438
- this.settle(entry, {
82439
- status: "invalidated",
82440
- 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`
82441
- });
82800
+ if (this.attachedFor(entry)) {
82801
+ entry.lastAttachedMs = now;
82802
+ continue;
82442
82803
  }
82804
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
82805
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
82443
82806
  }
82444
82807
  }
82808
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
82809
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
82810
+ unattendedReason(entry) {
82811
+ if (entry.dispatched && entry.request.kind === "transaction") {
82812
+ 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.";
82813
+ }
82814
+ if (entry.owner === "wc") {
82815
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
82816
+ }
82817
+ 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`;
82818
+ }
82445
82819
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
82446
82820
  walletConnectActive() {
82447
82821
  return this.wcActive;
@@ -82565,6 +82939,7 @@ var SignatureBridge = class {
82565
82939
  if (info && refusal) {
82566
82940
  this.wcActive = false;
82567
82941
  this.rebuildSharedWallet();
82942
+ this.demoteWcEntries();
82568
82943
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82569
82944
  `);
82570
82945
  return;
@@ -82574,7 +82949,10 @@ var SignatureBridge = class {
82574
82949
  if (info === null) {
82575
82950
  for (const entry of this.pending.values()) {
82576
82951
  if (!entry.settled && !entry.collect) {
82577
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82952
+ this.settle(entry, {
82953
+ status: "invalidated",
82954
+ 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"
82955
+ });
82578
82956
  }
82579
82957
  }
82580
82958
  }
@@ -82646,9 +83024,7 @@ var SignatureBridge = class {
82646
83024
  session.sse?.end();
82647
83025
  session.sse = res;
82648
83026
  for (const entry of this.pending.values()) {
82649
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
82650
-
82651
- `);
83027
+ if (!entry.settled) res.write(this.wireFor(entry));
82652
83028
  }
82653
83029
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
82654
83030
  keepAlive.unref();
@@ -82724,10 +83100,36 @@ var SignatureBridge = class {
82724
83100
  }
82725
83101
  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";
82726
83102
  for (const entry of this.pending.values()) {
82727
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
83103
+ if (entry.settled || entry.collect) continue;
83104
+ if (this.ownedByWc(entry)) continue;
83105
+ this.settle(entry, { status: "invalidated", reason });
82728
83106
  }
82729
83107
  this.ok(res);
82730
83108
  }
83109
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
83110
+ * session hands the request back to the page rather than stranding it. */
83111
+ ownedByWc(entry) {
83112
+ if (entry.owner !== "wc") return false;
83113
+ return this.wcActive || entry.dispatched;
83114
+ }
83115
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
83116
+ * them so the card stops rendering read-only. Collections are already `both`.
83117
+ *
83118
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
83119
+ * phone is still holding does not replace one wallet with another, it adds a second: the
83120
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
83121
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
83122
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
83123
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
83124
+ * false for them, and `unattendedReason` says plainly that the phone may already have
83125
+ * acted. */
83126
+ demoteWcEntries() {
83127
+ for (const entry of this.pending.values()) {
83128
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
83129
+ entry.owner = "page";
83130
+ this.pushEntry(entry);
83131
+ }
83132
+ }
82731
83133
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
82732
83134
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
82733
83135
  async onFinalize(body, res) {
@@ -82741,6 +83143,10 @@ var SignatureBridge = class {
82741
83143
  this.deny(res, 400, "finalize applies only to personal-sign requests");
82742
83144
  return;
82743
83145
  }
83146
+ if (this.ownedByWc(entry)) {
83147
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
83148
+ return;
83149
+ }
82744
83150
  if (entry.finalize) {
82745
83151
  let fresh;
82746
83152
  try {
@@ -82767,10 +83173,22 @@ var SignatureBridge = class {
82767
83173
  return;
82768
83174
  }
82769
83175
  if (body["approved"] !== true) {
83176
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
83177
+ this.settle(entry, {
83178
+ status: "invalidated",
83179
+ 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."
83180
+ });
83181
+ this.ok(res);
83182
+ return;
83183
+ }
82770
83184
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
82771
83185
  this.ok(res);
82772
83186
  return;
82773
83187
  }
83188
+ if (this.ownedByWc(entry)) {
83189
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
83190
+ return;
83191
+ }
82774
83192
  const account = String(body["account"] ?? "");
82775
83193
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
82776
83194
  this.deny(res, 400, "approved result requires the signing account");
@@ -82807,11 +83225,20 @@ var SignatureBridge = class {
82807
83225
  this.pending.delete(entry.request.id);
82808
83226
  entry.resolve(outcome);
82809
83227
  }
82810
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
82811
- push(request) {
82812
- const data = `data: ${JSON.stringify(request)}
83228
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
83229
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
83230
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
83231
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
83232
+ * a permanently read-only card that nobody is allowed to decide. */
83233
+ wireFor(entry) {
83234
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
83235
+ return `data: ${JSON.stringify(payload)}
82813
83236
 
82814
83237
  `;
83238
+ }
83239
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
83240
+ pushEntry(entry) {
83241
+ const data = this.wireFor(entry);
82815
83242
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82816
83243
  }
82817
83244
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -83294,7 +83721,7 @@ var FIELD_GLOSSARY = {
83294
83721
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83295
83722
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83296
83723
  // ---- psm quote ----
83297
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83724
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
83298
83725
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83299
83726
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83300
83727
  amountInToken: "the token you pay with",
@@ -83361,6 +83788,17 @@ function signerModeSourceClause(d) {
83361
83788
  function phoneWalletOffer(d) {
83362
83789
  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";
83363
83790
  }
83791
+ function worldAxes(d) {
83792
+ const axes = [];
83793
+ axes.push(
83794
+ offers(d, "mock-simulated") ? "practice (mock) or real adapter" : "the REAL adapter \u2014 there is no practice (mock) world on this deployment"
83795
+ );
83796
+ axes.push(
83797
+ 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"
83798
+ );
83799
+ axes.push("that writes are enabled, and what actually gates one is whether a signing identity is connected");
83800
+ return axes.join("; ");
83801
+ }
83364
83802
  function moneyTruth(d) {
83365
83803
  const practice = offers(d, "mock-simulated");
83366
83804
  const sepolia = d.networks.includes("sepolia");
@@ -83392,11 +83830,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83392
83830
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83393
83831
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83394
83832
  signerModes: GUIDE_SIGNER_MODES,
83395
- // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
83396
- // leg genuinely is not there until an operator configures it. The first draft of this line
83397
- // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
83398
- // about — the default rendering would have promised a QR that most installs cannot show.
83399
- // A live boot derives this from env either way (network-switch.ts).
83833
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
83834
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
83835
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
83836
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
83837
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
83838
+ // nobody supplied a deployment at all, and understating a capability there is the safe
83839
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
83840
+ // overclaim C-44 is about — promising a QR the build cannot show.
83400
83841
  walletConnect: false
83401
83842
  };
83402
83843
  function servedNetworks(d) {
@@ -83407,7 +83848,7 @@ function servedNetworks(d) {
83407
83848
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
83408
83849
  }
83409
83850
  if (mainnet) {
83410
- 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";
83851
+ 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";
83411
83852
  }
83412
83853
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
83413
83854
  }
@@ -83486,13 +83927,14 @@ function switchNetworkRules(d) {
83486
83927
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83487
83928
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83488
83929
  A sepolia position does not exist on mainnet and vice versa.
83489
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83490
- and every one still requires the user's explicit confirmation plus the signer
83491
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83930
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83931
+ mainnet they move REAL money, and every one still requires the user's explicit
83932
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83933
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83934
+ signed.`;
83492
83935
  }
83493
83936
  const only = d.networks[0];
83494
83937
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83495
- 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.";
83496
83938
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83497
83939
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
83498
83940
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -83501,7 +83943,9 @@ function switchNetworkRules(d) {
83501
83943
  belong to ${only} and would not exist anywhere else.
83502
83944
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83503
83945
  confirmation plus the signer ceremony.
83504
- - ${psm}`;
83946
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83947
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83948
+ anything is signed.`;
83505
83949
  }
83506
83950
  function wrongNetworkTroubleshootingRow(d) {
83507
83951
  if (d.networks.length > 1) {
@@ -83521,20 +83965,23 @@ function switchNetworkIndexLine(d) {
83521
83965
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83522
83966
  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`;
83523
83967
  }
83524
- function psmAvailabilityNote(d) {
83525
- if (d.networks.includes("sepolia")) return "";
83526
- return `**Not executable on this deployment.** The PSM write port refuses on every network
83527
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
83528
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
83529
- the mechanism, not an offer: say so before a user plans around it.
83530
-
83531
- `;
83968
+ function psmStablecoinRealityNote(d) {
83969
+ if (d.networks.includes("sepolia")) {
83970
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83971
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83972
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83973
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83974
+ }
83975
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83976
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83977
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83978
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83979
+ have to guess whether the money is real.`;
83532
83980
  }
83533
83981
  function authorizationModeBullets(d) {
83534
83982
  const bullets = [];
83535
83983
  if (offers(d, "external")) {
83536
- bullets.push(` - \`external\` \u2014 the user approves in their OWN wallet (browser popup, or WalletConnect
83537
- mobile via QR/paste-code). Real adapter and mock. For TRANSACTIONS the approval card
83984
+ 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
83538
83985
  is decoded from the exact bytes being signed \u2014 what the user reads IS what executes.
83539
83986
  The ONE exception is the BTC withdrawal's EXECUTE phase: an opaque 32-byte hash the
83540
83987
  approval page states plainly it CANNOT decode. Never extend the card promise over
@@ -83597,8 +84044,7 @@ install matrix. ${connectorInstallNote(d)}
83597
84044
  Nothing needs a config file. Three steps:
83598
84045
 
83599
84046
  **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
83600
- \`protocol_status\`, then tell the user: practice (mock) or real adapter; sepolia
83601
- (practice money) or mainnet (real money); whether writes are enabled here and which
84047
+ \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
83602
84048
  signer modes exist; current terms (\`protocol_terms\`).
83603
84049
 
83604
84050
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
@@ -83642,7 +84088,7 @@ on the real adapter and the mock.
83642
84088
  **The walkthrough:**
83643
84089
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83644
84090
  desktop browser; ${approvalPageLocation(d)}
83645
- 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) + "."}
84091
+ 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) + "."}
83646
84092
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83647
84093
  login ceremony explicitly (one typed-data signature in the wallet).
83648
84094
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83681,7 +84127,14 @@ on the real adapter and the mock.
83681
84127
  hash the SDK builds internally, which the approval page shows bare and says plainly it
83682
84128
  cannot decode (the production web app signs the same way). Tell the user before that
83683
84129
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83684
- expect an unreadable card and click through the readable one.
84130
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
84131
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
84132
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
84133
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
84134
+ on the card, and the page is the only surface that shows it. With no page attached the
84135
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
84136
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
84137
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
83685
84138
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83686
84139
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83687
84140
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
@@ -83700,8 +84153,7 @@ on the real adapter and the mock.
83700
84153
  10 UCD.
83701
84154
 
83702
84155
  **Disconnecting \u2014 "log out / sign out / forget my wallet" (\`signer_setup\` action
83703
- \`disconnect\`):** the FULL wallet flush. It ends every approval-page session and any
83704
- WalletConnect session (pending approvals are cancelled loudly), discards the login
84156
+ \`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
83705
84157
  token from server memory AND revokes it at the service, and unbinds the borrower
83706
84158
  identity. Reconnecting afterwards ALWAYS requires opening the approval page again and
83707
84159
  a fresh wallet signature \u2014 a disconnect can never silently reconnect. Two truths to
@@ -83762,9 +84214,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83762
84214
 
83763
84215
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83764
84216
  signed, amounts included. Read it back when the user asks what happened.`,
83765
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
84217
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
83766
84218
 
83767
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
84219
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83768
84220
  directions, in user words:
83769
84221
 
83770
84222
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83772,20 +84224,27 @@ directions, in user words:
83772
84224
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83773
84225
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83774
84226
  and you receive 99 UCD.
83775
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
83776
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
83777
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
83778
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
83779
- shortfall refuses with both figures (available vs required).
84227
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
84228
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
84229
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
84230
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
84231
+ reserves, and a shortfall refuses with both figures (available vs required).
84232
+
84233
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
84234
+ default and that is deliberate: the PSM can carry several coins, each with its own
84235
+ reserves, fees and limits, so picking one silently would move someone's money through a
84236
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
84237
+ there rather than guessing one.
83780
84238
 
83781
84239
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83782
84240
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83783
84241
  1e18 = 1:1) and can be changed by protocol governance.
83784
84242
 
83785
84243
  **Limits and switches** (all visible in \`protocol://psm\`):
83786
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
83787
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
83788
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
84244
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
84245
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
84246
+ direction is DISABLED.
84247
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
83789
84248
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83790
84249
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
83791
84250
 
@@ -83794,23 +84253,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
83794
84253
  change between your quote and execution; the floor makes a drifted execution REFUSE
83795
84254
  rather than silently deliver less than quoted.
83796
84255
 
83797
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83798
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83799
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83800
- the money is real. On mainnet the stablecoin is real Circle USDC.
84256
+ ${psmStablecoinRealityNote(d)}
83801
84257
 
83802
84258
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83803
84259
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83804
84260
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83805
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
83806
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
83807
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84261
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84262
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
84263
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83808
84264
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83809
84265
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83810
84266
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83811
84267
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83812
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83813
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
84268
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84269
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84270
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
84271
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
84272
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
84273
+ per-operation and per-block limits,
84274
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
84275
+ mainnet swap, not after.`,
83814
84276
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83815
84277
 
83816
84278
  Every fund-moving operation needs TWO things, always in this order:
@@ -84069,9 +84531,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
84069
84531
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
84070
84532
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
84071
84533
  the same way \u2014 reconnect on the user's word.`}
84072
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
84073
- 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
84074
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
84534
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
84535
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
84536
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
84537
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
84538
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
84075
84539
  ${wrongNetworkTroubleshootingRow(d)}
84076
84540
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
84077
84541
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -84147,7 +84611,7 @@ function renderGuideIndex(deployment) {
84147
84611
 
84148
84612
  - getting-started \u2014 what this product is, practice-vs-real-money honesty (three cases)
84149
84613
  - first-setup \u2014 zero to ready by conversation (authorization choice included)
84150
- - connect-wallet \u2014 external-wallet walkthrough: approval page, extension or WalletConnect QR, popup cadence, login honesty, disconnect/log-out
84614
+ - 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
84151
84615
  - lifecycle \u2014 the exact calls, create \u2192 deposit \u2192 mint \u2192 pay \u2192 extend \u2192 withdraw
84152
84616
  - fees \u2014 the two fee models, plainly
84153
84617
  - psm \u2014 exchanging UCD \u2194 USDC: both directions, the two fees WITH their tokens, limits, why a floor exists
@@ -84229,12 +84693,13 @@ function guideDeployment(overrides, env) {
84229
84693
  tier: overrides?.bridgeMount ? "hosted" : "local",
84230
84694
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
84231
84695
  signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
84232
- // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
84233
- // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
84234
- // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
84235
- // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
84236
- // about the same server, which is exactly what they did before this line existed.
84237
- walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
84696
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
84697
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
84698
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
84699
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
84700
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
84701
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
84702
+ walletConnect: wcEnabled(env)
84238
84703
  };
84239
84704
  }
84240
84705
  function assembleWorld(opts) {
@@ -84874,39 +85339,45 @@ function registerPsmTools(server, getB) {
84874
85339
  server,
84875
85340
  "psm_quote",
84876
85341
  {
84877
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84878
- 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.",
85342
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
85343
+ 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.",
84879
85344
  inputSchema: {
84880
- 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)"),
84881
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
85345
+ stablecoin: import_zod4.z.string().min(1).describe(
85346
+ "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."
85347
+ ),
85348
+ 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)"),
85349
+ 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.")
84882
85350
  },
84883
85351
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84884
85352
  },
84885
- async ({ direction, amount }) => guarded(async () => {
84886
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
85353
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
85354
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
84887
85355
  const problem = checkUcdAmount(amount, label);
84888
85356
  if (problem) return validationFailed(problem);
84889
85357
  const b = getB();
84890
85358
  if (!b.ok) return renderError(b.error);
84891
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
85359
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
84892
85360
  })
84893
85361
  );
84894
85362
  registerBoundaryTool(
84895
85363
  server,
84896
85364
  "psm_swap",
84897
85365
  {
84898
- title: "Exchange UCD \u2194 USDC through the PSM",
84899
- 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).",
85366
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
85367
+ 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).",
84900
85368
  inputSchema: {
84901
- 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)"),
84902
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
85369
+ stablecoin: import_zod4.z.string().min(1).describe(
85370
+ "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."
85371
+ ),
85372
+ 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)"),
85373
+ 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."),
84903
85374
  confirmed: confirmedSchema2
84904
85375
  },
84905
85376
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84906
85377
  },
84907
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84908
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84909
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
85378
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
85379
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
85380
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84910
85381
  const gate = requireConfirmation(
84911
85382
  confirmed,
84912
85383
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84916,7 +85387,7 @@ function registerPsmTools(server, getB) {
84916
85387
  if (problem) return validationFailed(problem);
84917
85388
  const b = getB();
84918
85389
  if (!b.ok) return renderError(b.error);
84919
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
85390
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84920
85391
  })
84921
85392
  );
84922
85393
  }
@@ -85362,7 +85833,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85362
85833
  "network_switch",
85363
85834
  {
85364
85835
  title: "Show or switch the active network",
85365
- 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.",
85836
+ 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.",
85366
85837
  inputSchema: {
85367
85838
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
85368
85839
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -85380,7 +85851,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85380
85851
  lines.push(
85381
85852
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
85382
85853
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
85383
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
85854
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
85384
85855
  "Session-scoped: the configured default network returns when the server restarts."
85385
85856
  );
85386
85857
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -85486,13 +85957,26 @@ function registerProtocolResources(server, getB) {
85486
85957
  "protocol://psm",
85487
85958
  {
85488
85959
  title: "PSM status (UCD \u2194 USDC exchange)",
85489
- 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).",
85960
+ 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.",
85490
85961
  mimeType: "application/json"
85491
85962
  },
85492
85963
  async (uri) => {
85493
85964
  const b = getB();
85494
85965
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
85495
- const env = await b.boundary.getPsmStatus();
85966
+ const listed = await b.boundary.listPsmStablecoins();
85967
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85968
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85969
+ const failed = perCoin.find((s) => !s.ok);
85970
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85971
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85972
+ const head = coins[0];
85973
+ const env = {
85974
+ ...listed,
85975
+ data: {
85976
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85977
+ stablecoins: coins
85978
+ }
85979
+ };
85496
85980
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
85497
85981
  }
85498
85982
  );
@@ -85705,12 +86189,15 @@ function composeConnector(opts, rawPublicOrigin) {
85705
86189
  for (const session of sessions.values()) held.add(session.tenant);
85706
86190
  return held;
85707
86191
  }
85708
- function isReclaimable(tenantKey, world, held) {
85709
- if (held.has(tenantKey)) return false;
86192
+ function isEvictable(world) {
85710
86193
  const bridge = world.deps.signer?.bridge;
85711
86194
  if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85712
86195
  return true;
85713
86196
  }
86197
+ function isReclaimable(tenantKey, world, held) {
86198
+ if (held.has(tenantKey)) return false;
86199
+ return isEvictable(world);
86200
+ }
85714
86201
  function sweepService() {
85715
86202
  const now = clock();
85716
86203
  for (const [sid, session] of [...sessions]) {
@@ -85726,13 +86213,12 @@ function composeConnector(opts, rawPublicOrigin) {
85726
86213
  dropWorld(tenantKey, world, "idle eviction");
85727
86214
  }
85728
86215
  }
85729
- function reclaimIdleWorld() {
85730
- const held = tenantsWithSessions();
86216
+ function leastRecentlyActive(eligible) {
85731
86217
  let victimKey = null;
85732
86218
  let victim = null;
85733
86219
  let oldest = Number.POSITIVE_INFINITY;
85734
86220
  for (const [tenantKey, world] of readyWorlds) {
85735
- if (!isReclaimable(tenantKey, world, held)) continue;
86221
+ if (!eligible(tenantKey, world)) continue;
85736
86222
  const activeAt = lastActivity.get(tenantKey) ?? 0;
85737
86223
  if (activeAt < oldest) {
85738
86224
  oldest = activeAt;
@@ -85740,8 +86226,23 @@ function composeConnector(opts, rawPublicOrigin) {
85740
86226
  victim = world;
85741
86227
  }
85742
86228
  }
85743
- if (victimKey === null || victim === null) return false;
85744
- dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
86229
+ return victimKey !== null && victim !== null ? [victimKey, victim] : null;
86230
+ }
86231
+ function reclaimIdleWorld() {
86232
+ const held = tenantsWithSessions();
86233
+ const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
86234
+ if (tier1) {
86235
+ dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
86236
+ return true;
86237
+ }
86238
+ const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
86239
+ if (!tier2) return false;
86240
+ for (const [sid, session] of [...sessions]) {
86241
+ if (session.tenant !== tier2[0]) continue;
86242
+ sessions.delete(sid);
86243
+ void session.transport.close().catch(() => void 0);
86244
+ }
86245
+ dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
85745
86246
  return true;
85746
86247
  }
85747
86248
  class TenantCapacityError extends Error {
@@ -85959,7 +86460,8 @@ function composeConnector(opts, rawPublicOrigin) {
85959
86460
  if (opts.auth) {
85960
86461
  authImpl = opts.auth;
85961
86462
  } else {
85962
- const wcLeg = opts.siweWc ?? (opts.env["DH_WC_PROJECT_ID"] ? { projectId: opts.env["DH_WC_PROJECT_ID"] } : void 0);
86463
+ const envWcProjectId = resolvedWcProjectId(opts.env);
86464
+ const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
85963
86465
  const siwe = new SiweOAuthProvider({
85964
86466
  origin: () => publicOrigin,
85965
86467
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,