@gvnrdao/dh-mcp 0.5.13 → 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.
package/dist/connector.js CHANGED
@@ -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;
@@ -41030,7 +41032,7 @@ function htmlPageSecurityHeaders(extra) {
41030
41032
  }
41031
41033
 
41032
41034
  // src/version.ts
41033
- var SERVER_VERSION = "0.5.13";
41035
+ var SERVER_VERSION = "0.5.15";
41034
41036
 
41035
41037
  // src/connector/siwe-oauth.ts
41036
41038
  var import_node_crypto2 = require("crypto");
@@ -41537,6 +41539,21 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
41537
41539
  var ADAPTERS = ["mock", "real"];
41538
41540
  var LATENCIES = ["zero", "realistic"];
41539
41541
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
41542
+ var WC_DISABLED = "off";
41543
+ function wcEnabled(env) {
41544
+ return resolvedWcProjectId(env) !== void 0;
41545
+ }
41546
+ function resolvedWcProjectId(env) {
41547
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
41548
+ }
41549
+ function resolveWcProjectId(raw, problems) {
41550
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
41551
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
41552
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
41553
+ return void 0;
41554
+ }
41555
+ return raw;
41556
+ }
41540
41557
  var NETWORK_DEFAULTS = {
41541
41558
  sepolia: {
41542
41559
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -41611,10 +41628,7 @@ function resolveBoundaryConfig(env) {
41611
41628
  }
41612
41629
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41613
41630
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41614
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41615
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41616
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41617
- }
41631
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41618
41632
  let bridgeOpenBrowser;
41619
41633
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41620
41634
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41686,10 +41700,7 @@ function resolveRealConfig(env) {
41686
41700
  const stateDir = env["DH_STATE_DIR"];
41687
41701
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41688
41702
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41689
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41690
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41691
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41692
- }
41703
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41693
41704
  let bridgeOpenBrowser;
41694
41705
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41695
41706
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -42129,8 +42140,15 @@ var BoundaryCore = class {
42129
42140
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
42130
42141
  }
42131
42142
  // ---- PSM reads (plan 08 Part B Phase R) ----
42132
- async getPsmStatus() {
42133
- const r = await this.deps.plugin.chain.getPsmStatus();
42143
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
42144
+ * names the coin, and this is how they learn what they may name. */
42145
+ async listPsmStablecoins() {
42146
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
42147
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
42148
+ return okEnvelope(r.value, r.source);
42149
+ }
42150
+ async getPsmStatus(p) {
42151
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
42134
42152
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42135
42153
  return okEnvelope(this.psmStatusData(r.value), r.source);
42136
42154
  }
@@ -42141,7 +42159,7 @@ var BoundaryCore = class {
42141
42159
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
42142
42160
  * whenever `env.ok`. */
42143
42161
  async psmQuoteWithStatus(p) {
42144
- const statusR = await this.deps.plugin.chain.getPsmStatus();
42162
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
42145
42163
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
42146
42164
  const s = statusR.value;
42147
42165
  const toUcd = p.direction === "to-ucd";
@@ -42197,6 +42215,7 @@ var BoundaryCore = class {
42197
42215
  );
42198
42216
  }
42199
42217
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
42218
+ stablecoin: p.stablecoin,
42200
42219
  direction: toUcd ? "swap" : "redeem",
42201
42220
  amountIn: amountIn.toString()
42202
42221
  });
@@ -42263,6 +42282,7 @@ var BoundaryCore = class {
42263
42282
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
42264
42283
  if (floor === 0n) floor = 1n;
42265
42284
  const r = await this.deps.plugin.ops.psmSwap({
42285
+ stablecoin: p.stablecoin,
42266
42286
  direction: q.contractCall,
42267
42287
  amountIn: q.amountIn,
42268
42288
  minOut: floor.toString(),
@@ -42362,7 +42382,7 @@ var BoundaryCore = class {
42362
42382
  feeToken: "UCD",
42363
42383
  perBlockCap: s.maxSwapVolumePerBlock
42364
42384
  }),
42365
- toUsdc: direction({
42385
+ fromUcd: direction({
42366
42386
  minAmount: s.minRedeemAmount,
42367
42387
  maxAmount: s.maxRedeemAmount,
42368
42388
  amountUnit: ucdUnit,
@@ -42494,7 +42514,10 @@ var BoundaryCore = class {
42494
42514
  borrower: auth.borrower
42495
42515
  });
42496
42516
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42497
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
42517
+ return okEnvelope(
42518
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
42519
+ r.source
42520
+ );
42498
42521
  }
42499
42522
  // ---- meta ----
42500
42523
  world() {
@@ -43341,20 +43364,56 @@ var World = class {
43341
43364
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
43342
43365
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
43343
43366
  }
43344
- const c = this.state.collateral[p.positionId];
43345
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43346
- const transfers = pending.map((spend) => {
43367
+ const fee = BigInt(p.networkFeeSats);
43368
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
43369
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
43370
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
43371
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
43347
43372
  const { hash: txid } = this.nextId("btc-withdraw-retry");
43348
43373
  return {
43349
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
43374
+ utxoIdentifier,
43350
43375
  ok: true,
43351
43376
  txid,
43352
- amountSentSats: spend.satoshis,
43377
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
43378
+ // the authorized amount, never added on top — the same semantics `withdraw` above
43379
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
43380
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
43381
+ // whether the fee was honoured at all.
43382
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
43353
43383
  destination: spend.targetAddress
43354
43384
  };
43355
43385
  });
43356
43386
  return { ok: true, value: { attempted: transfers.length, transfers } };
43357
43387
  }
43388
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
43389
+ pendingSpends(positionId) {
43390
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43391
+ }
43392
+ /**
43393
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
43394
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
43395
+ *
43396
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
43397
+ *
43398
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
43399
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
43400
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
43401
+ */
43402
+ retryFeeRefusal(spend, networkFeeSats) {
43403
+ const target = BigInt(spend.satoshis);
43404
+ if (BigInt(networkFeeSats) * 2n >= target) {
43405
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
43406
+ }
43407
+ return null;
43408
+ }
43409
+ /**
43410
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
43411
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
43412
+ * wallet is never opened — which is what the mock's ceremony gate reads.
43413
+ */
43414
+ retryExecutableCount(positionId, networkFeeSats) {
43415
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
43416
+ }
43358
43417
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
43359
43418
  safesMap() {
43360
43419
  return this.state.safes;
@@ -44148,7 +44207,7 @@ var SINK_CONTRACTS = {
44148
44207
  PositionManager: sinkAddress("PositionManager"),
44149
44208
  UCDToken: sinkAddress("UCDToken"),
44150
44209
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
44151
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
44210
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
44152
44211
  SimplePSMV2: sinkAddress("SimplePSMV2"),
44153
44212
  UsdcToken: sinkAddress("UsdcToken"),
44154
44213
  UCDController: sinkAddress("UCDController")
@@ -44453,7 +44512,18 @@ var MockUpstreamPlugin = class {
44453
44512
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
44454
44513
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
44455
44514
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
44456
- getPsmStatus: () => this.read("mock-chain", () => {
44515
+ // The practice world models ONE stablecoin, and says so rather than implying a
44516
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
44517
+ // and naming anything but this one is refused the same way the real adapter refuses
44518
+ // an unsupported address — a mock that accepted any name would teach a habit the
44519
+ // real protocol punishes.
44520
+ listPsmStablecoins: () => this.read(
44521
+ "mock-chain",
44522
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
44523
+ ),
44524
+ getPsmStatus: (p) => this.read("mock-chain", () => {
44525
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44526
+ if (known) return known;
44457
44527
  const psm = this.world.psmSeed();
44458
44528
  return upOk(
44459
44529
  {
@@ -44478,6 +44548,8 @@ var MockUpstreamPlugin = class {
44478
44548
  );
44479
44549
  }),
44480
44550
  getPsmQuote: (p) => this.read("mock-chain", () => {
44551
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44552
+ if (known) return known;
44481
44553
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
44482
44554
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
44483
44555
  })
@@ -44550,11 +44622,7 @@ var MockUpstreamPlugin = class {
44550
44622
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
44551
44623
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
44552
44624
  }),
44553
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
44554
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
44555
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44556
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
44557
- })
44625
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
44558
44626
  };
44559
44627
  }
44560
44628
  indexer;
@@ -44606,6 +44674,19 @@ var MockUpstreamPlugin = class {
44606
44674
  return apply();
44607
44675
  }
44608
44676
  /** Mode `none`: every write answers with the conversational setup invitation. */
44677
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
44678
+ * refused with the same shape the real adapter uses for an address the chain does not
44679
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
44680
+ * instead of silently succeeding and teaching that any name works. */
44681
+ mockStablecoinRefusal(stablecoin) {
44682
+ const chosen = stablecoin.trim().toLowerCase();
44683
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
44684
+ return upFail({
44685
+ kind: "rejected",
44686
+ source: "mock-chain",
44687
+ 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.`
44688
+ });
44689
+ }
44609
44690
  noneRefusal() {
44610
44691
  if (this.signer && this.signer.manager.mode() === "none") {
44611
44692
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -44829,6 +44910,46 @@ var MockUpstreamPlugin = class {
44829
44910
  );
44830
44911
  });
44831
44912
  }
44913
+ /**
44914
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
44915
+ *
44916
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
44917
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
44918
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
44919
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
44920
+ * passing requests the real protocol would refuse, which is the one thing a practice world
44921
+ * must never do.
44922
+ *
44923
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
44924
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
44925
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
44926
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
44927
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
44928
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
44929
+ */
44930
+ async opRetryWithdrawExecute(p) {
44931
+ const none = this.noneRefusal();
44932
+ if (none) return none;
44933
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
44934
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
44935
+ const cer = executable > 0 ? this.ceremonyNow() : null;
44936
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
44937
+ if (auth && !auth.ok) return auth.failure;
44938
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
44939
+ return this.write("retryWithdrawExecute", () => {
44940
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
44941
+ if (sig && !sig.ok) return sig.failure;
44942
+ const r = this.applyAuthorized(
44943
+ sig ? sig.authorization : void 0,
44944
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
44945
+ );
44946
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44947
+ return upOk(
44948
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
44949
+ this.src("mock-ops")
44950
+ );
44951
+ });
44952
+ }
44832
44953
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
44833
44954
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
44834
44955
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -79449,6 +79570,19 @@ function listPositionsQuery(f) {
79449
79570
  }
79450
79571
  return { document: LIST_POSITIONS, variables: { first, skip } };
79451
79572
  }
79573
+ var SUPPORTED_STABLECOINS = `
79574
+ query SupportedStablecoins {
79575
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79576
+ id
79577
+ address
79578
+ isSupported
79579
+ decimals
79580
+ entryFee
79581
+ exitFee
79582
+ reserves
79583
+ }
79584
+ }
79585
+ `;
79452
79586
 
79453
79587
  // src/boundary/upstream/real/psm-calls.ts
79454
79588
  var import_ethers32 = require("ethers");
@@ -79588,6 +79722,11 @@ var PsmCalls = class {
79588
79722
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79589
79723
  });
79590
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
+ }
79591
79730
  async status() {
79592
79731
  return this.call(async () => {
79593
79732
  const s = this.deps.stablecoinAddress;
@@ -80047,13 +80186,6 @@ function buildValidationContext(network, chainId) {
80047
80186
  }
80048
80187
 
80049
80188
  // src/boundary/upstream/real/write-ops.ts
80050
- function psmMainnetWriteRefusal(network, chainId) {
80051
- return {
80052
- kind: "rejected",
80053
- source: SOURCE5,
80054
- 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.`
80055
- };
80056
- }
80057
80189
  var SOURCE5 = "real-ops";
80058
80190
  var OP_LAYOUT = "dh-op-envelope-v1";
80059
80191
  function randomNonceHex() {
@@ -80401,8 +80533,7 @@ function buildWriteOps(deps) {
80401
80533
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80402
80534
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
80403
80535
  psmSwap: async (p) => {
80404
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
80405
- const pr = deps.psm();
80536
+ const pr = await deps.psm(p.stablecoin);
80406
80537
  if (!pr.ok) return upFail(pr.failure);
80407
80538
  const calls = pr.calls;
80408
80539
  const addr = calls.addresses();
@@ -80783,6 +80914,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80783
80914
  );
80784
80915
  }
80785
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));
80786
80920
  const outcome = await this.deps.bridge.requestSignature({
80787
80921
  id: (0, import_node_crypto7.randomUUID)(),
80788
80922
  kind: "personal-sign",
@@ -80794,15 +80928,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80794
80928
  "(identical to how diamondhands.credit signs withdrawals).",
80795
80929
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80796
80930
  "",
80797
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80798
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80799
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80800
- "itself allows. If it expires the signature is refused, the withdrawal does not",
80801
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80802
- "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."
80803
80937
  ],
80804
80938
  expectedSigner: this.deps.borrower,
80805
80939
  chainId: this.deps.chainId,
80940
+ expiresAtSec,
80806
80941
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
80807
80942
  });
80808
80943
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -81006,13 +81141,27 @@ var RealUpstreamPlugin = class {
81006
81141
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
81007
81142
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81008
81143
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
81009
- getPsmStatus: () => {
81010
- const r = this.psmCalls();
81011
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
81144
+ listPsmStablecoins: async () => {
81145
+ const listed = await this.listSupportedStablecoins();
81146
+ if (!listed.ok) return listed;
81147
+ const rows = await Promise.all(
81148
+ listed.rows.map(async (row) => {
81149
+ const built = await this.psmCallsFor(row.address);
81150
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
81151
+ })
81152
+ );
81153
+ return upOk(
81154
+ rows.filter((r) => r !== null),
81155
+ this.src("subgraph")
81156
+ );
81157
+ },
81158
+ getPsmStatus: async (p) => {
81159
+ const r = await this.psmCallsFor(p.stablecoin);
81160
+ return r.ok ? r.calls.status() : upFail(r.failure);
81012
81161
  },
81013
- getPsmQuote: (p) => {
81014
- const r = this.psmCalls();
81015
- if (!r.ok) return Promise.resolve(upFail(r.failure));
81162
+ getPsmQuote: async (p) => {
81163
+ const r = await this.psmCallsFor(p.stablecoin);
81164
+ if (!r.ok) return upFail(r.failure);
81016
81165
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81017
81166
  }
81018
81167
  };
@@ -81080,12 +81229,13 @@ var RealUpstreamPlugin = class {
81080
81229
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
81081
81230
  delegationSetup: () => readOnly("delegationSetup"),
81082
81231
  delegationGrant: () => readOnly("delegationGrant"),
81083
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
81084
- // any non-sepolia network refuses typed — naming the network gate truthfully —
81085
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
81086
- // missing signer instead (the honest reason on that path).
81232
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
81233
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
81234
+ // signerless boot the honest refusal was always the missing signer; the network
81235
+ // gate sat in front of it and answered first. Now there is one reason left, and it
81236
+ // is the true one on this path.
81087
81237
  psmSwap: () => Promise.resolve(
81088
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
81238
+ upFail({
81089
81239
  kind: "signer-missing",
81090
81240
  source: "real-ops",
81091
81241
  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."
@@ -81202,7 +81352,7 @@ var RealUpstreamPlugin = class {
81202
81352
  session,
81203
81353
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81204
81354
  readDetails: (id) => this.readPositionDetails(id),
81205
- psm: () => this.psmCalls(),
81355
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81206
81356
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81207
81357
  });
81208
81358
  }
@@ -81336,7 +81486,7 @@ var RealUpstreamPlugin = class {
81336
81486
  session,
81337
81487
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81338
81488
  readDetails: (id) => this.readPositionDetails(id),
81339
- psm: () => this.psmCalls(),
81489
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81340
81490
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81341
81491
  });
81342
81492
  this.opsGatewayCache.set(key, gateway);
@@ -81482,35 +81632,91 @@ var RealUpstreamPlugin = class {
81482
81632
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
81483
81633
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
81484
81634
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
81485
- psmWrapper = null;
81486
- psmCalls() {
81487
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
81635
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
81636
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
81637
+ psmWrappers = /* @__PURE__ */ new Map();
81638
+ /**
81639
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
81640
+ *
81641
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
81642
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
81643
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
81644
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
81645
+ * `getPSMStablecoins` reads the index for the same reason.
81646
+ */
81647
+ async listSupportedStablecoins() {
81648
+ const r = await this.graphProxy(
81649
+ SUPPORTED_STABLECOINS,
81650
+ {}
81651
+ );
81652
+ if (!r.ok) return r;
81653
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
81654
+ address: String(x.address).toLowerCase(),
81655
+ decimals: Number(x.decimals)
81656
+ }));
81657
+ return { ok: true, rows };
81658
+ }
81659
+ /**
81660
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
81661
+ *
81662
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
81663
+ * indexer is how the list is discovered and is not authority over it: it can lag a
81664
+ * governance removal, and acting on a stale list would build a swap the contract reverts
81665
+ * — after the user has approved it in their wallet. List from the index, verify on the
81666
+ * chain, then sign.
81667
+ */
81668
+ async psmCallsFor(stablecoinAddress) {
81669
+ const key = stablecoinAddress.toLowerCase();
81670
+ const cached = this.psmWrappers.get(key);
81671
+ if (cached) return { ok: true, calls: cached };
81488
81672
  const psmAddress = this.contracts["SimplePSMV2"];
81489
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
81490
- if (!psmAddress || !stablecoinAddress) {
81491
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
81673
+ if (!psmAddress) {
81492
81674
  return {
81493
81675
  ok: false,
81494
81676
  failure: {
81495
81677
  kind: "unavailable",
81496
81678
  source: "chain-rpc",
81497
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
81679
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
81498
81680
  }
81499
81681
  };
81500
81682
  }
81683
+ let supported;
81684
+ let symbol;
81685
+ try {
81686
+ const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81687
+ supported = await psm["supportedStablecoins"](key);
81688
+ const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81689
+ symbol = await erc20["symbol"]();
81690
+ } catch (e) {
81691
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
81692
+ }
81693
+ if (!supported) {
81694
+ return {
81695
+ ok: false,
81696
+ failure: {
81697
+ kind: "rejected",
81698
+ source: "chain-rpc",
81699
+ 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.`
81700
+ }
81701
+ };
81702
+ }
81703
+ const stablecoinAddress2 = key;
81501
81704
  const ucdTokenAddress = this.contracts["UCDToken"];
81502
81705
  const ucdControllerAddress = this.contracts["UCDController"];
81503
- this.psmWrapper = new PsmCalls({
81706
+ const built = new PsmCalls({
81504
81707
  provider: this.provider,
81505
81708
  psmAddress,
81506
- stablecoinAddress,
81507
- stablecoinSymbol: "USDC",
81709
+ stablecoinAddress: stablecoinAddress2,
81710
+ // Read from the token, never assumed. The old value was the literal "USDC", which
81711
+ // stops being true the moment a second coin is supported.
81712
+ stablecoinSymbol: symbol,
81508
81713
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
81509
81714
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
81510
81715
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
81511
81716
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
81512
81717
  });
81513
- return { ok: true, calls: this.psmWrapper };
81718
+ this.psmWrappers.set(key, built);
81719
+ return { ok: true, calls: built };
81514
81720
  }
81515
81721
  src(id) {
81516
81722
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -81773,6 +81979,7 @@ function renderApprovalPage(sessionId, nonce) {
81773
81979
  <div id="request" class="hidden">
81774
81980
  <div id="action" class="action"></div>
81775
81981
  <div id="card" class="card"></div>
81982
+ <div id="deadline" class="status hidden"></div>
81776
81983
  <button id="approve">Approve in wallet</button>
81777
81984
  <button id="reject">Reject</button>
81778
81985
  </div>
@@ -81805,10 +82012,19 @@ const statusEl = document.getElementById("status");
81805
82012
  const requestEl = document.getElementById("request");
81806
82013
  const actionEl = document.getElementById("action");
81807
82014
  const cardEl = document.getElementById("card");
82015
+ const approveEl = document.getElementById("approve");
82016
+ const rejectEl = document.getElementById("reject");
82017
+ const deadlineEl = document.getElementById("deadline");
82018
+ let deadlineTimer = null;
81808
82019
  const walletEl = document.getElementById("wallet");
81809
82020
  let account = null;
81810
82021
  let chainId = null;
81811
82022
  let current = null;
82023
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
82024
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
82025
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
82026
+ // card the page never renders is one the human can neither read nor reject.
82027
+ const pending = new Map();
81812
82028
 
81813
82029
  function post(path, body) {
81814
82030
  return fetch(path, {
@@ -81871,43 +82087,135 @@ async function onAccountsChanged(accounts) {
81871
82087
  account = (accounts && accounts[0]) || null;
81872
82088
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81873
82089
  showWallet();
81874
- clearRequest("Wallet changed \u2014 pending request invalidated.");
82090
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81875
82091
  }
81876
82092
 
81877
82093
  async function onChainChanged(cid) {
81878
82094
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81879
82095
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81880
82096
  showWallet();
81881
- clearRequest("Network changed \u2014 pending request invalidated.");
82097
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81882
82098
  }
81883
82099
 
81884
82100
  function listen() {
81885
82101
  const es = new EventSource(BASE + "events?s=" + SESSION);
81886
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
82102
+ es.onmessage = (ev) => {
82103
+ const next = JSON.parse(ev.data);
82104
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
82105
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
82106
+ pending.set(next.id, next);
82107
+ showPending();
82108
+ };
81887
82109
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81888
82110
  }
81889
82111
 
82112
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
82113
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
82114
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
82115
+ // gets approved.
82116
+ function pickPending() {
82117
+ const held = current ? pending.get(current.id) : undefined;
82118
+ if (held && held.mirror !== true) return held;
82119
+ let best = held || null;
82120
+ pending.forEach((frame) => {
82121
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
82122
+ });
82123
+ return best;
82124
+ }
82125
+
82126
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
82127
+ function showPending(emptyText) {
82128
+ const next = pickPending();
82129
+ if (!next) {
82130
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
82131
+ // an expiry for a ceremony that is already decided.
82132
+ stopDeadline();
82133
+ current = null;
82134
+ requestEl.classList.add("hidden");
82135
+ if (emptyText) showStatus(emptyText);
82136
+ return;
82137
+ }
82138
+ current = next;
82139
+ renderRequest();
82140
+ }
82141
+
81890
82142
  function renderRequest() {
81891
82143
  actionEl.textContent = current.action;
81892
82144
  cardEl.textContent = current.card.join("\\n");
82145
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
82146
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
82147
+ // server-side, which is the actual boundary.
82148
+ const mirrored = current.mirror === true;
82149
+ approveEl.classList.toggle("hidden", mirrored);
82150
+ rejectEl.classList.remove("hidden");
81893
82151
  requestEl.classList.remove("hidden");
81894
- showStatus("Review the operation below. Nothing signs without your approval.");
82152
+ showStatus(mirrored
82153
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
82154
+ : "Review the operation below. Nothing signs without your approval.");
82155
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
82156
+ // card promoted after another settles gets its own clock, not the previous one's.
82157
+ startDeadline();
82158
+ }
82159
+
82160
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
82161
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
82162
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
82163
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
82164
+ // honest without it needing to know anything about quantum windows.
82165
+ function stopDeadline() {
82166
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82167
+ deadlineEl.classList.add("hidden");
82168
+ }
82169
+
82170
+ function startDeadline() {
82171
+ stopDeadline();
82172
+ if (!current || typeof current.expiresAtSec !== "number") return;
82173
+ const tick = () => {
82174
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
82175
+ if (left > 0) {
82176
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
82177
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
82178
+ } else {
82179
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
82180
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
82181
+ // after. The button is deliberately left enabled \u2014 declining is still the right
82182
+ // action and the page must not trap them.
82183
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
82184
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82185
+ }
82186
+ deadlineEl.classList.remove("hidden");
82187
+ };
82188
+ tick();
82189
+ deadlineTimer = setInterval(tick, 1000);
81895
82190
  }
81896
82191
 
82192
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
82193
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
82194
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81897
82195
  function clearRequest(text) {
81898
- current = null;
81899
- requestEl.classList.add("hidden");
81900
- showStatus(text);
82196
+ if (current) pending.delete(current.id);
82197
+ showPending(text);
81901
82198
  }
81902
82199
 
81903
- document.getElementById("reject").onclick = async () => {
82200
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
82201
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
82202
+ // stays readable and rejectable.
82203
+ function invalidatePageRequests(text) {
82204
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
82205
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
82206
+ }
82207
+
82208
+ rejectEl.onclick = async () => {
81904
82209
  if (!current) return;
81905
82210
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81906
82211
  clearRequest("Rejected. Waiting for the next request\u2026");
81907
82212
  };
81908
82213
 
81909
- document.getElementById("approve").onclick = async () => {
82214
+ approveEl.onclick = async () => {
81910
82215
  if (!current) return;
82216
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
82217
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
82218
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81911
82219
  const req = current;
81912
82220
  try {
81913
82221
  if (req.kind === "transaction") {
@@ -81924,7 +82232,10 @@ document.getElementById("approve").onclick = async () => {
81924
82232
  const fbody = await fr.json();
81925
82233
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
81926
82234
  const fresh = fbody.request;
81927
- // \u2026re-render what will actually sign\u2026
82235
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
82236
+ // another card arriving while the wallet popup is open re-picks from there, and the
82237
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
82238
+ pending.set(fresh.id, fresh);
81928
82239
  current = fresh; renderRequest();
81929
82240
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
81930
82241
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -82079,9 +82390,6 @@ var SignatureBridge = class {
82079
82390
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
82080
82391
  maxPending;
82081
82392
  attachGraceMs;
82082
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
82083
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
82084
- lastAttachedMs = 0;
82085
82393
  server = null;
82086
82394
  port = 0;
82087
82395
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -82192,7 +82500,7 @@ var SignatureBridge = class {
82192
82500
  connectedAccounts() {
82193
82501
  const seen = /* @__PURE__ */ new Map();
82194
82502
  for (const s of this.sessions.values()) {
82195
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82503
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82196
82504
  }
82197
82505
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
82198
82506
  return [...seen.values()];
@@ -82232,13 +82540,16 @@ var SignatureBridge = class {
82232
82540
  enqueuedMs: now,
82233
82541
  resolve,
82234
82542
  settled: false,
82235
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
82543
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
82544
+ owner: this.wcActive ? "wc" : "page",
82545
+ dispatched: false,
82546
+ lastAttachedMs: now
82236
82547
  };
82237
82548
  this.pending.set(request.id, entry);
82238
- if (this.wcActive) {
82549
+ if (entry.owner === "wc") {
82239
82550
  void this.driveWc(entry);
82240
82551
  } else {
82241
- this.push(request);
82552
+ this.pushEntry(entry);
82242
82553
  }
82243
82554
  });
82244
82555
  }
@@ -82259,10 +82570,16 @@ var SignatureBridge = class {
82259
82570
  enqueuedMs: now,
82260
82571
  resolve,
82261
82572
  settled: false,
82262
- collect
82573
+ collect,
82574
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
82575
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
82576
+ // ceremony could not reach quorum through the very pages it is broadcast to.
82577
+ owner: "both",
82578
+ dispatched: false,
82579
+ lastAttachedMs: now
82263
82580
  };
82264
82581
  this.pending.set(request.id, entry);
82265
- this.push(request);
82582
+ this.pushEntry(entry);
82266
82583
  if (this.wcActive) void this.driveWcCollection(entry);
82267
82584
  });
82268
82585
  }
@@ -82301,7 +82618,9 @@ var SignatureBridge = class {
82301
82618
  }
82302
82619
  try {
82303
82620
  if (req.kind === "transaction") {
82621
+ this.pushEntry(entry);
82304
82622
  const tx2 = req.tx;
82623
+ entry.dispatched = true;
82305
82624
  const txHash = await transport.request("eth_sendTransaction", [
82306
82625
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
82307
82626
  ]);
@@ -82313,11 +82632,22 @@ var SignatureBridge = class {
82313
82632
  req.card = fresh.card;
82314
82633
  }
82315
82634
  const ps = req.personalSign;
82635
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
82636
+ this.settle(entry, {
82637
+ status: "invalidated",
82638
+ 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)`
82639
+ });
82640
+ return;
82641
+ }
82642
+ this.pushEntry(entry);
82643
+ entry.dispatched = true;
82316
82644
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
82317
82645
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82318
82646
  } else {
82647
+ this.pushEntry(entry);
82319
82648
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
82320
82649
  const payload = withEip712DomainType2(req.typedData);
82650
+ entry.dispatched = true;
82321
82651
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
82322
82652
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82323
82653
  }
@@ -82337,29 +82667,54 @@ var SignatureBridge = class {
82337
82667
  * with a live attachment is in use and must never be evicted. */
82338
82668
  attachedNow() {
82339
82669
  if (this.wcActive) return true;
82340
- for (const s of this.sessions.values()) if (s.sse) return true;
82670
+ return this.pageAttached();
82671
+ }
82672
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
82673
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
82674
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
82675
+ * WalletConnect and must stay global for the connector's eviction predicate. */
82676
+ pageAttached() {
82677
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
82341
82678
  return false;
82342
82679
  }
82680
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
82681
+ * predicate said "a WC session is attached", which is true but irrelevant to a
82682
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
82683
+ * out the full expiry instead of failing fast at the grace. */
82684
+ attachedFor(entry) {
82685
+ if (entry.owner === "wc") return this.wcActive;
82686
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
82687
+ return this.pageAttached();
82688
+ }
82343
82689
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
82344
82690
  * interval; tests call it directly with the injected clock advanced. Order matters:
82345
82691
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
82346
82692
  sweep() {
82347
82693
  const now = this.clock();
82348
- const attached = this.attachedNow();
82349
- if (attached) this.lastAttachedMs = now;
82350
82694
  for (const entry of this.pending.values()) {
82351
82695
  if (entry.settled) continue;
82352
82696
  if (now >= entry.deadlineMs) {
82353
82697
  this.settle(entry, { status: "expired" });
82354
82698
  continue;
82355
82699
  }
82356
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
82357
- this.settle(entry, {
82358
- status: "invalidated",
82359
- 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`
82360
- });
82700
+ if (this.attachedFor(entry)) {
82701
+ entry.lastAttachedMs = now;
82702
+ continue;
82361
82703
  }
82704
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
82705
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
82706
+ }
82707
+ }
82708
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
82709
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
82710
+ unattendedReason(entry) {
82711
+ if (entry.dispatched && entry.request.kind === "transaction") {
82712
+ 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.";
82713
+ }
82714
+ if (entry.owner === "wc") {
82715
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
82362
82716
  }
82717
+ 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`;
82363
82718
  }
82364
82719
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
82365
82720
  walletConnectActive() {
@@ -82453,7 +82808,7 @@ var SignatureBridge = class {
82453
82808
  return;
82454
82809
  }
82455
82810
  const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82456
- this.sessions.set(sessionId, { wallet: null, sse: null });
82811
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
82457
82812
  const page = htmlPageSecurityHeaders();
82458
82813
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82459
82814
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -82483,7 +82838,8 @@ var SignatureBridge = class {
82483
82838
  const refusal = info ? this.accountRefusal(info.account) : null;
82484
82839
  if (info && refusal) {
82485
82840
  this.wcActive = false;
82486
- this.wallet = null;
82841
+ this.rebuildSharedWallet();
82842
+ this.demoteWcEntries();
82487
82843
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82488
82844
  `);
82489
82845
  return;
@@ -82493,7 +82849,10 @@ var SignatureBridge = class {
82493
82849
  if (info === null) {
82494
82850
  for (const entry of this.pending.values()) {
82495
82851
  if (!entry.settled && !entry.collect) {
82496
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82852
+ this.settle(entry, {
82853
+ status: "invalidated",
82854
+ 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"
82855
+ });
82497
82856
  }
82498
82857
  }
82499
82858
  }
@@ -82565,9 +82924,7 @@ var SignatureBridge = class {
82565
82924
  session.sse?.end();
82566
82925
  session.sse = res;
82567
82926
  for (const entry of this.pending.values()) {
82568
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
82569
-
82570
- `);
82927
+ if (!entry.settled) res.write(this.wireFor(entry));
82571
82928
  }
82572
82929
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
82573
82930
  keepAlive.unref();
@@ -82587,6 +82944,7 @@ var SignatureBridge = class {
82587
82944
  }
82588
82945
  const refusal = this.accountRefusal(account);
82589
82946
  if (refusal) {
82947
+ this.quarantine(session, refusal);
82590
82948
  this.deny(res, 403, refusal);
82591
82949
  return;
82592
82950
  }
@@ -82625,10 +82983,15 @@ var SignatureBridge = class {
82625
82983
  const chainId = Number(body["chainId"]);
82626
82984
  const prev = session.wallet;
82627
82985
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
82628
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
82629
- session.wallet = refusedSwitch ? null : offered;
82630
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82631
- this.wallet = session.wallet;
82986
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
82987
+ const refusedSwitch = switchRefusal !== null;
82988
+ if (refusedSwitch) {
82989
+ this.quarantine(session, switchRefusal);
82990
+ } else {
82991
+ session.wallet = offered;
82992
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82993
+ this.wallet = session.wallet;
82994
+ }
82632
82995
  }
82633
82996
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
82634
82997
  if (unchanged) {
@@ -82637,10 +83000,36 @@ var SignatureBridge = class {
82637
83000
  }
82638
83001
  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";
82639
83002
  for (const entry of this.pending.values()) {
82640
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
83003
+ if (entry.settled || entry.collect) continue;
83004
+ if (this.ownedByWc(entry)) continue;
83005
+ this.settle(entry, { status: "invalidated", reason });
82641
83006
  }
82642
83007
  this.ok(res);
82643
83008
  }
83009
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
83010
+ * session hands the request back to the page rather than stranding it. */
83011
+ ownedByWc(entry) {
83012
+ if (entry.owner !== "wc") return false;
83013
+ return this.wcActive || entry.dispatched;
83014
+ }
83015
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
83016
+ * them so the card stops rendering read-only. Collections are already `both`.
83017
+ *
83018
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
83019
+ * phone is still holding does not replace one wallet with another, it adds a second: the
83020
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
83021
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
83022
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
83023
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
83024
+ * false for them, and `unattendedReason` says plainly that the phone may already have
83025
+ * acted. */
83026
+ demoteWcEntries() {
83027
+ for (const entry of this.pending.values()) {
83028
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
83029
+ entry.owner = "page";
83030
+ this.pushEntry(entry);
83031
+ }
83032
+ }
82644
83033
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
82645
83034
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
82646
83035
  async onFinalize(body, res) {
@@ -82654,6 +83043,10 @@ var SignatureBridge = class {
82654
83043
  this.deny(res, 400, "finalize applies only to personal-sign requests");
82655
83044
  return;
82656
83045
  }
83046
+ if (this.ownedByWc(entry)) {
83047
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
83048
+ return;
83049
+ }
82657
83050
  if (entry.finalize) {
82658
83051
  let fresh;
82659
83052
  try {
@@ -82680,10 +83073,22 @@ var SignatureBridge = class {
82680
83073
  return;
82681
83074
  }
82682
83075
  if (body["approved"] !== true) {
83076
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
83077
+ this.settle(entry, {
83078
+ status: "invalidated",
83079
+ 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."
83080
+ });
83081
+ this.ok(res);
83082
+ return;
83083
+ }
82683
83084
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
82684
83085
  this.ok(res);
82685
83086
  return;
82686
83087
  }
83088
+ if (this.ownedByWc(entry)) {
83089
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
83090
+ return;
83091
+ }
82687
83092
  const account = String(body["account"] ?? "");
82688
83093
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
82689
83094
  this.deny(res, 400, "approved result requires the signing account");
@@ -82720,12 +83125,21 @@ var SignatureBridge = class {
82720
83125
  this.pending.delete(entry.request.id);
82721
83126
  entry.resolve(outcome);
82722
83127
  }
82723
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
82724
- push(request) {
82725
- const data = `data: ${JSON.stringify(request)}
83128
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
83129
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
83130
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
83131
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
83132
+ * a permanently read-only card that nobody is allowed to decide. */
83133
+ wireFor(entry) {
83134
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
83135
+ return `data: ${JSON.stringify(payload)}
82726
83136
 
82727
83137
  `;
82728
- for (const s of this.sessions.values()) s.sse?.write(data);
83138
+ }
83139
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
83140
+ pushEntry(entry) {
83141
+ const data = this.wireFor(entry);
83142
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82729
83143
  }
82730
83144
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
82731
83145
  pushProgress(payload) {
@@ -82733,7 +83147,48 @@ var SignatureBridge = class {
82733
83147
  data: ${JSON.stringify(payload)}
82734
83148
 
82735
83149
  `;
82736
- for (const s of this.sessions.values()) s.sse?.write(data);
83150
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
83151
+ }
83152
+ /**
83153
+ * C-47: `this.wallet` is DERIVED, never guessed.
83154
+ *
83155
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
83156
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
83157
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
83158
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
83159
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
83160
+ * wrong account into a disconnect for the legitimate user.
83161
+ *
83162
+ * Deriving it from live state removes the guess. Preference order matches
83163
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
83164
+ */
83165
+ rebuildSharedWallet() {
83166
+ if (this.wcActive && this.wcTransport) {
83167
+ const wc = this.wcTransport.active();
83168
+ if (wc && !this.accountRefusal(wc.account)) {
83169
+ this.wallet = { account: wc.account, chainId: wc.chainId };
83170
+ return;
83171
+ }
83172
+ }
83173
+ let latest = null;
83174
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
83175
+ this.wallet = latest;
83176
+ }
83177
+ /**
83178
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
83179
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
83180
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
83181
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
83182
+ * stream, and re-derive the shared view without it.
83183
+ */
83184
+ quarantine(session, reason) {
83185
+ session.refused = reason;
83186
+ session.wallet = null;
83187
+ if (session.sse) {
83188
+ session.sse.end();
83189
+ session.sse = null;
83190
+ }
83191
+ this.rebuildSharedWallet();
82737
83192
  }
82738
83193
  sessionOf(candidate, res) {
82739
83194
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -82741,6 +83196,10 @@ data: ${JSON.stringify(payload)}
82741
83196
  this.deny(res, 403, "missing or wrong session");
82742
83197
  return null;
82743
83198
  }
83199
+ if (session.refused) {
83200
+ this.deny(res, 403, session.refused);
83201
+ return null;
83202
+ }
82744
83203
  return session;
82745
83204
  }
82746
83205
  checkSession(candidate, res) {
@@ -83162,7 +83621,7 @@ var FIELD_GLOSSARY = {
83162
83621
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83163
83622
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83164
83623
  // ---- psm quote ----
83165
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83624
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
83166
83625
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83167
83626
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83168
83627
  amountInToken: "the token you pay with",
@@ -83260,11 +83719,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83260
83719
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83261
83720
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83262
83721
  signerModes: GUIDE_SIGNER_MODES,
83263
- // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
83264
- // leg genuinely is not there until an operator configures it. The first draft of this line
83265
- // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
83266
- // about — the default rendering would have promised a QR that most installs cannot show.
83267
- // A live boot derives this from env either way (network-switch.ts).
83722
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
83723
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
83724
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
83725
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
83726
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
83727
+ // nobody supplied a deployment at all, and understating a capability there is the safe
83728
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
83729
+ // overclaim C-44 is about — promising a QR the build cannot show.
83268
83730
  walletConnect: false
83269
83731
  };
83270
83732
  function servedNetworks(d) {
@@ -83275,7 +83737,7 @@ function servedNetworks(d) {
83275
83737
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
83276
83738
  }
83277
83739
  if (mainnet) {
83278
- 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";
83740
+ 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";
83279
83741
  }
83280
83742
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
83281
83743
  }
@@ -83354,13 +83816,14 @@ function switchNetworkRules(d) {
83354
83816
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83355
83817
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83356
83818
  A sepolia position does not exist on mainnet and vice versa.
83357
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83358
- and every one still requires the user's explicit confirmation plus the signer
83359
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83819
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83820
+ mainnet they move REAL money, and every one still requires the user's explicit
83821
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83822
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83823
+ signed.`;
83360
83824
  }
83361
83825
  const only = d.networks[0];
83362
83826
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83363
- 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.";
83364
83827
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83365
83828
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
83366
83829
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -83369,7 +83832,9 @@ function switchNetworkRules(d) {
83369
83832
  belong to ${only} and would not exist anywhere else.
83370
83833
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83371
83834
  confirmation plus the signer ceremony.
83372
- - ${psm}`;
83835
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83836
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83837
+ anything is signed.`;
83373
83838
  }
83374
83839
  function wrongNetworkTroubleshootingRow(d) {
83375
83840
  if (d.networks.length > 1) {
@@ -83389,14 +83854,18 @@ function switchNetworkIndexLine(d) {
83389
83854
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83390
83855
  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`;
83391
83856
  }
83392
- function psmAvailabilityNote(d) {
83393
- if (d.networks.includes("sepolia")) return "";
83394
- return `**Not executable on this deployment.** The PSM write port refuses on every network
83395
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
83396
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
83397
- the mechanism, not an offer: say so before a user plans around it.
83398
-
83399
- `;
83857
+ function psmStablecoinRealityNote(d) {
83858
+ if (d.networks.includes("sepolia")) {
83859
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83860
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83861
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83862
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83863
+ }
83864
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83865
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83866
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83867
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83868
+ have to guess whether the money is real.`;
83400
83869
  }
83401
83870
  function authorizationModeBullets(d) {
83402
83871
  const bullets = [];
@@ -83510,7 +83979,7 @@ on the real adapter and the mock.
83510
83979
  **The walkthrough:**
83511
83980
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83512
83981
  desktop browser; ${approvalPageLocation(d)}
83513
- 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) + "."}
83982
+ 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) + "."}
83514
83983
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83515
83984
  login ceremony explicitly (one typed-data signature in the wallet).
83516
83985
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83549,13 +84018,24 @@ on the real adapter and the mock.
83549
84018
  hash the SDK builds internally, which the approval page shows bare and says plainly it
83550
84019
  cannot decode (the production web app signs the same way). Tell the user before that
83551
84020
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83552
- expect an unreadable card and click through the readable one.
84021
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
84022
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
84023
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
84024
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
84025
+ on the card, and the page is the only surface that shows it. With no page attached the
84026
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
84027
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
84028
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
83553
84029
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83554
84030
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83555
84031
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83556
84032
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83557
84033
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83558
- signature. The blind execute popup happens once.
84034
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
84035
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
84036
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
84037
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
84038
+ typed-data card. Promise the unreadable one only where it is real.
83559
84039
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83560
84040
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83561
84041
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83598,6 +84078,14 @@ Connections / Connected sites).`,
83598
84078
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
83599
84079
  fresh stamp using the destination and amount the CHAIN already holds. Check
83600
84080
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
84081
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
84082
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
84083
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
84084
+ Say which one before they open the page, not after the popup surprises them.
84085
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
84086
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
84087
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
84088
+ the original withdrawal authorized.
83601
84089
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83602
84090
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83603
84091
 
@@ -83618,9 +84106,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83618
84106
 
83619
84107
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83620
84108
  signed, amounts included. Read it back when the user asks what happened.`,
83621
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
84109
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
83622
84110
 
83623
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
84111
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83624
84112
  directions, in user words:
83625
84113
 
83626
84114
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83628,20 +84116,27 @@ directions, in user words:
83628
84116
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83629
84117
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83630
84118
  and you receive 99 UCD.
83631
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
83632
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
83633
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
83634
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
83635
- shortfall refuses with both figures (available vs required).
84119
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
84120
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
84121
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
84122
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
84123
+ reserves, and a shortfall refuses with both figures (available vs required).
84124
+
84125
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
84126
+ default and that is deliberate: the PSM can carry several coins, each with its own
84127
+ reserves, fees and limits, so picking one silently would move someone's money through a
84128
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
84129
+ there rather than guessing one.
83636
84130
 
83637
84131
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83638
84132
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83639
84133
  1e18 = 1:1) and can be changed by protocol governance.
83640
84134
 
83641
84135
  **Limits and switches** (all visible in \`protocol://psm\`):
83642
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
83643
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
83644
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
84136
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
84137
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
84138
+ direction is DISABLED.
84139
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
83645
84140
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83646
84141
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
83647
84142
 
@@ -83650,23 +84145,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
83650
84145
  change between your quote and execution; the floor makes a drifted execution REFUSE
83651
84146
  rather than silently deliver less than quoted.
83652
84147
 
83653
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83654
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83655
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83656
- the money is real. On mainnet the stablecoin is real Circle USDC.
84148
+ ${psmStablecoinRealityNote(d)}
83657
84149
 
83658
84150
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83659
84151
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83660
84152
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83661
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
83662
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
83663
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84153
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84154
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
84155
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83664
84156
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83665
84157
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83666
84158
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83667
84159
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83668
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83669
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
84160
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84161
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84162
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
84163
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
84164
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
84165
+ per-operation and per-block limits,
84166
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
84167
+ mainnet swap, not after.`,
83670
84168
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83671
84169
 
83672
84170
  Every fund-moving operation needs TWO things, always in this order:
@@ -83925,9 +84423,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
83925
84423
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83926
84424
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83927
84425
  the same way \u2014 reconnect on the user's word.`}
83928
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83929
- 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
83930
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
84426
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
84427
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
84428
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
84429
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
84430
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
83931
84431
  ${wrongNetworkTroubleshootingRow(d)}
83932
84432
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
83933
84433
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -84085,12 +84585,13 @@ function guideDeployment(overrides, env) {
84085
84585
  tier: overrides?.bridgeMount ? "hosted" : "local",
84086
84586
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
84087
84587
  signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
84088
- // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
84089
- // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
84090
- // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
84091
- // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
84092
- // about the same server, which is exactly what they did before this line existed.
84093
- walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
84588
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
84589
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
84590
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
84591
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
84592
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
84593
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
84594
+ walletConnect: wcEnabled(env)
84094
84595
  };
84095
84596
  }
84096
84597
  function assembleWorld(opts) {
@@ -84730,39 +85231,45 @@ function registerPsmTools(server, getB) {
84730
85231
  server,
84731
85232
  "psm_quote",
84732
85233
  {
84733
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84734
- 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.",
85234
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
85235
+ 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.",
84735
85236
  inputSchema: {
84736
- 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)"),
84737
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
85237
+ stablecoin: import_zod4.z.string().min(1).describe(
85238
+ "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."
85239
+ ),
85240
+ 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)"),
85241
+ 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.")
84738
85242
  },
84739
85243
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84740
85244
  },
84741
- async ({ direction, amount }) => guarded(async () => {
84742
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
85245
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
85246
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
84743
85247
  const problem = checkUcdAmount(amount, label);
84744
85248
  if (problem) return validationFailed(problem);
84745
85249
  const b = getB();
84746
85250
  if (!b.ok) return renderError(b.error);
84747
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
85251
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
84748
85252
  })
84749
85253
  );
84750
85254
  registerBoundaryTool(
84751
85255
  server,
84752
85256
  "psm_swap",
84753
85257
  {
84754
- title: "Exchange UCD \u2194 USDC through the PSM",
84755
- 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).",
85258
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
85259
+ 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).",
84756
85260
  inputSchema: {
84757
- 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)"),
84758
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
85261
+ stablecoin: import_zod4.z.string().min(1).describe(
85262
+ "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."
85263
+ ),
85264
+ 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)"),
85265
+ 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."),
84759
85266
  confirmed: confirmedSchema2
84760
85267
  },
84761
85268
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84762
85269
  },
84763
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84764
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84765
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
85270
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
85271
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
85272
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84766
85273
  const gate = requireConfirmation(
84767
85274
  confirmed,
84768
85275
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84772,7 +85279,7 @@ function registerPsmTools(server, getB) {
84772
85279
  if (problem) return validationFailed(problem);
84773
85280
  const b = getB();
84774
85281
  if (!b.ok) return renderError(b.error);
84775
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
85282
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84776
85283
  })
84777
85284
  );
84778
85285
  }
@@ -85218,7 +85725,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85218
85725
  "network_switch",
85219
85726
  {
85220
85727
  title: "Show or switch the active network",
85221
- 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.",
85728
+ 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.",
85222
85729
  inputSchema: {
85223
85730
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
85224
85731
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -85236,7 +85743,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85236
85743
  lines.push(
85237
85744
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
85238
85745
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
85239
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
85746
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
85240
85747
  "Session-scoped: the configured default network returns when the server restarts."
85241
85748
  );
85242
85749
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -85342,13 +85849,26 @@ function registerProtocolResources(server, getB) {
85342
85849
  "protocol://psm",
85343
85850
  {
85344
85851
  title: "PSM status (UCD \u2194 USDC exchange)",
85345
- 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).",
85852
+ 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.",
85346
85853
  mimeType: "application/json"
85347
85854
  },
85348
85855
  async (uri) => {
85349
85856
  const b = getB();
85350
85857
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
85351
- const env = await b.boundary.getPsmStatus();
85858
+ const listed = await b.boundary.listPsmStablecoins();
85859
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85860
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85861
+ const failed = perCoin.find((s) => !s.ok);
85862
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85863
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85864
+ const head = coins[0];
85865
+ const env = {
85866
+ ...listed,
85867
+ data: {
85868
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85869
+ stablecoins: coins
85870
+ }
85871
+ };
85352
85872
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
85353
85873
  }
85354
85874
  );
@@ -85561,12 +86081,15 @@ function composeConnector(opts, rawPublicOrigin) {
85561
86081
  for (const session of sessions.values()) held.add(session.tenant);
85562
86082
  return held;
85563
86083
  }
85564
- function isReclaimable(tenantKey, world, held) {
85565
- if (held.has(tenantKey)) return false;
86084
+ function isEvictable(world) {
85566
86085
  const bridge = world.deps.signer?.bridge;
85567
86086
  if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85568
86087
  return true;
85569
86088
  }
86089
+ function isReclaimable(tenantKey, world, held) {
86090
+ if (held.has(tenantKey)) return false;
86091
+ return isEvictable(world);
86092
+ }
85570
86093
  function sweepService() {
85571
86094
  const now = clock();
85572
86095
  for (const [sid, session] of [...sessions]) {
@@ -85582,13 +86105,12 @@ function composeConnector(opts, rawPublicOrigin) {
85582
86105
  dropWorld(tenantKey, world, "idle eviction");
85583
86106
  }
85584
86107
  }
85585
- function reclaimIdleWorld() {
85586
- const held = tenantsWithSessions();
86108
+ function leastRecentlyActive(eligible) {
85587
86109
  let victimKey = null;
85588
86110
  let victim = null;
85589
86111
  let oldest = Number.POSITIVE_INFINITY;
85590
86112
  for (const [tenantKey, world] of readyWorlds) {
85591
- if (!isReclaimable(tenantKey, world, held)) continue;
86113
+ if (!eligible(tenantKey, world)) continue;
85592
86114
  const activeAt = lastActivity.get(tenantKey) ?? 0;
85593
86115
  if (activeAt < oldest) {
85594
86116
  oldest = activeAt;
@@ -85596,8 +86118,23 @@ function composeConnector(opts, rawPublicOrigin) {
85596
86118
  victim = world;
85597
86119
  }
85598
86120
  }
85599
- if (victimKey === null || victim === null) return false;
85600
- dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
86121
+ return victimKey !== null && victim !== null ? [victimKey, victim] : null;
86122
+ }
86123
+ function reclaimIdleWorld() {
86124
+ const held = tenantsWithSessions();
86125
+ const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
86126
+ if (tier1) {
86127
+ dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
86128
+ return true;
86129
+ }
86130
+ const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
86131
+ if (!tier2) return false;
86132
+ for (const [sid, session] of [...sessions]) {
86133
+ if (session.tenant !== tier2[0]) continue;
86134
+ sessions.delete(sid);
86135
+ void session.transport.close().catch(() => void 0);
86136
+ }
86137
+ dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
85601
86138
  return true;
85602
86139
  }
85603
86140
  class TenantCapacityError extends Error {
@@ -85815,7 +86352,8 @@ function composeConnector(opts, rawPublicOrigin) {
85815
86352
  if (opts.auth) {
85816
86353
  authImpl = opts.auth;
85817
86354
  } else {
85818
- const wcLeg = opts.siweWc ?? (opts.env["DH_WC_PROJECT_ID"] ? { projectId: opts.env["DH_WC_PROJECT_ID"] } : void 0);
86355
+ const envWcProjectId = resolvedWcProjectId(opts.env);
86356
+ const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
85819
86357
  const siwe = new SiweOAuthProvider({
85820
86358
  origin: () => publicOrigin,
85821
86359
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,