@gvnrdao/dh-mcp 0.5.14 → 0.5.15

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.15";
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,19 @@ function listPositionsQuery(f) {
79530
79576
  }
79531
79577
  return { document: LIST_POSITIONS, variables: { first, skip } };
79532
79578
  }
79579
+ var SUPPORTED_STABLECOINS = `
79580
+ query SupportedStablecoins {
79581
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79582
+ id
79583
+ address
79584
+ isSupported
79585
+ decimals
79586
+ entryFee
79587
+ exitFee
79588
+ reserves
79589
+ }
79590
+ }
79591
+ `;
79533
79592
 
79534
79593
  // src/boundary/upstream/real/psm-calls.ts
79535
79594
  var import_ethers32 = require("ethers");
@@ -79669,6 +79728,11 @@ var PsmCalls = class {
79669
79728
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79670
79729
  });
79671
79730
  }
79731
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
79732
+ * so it must come from the token rather than from a per-network assumption. */
79733
+ symbol() {
79734
+ return this.deps.stablecoinSymbol;
79735
+ }
79672
79736
  async status() {
79673
79737
  return this.call(async () => {
79674
79738
  const s = this.deps.stablecoinAddress;
@@ -80128,13 +80192,6 @@ function buildValidationContext(network, chainId) {
80128
80192
  }
80129
80193
 
80130
80194
  // 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
80195
  var SOURCE5 = "real-ops";
80139
80196
  var OP_LAYOUT = "dh-op-envelope-v1";
80140
80197
  function randomNonceHex() {
@@ -80482,8 +80539,7 @@ function buildWriteOps(deps) {
80482
80539
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80483
80540
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
80484
80541
  psmSwap: async (p) => {
80485
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
80486
- const pr = deps.psm();
80542
+ const pr = await deps.psm(p.stablecoin);
80487
80543
  if (!pr.ok) return upFail(pr.failure);
80488
80544
  const calls = pr.calls;
80489
80545
  const addr = calls.addresses();
@@ -80864,6 +80920,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80864
80920
  );
80865
80921
  }
80866
80922
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80923
+ const nowMs = (this.deps.clock ?? Date.now)();
80924
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80925
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
80867
80926
  const outcome = await this.deps.bridge.requestSignature({
80868
80927
  id: (0, import_node_crypto7.randomUUID)(),
80869
80928
  kind: "personal-sign",
@@ -80875,15 +80934,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80875
80934
  "(identical to how diamondhands.credit signs withdrawals).",
80876
80935
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80877
80936
  "",
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."
80937
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80938
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80939
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80940
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80941
+ "stay reserved until that is cleared. If the number above is already small, decline",
80942
+ "and start again rather than signing something you have not finished reading."
80884
80943
  ],
80885
80944
  expectedSigner: this.deps.borrower,
80886
80945
  chainId: this.deps.chainId,
80946
+ expiresAtSec,
80887
80947
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
80888
80948
  });
80889
80949
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -81087,13 +81147,27 @@ var RealUpstreamPlugin = class {
81087
81147
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
81088
81148
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81089
81149
  // 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));
81150
+ listPsmStablecoins: async () => {
81151
+ const listed = await this.listSupportedStablecoins();
81152
+ if (!listed.ok) return listed;
81153
+ const rows = await Promise.all(
81154
+ listed.rows.map(async (row) => {
81155
+ const built = await this.psmCallsFor(row.address);
81156
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
81157
+ })
81158
+ );
81159
+ return upOk(
81160
+ rows.filter((r) => r !== null),
81161
+ this.src("subgraph")
81162
+ );
81093
81163
  },
81094
- getPsmQuote: (p) => {
81095
- const r = this.psmCalls();
81096
- if (!r.ok) return Promise.resolve(upFail(r.failure));
81164
+ getPsmStatus: async (p) => {
81165
+ const r = await this.psmCallsFor(p.stablecoin);
81166
+ return r.ok ? r.calls.status() : upFail(r.failure);
81167
+ },
81168
+ getPsmQuote: async (p) => {
81169
+ const r = await this.psmCallsFor(p.stablecoin);
81170
+ if (!r.ok) return upFail(r.failure);
81097
81171
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81098
81172
  }
81099
81173
  };
@@ -81161,12 +81235,13 @@ var RealUpstreamPlugin = class {
81161
81235
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
81162
81236
  delegationSetup: () => readOnly("delegationSetup"),
81163
81237
  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).
81238
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
81239
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
81240
+ // signerless boot the honest refusal was always the missing signer; the network
81241
+ // gate sat in front of it and answered first. Now there is one reason left, and it
81242
+ // is the true one on this path.
81168
81243
  psmSwap: () => Promise.resolve(
81169
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
81244
+ upFail({
81170
81245
  kind: "signer-missing",
81171
81246
  source: "real-ops",
81172
81247
  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 +81358,7 @@ var RealUpstreamPlugin = class {
81283
81358
  session,
81284
81359
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81285
81360
  readDetails: (id) => this.readPositionDetails(id),
81286
- psm: () => this.psmCalls(),
81361
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81287
81362
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81288
81363
  });
81289
81364
  }
@@ -81417,7 +81492,7 @@ var RealUpstreamPlugin = class {
81417
81492
  session,
81418
81493
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81419
81494
  readDetails: (id) => this.readPositionDetails(id),
81420
- psm: () => this.psmCalls(),
81495
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81421
81496
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81422
81497
  });
81423
81498
  this.opsGatewayCache.set(key, gateway);
@@ -81563,35 +81638,91 @@ var RealUpstreamPlugin = class {
81563
81638
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
81564
81639
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
81565
81640
  * 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 };
81641
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
81642
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
81643
+ psmWrappers = /* @__PURE__ */ new Map();
81644
+ /**
81645
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
81646
+ *
81647
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
81648
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
81649
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
81650
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
81651
+ * `getPSMStablecoins` reads the index for the same reason.
81652
+ */
81653
+ async listSupportedStablecoins() {
81654
+ const r = await this.graphProxy(
81655
+ SUPPORTED_STABLECOINS,
81656
+ {}
81657
+ );
81658
+ if (!r.ok) return r;
81659
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
81660
+ address: String(x.address).toLowerCase(),
81661
+ decimals: Number(x.decimals)
81662
+ }));
81663
+ return { ok: true, rows };
81664
+ }
81665
+ /**
81666
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
81667
+ *
81668
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
81669
+ * indexer is how the list is discovered and is not authority over it: it can lag a
81670
+ * governance removal, and acting on a stale list would build a swap the contract reverts
81671
+ * — after the user has approved it in their wallet. List from the index, verify on the
81672
+ * chain, then sign.
81673
+ */
81674
+ async psmCallsFor(stablecoinAddress) {
81675
+ const key = stablecoinAddress.toLowerCase();
81676
+ const cached = this.psmWrappers.get(key);
81677
+ if (cached) return { ok: true, calls: cached };
81569
81678
  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 ");
81679
+ if (!psmAddress) {
81573
81680
  return {
81574
81681
  ok: false,
81575
81682
  failure: {
81576
81683
  kind: "unavailable",
81577
81684
  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.`
81685
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
81579
81686
  }
81580
81687
  };
81581
81688
  }
81689
+ let supported;
81690
+ let symbol;
81691
+ try {
81692
+ const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81693
+ supported = await psm["supportedStablecoins"](key);
81694
+ const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81695
+ symbol = await erc20["symbol"]();
81696
+ } catch (e) {
81697
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
81698
+ }
81699
+ if (!supported) {
81700
+ return {
81701
+ ok: false,
81702
+ failure: {
81703
+ kind: "rejected",
81704
+ source: "chain-rpc",
81705
+ 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.`
81706
+ }
81707
+ };
81708
+ }
81709
+ const stablecoinAddress2 = key;
81582
81710
  const ucdTokenAddress = this.contracts["UCDToken"];
81583
81711
  const ucdControllerAddress = this.contracts["UCDController"];
81584
- this.psmWrapper = new PsmCalls({
81712
+ const built = new PsmCalls({
81585
81713
  provider: this.provider,
81586
81714
  psmAddress,
81587
- stablecoinAddress,
81588
- stablecoinSymbol: "USDC",
81715
+ stablecoinAddress: stablecoinAddress2,
81716
+ // Read from the token, never assumed. The old value was the literal "USDC", which
81717
+ // stops being true the moment a second coin is supported.
81718
+ stablecoinSymbol: symbol,
81589
81719
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
81590
81720
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
81591
81721
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
81592
81722
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
81593
81723
  });
81594
- return { ok: true, calls: this.psmWrapper };
81724
+ this.psmWrappers.set(key, built);
81725
+ return { ok: true, calls: built };
81595
81726
  }
81596
81727
  src(id) {
81597
81728
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -81854,6 +81985,7 @@ function renderApprovalPage(sessionId, nonce) {
81854
81985
  <div id="request" class="hidden">
81855
81986
  <div id="action" class="action"></div>
81856
81987
  <div id="card" class="card"></div>
81988
+ <div id="deadline" class="status hidden"></div>
81857
81989
  <button id="approve">Approve in wallet</button>
81858
81990
  <button id="reject">Reject</button>
81859
81991
  </div>
@@ -81886,10 +82018,19 @@ const statusEl = document.getElementById("status");
81886
82018
  const requestEl = document.getElementById("request");
81887
82019
  const actionEl = document.getElementById("action");
81888
82020
  const cardEl = document.getElementById("card");
82021
+ const approveEl = document.getElementById("approve");
82022
+ const rejectEl = document.getElementById("reject");
82023
+ const deadlineEl = document.getElementById("deadline");
82024
+ let deadlineTimer = null;
81889
82025
  const walletEl = document.getElementById("wallet");
81890
82026
  let account = null;
81891
82027
  let chainId = null;
81892
82028
  let current = null;
82029
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
82030
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
82031
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
82032
+ // card the page never renders is one the human can neither read nor reject.
82033
+ const pending = new Map();
81893
82034
 
81894
82035
  function post(path, body) {
81895
82036
  return fetch(path, {
@@ -81952,43 +82093,135 @@ async function onAccountsChanged(accounts) {
81952
82093
  account = (accounts && accounts[0]) || null;
81953
82094
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81954
82095
  showWallet();
81955
- clearRequest("Wallet changed \u2014 pending request invalidated.");
82096
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81956
82097
  }
81957
82098
 
81958
82099
  async function onChainChanged(cid) {
81959
82100
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81960
82101
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81961
82102
  showWallet();
81962
- clearRequest("Network changed \u2014 pending request invalidated.");
82103
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81963
82104
  }
81964
82105
 
81965
82106
  function listen() {
81966
82107
  const es = new EventSource(BASE + "events?s=" + SESSION);
81967
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
82108
+ es.onmessage = (ev) => {
82109
+ const next = JSON.parse(ev.data);
82110
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
82111
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
82112
+ pending.set(next.id, next);
82113
+ showPending();
82114
+ };
81968
82115
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81969
82116
  }
81970
82117
 
82118
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
82119
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
82120
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
82121
+ // gets approved.
82122
+ function pickPending() {
82123
+ const held = current ? pending.get(current.id) : undefined;
82124
+ if (held && held.mirror !== true) return held;
82125
+ let best = held || null;
82126
+ pending.forEach((frame) => {
82127
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
82128
+ });
82129
+ return best;
82130
+ }
82131
+
82132
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
82133
+ function showPending(emptyText) {
82134
+ const next = pickPending();
82135
+ if (!next) {
82136
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
82137
+ // an expiry for a ceremony that is already decided.
82138
+ stopDeadline();
82139
+ current = null;
82140
+ requestEl.classList.add("hidden");
82141
+ if (emptyText) showStatus(emptyText);
82142
+ return;
82143
+ }
82144
+ current = next;
82145
+ renderRequest();
82146
+ }
82147
+
81971
82148
  function renderRequest() {
81972
82149
  actionEl.textContent = current.action;
81973
82150
  cardEl.textContent = current.card.join("\\n");
82151
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
82152
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
82153
+ // server-side, which is the actual boundary.
82154
+ const mirrored = current.mirror === true;
82155
+ approveEl.classList.toggle("hidden", mirrored);
82156
+ rejectEl.classList.remove("hidden");
81974
82157
  requestEl.classList.remove("hidden");
81975
- showStatus("Review the operation below. Nothing signs without your approval.");
82158
+ showStatus(mirrored
82159
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
82160
+ : "Review the operation below. Nothing signs without your approval.");
82161
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
82162
+ // card promoted after another settles gets its own clock, not the previous one's.
82163
+ startDeadline();
82164
+ }
82165
+
82166
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
82167
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
82168
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
82169
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
82170
+ // honest without it needing to know anything about quantum windows.
82171
+ function stopDeadline() {
82172
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82173
+ deadlineEl.classList.add("hidden");
82174
+ }
82175
+
82176
+ function startDeadline() {
82177
+ stopDeadline();
82178
+ if (!current || typeof current.expiresAtSec !== "number") return;
82179
+ const tick = () => {
82180
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
82181
+ if (left > 0) {
82182
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
82183
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
82184
+ } else {
82185
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
82186
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
82187
+ // after. The button is deliberately left enabled \u2014 declining is still the right
82188
+ // action and the page must not trap them.
82189
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
82190
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82191
+ }
82192
+ deadlineEl.classList.remove("hidden");
82193
+ };
82194
+ tick();
82195
+ deadlineTimer = setInterval(tick, 1000);
81976
82196
  }
81977
82197
 
82198
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
82199
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
82200
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81978
82201
  function clearRequest(text) {
81979
- current = null;
81980
- requestEl.classList.add("hidden");
81981
- showStatus(text);
82202
+ if (current) pending.delete(current.id);
82203
+ showPending(text);
82204
+ }
82205
+
82206
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
82207
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
82208
+ // stays readable and rejectable.
82209
+ function invalidatePageRequests(text) {
82210
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
82211
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
81982
82212
  }
81983
82213
 
81984
- document.getElementById("reject").onclick = async () => {
82214
+ rejectEl.onclick = async () => {
81985
82215
  if (!current) return;
81986
82216
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81987
82217
  clearRequest("Rejected. Waiting for the next request\u2026");
81988
82218
  };
81989
82219
 
81990
- document.getElementById("approve").onclick = async () => {
82220
+ approveEl.onclick = async () => {
81991
82221
  if (!current) return;
82222
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
82223
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
82224
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81992
82225
  const req = current;
81993
82226
  try {
81994
82227
  if (req.kind === "transaction") {
@@ -82005,7 +82238,10 @@ document.getElementById("approve").onclick = async () => {
82005
82238
  const fbody = await fr.json();
82006
82239
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
82007
82240
  const fresh = fbody.request;
82008
- // \u2026re-render what will actually sign\u2026
82241
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
82242
+ // another card arriving while the wallet popup is open re-picks from there, and the
82243
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
82244
+ pending.set(fresh.id, fresh);
82009
82245
  current = fresh; renderRequest();
82010
82246
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
82011
82247
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -82160,9 +82396,6 @@ var SignatureBridge = class {
82160
82396
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
82161
82397
  maxPending;
82162
82398
  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
82399
  server = null;
82167
82400
  port = 0;
82168
82401
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -82313,13 +82546,16 @@ var SignatureBridge = class {
82313
82546
  enqueuedMs: now,
82314
82547
  resolve,
82315
82548
  settled: false,
82316
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
82549
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
82550
+ owner: this.wcActive ? "wc" : "page",
82551
+ dispatched: false,
82552
+ lastAttachedMs: now
82317
82553
  };
82318
82554
  this.pending.set(request.id, entry);
82319
- if (this.wcActive) {
82555
+ if (entry.owner === "wc") {
82320
82556
  void this.driveWc(entry);
82321
82557
  } else {
82322
- this.push(request);
82558
+ this.pushEntry(entry);
82323
82559
  }
82324
82560
  });
82325
82561
  }
@@ -82340,10 +82576,16 @@ var SignatureBridge = class {
82340
82576
  enqueuedMs: now,
82341
82577
  resolve,
82342
82578
  settled: false,
82343
- collect
82579
+ collect,
82580
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
82581
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
82582
+ // ceremony could not reach quorum through the very pages it is broadcast to.
82583
+ owner: "both",
82584
+ dispatched: false,
82585
+ lastAttachedMs: now
82344
82586
  };
82345
82587
  this.pending.set(request.id, entry);
82346
- this.push(request);
82588
+ this.pushEntry(entry);
82347
82589
  if (this.wcActive) void this.driveWcCollection(entry);
82348
82590
  });
82349
82591
  }
@@ -82382,7 +82624,9 @@ var SignatureBridge = class {
82382
82624
  }
82383
82625
  try {
82384
82626
  if (req.kind === "transaction") {
82627
+ this.pushEntry(entry);
82385
82628
  const tx2 = req.tx;
82629
+ entry.dispatched = true;
82386
82630
  const txHash = await transport.request("eth_sendTransaction", [
82387
82631
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
82388
82632
  ]);
@@ -82394,11 +82638,22 @@ var SignatureBridge = class {
82394
82638
  req.card = fresh.card;
82395
82639
  }
82396
82640
  const ps = req.personalSign;
82641
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
82642
+ this.settle(entry, {
82643
+ status: "invalidated",
82644
+ 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)`
82645
+ });
82646
+ return;
82647
+ }
82648
+ this.pushEntry(entry);
82649
+ entry.dispatched = true;
82397
82650
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
82398
82651
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82399
82652
  } else {
82653
+ this.pushEntry(entry);
82400
82654
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
82401
82655
  const payload = withEip712DomainType2(req.typedData);
82656
+ entry.dispatched = true;
82402
82657
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
82403
82658
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82404
82659
  }
@@ -82418,30 +82673,55 @@ var SignatureBridge = class {
82418
82673
  * with a live attachment is in use and must never be evicted. */
82419
82674
  attachedNow() {
82420
82675
  if (this.wcActive) return true;
82421
- for (const s of this.sessions.values()) if (s.sse) return true;
82676
+ return this.pageAttached();
82677
+ }
82678
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
82679
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
82680
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
82681
+ * WalletConnect and must stay global for the connector's eviction predicate. */
82682
+ pageAttached() {
82683
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
82422
82684
  return false;
82423
82685
  }
82686
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
82687
+ * predicate said "a WC session is attached", which is true but irrelevant to a
82688
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
82689
+ * out the full expiry instead of failing fast at the grace. */
82690
+ attachedFor(entry) {
82691
+ if (entry.owner === "wc") return this.wcActive;
82692
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
82693
+ return this.pageAttached();
82694
+ }
82424
82695
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
82425
82696
  * interval; tests call it directly with the injected clock advanced. Order matters:
82426
82697
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
82427
82698
  sweep() {
82428
82699
  const now = this.clock();
82429
- const attached = this.attachedNow();
82430
- if (attached) this.lastAttachedMs = now;
82431
82700
  for (const entry of this.pending.values()) {
82432
82701
  if (entry.settled) continue;
82433
82702
  if (now >= entry.deadlineMs) {
82434
82703
  this.settle(entry, { status: "expired" });
82435
82704
  continue;
82436
82705
  }
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
- });
82706
+ if (this.attachedFor(entry)) {
82707
+ entry.lastAttachedMs = now;
82708
+ continue;
82442
82709
  }
82710
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
82711
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
82443
82712
  }
82444
82713
  }
82714
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
82715
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
82716
+ unattendedReason(entry) {
82717
+ if (entry.dispatched && entry.request.kind === "transaction") {
82718
+ 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.";
82719
+ }
82720
+ if (entry.owner === "wc") {
82721
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
82722
+ }
82723
+ 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`;
82724
+ }
82445
82725
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
82446
82726
  walletConnectActive() {
82447
82727
  return this.wcActive;
@@ -82565,6 +82845,7 @@ var SignatureBridge = class {
82565
82845
  if (info && refusal) {
82566
82846
  this.wcActive = false;
82567
82847
  this.rebuildSharedWallet();
82848
+ this.demoteWcEntries();
82568
82849
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82569
82850
  `);
82570
82851
  return;
@@ -82574,7 +82855,10 @@ var SignatureBridge = class {
82574
82855
  if (info === null) {
82575
82856
  for (const entry of this.pending.values()) {
82576
82857
  if (!entry.settled && !entry.collect) {
82577
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82858
+ this.settle(entry, {
82859
+ status: "invalidated",
82860
+ 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"
82861
+ });
82578
82862
  }
82579
82863
  }
82580
82864
  }
@@ -82646,9 +82930,7 @@ var SignatureBridge = class {
82646
82930
  session.sse?.end();
82647
82931
  session.sse = res;
82648
82932
  for (const entry of this.pending.values()) {
82649
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
82650
-
82651
- `);
82933
+ if (!entry.settled) res.write(this.wireFor(entry));
82652
82934
  }
82653
82935
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
82654
82936
  keepAlive.unref();
@@ -82724,10 +83006,36 @@ var SignatureBridge = class {
82724
83006
  }
82725
83007
  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
83008
  for (const entry of this.pending.values()) {
82727
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
83009
+ if (entry.settled || entry.collect) continue;
83010
+ if (this.ownedByWc(entry)) continue;
83011
+ this.settle(entry, { status: "invalidated", reason });
82728
83012
  }
82729
83013
  this.ok(res);
82730
83014
  }
83015
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
83016
+ * session hands the request back to the page rather than stranding it. */
83017
+ ownedByWc(entry) {
83018
+ if (entry.owner !== "wc") return false;
83019
+ return this.wcActive || entry.dispatched;
83020
+ }
83021
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
83022
+ * them so the card stops rendering read-only. Collections are already `both`.
83023
+ *
83024
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
83025
+ * phone is still holding does not replace one wallet with another, it adds a second: the
83026
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
83027
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
83028
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
83029
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
83030
+ * false for them, and `unattendedReason` says plainly that the phone may already have
83031
+ * acted. */
83032
+ demoteWcEntries() {
83033
+ for (const entry of this.pending.values()) {
83034
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
83035
+ entry.owner = "page";
83036
+ this.pushEntry(entry);
83037
+ }
83038
+ }
82731
83039
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
82732
83040
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
82733
83041
  async onFinalize(body, res) {
@@ -82741,6 +83049,10 @@ var SignatureBridge = class {
82741
83049
  this.deny(res, 400, "finalize applies only to personal-sign requests");
82742
83050
  return;
82743
83051
  }
83052
+ if (this.ownedByWc(entry)) {
83053
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
83054
+ return;
83055
+ }
82744
83056
  if (entry.finalize) {
82745
83057
  let fresh;
82746
83058
  try {
@@ -82767,10 +83079,22 @@ var SignatureBridge = class {
82767
83079
  return;
82768
83080
  }
82769
83081
  if (body["approved"] !== true) {
83082
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
83083
+ this.settle(entry, {
83084
+ status: "invalidated",
83085
+ 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."
83086
+ });
83087
+ this.ok(res);
83088
+ return;
83089
+ }
82770
83090
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
82771
83091
  this.ok(res);
82772
83092
  return;
82773
83093
  }
83094
+ if (this.ownedByWc(entry)) {
83095
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
83096
+ return;
83097
+ }
82774
83098
  const account = String(body["account"] ?? "");
82775
83099
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
82776
83100
  this.deny(res, 400, "approved result requires the signing account");
@@ -82807,11 +83131,20 @@ var SignatureBridge = class {
82807
83131
  this.pending.delete(entry.request.id);
82808
83132
  entry.resolve(outcome);
82809
83133
  }
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)}
83134
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
83135
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
83136
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
83137
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
83138
+ * a permanently read-only card that nobody is allowed to decide. */
83139
+ wireFor(entry) {
83140
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
83141
+ return `data: ${JSON.stringify(payload)}
82813
83142
 
82814
83143
  `;
83144
+ }
83145
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
83146
+ pushEntry(entry) {
83147
+ const data = this.wireFor(entry);
82815
83148
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82816
83149
  }
82817
83150
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -83294,7 +83627,7 @@ var FIELD_GLOSSARY = {
83294
83627
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83295
83628
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83296
83629
  // ---- psm quote ----
83297
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83630
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
83298
83631
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83299
83632
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83300
83633
  amountInToken: "the token you pay with",
@@ -83392,11 +83725,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83392
83725
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83393
83726
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83394
83727
  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).
83728
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
83729
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
83730
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
83731
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
83732
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
83733
+ // nobody supplied a deployment at all, and understating a capability there is the safe
83734
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
83735
+ // overclaim C-44 is about — promising a QR the build cannot show.
83400
83736
  walletConnect: false
83401
83737
  };
83402
83738
  function servedNetworks(d) {
@@ -83407,7 +83743,7 @@ function servedNetworks(d) {
83407
83743
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
83408
83744
  }
83409
83745
  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";
83746
+ 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
83747
  }
83412
83748
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
83413
83749
  }
@@ -83486,13 +83822,14 @@ function switchNetworkRules(d) {
83486
83822
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83487
83823
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83488
83824
  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.`;
83825
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83826
+ mainnet they move REAL money, and every one still requires the user's explicit
83827
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83828
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83829
+ signed.`;
83492
83830
  }
83493
83831
  const only = d.networks[0];
83494
83832
  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
83833
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83497
83834
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
83498
83835
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -83501,7 +83838,9 @@ function switchNetworkRules(d) {
83501
83838
  belong to ${only} and would not exist anywhere else.
83502
83839
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83503
83840
  confirmation plus the signer ceremony.
83504
- - ${psm}`;
83841
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83842
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83843
+ anything is signed.`;
83505
83844
  }
83506
83845
  function wrongNetworkTroubleshootingRow(d) {
83507
83846
  if (d.networks.length > 1) {
@@ -83521,14 +83860,18 @@ function switchNetworkIndexLine(d) {
83521
83860
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83522
83861
  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
83862
  }
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
- `;
83863
+ function psmStablecoinRealityNote(d) {
83864
+ if (d.networks.includes("sepolia")) {
83865
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83866
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83867
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83868
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83869
+ }
83870
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83871
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83872
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83873
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83874
+ have to guess whether the money is real.`;
83532
83875
  }
83533
83876
  function authorizationModeBullets(d) {
83534
83877
  const bullets = [];
@@ -83642,7 +83985,7 @@ on the real adapter and the mock.
83642
83985
  **The walkthrough:**
83643
83986
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83644
83987
  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) + "."}
83988
+ 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
83989
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83647
83990
  login ceremony explicitly (one typed-data signature in the wallet).
83648
83991
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83681,7 +84024,14 @@ on the real adapter and the mock.
83681
84024
  hash the SDK builds internally, which the approval page shows bare and says plainly it
83682
84025
  cannot decode (the production web app signs the same way). Tell the user before that
83683
84026
  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.
84027
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
84028
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
84029
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
84030
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
84031
+ on the card, and the page is the only surface that shows it. With no page attached the
84032
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
84033
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
84034
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
83685
84035
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83686
84036
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83687
84037
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
@@ -83762,9 +84112,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83762
84112
 
83763
84113
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83764
84114
  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)
84115
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
83766
84116
 
83767
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
84117
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83768
84118
  directions, in user words:
83769
84119
 
83770
84120
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83772,20 +84122,27 @@ directions, in user words:
83772
84122
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83773
84123
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83774
84124
  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).
84125
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
84126
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
84127
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
84128
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
84129
+ reserves, and a shortfall refuses with both figures (available vs required).
84130
+
84131
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
84132
+ default and that is deliberate: the PSM can carry several coins, each with its own
84133
+ reserves, fees and limits, so picking one silently would move someone's money through a
84134
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
84135
+ there rather than guessing one.
83780
84136
 
83781
84137
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83782
84138
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83783
84139
  1e18 = 1:1) and can be changed by protocol governance.
83784
84140
 
83785
84141
  **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
84142
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
84143
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
84144
+ direction is DISABLED.
84145
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
83789
84146
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83790
84147
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
83791
84148
 
@@ -83794,23 +84151,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
83794
84151
  change between your quote and execution; the floor makes a drifted execution REFUSE
83795
84152
  rather than silently deliver less than quoted.
83796
84153
 
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.
84154
+ ${psmStablecoinRealityNote(d)}
83801
84155
 
83802
84156
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83803
84157
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83804
84158
  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
84159
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84160
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
84161
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83808
84162
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83809
84163
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83810
84164
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83811
84165
  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).`,
84166
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84167
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84168
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
84169
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
84170
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
84171
+ per-operation and per-block limits,
84172
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
84173
+ mainnet swap, not after.`,
83814
84174
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83815
84175
 
83816
84176
  Every fund-moving operation needs TWO things, always in this order:
@@ -84069,9 +84429,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
84069
84429
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
84070
84430
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
84071
84431
  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.`}
84432
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
84433
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
84434
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
84435
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
84436
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
84075
84437
  ${wrongNetworkTroubleshootingRow(d)}
84076
84438
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
84077
84439
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -84229,12 +84591,13 @@ function guideDeployment(overrides, env) {
84229
84591
  tier: overrides?.bridgeMount ? "hosted" : "local",
84230
84592
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
84231
84593
  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"])
84594
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
84595
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
84596
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
84597
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
84598
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
84599
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
84600
+ walletConnect: wcEnabled(env)
84238
84601
  };
84239
84602
  }
84240
84603
  function assembleWorld(opts) {
@@ -84874,39 +85237,45 @@ function registerPsmTools(server, getB) {
84874
85237
  server,
84875
85238
  "psm_quote",
84876
85239
  {
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.",
85240
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
85241
+ 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
85242
  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.")
85243
+ stablecoin: import_zod4.z.string().min(1).describe(
85244
+ "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."
85245
+ ),
85246
+ 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)"),
85247
+ 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
85248
  },
84883
85249
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84884
85250
  },
84885
- async ({ direction, amount }) => guarded(async () => {
84886
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
85251
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
85252
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
84887
85253
  const problem = checkUcdAmount(amount, label);
84888
85254
  if (problem) return validationFailed(problem);
84889
85255
  const b = getB();
84890
85256
  if (!b.ok) return renderError(b.error);
84891
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
85257
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
84892
85258
  })
84893
85259
  );
84894
85260
  registerBoundaryTool(
84895
85261
  server,
84896
85262
  "psm_swap",
84897
85263
  {
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).",
85264
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
85265
+ 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
85266
  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."),
85267
+ stablecoin: import_zod4.z.string().min(1).describe(
85268
+ "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."
85269
+ ),
85270
+ 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)"),
85271
+ 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
85272
  confirmed: confirmedSchema2
84904
85273
  },
84905
85274
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84906
85275
  },
84907
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84908
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84909
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
85276
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
85277
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
85278
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84910
85279
  const gate = requireConfirmation(
84911
85280
  confirmed,
84912
85281
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84916,7 +85285,7 @@ function registerPsmTools(server, getB) {
84916
85285
  if (problem) return validationFailed(problem);
84917
85286
  const b = getB();
84918
85287
  if (!b.ok) return renderError(b.error);
84919
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
85288
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84920
85289
  })
84921
85290
  );
84922
85291
  }
@@ -85362,7 +85731,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85362
85731
  "network_switch",
85363
85732
  {
85364
85733
  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.",
85734
+ 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
85735
  inputSchema: {
85367
85736
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
85368
85737
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -85380,7 +85749,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85380
85749
  lines.push(
85381
85750
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
85382
85751
  "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).",
85752
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
85384
85753
  "Session-scoped: the configured default network returns when the server restarts."
85385
85754
  );
85386
85755
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -85486,13 +85855,26 @@ function registerProtocolResources(server, getB) {
85486
85855
  "protocol://psm",
85487
85856
  {
85488
85857
  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).",
85858
+ 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
85859
  mimeType: "application/json"
85491
85860
  },
85492
85861
  async (uri) => {
85493
85862
  const b = getB();
85494
85863
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
85495
- const env = await b.boundary.getPsmStatus();
85864
+ const listed = await b.boundary.listPsmStablecoins();
85865
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85866
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85867
+ const failed = perCoin.find((s) => !s.ok);
85868
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85869
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85870
+ const head = coins[0];
85871
+ const env = {
85872
+ ...listed,
85873
+ data: {
85874
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85875
+ stablecoins: coins
85876
+ }
85877
+ };
85496
85878
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
85497
85879
  }
85498
85880
  );
@@ -85705,12 +86087,15 @@ function composeConnector(opts, rawPublicOrigin) {
85705
86087
  for (const session of sessions.values()) held.add(session.tenant);
85706
86088
  return held;
85707
86089
  }
85708
- function isReclaimable(tenantKey, world, held) {
85709
- if (held.has(tenantKey)) return false;
86090
+ function isEvictable(world) {
85710
86091
  const bridge = world.deps.signer?.bridge;
85711
86092
  if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85712
86093
  return true;
85713
86094
  }
86095
+ function isReclaimable(tenantKey, world, held) {
86096
+ if (held.has(tenantKey)) return false;
86097
+ return isEvictable(world);
86098
+ }
85714
86099
  function sweepService() {
85715
86100
  const now = clock();
85716
86101
  for (const [sid, session] of [...sessions]) {
@@ -85726,13 +86111,12 @@ function composeConnector(opts, rawPublicOrigin) {
85726
86111
  dropWorld(tenantKey, world, "idle eviction");
85727
86112
  }
85728
86113
  }
85729
- function reclaimIdleWorld() {
85730
- const held = tenantsWithSessions();
86114
+ function leastRecentlyActive(eligible) {
85731
86115
  let victimKey = null;
85732
86116
  let victim = null;
85733
86117
  let oldest = Number.POSITIVE_INFINITY;
85734
86118
  for (const [tenantKey, world] of readyWorlds) {
85735
- if (!isReclaimable(tenantKey, world, held)) continue;
86119
+ if (!eligible(tenantKey, world)) continue;
85736
86120
  const activeAt = lastActivity.get(tenantKey) ?? 0;
85737
86121
  if (activeAt < oldest) {
85738
86122
  oldest = activeAt;
@@ -85740,8 +86124,23 @@ function composeConnector(opts, rawPublicOrigin) {
85740
86124
  victim = world;
85741
86125
  }
85742
86126
  }
85743
- if (victimKey === null || victim === null) return false;
85744
- dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
86127
+ return victimKey !== null && victim !== null ? [victimKey, victim] : null;
86128
+ }
86129
+ function reclaimIdleWorld() {
86130
+ const held = tenantsWithSessions();
86131
+ const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
86132
+ if (tier1) {
86133
+ dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
86134
+ return true;
86135
+ }
86136
+ const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
86137
+ if (!tier2) return false;
86138
+ for (const [sid, session] of [...sessions]) {
86139
+ if (session.tenant !== tier2[0]) continue;
86140
+ sessions.delete(sid);
86141
+ void session.transport.close().catch(() => void 0);
86142
+ }
86143
+ dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
85745
86144
  return true;
85746
86145
  }
85747
86146
  class TenantCapacityError extends Error {
@@ -85959,7 +86358,8 @@ function composeConnector(opts, rawPublicOrigin) {
85959
86358
  if (opts.auth) {
85960
86359
  authImpl = opts.auth;
85961
86360
  } else {
85962
- const wcLeg = opts.siweWc ?? (opts.env["DH_WC_PROJECT_ID"] ? { projectId: opts.env["DH_WC_PROJECT_ID"] } : void 0);
86361
+ const envWcProjectId = resolvedWcProjectId(opts.env);
86362
+ const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
85963
86363
  const siwe = new SiweOAuthProvider({
85964
86364
  origin: () => publicOrigin,
85965
86365
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,