@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.
@@ -37,6 +37,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
37
37
  // src/boundary/upstream/shared/external-bridge/wc-transport.ts
38
38
  var wc_transport_exports = {};
39
39
  __export(wc_transport_exports, {
40
+ WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40
41
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
41
42
  WcTransport: () => WcTransport,
42
43
  newIsolatedCore: () => newIsolatedCore,
@@ -72,7 +73,7 @@ function newIsolatedCore(cfg, label) {
72
73
  });
73
74
  return { core, scratch };
74
75
  }
75
- var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
76
+ var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
76
77
  var init_wc_transport = __esm({
77
78
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
78
79
  "use strict";
@@ -82,6 +83,12 @@ var init_wc_transport = __esm({
82
83
  path = __toESM(require("path"));
83
84
  import_node_fs = require("fs");
84
85
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
86
+ WC_DAPP_METADATA = {
87
+ name: "Diamond Hands MCP",
88
+ description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
89
+ url: "https://app.diamondhands.credit",
90
+ icons: []
91
+ };
85
92
  EVENTS = ["accountsChanged", "chainChanged"];
86
93
  WcTransport = class _WcTransport {
87
94
  constructor(client, cfg, scratch) {
@@ -100,12 +107,7 @@ var init_wc_transport = __esm({
100
107
  const client = await import_sign_client.default.init({
101
108
  core,
102
109
  projectId: cfg.projectId,
103
- metadata: {
104
- name: "Diamond Hands MCP",
105
- description: "Human approval for Diamond Hands operations",
106
- url: "https://gvnr.xyz",
107
- icons: []
108
- }
110
+ metadata: WC_DAPP_METADATA
109
111
  });
110
112
  return new _WcTransport(client, cfg, scratch);
111
113
  }
@@ -15559,9 +15561,9 @@ ${errorReport}`);
15559
15561
  var MAX_BTC_AMOUNT = 25e6 * 1e8;
15560
15562
  var UTXO_QUERY_MAX_RETRIES = 3;
15561
15563
  var UTXO_QUERY_RETRY_DELAY_MS = 500;
15562
- var QUANTUM_WINDOW_SECONDS3 = 60;
15564
+ var QUANTUM_WINDOW_SECONDS4 = 60;
15563
15565
  var DEAD_ZONE_SECONDS2 = 16;
15564
- var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS3 - DEAD_ZONE_SECONDS2;
15566
+ var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
15565
15567
  var SECONDS_PER_DAY = 86400;
15566
15568
  var DAYS_PER_MONTH = 30;
15567
15569
  var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
@@ -41036,7 +41038,7 @@ function htmlPageSecurityHeaders(extra) {
41036
41038
  }
41037
41039
 
41038
41040
  // src/version.ts
41039
- var SERVER_VERSION = "0.5.13";
41041
+ var SERVER_VERSION = "0.5.15";
41040
41042
 
41041
41043
  // src/connector/siwe-oauth.ts
41042
41044
  var import_node_crypto2 = require("crypto");
@@ -41543,6 +41545,21 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
41543
41545
  var ADAPTERS = ["mock", "real"];
41544
41546
  var LATENCIES = ["zero", "realistic"];
41545
41547
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
41548
+ var WC_DISABLED = "off";
41549
+ function wcEnabled(env) {
41550
+ return resolvedWcProjectId(env) !== void 0;
41551
+ }
41552
+ function resolvedWcProjectId(env) {
41553
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
41554
+ }
41555
+ function resolveWcProjectId(raw, problems) {
41556
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
41557
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
41558
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
41559
+ return void 0;
41560
+ }
41561
+ return raw;
41562
+ }
41546
41563
  var NETWORK_DEFAULTS = {
41547
41564
  sepolia: {
41548
41565
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -41617,10 +41634,7 @@ function resolveBoundaryConfig(env) {
41617
41634
  }
41618
41635
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41619
41636
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41620
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41621
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41622
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41623
- }
41637
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41624
41638
  let bridgeOpenBrowser;
41625
41639
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41626
41640
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41692,10 +41706,7 @@ function resolveRealConfig(env) {
41692
41706
  const stateDir = env["DH_STATE_DIR"];
41693
41707
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41694
41708
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41695
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41696
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41697
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41698
- }
41709
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41699
41710
  let bridgeOpenBrowser;
41700
41711
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41701
41712
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -42135,8 +42146,15 @@ var BoundaryCore = class {
42135
42146
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
42136
42147
  }
42137
42148
  // ---- PSM reads (plan 08 Part B Phase R) ----
42138
- async getPsmStatus() {
42139
- const r = await this.deps.plugin.chain.getPsmStatus();
42149
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
42150
+ * names the coin, and this is how they learn what they may name. */
42151
+ async listPsmStablecoins() {
42152
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
42153
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
42154
+ return okEnvelope(r.value, r.source);
42155
+ }
42156
+ async getPsmStatus(p) {
42157
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
42140
42158
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42141
42159
  return okEnvelope(this.psmStatusData(r.value), r.source);
42142
42160
  }
@@ -42147,7 +42165,7 @@ var BoundaryCore = class {
42147
42165
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
42148
42166
  * whenever `env.ok`. */
42149
42167
  async psmQuoteWithStatus(p) {
42150
- const statusR = await this.deps.plugin.chain.getPsmStatus();
42168
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
42151
42169
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
42152
42170
  const s = statusR.value;
42153
42171
  const toUcd = p.direction === "to-ucd";
@@ -42203,6 +42221,7 @@ var BoundaryCore = class {
42203
42221
  );
42204
42222
  }
42205
42223
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
42224
+ stablecoin: p.stablecoin,
42206
42225
  direction: toUcd ? "swap" : "redeem",
42207
42226
  amountIn: amountIn.toString()
42208
42227
  });
@@ -42269,6 +42288,7 @@ var BoundaryCore = class {
42269
42288
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
42270
42289
  if (floor === 0n) floor = 1n;
42271
42290
  const r = await this.deps.plugin.ops.psmSwap({
42291
+ stablecoin: p.stablecoin,
42272
42292
  direction: q.contractCall,
42273
42293
  amountIn: q.amountIn,
42274
42294
  minOut: floor.toString(),
@@ -42368,7 +42388,7 @@ var BoundaryCore = class {
42368
42388
  feeToken: "UCD",
42369
42389
  perBlockCap: s.maxSwapVolumePerBlock
42370
42390
  }),
42371
- toUsdc: direction({
42391
+ fromUcd: direction({
42372
42392
  minAmount: s.minRedeemAmount,
42373
42393
  maxAmount: s.maxRedeemAmount,
42374
42394
  amountUnit: ucdUnit,
@@ -42500,7 +42520,10 @@ var BoundaryCore = class {
42500
42520
  borrower: auth.borrower
42501
42521
  });
42502
42522
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42503
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
42523
+ return okEnvelope(
42524
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
42525
+ r.source
42526
+ );
42504
42527
  }
42505
42528
  // ---- meta ----
42506
42529
  world() {
@@ -43347,20 +43370,56 @@ var World = class {
43347
43370
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
43348
43371
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
43349
43372
  }
43350
- const c = this.state.collateral[p.positionId];
43351
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43352
- const transfers = pending.map((spend) => {
43373
+ const fee = BigInt(p.networkFeeSats);
43374
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
43375
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
43376
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
43377
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
43353
43378
  const { hash: txid } = this.nextId("btc-withdraw-retry");
43354
43379
  return {
43355
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
43380
+ utxoIdentifier,
43356
43381
  ok: true,
43357
43382
  txid,
43358
- amountSentSats: spend.satoshis,
43383
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
43384
+ // the authorized amount, never added on top — the same semantics `withdraw` above
43385
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
43386
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
43387
+ // whether the fee was honoured at all.
43388
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
43359
43389
  destination: spend.targetAddress
43360
43390
  };
43361
43391
  });
43362
43392
  return { ok: true, value: { attempted: transfers.length, transfers } };
43363
43393
  }
43394
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
43395
+ pendingSpends(positionId) {
43396
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
43397
+ }
43398
+ /**
43399
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
43400
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
43401
+ *
43402
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
43403
+ *
43404
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
43405
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
43406
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
43407
+ */
43408
+ retryFeeRefusal(spend, networkFeeSats) {
43409
+ const target = BigInt(spend.satoshis);
43410
+ if (BigInt(networkFeeSats) * 2n >= target) {
43411
+ 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)`;
43412
+ }
43413
+ return null;
43414
+ }
43415
+ /**
43416
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
43417
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
43418
+ * wallet is never opened — which is what the mock's ceremony gate reads.
43419
+ */
43420
+ retryExecutableCount(positionId, networkFeeSats) {
43421
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
43422
+ }
43364
43423
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
43365
43424
  safesMap() {
43366
43425
  return this.state.safes;
@@ -44154,7 +44213,7 @@ var SINK_CONTRACTS = {
44154
44213
  PositionManager: sinkAddress("PositionManager"),
44155
44214
  UCDToken: sinkAddress("UCDToken"),
44156
44215
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
44157
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
44216
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
44158
44217
  SimplePSMV2: sinkAddress("SimplePSMV2"),
44159
44218
  UsdcToken: sinkAddress("UsdcToken"),
44160
44219
  UCDController: sinkAddress("UCDController")
@@ -44459,7 +44518,18 @@ var MockUpstreamPlugin = class {
44459
44518
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
44460
44519
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
44461
44520
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
44462
- getPsmStatus: () => this.read("mock-chain", () => {
44521
+ // The practice world models ONE stablecoin, and says so rather than implying a
44522
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
44523
+ // and naming anything but this one is refused the same way the real adapter refuses
44524
+ // an unsupported address — a mock that accepted any name would teach a habit the
44525
+ // real protocol punishes.
44526
+ listPsmStablecoins: () => this.read(
44527
+ "mock-chain",
44528
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
44529
+ ),
44530
+ getPsmStatus: (p) => this.read("mock-chain", () => {
44531
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44532
+ if (known) return known;
44463
44533
  const psm = this.world.psmSeed();
44464
44534
  return upOk(
44465
44535
  {
@@ -44484,6 +44554,8 @@ var MockUpstreamPlugin = class {
44484
44554
  );
44485
44555
  }),
44486
44556
  getPsmQuote: (p) => this.read("mock-chain", () => {
44557
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44558
+ if (known) return known;
44487
44559
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
44488
44560
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
44489
44561
  })
@@ -44556,11 +44628,7 @@ var MockUpstreamPlugin = class {
44556
44628
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
44557
44629
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
44558
44630
  }),
44559
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
44560
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
44561
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44562
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
44563
- })
44631
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
44564
44632
  };
44565
44633
  }
44566
44634
  indexer;
@@ -44612,6 +44680,19 @@ var MockUpstreamPlugin = class {
44612
44680
  return apply();
44613
44681
  }
44614
44682
  /** Mode `none`: every write answers with the conversational setup invitation. */
44683
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
44684
+ * refused with the same shape the real adapter uses for an address the chain does not
44685
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
44686
+ * instead of silently succeeding and teaching that any name works. */
44687
+ mockStablecoinRefusal(stablecoin) {
44688
+ const chosen = stablecoin.trim().toLowerCase();
44689
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
44690
+ return upFail({
44691
+ kind: "rejected",
44692
+ source: "mock-chain",
44693
+ message: `'${stablecoin}' is not a PSM-supported stablecoin in this practice world \u2014 it supports 'USDC' only. Read protocol://psm for the coins a deployment actually supports; there is no default coin on any tier.`
44694
+ });
44695
+ }
44615
44696
  noneRefusal() {
44616
44697
  if (this.signer && this.signer.manager.mode() === "none") {
44617
44698
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -44835,6 +44916,46 @@ var MockUpstreamPlugin = class {
44835
44916
  );
44836
44917
  });
44837
44918
  }
44919
+ /**
44920
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
44921
+ *
44922
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
44923
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
44924
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
44925
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
44926
+ * passing requests the real protocol would refuse, which is the one thing a practice world
44927
+ * must never do.
44928
+ *
44929
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
44930
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
44931
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
44932
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
44933
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
44934
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
44935
+ */
44936
+ async opRetryWithdrawExecute(p) {
44937
+ const none = this.noneRefusal();
44938
+ if (none) return none;
44939
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
44940
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
44941
+ const cer = executable > 0 ? this.ceremonyNow() : null;
44942
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
44943
+ if (auth && !auth.ok) return auth.failure;
44944
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
44945
+ return this.write("retryWithdrawExecute", () => {
44946
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
44947
+ if (sig && !sig.ok) return sig.failure;
44948
+ const r = this.applyAuthorized(
44949
+ sig ? sig.authorization : void 0,
44950
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
44951
+ );
44952
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44953
+ return upOk(
44954
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
44955
+ this.src("mock-ops")
44956
+ );
44957
+ });
44958
+ }
44838
44959
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
44839
44960
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
44840
44961
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -79455,6 +79576,19 @@ function listPositionsQuery(f) {
79455
79576
  }
79456
79577
  return { document: LIST_POSITIONS, variables: { first, skip } };
79457
79578
  }
79579
+ var SUPPORTED_STABLECOINS = `
79580
+ query SupportedStablecoins {
79581
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79582
+ id
79583
+ address
79584
+ isSupported
79585
+ decimals
79586
+ entryFee
79587
+ exitFee
79588
+ reserves
79589
+ }
79590
+ }
79591
+ `;
79458
79592
 
79459
79593
  // src/boundary/upstream/real/psm-calls.ts
79460
79594
  var import_ethers32 = require("ethers");
@@ -79594,6 +79728,11 @@ var PsmCalls = class {
79594
79728
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79595
79729
  });
79596
79730
  }
79731
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
79732
+ * so it must come from the token rather than from a per-network assumption. */
79733
+ symbol() {
79734
+ return this.deps.stablecoinSymbol;
79735
+ }
79597
79736
  async status() {
79598
79737
  return this.call(async () => {
79599
79738
  const s = this.deps.stablecoinAddress;
@@ -80053,13 +80192,6 @@ function buildValidationContext(network, chainId) {
80053
80192
  }
80054
80193
 
80055
80194
  // src/boundary/upstream/real/write-ops.ts
80056
- function psmMainnetWriteRefusal(network, chainId) {
80057
- return {
80058
- kind: "rejected",
80059
- source: SOURCE5,
80060
- 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.`
80061
- };
80062
- }
80063
80195
  var SOURCE5 = "real-ops";
80064
80196
  var OP_LAYOUT = "dh-op-envelope-v1";
80065
80197
  function randomNonceHex() {
@@ -80407,8 +80539,7 @@ function buildWriteOps(deps) {
80407
80539
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80408
80540
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
80409
80541
  psmSwap: async (p) => {
80410
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
80411
- const pr = deps.psm();
80542
+ const pr = await deps.psm(p.stablecoin);
80412
80543
  if (!pr.ok) return upFail(pr.failure);
80413
80544
  const calls = pr.calls;
80414
80545
  const addr = calls.addresses();
@@ -80789,6 +80920,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80789
80920
  );
80790
80921
  }
80791
80922
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80923
+ const nowMs = (this.deps.clock ?? Date.now)();
80924
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80925
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
80792
80926
  const outcome = await this.deps.bridge.requestSignature({
80793
80927
  id: (0, import_node_crypto7.randomUUID)(),
80794
80928
  kind: "personal-sign",
@@ -80800,15 +80934,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80800
80934
  "(identical to how diamondhands.credit signs withdrawals).",
80801
80935
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80802
80936
  "",
80803
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80804
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80805
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80806
- "itself allows. If it expires the signature is refused, the withdrawal does not",
80807
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80808
- "start again rather than signing something you have not finished reading."
80937
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80938
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80939
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80940
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80941
+ "stay reserved until that is cleared. If the number above is already small, decline",
80942
+ "and start again rather than signing something you have not finished reading."
80809
80943
  ],
80810
80944
  expectedSigner: this.deps.borrower,
80811
80945
  chainId: this.deps.chainId,
80946
+ expiresAtSec,
80812
80947
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
80813
80948
  });
80814
80949
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -81012,13 +81147,27 @@ var RealUpstreamPlugin = class {
81012
81147
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
81013
81148
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81014
81149
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
81015
- getPsmStatus: () => {
81016
- const r = this.psmCalls();
81017
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
81150
+ listPsmStablecoins: async () => {
81151
+ const listed = await this.listSupportedStablecoins();
81152
+ if (!listed.ok) return listed;
81153
+ const rows = await Promise.all(
81154
+ listed.rows.map(async (row) => {
81155
+ const built = await this.psmCallsFor(row.address);
81156
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
81157
+ })
81158
+ );
81159
+ return upOk(
81160
+ rows.filter((r) => r !== null),
81161
+ this.src("subgraph")
81162
+ );
81163
+ },
81164
+ getPsmStatus: async (p) => {
81165
+ const r = await this.psmCallsFor(p.stablecoin);
81166
+ return r.ok ? r.calls.status() : upFail(r.failure);
81018
81167
  },
81019
- getPsmQuote: (p) => {
81020
- const r = this.psmCalls();
81021
- if (!r.ok) return Promise.resolve(upFail(r.failure));
81168
+ getPsmQuote: async (p) => {
81169
+ const r = await this.psmCallsFor(p.stablecoin);
81170
+ if (!r.ok) return upFail(r.failure);
81022
81171
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81023
81172
  }
81024
81173
  };
@@ -81086,12 +81235,13 @@ var RealUpstreamPlugin = class {
81086
81235
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
81087
81236
  delegationSetup: () => readOnly("delegationSetup"),
81088
81237
  delegationGrant: () => readOnly("delegationGrant"),
81089
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
81090
- // any non-sepolia network refuses typed — naming the network gate truthfully —
81091
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
81092
- // missing signer instead (the honest reason on that path).
81238
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
81239
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
81240
+ // signerless boot the honest refusal was always the missing signer; the network
81241
+ // gate sat in front of it and answered first. Now there is one reason left, and it
81242
+ // is the true one on this path.
81093
81243
  psmSwap: () => Promise.resolve(
81094
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
81244
+ upFail({
81095
81245
  kind: "signer-missing",
81096
81246
  source: "real-ops",
81097
81247
  message: "no signer configured \u2014 psmSwap signs two on-chain transactions (exact-amount approve, then swap/redeem) with the keystore signer. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
@@ -81208,7 +81358,7 @@ var RealUpstreamPlugin = class {
81208
81358
  session,
81209
81359
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81210
81360
  readDetails: (id) => this.readPositionDetails(id),
81211
- psm: () => this.psmCalls(),
81361
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81212
81362
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81213
81363
  });
81214
81364
  }
@@ -81342,7 +81492,7 @@ var RealUpstreamPlugin = class {
81342
81492
  session,
81343
81493
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81344
81494
  readDetails: (id) => this.readPositionDetails(id),
81345
- psm: () => this.psmCalls(),
81495
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81346
81496
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81347
81497
  });
81348
81498
  this.opsGatewayCache.set(key, gateway);
@@ -81488,35 +81638,91 @@ var RealUpstreamPlugin = class {
81488
81638
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
81489
81639
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
81490
81640
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
81491
- psmWrapper = null;
81492
- psmCalls() {
81493
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
81641
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
81642
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
81643
+ psmWrappers = /* @__PURE__ */ new Map();
81644
+ /**
81645
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
81646
+ *
81647
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
81648
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
81649
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
81650
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
81651
+ * `getPSMStablecoins` reads the index for the same reason.
81652
+ */
81653
+ async listSupportedStablecoins() {
81654
+ const r = await this.graphProxy(
81655
+ SUPPORTED_STABLECOINS,
81656
+ {}
81657
+ );
81658
+ if (!r.ok) return r;
81659
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
81660
+ address: String(x.address).toLowerCase(),
81661
+ decimals: Number(x.decimals)
81662
+ }));
81663
+ return { ok: true, rows };
81664
+ }
81665
+ /**
81666
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
81667
+ *
81668
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
81669
+ * indexer is how the list is discovered and is not authority over it: it can lag a
81670
+ * governance removal, and acting on a stale list would build a swap the contract reverts
81671
+ * — after the user has approved it in their wallet. List from the index, verify on the
81672
+ * chain, then sign.
81673
+ */
81674
+ async psmCallsFor(stablecoinAddress) {
81675
+ const key = stablecoinAddress.toLowerCase();
81676
+ const cached = this.psmWrappers.get(key);
81677
+ if (cached) return { ok: true, calls: cached };
81494
81678
  const psmAddress = this.contracts["SimplePSMV2"];
81495
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
81496
- if (!psmAddress || !stablecoinAddress) {
81497
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
81679
+ if (!psmAddress) {
81498
81680
  return {
81499
81681
  ok: false,
81500
81682
  failure: {
81501
81683
  kind: "unavailable",
81502
81684
  source: "chain-rpc",
81503
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
81685
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
81504
81686
  }
81505
81687
  };
81506
81688
  }
81689
+ let supported;
81690
+ let symbol;
81691
+ try {
81692
+ const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81693
+ supported = await psm["supportedStablecoins"](key);
81694
+ const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81695
+ symbol = await erc20["symbol"]();
81696
+ } catch (e) {
81697
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
81698
+ }
81699
+ if (!supported) {
81700
+ return {
81701
+ ok: false,
81702
+ failure: {
81703
+ kind: "rejected",
81704
+ source: "chain-rpc",
81705
+ message: `${key} is not a PSM-supported stablecoin on ${this.config.network} (checked on-chain against SimplePSMV2.supportedStablecoins). Read protocol://psm for the coins this deployment actually supports.`
81706
+ }
81707
+ };
81708
+ }
81709
+ const stablecoinAddress2 = key;
81507
81710
  const ucdTokenAddress = this.contracts["UCDToken"];
81508
81711
  const ucdControllerAddress = this.contracts["UCDController"];
81509
- this.psmWrapper = new PsmCalls({
81712
+ const built = new PsmCalls({
81510
81713
  provider: this.provider,
81511
81714
  psmAddress,
81512
- stablecoinAddress,
81513
- stablecoinSymbol: "USDC",
81715
+ stablecoinAddress: stablecoinAddress2,
81716
+ // Read from the token, never assumed. The old value was the literal "USDC", which
81717
+ // stops being true the moment a second coin is supported.
81718
+ stablecoinSymbol: symbol,
81514
81719
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
81515
81720
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
81516
81721
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
81517
81722
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
81518
81723
  });
81519
- return { ok: true, calls: this.psmWrapper };
81724
+ this.psmWrappers.set(key, built);
81725
+ return { ok: true, calls: built };
81520
81726
  }
81521
81727
  src(id) {
81522
81728
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -81779,6 +81985,7 @@ function renderApprovalPage(sessionId, nonce) {
81779
81985
  <div id="request" class="hidden">
81780
81986
  <div id="action" class="action"></div>
81781
81987
  <div id="card" class="card"></div>
81988
+ <div id="deadline" class="status hidden"></div>
81782
81989
  <button id="approve">Approve in wallet</button>
81783
81990
  <button id="reject">Reject</button>
81784
81991
  </div>
@@ -81811,10 +82018,19 @@ const statusEl = document.getElementById("status");
81811
82018
  const requestEl = document.getElementById("request");
81812
82019
  const actionEl = document.getElementById("action");
81813
82020
  const cardEl = document.getElementById("card");
82021
+ const approveEl = document.getElementById("approve");
82022
+ const rejectEl = document.getElementById("reject");
82023
+ const deadlineEl = document.getElementById("deadline");
82024
+ let deadlineTimer = null;
81814
82025
  const walletEl = document.getElementById("wallet");
81815
82026
  let account = null;
81816
82027
  let chainId = null;
81817
82028
  let current = null;
82029
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
82030
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
82031
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
82032
+ // card the page never renders is one the human can neither read nor reject.
82033
+ const pending = new Map();
81818
82034
 
81819
82035
  function post(path, body) {
81820
82036
  return fetch(path, {
@@ -81877,43 +82093,135 @@ async function onAccountsChanged(accounts) {
81877
82093
  account = (accounts && accounts[0]) || null;
81878
82094
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81879
82095
  showWallet();
81880
- clearRequest("Wallet changed \u2014 pending request invalidated.");
82096
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81881
82097
  }
81882
82098
 
81883
82099
  async function onChainChanged(cid) {
81884
82100
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81885
82101
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81886
82102
  showWallet();
81887
- clearRequest("Network changed \u2014 pending request invalidated.");
82103
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81888
82104
  }
81889
82105
 
81890
82106
  function listen() {
81891
82107
  const es = new EventSource(BASE + "events?s=" + SESSION);
81892
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
82108
+ es.onmessage = (ev) => {
82109
+ const next = JSON.parse(ev.data);
82110
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
82111
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
82112
+ pending.set(next.id, next);
82113
+ showPending();
82114
+ };
81893
82115
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81894
82116
  }
81895
82117
 
82118
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
82119
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
82120
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
82121
+ // gets approved.
82122
+ function pickPending() {
82123
+ const held = current ? pending.get(current.id) : undefined;
82124
+ if (held && held.mirror !== true) return held;
82125
+ let best = held || null;
82126
+ pending.forEach((frame) => {
82127
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
82128
+ });
82129
+ return best;
82130
+ }
82131
+
82132
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
82133
+ function showPending(emptyText) {
82134
+ const next = pickPending();
82135
+ if (!next) {
82136
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
82137
+ // an expiry for a ceremony that is already decided.
82138
+ stopDeadline();
82139
+ current = null;
82140
+ requestEl.classList.add("hidden");
82141
+ if (emptyText) showStatus(emptyText);
82142
+ return;
82143
+ }
82144
+ current = next;
82145
+ renderRequest();
82146
+ }
82147
+
81896
82148
  function renderRequest() {
81897
82149
  actionEl.textContent = current.action;
81898
82150
  cardEl.textContent = current.card.join("\\n");
82151
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
82152
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
82153
+ // server-side, which is the actual boundary.
82154
+ const mirrored = current.mirror === true;
82155
+ approveEl.classList.toggle("hidden", mirrored);
82156
+ rejectEl.classList.remove("hidden");
81899
82157
  requestEl.classList.remove("hidden");
81900
- showStatus("Review the operation below. Nothing signs without your approval.");
82158
+ showStatus(mirrored
82159
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
82160
+ : "Review the operation below. Nothing signs without your approval.");
82161
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
82162
+ // card promoted after another settles gets its own clock, not the previous one's.
82163
+ startDeadline();
82164
+ }
82165
+
82166
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
82167
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
82168
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
82169
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
82170
+ // honest without it needing to know anything about quantum windows.
82171
+ function stopDeadline() {
82172
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82173
+ deadlineEl.classList.add("hidden");
82174
+ }
82175
+
82176
+ function startDeadline() {
82177
+ stopDeadline();
82178
+ if (!current || typeof current.expiresAtSec !== "number") return;
82179
+ const tick = () => {
82180
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
82181
+ if (left > 0) {
82182
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
82183
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
82184
+ } else {
82185
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
82186
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
82187
+ // after. The button is deliberately left enabled \u2014 declining is still the right
82188
+ // action and the page must not trap them.
82189
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
82190
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82191
+ }
82192
+ deadlineEl.classList.remove("hidden");
82193
+ };
82194
+ tick();
82195
+ deadlineTimer = setInterval(tick, 1000);
81901
82196
  }
81902
82197
 
82198
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
82199
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
82200
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81903
82201
  function clearRequest(text) {
81904
- current = null;
81905
- requestEl.classList.add("hidden");
81906
- showStatus(text);
82202
+ if (current) pending.delete(current.id);
82203
+ showPending(text);
81907
82204
  }
81908
82205
 
81909
- document.getElementById("reject").onclick = async () => {
82206
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
82207
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
82208
+ // stays readable and rejectable.
82209
+ function invalidatePageRequests(text) {
82210
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
82211
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
82212
+ }
82213
+
82214
+ rejectEl.onclick = async () => {
81910
82215
  if (!current) return;
81911
82216
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81912
82217
  clearRequest("Rejected. Waiting for the next request\u2026");
81913
82218
  };
81914
82219
 
81915
- document.getElementById("approve").onclick = async () => {
82220
+ approveEl.onclick = async () => {
81916
82221
  if (!current) return;
82222
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
82223
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
82224
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81917
82225
  const req = current;
81918
82226
  try {
81919
82227
  if (req.kind === "transaction") {
@@ -81930,7 +82238,10 @@ document.getElementById("approve").onclick = async () => {
81930
82238
  const fbody = await fr.json();
81931
82239
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
81932
82240
  const fresh = fbody.request;
81933
- // \u2026re-render what will actually sign\u2026
82241
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
82242
+ // another card arriving while the wallet popup is open re-picks from there, and the
82243
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
82244
+ pending.set(fresh.id, fresh);
81934
82245
  current = fresh; renderRequest();
81935
82246
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
81936
82247
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -82085,9 +82396,6 @@ var SignatureBridge = class {
82085
82396
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
82086
82397
  maxPending;
82087
82398
  attachGraceMs;
82088
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
82089
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
82090
- lastAttachedMs = 0;
82091
82399
  server = null;
82092
82400
  port = 0;
82093
82401
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -82198,7 +82506,7 @@ var SignatureBridge = class {
82198
82506
  connectedAccounts() {
82199
82507
  const seen = /* @__PURE__ */ new Map();
82200
82508
  for (const s of this.sessions.values()) {
82201
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82509
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
82202
82510
  }
82203
82511
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
82204
82512
  return [...seen.values()];
@@ -82238,13 +82546,16 @@ var SignatureBridge = class {
82238
82546
  enqueuedMs: now,
82239
82547
  resolve,
82240
82548
  settled: false,
82241
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
82549
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
82550
+ owner: this.wcActive ? "wc" : "page",
82551
+ dispatched: false,
82552
+ lastAttachedMs: now
82242
82553
  };
82243
82554
  this.pending.set(request.id, entry);
82244
- if (this.wcActive) {
82555
+ if (entry.owner === "wc") {
82245
82556
  void this.driveWc(entry);
82246
82557
  } else {
82247
- this.push(request);
82558
+ this.pushEntry(entry);
82248
82559
  }
82249
82560
  });
82250
82561
  }
@@ -82265,10 +82576,16 @@ var SignatureBridge = class {
82265
82576
  enqueuedMs: now,
82266
82577
  resolve,
82267
82578
  settled: false,
82268
- collect
82579
+ collect,
82580
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
82581
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
82582
+ // ceremony could not reach quorum through the very pages it is broadcast to.
82583
+ owner: "both",
82584
+ dispatched: false,
82585
+ lastAttachedMs: now
82269
82586
  };
82270
82587
  this.pending.set(request.id, entry);
82271
- this.push(request);
82588
+ this.pushEntry(entry);
82272
82589
  if (this.wcActive) void this.driveWcCollection(entry);
82273
82590
  });
82274
82591
  }
@@ -82307,7 +82624,9 @@ var SignatureBridge = class {
82307
82624
  }
82308
82625
  try {
82309
82626
  if (req.kind === "transaction") {
82627
+ this.pushEntry(entry);
82310
82628
  const tx2 = req.tx;
82629
+ entry.dispatched = true;
82311
82630
  const txHash = await transport.request("eth_sendTransaction", [
82312
82631
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
82313
82632
  ]);
@@ -82319,11 +82638,22 @@ var SignatureBridge = class {
82319
82638
  req.card = fresh.card;
82320
82639
  }
82321
82640
  const ps = req.personalSign;
82641
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
82642
+ this.settle(entry, {
82643
+ status: "invalidated",
82644
+ reason: `this step signs a 32-byte hash your wallet cannot decode, and no approval page is open to show you what it authorizes \u2014 open ${this.url()} and re-run the withdrawal with loan_withdraw_retry (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`
82645
+ });
82646
+ return;
82647
+ }
82648
+ this.pushEntry(entry);
82649
+ entry.dispatched = true;
82322
82650
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
82323
82651
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82324
82652
  } else {
82653
+ this.pushEntry(entry);
82325
82654
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
82326
82655
  const payload = withEip712DomainType2(req.typedData);
82656
+ entry.dispatched = true;
82327
82657
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
82328
82658
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82329
82659
  }
@@ -82343,29 +82673,54 @@ var SignatureBridge = class {
82343
82673
  * with a live attachment is in use and must never be evicted. */
82344
82674
  attachedNow() {
82345
82675
  if (this.wcActive) return true;
82346
- for (const s of this.sessions.values()) if (s.sse) return true;
82676
+ return this.pageAttached();
82677
+ }
82678
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
82679
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
82680
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
82681
+ * WalletConnect and must stay global for the connector's eviction predicate. */
82682
+ pageAttached() {
82683
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
82347
82684
  return false;
82348
82685
  }
82686
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
82687
+ * predicate said "a WC session is attached", which is true but irrelevant to a
82688
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
82689
+ * out the full expiry instead of failing fast at the grace. */
82690
+ attachedFor(entry) {
82691
+ if (entry.owner === "wc") return this.wcActive;
82692
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
82693
+ return this.pageAttached();
82694
+ }
82349
82695
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
82350
82696
  * interval; tests call it directly with the injected clock advanced. Order matters:
82351
82697
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
82352
82698
  sweep() {
82353
82699
  const now = this.clock();
82354
- const attached = this.attachedNow();
82355
- if (attached) this.lastAttachedMs = now;
82356
82700
  for (const entry of this.pending.values()) {
82357
82701
  if (entry.settled) continue;
82358
82702
  if (now >= entry.deadlineMs) {
82359
82703
  this.settle(entry, { status: "expired" });
82360
82704
  continue;
82361
82705
  }
82362
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
82363
- this.settle(entry, {
82364
- status: "invalidated",
82365
- 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`
82366
- });
82706
+ if (this.attachedFor(entry)) {
82707
+ entry.lastAttachedMs = now;
82708
+ continue;
82367
82709
  }
82710
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
82711
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
82712
+ }
82713
+ }
82714
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
82715
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
82716
+ unattendedReason(entry) {
82717
+ if (entry.dispatched && entry.request.kind === "transaction") {
82718
+ return "the mobile wallet holding this transaction went away before answering, but it was already asked to send it \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice.";
82719
+ }
82720
+ if (entry.owner === "wc") {
82721
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
82368
82722
  }
82723
+ return `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`;
82369
82724
  }
82370
82725
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
82371
82726
  walletConnectActive() {
@@ -82459,7 +82814,7 @@ var SignatureBridge = class {
82459
82814
  return;
82460
82815
  }
82461
82816
  const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
82462
- this.sessions.set(sessionId, { wallet: null, sse: null });
82817
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
82463
82818
  const page = htmlPageSecurityHeaders();
82464
82819
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
82465
82820
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -82489,7 +82844,8 @@ var SignatureBridge = class {
82489
82844
  const refusal = info ? this.accountRefusal(info.account) : null;
82490
82845
  if (info && refusal) {
82491
82846
  this.wcActive = false;
82492
- this.wallet = null;
82847
+ this.rebuildSharedWallet();
82848
+ this.demoteWcEntries();
82493
82849
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82494
82850
  `);
82495
82851
  return;
@@ -82499,7 +82855,10 @@ var SignatureBridge = class {
82499
82855
  if (info === null) {
82500
82856
  for (const entry of this.pending.values()) {
82501
82857
  if (!entry.settled && !entry.collect) {
82502
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82858
+ this.settle(entry, {
82859
+ status: "invalidated",
82860
+ reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
82861
+ });
82503
82862
  }
82504
82863
  }
82505
82864
  }
@@ -82571,9 +82930,7 @@ var SignatureBridge = class {
82571
82930
  session.sse?.end();
82572
82931
  session.sse = res;
82573
82932
  for (const entry of this.pending.values()) {
82574
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
82575
-
82576
- `);
82933
+ if (!entry.settled) res.write(this.wireFor(entry));
82577
82934
  }
82578
82935
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
82579
82936
  keepAlive.unref();
@@ -82593,6 +82950,7 @@ var SignatureBridge = class {
82593
82950
  }
82594
82951
  const refusal = this.accountRefusal(account);
82595
82952
  if (refusal) {
82953
+ this.quarantine(session, refusal);
82596
82954
  this.deny(res, 403, refusal);
82597
82955
  return;
82598
82956
  }
@@ -82631,10 +82989,15 @@ var SignatureBridge = class {
82631
82989
  const chainId = Number(body["chainId"]);
82632
82990
  const prev = session.wallet;
82633
82991
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
82634
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
82635
- session.wallet = refusedSwitch ? null : offered;
82636
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82637
- this.wallet = session.wallet;
82992
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
82993
+ const refusedSwitch = switchRefusal !== null;
82994
+ if (refusedSwitch) {
82995
+ this.quarantine(session, switchRefusal);
82996
+ } else {
82997
+ session.wallet = offered;
82998
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82999
+ this.wallet = session.wallet;
83000
+ }
82638
83001
  }
82639
83002
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
82640
83003
  if (unchanged) {
@@ -82643,10 +83006,36 @@ var SignatureBridge = class {
82643
83006
  }
82644
83007
  const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
82645
83008
  for (const entry of this.pending.values()) {
82646
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
83009
+ if (entry.settled || entry.collect) continue;
83010
+ if (this.ownedByWc(entry)) continue;
83011
+ this.settle(entry, { status: "invalidated", reason });
82647
83012
  }
82648
83013
  this.ok(res);
82649
83014
  }
83015
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
83016
+ * session hands the request back to the page rather than stranding it. */
83017
+ ownedByWc(entry) {
83018
+ if (entry.owner !== "wc") return false;
83019
+ return this.wcActive || entry.dispatched;
83020
+ }
83021
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
83022
+ * them so the card stops rendering read-only. Collections are already `both`.
83023
+ *
83024
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
83025
+ * phone is still holding does not replace one wallet with another, it adds a second: the
83026
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
83027
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
83028
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
83029
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
83030
+ * false for them, and `unattendedReason` says plainly that the phone may already have
83031
+ * acted. */
83032
+ demoteWcEntries() {
83033
+ for (const entry of this.pending.values()) {
83034
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
83035
+ entry.owner = "page";
83036
+ this.pushEntry(entry);
83037
+ }
83038
+ }
82650
83039
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
82651
83040
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
82652
83041
  async onFinalize(body, res) {
@@ -82660,6 +83049,10 @@ var SignatureBridge = class {
82660
83049
  this.deny(res, 400, "finalize applies only to personal-sign requests");
82661
83050
  return;
82662
83051
  }
83052
+ if (this.ownedByWc(entry)) {
83053
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
83054
+ return;
83055
+ }
82663
83056
  if (entry.finalize) {
82664
83057
  let fresh;
82665
83058
  try {
@@ -82686,10 +83079,22 @@ var SignatureBridge = class {
82686
83079
  return;
82687
83080
  }
82688
83081
  if (body["approved"] !== true) {
83082
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
83083
+ this.settle(entry, {
83084
+ status: "invalidated",
83085
+ reason: "cancelled on the approval page, but a mobile wallet was already asked to send this transaction \u2014 it may have broadcast already. Check the chain (or your wallet's activity) before retrying, or you may pay twice."
83086
+ });
83087
+ this.ok(res);
83088
+ return;
83089
+ }
82689
83090
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
82690
83091
  this.ok(res);
82691
83092
  return;
82692
83093
  }
83094
+ if (this.ownedByWc(entry)) {
83095
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
83096
+ return;
83097
+ }
82693
83098
  const account = String(body["account"] ?? "");
82694
83099
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
82695
83100
  this.deny(res, 400, "approved result requires the signing account");
@@ -82726,12 +83131,21 @@ var SignatureBridge = class {
82726
83131
  this.pending.delete(entry.request.id);
82727
83132
  entry.resolve(outcome);
82728
83133
  }
82729
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
82730
- push(request) {
82731
- const data = `data: ${JSON.stringify(request)}
83134
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
83135
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
83136
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
83137
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
83138
+ * a permanently read-only card that nobody is allowed to decide. */
83139
+ wireFor(entry) {
83140
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
83141
+ return `data: ${JSON.stringify(payload)}
82732
83142
 
82733
83143
  `;
82734
- for (const s of this.sessions.values()) s.sse?.write(data);
83144
+ }
83145
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
83146
+ pushEntry(entry) {
83147
+ const data = this.wireFor(entry);
83148
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82735
83149
  }
82736
83150
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
82737
83151
  pushProgress(payload) {
@@ -82739,7 +83153,48 @@ var SignatureBridge = class {
82739
83153
  data: ${JSON.stringify(payload)}
82740
83154
 
82741
83155
  `;
82742
- for (const s of this.sessions.values()) s.sse?.write(data);
83156
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
83157
+ }
83158
+ /**
83159
+ * C-47: `this.wallet` is DERIVED, never guessed.
83160
+ *
83161
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
83162
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
83163
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
83164
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
83165
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
83166
+ * wrong account into a disconnect for the legitimate user.
83167
+ *
83168
+ * Deriving it from live state removes the guess. Preference order matches
83169
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
83170
+ */
83171
+ rebuildSharedWallet() {
83172
+ if (this.wcActive && this.wcTransport) {
83173
+ const wc = this.wcTransport.active();
83174
+ if (wc && !this.accountRefusal(wc.account)) {
83175
+ this.wallet = { account: wc.account, chainId: wc.chainId };
83176
+ return;
83177
+ }
83178
+ }
83179
+ let latest = null;
83180
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
83181
+ this.wallet = latest;
83182
+ }
83183
+ /**
83184
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
83185
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
83186
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
83187
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
83188
+ * stream, and re-derive the shared view without it.
83189
+ */
83190
+ quarantine(session, reason) {
83191
+ session.refused = reason;
83192
+ session.wallet = null;
83193
+ if (session.sse) {
83194
+ session.sse.end();
83195
+ session.sse = null;
83196
+ }
83197
+ this.rebuildSharedWallet();
82743
83198
  }
82744
83199
  sessionOf(candidate, res) {
82745
83200
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -82747,6 +83202,10 @@ data: ${JSON.stringify(payload)}
82747
83202
  this.deny(res, 403, "missing or wrong session");
82748
83203
  return null;
82749
83204
  }
83205
+ if (session.refused) {
83206
+ this.deny(res, 403, session.refused);
83207
+ return null;
83208
+ }
82750
83209
  return session;
82751
83210
  }
82752
83211
  checkSession(candidate, res) {
@@ -83168,7 +83627,7 @@ var FIELD_GLOSSARY = {
83168
83627
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83169
83628
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83170
83629
  // ---- psm quote ----
83171
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83630
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
83172
83631
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83173
83632
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83174
83633
  amountInToken: "the token you pay with",
@@ -83266,11 +83725,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83266
83725
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83267
83726
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83268
83727
  signerModes: GUIDE_SIGNER_MODES,
83269
- // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
83270
- // leg genuinely is not there until an operator configures it. The first draft of this line
83271
- // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
83272
- // about — the default rendering would have promised a QR that most installs cannot show.
83273
- // A live boot derives this from env either way (network-switch.ts).
83728
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
83729
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
83730
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
83731
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
83732
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
83733
+ // nobody supplied a deployment at all, and understating a capability there is the safe
83734
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
83735
+ // overclaim C-44 is about — promising a QR the build cannot show.
83274
83736
  walletConnect: false
83275
83737
  };
83276
83738
  function servedNetworks(d) {
@@ -83281,7 +83743,7 @@ function servedNetworks(d) {
83281
83743
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
83282
83744
  }
83283
83745
  if (mainnet) {
83284
- return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
83746
+ return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing; PSM swaps are NOT an exception \u2014 they execute here and move real funds), and there is no practice network on this deployment to fall back to";
83285
83747
  }
83286
83748
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
83287
83749
  }
@@ -83360,13 +83822,14 @@ function switchNetworkRules(d) {
83360
83822
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83361
83823
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83362
83824
  A sepolia position does not exist on mainnet and vice versa.
83363
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83364
- and every one still requires the user's explicit confirmation plus the signer
83365
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83825
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83826
+ mainnet they move REAL money, and every one still requires the user's explicit
83827
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83828
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83829
+ signed.`;
83366
83830
  }
83367
83831
  const only = d.networks[0];
83368
83832
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83369
- 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.";
83370
83833
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83371
83834
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
83372
83835
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -83375,7 +83838,9 @@ function switchNetworkRules(d) {
83375
83838
  belong to ${only} and would not exist anywhere else.
83376
83839
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83377
83840
  confirmation plus the signer ceremony.
83378
- - ${psm}`;
83841
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83842
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83843
+ anything is signed.`;
83379
83844
  }
83380
83845
  function wrongNetworkTroubleshootingRow(d) {
83381
83846
  if (d.networks.length > 1) {
@@ -83395,14 +83860,18 @@ function switchNetworkIndexLine(d) {
83395
83860
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83396
83861
  return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
83397
83862
  }
83398
- function psmAvailabilityNote(d) {
83399
- if (d.networks.includes("sepolia")) return "";
83400
- return `**Not executable on this deployment.** The PSM write port refuses on every network
83401
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
83402
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
83403
- the mechanism, not an offer: say so before a user plans around it.
83404
-
83405
- `;
83863
+ function psmStablecoinRealityNote(d) {
83864
+ if (d.networks.includes("sepolia")) {
83865
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83866
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83867
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83868
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83869
+ }
83870
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83871
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83872
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83873
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83874
+ have to guess whether the money is real.`;
83406
83875
  }
83407
83876
  function authorizationModeBullets(d) {
83408
83877
  const bullets = [];
@@ -83516,7 +83985,7 @@ on the real adapter and the mock.
83516
83985
  **The walkthrough:**
83517
83986
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83518
83987
  desktop browser; ${approvalPageLocation(d)}
83519
- 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code." : ". " + phoneWalletOffer(d) + "."}
83988
+ 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
83520
83989
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83521
83990
  login ceremony explicitly (one typed-data signature in the wallet).
83522
83991
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83555,13 +84024,24 @@ on the real adapter and the mock.
83555
84024
  hash the SDK builds internally, which the approval page shows bare and says plainly it
83556
84025
  cannot decode (the production web app signs the same way). Tell the user before that
83557
84026
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83558
- expect an unreadable card and click through the readable one.
84027
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
84028
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
84029
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
84030
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
84031
+ on the card, and the page is the only surface that shows it. With no page attached the
84032
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
84033
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
84034
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
83559
84035
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83560
84036
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83561
84037
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
83562
84038
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
83563
84039
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
83564
- signature. The blind execute popup happens once.
84040
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
84041
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
84042
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
84043
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
84044
+ typed-data card. Promise the unreadable one only where it is real.
83565
84045
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
83566
84046
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
83567
84047
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -83604,6 +84084,14 @@ Connections / Connected sites).`,
83604
84084
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
83605
84085
  fresh stamp using the destination and amount the CHAIN already holds. Check
83606
84086
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
84087
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
84088
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
84089
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
84090
+ Say which one before they open the page, not after the popup surprises them.
84091
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
84092
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
84093
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
84094
+ the original withdrawal authorized.
83607
84095
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
83608
84096
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
83609
84097
 
@@ -83624,9 +84112,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83624
84112
 
83625
84113
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83626
84114
  signed, amounts included. Read it back when the user asks what happened.`,
83627
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
84115
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
83628
84116
 
83629
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
84117
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83630
84118
  directions, in user words:
83631
84119
 
83632
84120
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83634,20 +84122,27 @@ directions, in user words:
83634
84122
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83635
84123
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83636
84124
  and you receive 99 UCD.
83637
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
83638
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
83639
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
83640
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
83641
- shortfall refuses with both figures (available vs required).
84125
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
84126
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
84127
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
84128
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
84129
+ reserves, and a shortfall refuses with both figures (available vs required).
84130
+
84131
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
84132
+ default and that is deliberate: the PSM can carry several coins, each with its own
84133
+ reserves, fees and limits, so picking one silently would move someone's money through a
84134
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
84135
+ there rather than guessing one.
83642
84136
 
83643
84137
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83644
84138
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83645
84139
  1e18 = 1:1) and can be changed by protocol governance.
83646
84140
 
83647
84141
  **Limits and switches** (all visible in \`protocol://psm\`):
83648
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
83649
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
83650
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
84142
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
84143
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
84144
+ direction is DISABLED.
84145
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
83651
84146
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83652
84147
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
83653
84148
 
@@ -83656,23 +84151,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
83656
84151
  change between your quote and execution; the floor makes a drifted execution REFUSE
83657
84152
  rather than silently deliver less than quoted.
83658
84153
 
83659
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83660
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83661
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83662
- the money is real. On mainnet the stablecoin is real Circle USDC.
84154
+ ${psmStablecoinRealityNote(d)}
83663
84155
 
83664
84156
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83665
84157
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83666
84158
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83667
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
83668
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
83669
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84159
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84160
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
84161
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83670
84162
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83671
84163
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83672
84164
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83673
84165
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83674
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83675
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
84166
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84167
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84168
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
84169
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
84170
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
84171
+ per-operation and per-block limits,
84172
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
84173
+ mainnet swap, not after.`,
83676
84174
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83677
84175
 
83678
84176
  Every fund-moving operation needs TWO things, always in this order:
@@ -83931,9 +84429,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
83931
84429
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83932
84430
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83933
84431
  the same way \u2014 reconnect on the user's word.`}
83934
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83935
- 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
83936
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
84432
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
84433
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
84434
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
84435
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
84436
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
83937
84437
  ${wrongNetworkTroubleshootingRow(d)}
83938
84438
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
83939
84439
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -84091,12 +84591,13 @@ function guideDeployment(overrides, env) {
84091
84591
  tier: overrides?.bridgeMount ? "hosted" : "local",
84092
84592
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
84093
84593
  signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
84094
- // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
84095
- // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
84096
- // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
84097
- // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
84098
- // about the same server, which is exactly what they did before this line existed.
84099
- walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
84594
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
84595
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
84596
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
84597
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
84598
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
84599
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
84600
+ walletConnect: wcEnabled(env)
84100
84601
  };
84101
84602
  }
84102
84603
  function assembleWorld(opts) {
@@ -84736,39 +85237,45 @@ function registerPsmTools(server, getB) {
84736
85237
  server,
84737
85238
  "psm_quote",
84738
85239
  {
84739
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84740
- description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
85240
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
85241
+ description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay the stablecoin, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'from-ucd' = pay UCD, receive the stablecoin back from the PSM's reserves; the EXIT fee is charged IN that stablecoin and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). The result names both amounts, the fee WITH its token, and (from-ucd) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
84741
85242
  inputSchema: {
84742
- 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)"),
84743
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
85243
+ stablecoin: import_zod4.z.string().min(1).describe(
85244
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
85245
+ ),
85246
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
85247
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals.")
84744
85248
  },
84745
85249
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84746
85250
  },
84747
- async ({ direction, amount }) => guarded(async () => {
84748
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
85251
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
85252
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
84749
85253
  const problem = checkUcdAmount(amount, label);
84750
85254
  if (problem) return validationFailed(problem);
84751
85255
  const b = getB();
84752
85256
  if (!b.ok) return renderError(b.error);
84753
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
85257
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
84754
85258
  })
84755
85259
  );
84756
85260
  registerBoundaryTool(
84757
85261
  server,
84758
85262
  "psm_swap",
84759
85263
  {
84760
- title: "Exchange UCD \u2194 USDC through the PSM",
84761
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
85264
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
85265
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
84762
85266
  inputSchema: {
84763
- 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)"),
84764
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
85267
+ stablecoin: import_zod4.z.string().min(1).describe(
85268
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
85269
+ ),
85270
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
85271
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals."),
84765
85272
  confirmed: confirmedSchema2
84766
85273
  },
84767
85274
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84768
85275
  },
84769
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84770
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84771
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
85276
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
85277
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
85278
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84772
85279
  const gate = requireConfirmation(
84773
85280
  confirmed,
84774
85281
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84778,7 +85285,7 @@ function registerPsmTools(server, getB) {
84778
85285
  if (problem) return validationFailed(problem);
84779
85286
  const b = getB();
84780
85287
  if (!b.ok) return renderError(b.error);
84781
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
85288
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84782
85289
  })
84783
85290
  );
84784
85291
  }
@@ -85224,7 +85731,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85224
85731
  "network_switch",
85225
85732
  {
85226
85733
  title: "Show or switch the active network",
85227
- description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks (on mainnet they move REAL money; PSM swaps stay sepolia-only). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
85734
+ description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks \u2014 loan operations and PSM swaps alike (on mainnet they move REAL money). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
85228
85735
  inputSchema: {
85229
85736
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
85230
85737
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -85242,7 +85749,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85242
85749
  lines.push(
85243
85750
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
85244
85751
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
85245
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
85752
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
85246
85753
  "Session-scoped: the configured default network returns when the server restarts."
85247
85754
  );
85248
85755
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -85348,13 +85855,26 @@ function registerProtocolResources(server, getB) {
85348
85855
  "protocol://psm",
85349
85856
  {
85350
85857
  title: "PSM status (UCD \u2194 USDC exchange)",
85351
- description: "Live SimplePSMV2 state as {data, warnings, source}: network + chainId + addresses (the money surface names its chain), stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in USDC smallest units, to-usdc caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0).",
85858
+ description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
85352
85859
  mimeType: "application/json"
85353
85860
  },
85354
85861
  async (uri) => {
85355
85862
  const b = getB();
85356
85863
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
85357
- const env = await b.boundary.getPsmStatus();
85864
+ const listed = await b.boundary.listPsmStablecoins();
85865
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85866
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85867
+ const failed = perCoin.find((s) => !s.ok);
85868
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85869
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85870
+ const head = coins[0];
85871
+ const env = {
85872
+ ...listed,
85873
+ data: {
85874
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85875
+ stablecoins: coins
85876
+ }
85877
+ };
85358
85878
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
85359
85879
  }
85360
85880
  );
@@ -85567,12 +86087,15 @@ function composeConnector(opts, rawPublicOrigin) {
85567
86087
  for (const session of sessions.values()) held.add(session.tenant);
85568
86088
  return held;
85569
86089
  }
85570
- function isReclaimable(tenantKey, world, held) {
85571
- if (held.has(tenantKey)) return false;
86090
+ function isEvictable(world) {
85572
86091
  const bridge = world.deps.signer?.bridge;
85573
86092
  if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85574
86093
  return true;
85575
86094
  }
86095
+ function isReclaimable(tenantKey, world, held) {
86096
+ if (held.has(tenantKey)) return false;
86097
+ return isEvictable(world);
86098
+ }
85576
86099
  function sweepService() {
85577
86100
  const now = clock();
85578
86101
  for (const [sid, session] of [...sessions]) {
@@ -85588,13 +86111,12 @@ function composeConnector(opts, rawPublicOrigin) {
85588
86111
  dropWorld(tenantKey, world, "idle eviction");
85589
86112
  }
85590
86113
  }
85591
- function reclaimIdleWorld() {
85592
- const held = tenantsWithSessions();
86114
+ function leastRecentlyActive(eligible) {
85593
86115
  let victimKey = null;
85594
86116
  let victim = null;
85595
86117
  let oldest = Number.POSITIVE_INFINITY;
85596
86118
  for (const [tenantKey, world] of readyWorlds) {
85597
- if (!isReclaimable(tenantKey, world, held)) continue;
86119
+ if (!eligible(tenantKey, world)) continue;
85598
86120
  const activeAt = lastActivity.get(tenantKey) ?? 0;
85599
86121
  if (activeAt < oldest) {
85600
86122
  oldest = activeAt;
@@ -85602,8 +86124,23 @@ function composeConnector(opts, rawPublicOrigin) {
85602
86124
  victim = world;
85603
86125
  }
85604
86126
  }
85605
- if (victimKey === null || victim === null) return false;
85606
- dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
86127
+ return victimKey !== null && victim !== null ? [victimKey, victim] : null;
86128
+ }
86129
+ function reclaimIdleWorld() {
86130
+ const held = tenantsWithSessions();
86131
+ const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
86132
+ if (tier1) {
86133
+ dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
86134
+ return true;
86135
+ }
86136
+ const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
86137
+ if (!tier2) return false;
86138
+ for (const [sid, session] of [...sessions]) {
86139
+ if (session.tenant !== tier2[0]) continue;
86140
+ sessions.delete(sid);
86141
+ void session.transport.close().catch(() => void 0);
86142
+ }
86143
+ dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
85607
86144
  return true;
85608
86145
  }
85609
86146
  class TenantCapacityError extends Error {
@@ -85821,7 +86358,8 @@ function composeConnector(opts, rawPublicOrigin) {
85821
86358
  if (opts.auth) {
85822
86359
  authImpl = opts.auth;
85823
86360
  } else {
85824
- const wcLeg = opts.siweWc ?? (opts.env["DH_WC_PROJECT_ID"] ? { projectId: opts.env["DH_WC_PROJECT_ID"] } : void 0);
86361
+ const envWcProjectId = resolvedWcProjectId(opts.env);
86362
+ const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
85825
86363
  const siwe = new SiweOAuthProvider({
85826
86364
  origin: () => publicOrigin,
85827
86365
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,