@gvnrdao/dh-mcp 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15440,9 +15440,9 @@ ${errorReport}`);
15440
15440
  var MAX_BTC_AMOUNT = 25e6 * 1e8;
15441
15441
  var UTXO_QUERY_MAX_RETRIES = 3;
15442
15442
  var UTXO_QUERY_RETRY_DELAY_MS = 500;
15443
- var QUANTUM_WINDOW_SECONDS3 = 60;
15443
+ var QUANTUM_WINDOW_SECONDS4 = 60;
15444
15444
  var DEAD_ZONE_SECONDS2 = 16;
15445
- var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS3 - DEAD_ZONE_SECONDS2;
15445
+ var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
15446
15446
  var SECONDS_PER_DAY = 86400;
15447
15447
  var DAYS_PER_MONTH = 30;
15448
15448
  var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
@@ -40498,6 +40498,7 @@ var require_dist3 = __commonJS({
40498
40498
  // src/boundary/upstream/shared/external-bridge/wc-transport.ts
40499
40499
  var wc_transport_exports = {};
40500
40500
  __export(wc_transport_exports, {
40501
+ WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40501
40502
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
40502
40503
  WcTransport: () => WcTransport,
40503
40504
  newIsolatedCore: () => newIsolatedCore,
@@ -40533,7 +40534,7 @@ function newIsolatedCore(cfg, label) {
40533
40534
  });
40534
40535
  return { core, scratch };
40535
40536
  }
40536
- var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
40537
+ var import_core, import_sign_client, os, path3, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
40537
40538
  var init_wc_transport = __esm({
40538
40539
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
40539
40540
  "use strict";
@@ -40543,6 +40544,12 @@ var init_wc_transport = __esm({
40543
40544
  path3 = __toESM(require("path"));
40544
40545
  import_node_fs = require("fs");
40545
40546
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
40547
+ WC_DAPP_METADATA = {
40548
+ name: "Diamond Hands MCP",
40549
+ description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
40550
+ url: "https://app.diamondhands.credit",
40551
+ icons: []
40552
+ };
40546
40553
  EVENTS = ["accountsChanged", "chainChanged"];
40547
40554
  WcTransport = class _WcTransport {
40548
40555
  constructor(client, cfg, scratch) {
@@ -40561,12 +40568,7 @@ var init_wc_transport = __esm({
40561
40568
  const client = await import_sign_client.default.init({
40562
40569
  core,
40563
40570
  projectId: cfg.projectId,
40564
- metadata: {
40565
- name: "Diamond Hands MCP",
40566
- description: "Human approval for Diamond Hands operations",
40567
- url: "https://gvnr.xyz",
40568
- icons: []
40569
- }
40571
+ metadata: WC_DAPP_METADATA
40570
40572
  });
40571
40573
  return new _WcTransport(client, cfg, scratch);
40572
40574
  }
@@ -40628,6 +40630,27 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
40628
40630
  var ADAPTERS = ["mock", "real"];
40629
40631
  var LATENCIES = ["zero", "realistic"];
40630
40632
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
40633
+ var DEFAULT_WC_PROJECT_ID = "f93d3047a55f38275553a49b32ed5372";
40634
+ var WC_DISABLED = "off";
40635
+ function withLocalWcDefault(env) {
40636
+ const raw = env["DH_WC_PROJECT_ID"];
40637
+ if (raw !== void 0 && raw !== "") return env;
40638
+ return { ...env, DH_WC_PROJECT_ID: DEFAULT_WC_PROJECT_ID };
40639
+ }
40640
+ function wcEnabled(env) {
40641
+ return resolvedWcProjectId(env) !== void 0;
40642
+ }
40643
+ function resolvedWcProjectId(env) {
40644
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
40645
+ }
40646
+ function resolveWcProjectId(raw, problems) {
40647
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
40648
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
40649
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
40650
+ return void 0;
40651
+ }
40652
+ return raw;
40653
+ }
40631
40654
  var NETWORK_DEFAULTS = {
40632
40655
  sepolia: {
40633
40656
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -40702,10 +40725,7 @@ function resolveBoundaryConfig(env) {
40702
40725
  }
40703
40726
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
40704
40727
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
40705
- const wcProjectId = env["DH_WC_PROJECT_ID"];
40706
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
40707
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
40708
- }
40728
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
40709
40729
  let bridgeOpenBrowser;
40710
40730
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
40711
40731
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -40777,10 +40797,7 @@ function resolveRealConfig(env) {
40777
40797
  const stateDir = env["DH_STATE_DIR"];
40778
40798
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
40779
40799
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
40780
- const wcProjectId = env["DH_WC_PROJECT_ID"];
40781
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
40782
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
40783
- }
40800
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
40784
40801
  let bridgeOpenBrowser;
40785
40802
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
40786
40803
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41220,8 +41237,15 @@ var BoundaryCore = class {
41220
41237
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
41221
41238
  }
41222
41239
  // ---- PSM reads (plan 08 Part B Phase R) ----
41223
- async getPsmStatus() {
41224
- const r = await this.deps.plugin.chain.getPsmStatus();
41240
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
41241
+ * names the coin, and this is how they learn what they may name. */
41242
+ async listPsmStablecoins() {
41243
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
41244
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
41245
+ return okEnvelope(r.value, r.source);
41246
+ }
41247
+ async getPsmStatus(p) {
41248
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
41225
41249
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41226
41250
  return okEnvelope(this.psmStatusData(r.value), r.source);
41227
41251
  }
@@ -41232,7 +41256,7 @@ var BoundaryCore = class {
41232
41256
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
41233
41257
  * whenever `env.ok`. */
41234
41258
  async psmQuoteWithStatus(p) {
41235
- const statusR = await this.deps.plugin.chain.getPsmStatus();
41259
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
41236
41260
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
41237
41261
  const s = statusR.value;
41238
41262
  const toUcd = p.direction === "to-ucd";
@@ -41288,6 +41312,7 @@ var BoundaryCore = class {
41288
41312
  );
41289
41313
  }
41290
41314
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
41315
+ stablecoin: p.stablecoin,
41291
41316
  direction: toUcd ? "swap" : "redeem",
41292
41317
  amountIn: amountIn.toString()
41293
41318
  });
@@ -41354,6 +41379,7 @@ var BoundaryCore = class {
41354
41379
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
41355
41380
  if (floor === 0n) floor = 1n;
41356
41381
  const r = await this.deps.plugin.ops.psmSwap({
41382
+ stablecoin: p.stablecoin,
41357
41383
  direction: q.contractCall,
41358
41384
  amountIn: q.amountIn,
41359
41385
  minOut: floor.toString(),
@@ -41453,7 +41479,7 @@ var BoundaryCore = class {
41453
41479
  feeToken: "UCD",
41454
41480
  perBlockCap: s.maxSwapVolumePerBlock
41455
41481
  }),
41456
- toUsdc: direction({
41482
+ fromUcd: direction({
41457
41483
  minAmount: s.minRedeemAmount,
41458
41484
  maxAmount: s.maxRedeemAmount,
41459
41485
  amountUnit: ucdUnit,
@@ -41585,7 +41611,10 @@ var BoundaryCore = class {
41585
41611
  borrower: auth.borrower
41586
41612
  });
41587
41613
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41588
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
41614
+ return okEnvelope(
41615
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41616
+ r.source
41617
+ );
41589
41618
  }
41590
41619
  // ---- meta ----
41591
41620
  world() {
@@ -42432,20 +42461,56 @@ var World = class {
42432
42461
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42433
42462
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42434
42463
  }
42435
- const c = this.state.collateral[p.positionId];
42436
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42437
- const transfers = pending.map((spend) => {
42464
+ const fee = BigInt(p.networkFeeSats);
42465
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
42466
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
42467
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
42468
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
42438
42469
  const { hash: txid } = this.nextId("btc-withdraw-retry");
42439
42470
  return {
42440
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
42471
+ utxoIdentifier,
42441
42472
  ok: true,
42442
42473
  txid,
42443
- amountSentSats: spend.satoshis,
42474
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
42475
+ // the authorized amount, never added on top — the same semantics `withdraw` above
42476
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
42477
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
42478
+ // whether the fee was honoured at all.
42479
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
42444
42480
  destination: spend.targetAddress
42445
42481
  };
42446
42482
  });
42447
42483
  return { ok: true, value: { attempted: transfers.length, transfers } };
42448
42484
  }
42485
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
42486
+ pendingSpends(positionId) {
42487
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42488
+ }
42489
+ /**
42490
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
42491
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
42492
+ *
42493
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
42494
+ *
42495
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
42496
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
42497
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
42498
+ */
42499
+ retryFeeRefusal(spend, networkFeeSats) {
42500
+ const target = BigInt(spend.satoshis);
42501
+ if (BigInt(networkFeeSats) * 2n >= target) {
42502
+ 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)`;
42503
+ }
42504
+ return null;
42505
+ }
42506
+ /**
42507
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
42508
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
42509
+ * wallet is never opened — which is what the mock's ceremony gate reads.
42510
+ */
42511
+ retryExecutableCount(positionId, networkFeeSats) {
42512
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
42513
+ }
42449
42514
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42450
42515
  safesMap() {
42451
42516
  return this.state.safes;
@@ -43239,7 +43304,7 @@ var SINK_CONTRACTS = {
43239
43304
  PositionManager: sinkAddress("PositionManager"),
43240
43305
  UCDToken: sinkAddress("UCDToken"),
43241
43306
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
43242
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
43307
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
43243
43308
  SimplePSMV2: sinkAddress("SimplePSMV2"),
43244
43309
  UsdcToken: sinkAddress("UsdcToken"),
43245
43310
  UCDController: sinkAddress("UCDController")
@@ -43535,7 +43600,18 @@ var MockUpstreamPlugin = class {
43535
43600
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
43536
43601
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
43537
43602
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
43538
- getPsmStatus: () => this.read("mock-chain", () => {
43603
+ // The practice world models ONE stablecoin, and says so rather than implying a
43604
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
43605
+ // and naming anything but this one is refused the same way the real adapter refuses
43606
+ // an unsupported address — a mock that accepted any name would teach a habit the
43607
+ // real protocol punishes.
43608
+ listPsmStablecoins: () => this.read(
43609
+ "mock-chain",
43610
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
43611
+ ),
43612
+ getPsmStatus: (p) => this.read("mock-chain", () => {
43613
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43614
+ if (known) return known;
43539
43615
  const psm = this.world.psmSeed();
43540
43616
  return upOk(
43541
43617
  {
@@ -43560,6 +43636,8 @@ var MockUpstreamPlugin = class {
43560
43636
  );
43561
43637
  }),
43562
43638
  getPsmQuote: (p) => this.read("mock-chain", () => {
43639
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43640
+ if (known) return known;
43563
43641
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
43564
43642
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
43565
43643
  })
@@ -43632,11 +43710,7 @@ var MockUpstreamPlugin = class {
43632
43710
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43633
43711
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43634
43712
  }),
43635
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
43636
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
43637
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43638
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
43639
- })
43713
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43640
43714
  };
43641
43715
  }
43642
43716
  indexer;
@@ -43688,6 +43762,19 @@ var MockUpstreamPlugin = class {
43688
43762
  return apply();
43689
43763
  }
43690
43764
  /** Mode `none`: every write answers with the conversational setup invitation. */
43765
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
43766
+ * refused with the same shape the real adapter uses for an address the chain does not
43767
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
43768
+ * instead of silently succeeding and teaching that any name works. */
43769
+ mockStablecoinRefusal(stablecoin) {
43770
+ const chosen = stablecoin.trim().toLowerCase();
43771
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
43772
+ return upFail({
43773
+ kind: "rejected",
43774
+ source: "mock-chain",
43775
+ message: `'${stablecoin}' is not a PSM-supported stablecoin in this practice world \u2014 it supports 'USDC' only. Read protocol://psm for the coins a deployment actually supports; there is no default coin on any tier.`
43776
+ });
43777
+ }
43691
43778
  noneRefusal() {
43692
43779
  if (this.signer && this.signer.manager.mode() === "none") {
43693
43780
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -43911,6 +43998,46 @@ var MockUpstreamPlugin = class {
43911
43998
  );
43912
43999
  });
43913
44000
  }
44001
+ /**
44002
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
44003
+ *
44004
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
44005
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
44006
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
44007
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
44008
+ * passing requests the real protocol would refuse, which is the one thing a practice world
44009
+ * must never do.
44010
+ *
44011
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
44012
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
44013
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
44014
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
44015
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
44016
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
44017
+ */
44018
+ async opRetryWithdrawExecute(p) {
44019
+ const none = this.noneRefusal();
44020
+ if (none) return none;
44021
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
44022
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
44023
+ const cer = executable > 0 ? this.ceremonyNow() : null;
44024
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
44025
+ if (auth && !auth.ok) return auth.failure;
44026
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
44027
+ return this.write("retryWithdrawExecute", () => {
44028
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
44029
+ if (sig && !sig.ok) return sig.failure;
44030
+ const r = this.applyAuthorized(
44031
+ sig ? sig.authorization : void 0,
44032
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
44033
+ );
44034
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
44035
+ return upOk(
44036
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
44037
+ this.src("mock-ops")
44038
+ );
44039
+ });
44040
+ }
43914
44041
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43915
44042
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43916
44043
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -78531,6 +78658,19 @@ function listPositionsQuery(f) {
78531
78658
  }
78532
78659
  return { document: LIST_POSITIONS, variables: { first, skip } };
78533
78660
  }
78661
+ var SUPPORTED_STABLECOINS = `
78662
+ query SupportedStablecoins {
78663
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
78664
+ id
78665
+ address
78666
+ isSupported
78667
+ decimals
78668
+ entryFee
78669
+ exitFee
78670
+ reserves
78671
+ }
78672
+ }
78673
+ `;
78534
78674
 
78535
78675
  // src/boundary/upstream/real/psm-calls.ts
78536
78676
  var import_ethers31 = require("ethers");
@@ -78670,6 +78810,11 @@ var PsmCalls = class {
78670
78810
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78671
78811
  });
78672
78812
  }
78813
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
78814
+ * so it must come from the token rather than from a per-network assumption. */
78815
+ symbol() {
78816
+ return this.deps.stablecoinSymbol;
78817
+ }
78673
78818
  async status() {
78674
78819
  return this.call(async () => {
78675
78820
  const s = this.deps.stablecoinAddress;
@@ -79129,13 +79274,6 @@ function buildValidationContext(network, chainId) {
79129
79274
  }
79130
79275
 
79131
79276
  // src/boundary/upstream/real/write-ops.ts
79132
- function psmMainnetWriteRefusal(network, chainId) {
79133
- return {
79134
- kind: "rejected",
79135
- source: SOURCE5,
79136
- 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.`
79137
- };
79138
- }
79139
79277
  var SOURCE5 = "real-ops";
79140
79278
  var OP_LAYOUT = "dh-op-envelope-v1";
79141
79279
  function randomNonceHex() {
@@ -79483,8 +79621,7 @@ function buildWriteOps(deps) {
79483
79621
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79484
79622
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
79485
79623
  psmSwap: async (p) => {
79486
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
79487
- const pr = deps.psm();
79624
+ const pr = await deps.psm(p.stablecoin);
79488
79625
  if (!pr.ok) return upFail(pr.failure);
79489
79626
  const calls = pr.calls;
79490
79627
  const addr = calls.addresses();
@@ -79865,6 +80002,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79865
80002
  );
79866
80003
  }
79867
80004
  const hashHex = import_ethers37.ethers.hexlify(bytes).toLowerCase();
80005
+ const nowMs = (this.deps.clock ?? Date.now)();
80006
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80007
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
79868
80008
  const outcome = await this.deps.bridge.requestSignature({
79869
80009
  id: (0, import_node_crypto5.randomUUID)(),
79870
80010
  kind: "personal-sign",
@@ -79876,15 +80016,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79876
80016
  "(identical to how diamondhands.credit signs withdrawals).",
79877
80017
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79878
80018
  "",
79879
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
79880
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
79881
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
79882
- "itself allows. If it expires the signature is refused, the withdrawal does not",
79883
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
79884
- "start again rather than signing something you have not finished reading."
80019
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80020
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80021
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80022
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80023
+ "stay reserved until that is cleared. If the number above is already small, decline",
80024
+ "and start again rather than signing something you have not finished reading."
79885
80025
  ],
79886
80026
  expectedSigner: this.deps.borrower,
79887
80027
  chainId: this.deps.chainId,
80028
+ expiresAtSec,
79888
80029
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
79889
80030
  });
79890
80031
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -80088,13 +80229,27 @@ var RealUpstreamPlugin = class {
80088
80229
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
80089
80230
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
80090
80231
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
80091
- getPsmStatus: () => {
80092
- const r = this.psmCalls();
80093
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
80232
+ listPsmStablecoins: async () => {
80233
+ const listed = await this.listSupportedStablecoins();
80234
+ if (!listed.ok) return listed;
80235
+ const rows = await Promise.all(
80236
+ listed.rows.map(async (row) => {
80237
+ const built = await this.psmCallsFor(row.address);
80238
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
80239
+ })
80240
+ );
80241
+ return upOk(
80242
+ rows.filter((r) => r !== null),
80243
+ this.src("subgraph")
80244
+ );
80094
80245
  },
80095
- getPsmQuote: (p) => {
80096
- const r = this.psmCalls();
80097
- if (!r.ok) return Promise.resolve(upFail(r.failure));
80246
+ getPsmStatus: async (p) => {
80247
+ const r = await this.psmCallsFor(p.stablecoin);
80248
+ return r.ok ? r.calls.status() : upFail(r.failure);
80249
+ },
80250
+ getPsmQuote: async (p) => {
80251
+ const r = await this.psmCallsFor(p.stablecoin);
80252
+ if (!r.ok) return upFail(r.failure);
80098
80253
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
80099
80254
  }
80100
80255
  };
@@ -80162,12 +80317,13 @@ var RealUpstreamPlugin = class {
80162
80317
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
80163
80318
  delegationSetup: () => readOnly("delegationSetup"),
80164
80319
  delegationGrant: () => readOnly("delegationGrant"),
80165
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
80166
- // any non-sepolia network refuses typed — naming the network gate truthfully —
80167
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
80168
- // missing signer instead (the honest reason on that path).
80320
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
80321
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
80322
+ // signerless boot the honest refusal was always the missing signer; the network
80323
+ // gate sat in front of it and answered first. Now there is one reason left, and it
80324
+ // is the true one on this path.
80169
80325
  psmSwap: () => Promise.resolve(
80170
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
80326
+ upFail({
80171
80327
  kind: "signer-missing",
80172
80328
  source: "real-ops",
80173
80329
  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."
@@ -80284,7 +80440,7 @@ var RealUpstreamPlugin = class {
80284
80440
  session,
80285
80441
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80286
80442
  readDetails: (id) => this.readPositionDetails(id),
80287
- psm: () => this.psmCalls(),
80443
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80288
80444
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80289
80445
  });
80290
80446
  }
@@ -80418,7 +80574,7 @@ var RealUpstreamPlugin = class {
80418
80574
  session,
80419
80575
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80420
80576
  readDetails: (id) => this.readPositionDetails(id),
80421
- psm: () => this.psmCalls(),
80577
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80422
80578
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80423
80579
  });
80424
80580
  this.opsGatewayCache.set(key, gateway);
@@ -80564,35 +80720,91 @@ var RealUpstreamPlugin = class {
80564
80720
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
80565
80721
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
80566
80722
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
80567
- psmWrapper = null;
80568
- psmCalls() {
80569
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
80723
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
80724
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
80725
+ psmWrappers = /* @__PURE__ */ new Map();
80726
+ /**
80727
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
80728
+ *
80729
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
80730
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
80731
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
80732
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
80733
+ * `getPSMStablecoins` reads the index for the same reason.
80734
+ */
80735
+ async listSupportedStablecoins() {
80736
+ const r = await this.graphProxy(
80737
+ SUPPORTED_STABLECOINS,
80738
+ {}
80739
+ );
80740
+ if (!r.ok) return r;
80741
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
80742
+ address: String(x.address).toLowerCase(),
80743
+ decimals: Number(x.decimals)
80744
+ }));
80745
+ return { ok: true, rows };
80746
+ }
80747
+ /**
80748
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
80749
+ *
80750
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
80751
+ * indexer is how the list is discovered and is not authority over it: it can lag a
80752
+ * governance removal, and acting on a stale list would build a swap the contract reverts
80753
+ * — after the user has approved it in their wallet. List from the index, verify on the
80754
+ * chain, then sign.
80755
+ */
80756
+ async psmCallsFor(stablecoinAddress) {
80757
+ const key = stablecoinAddress.toLowerCase();
80758
+ const cached = this.psmWrappers.get(key);
80759
+ if (cached) return { ok: true, calls: cached };
80570
80760
  const psmAddress = this.contracts["SimplePSMV2"];
80571
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
80572
- if (!psmAddress || !stablecoinAddress) {
80573
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
80761
+ if (!psmAddress) {
80574
80762
  return {
80575
80763
  ok: false,
80576
80764
  failure: {
80577
80765
  kind: "unavailable",
80578
80766
  source: "chain-rpc",
80579
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
80767
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
80768
+ }
80769
+ };
80770
+ }
80771
+ let supported;
80772
+ let symbol;
80773
+ try {
80774
+ const psm = new import_ethers38.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
80775
+ supported = await psm["supportedStablecoins"](key);
80776
+ const erc20 = new import_ethers38.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
80777
+ symbol = await erc20["symbol"]();
80778
+ } catch (e) {
80779
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
80780
+ }
80781
+ if (!supported) {
80782
+ return {
80783
+ ok: false,
80784
+ failure: {
80785
+ kind: "rejected",
80786
+ source: "chain-rpc",
80787
+ 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.`
80580
80788
  }
80581
80789
  };
80582
80790
  }
80791
+ const stablecoinAddress2 = key;
80583
80792
  const ucdTokenAddress = this.contracts["UCDToken"];
80584
80793
  const ucdControllerAddress = this.contracts["UCDController"];
80585
- this.psmWrapper = new PsmCalls({
80794
+ const built = new PsmCalls({
80586
80795
  provider: this.provider,
80587
80796
  psmAddress,
80588
- stablecoinAddress,
80589
- stablecoinSymbol: "USDC",
80797
+ stablecoinAddress: stablecoinAddress2,
80798
+ // Read from the token, never assumed. The old value was the literal "USDC", which
80799
+ // stops being true the moment a second coin is supported.
80800
+ stablecoinSymbol: symbol,
80590
80801
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
80591
80802
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
80592
80803
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
80593
80804
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
80594
80805
  });
80595
- return { ok: true, calls: this.psmWrapper };
80806
+ this.psmWrappers.set(key, built);
80807
+ return { ok: true, calls: built };
80596
80808
  }
80597
80809
  src(id) {
80598
80810
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -80855,6 +81067,7 @@ function renderApprovalPage(sessionId, nonce) {
80855
81067
  <div id="request" class="hidden">
80856
81068
  <div id="action" class="action"></div>
80857
81069
  <div id="card" class="card"></div>
81070
+ <div id="deadline" class="status hidden"></div>
80858
81071
  <button id="approve">Approve in wallet</button>
80859
81072
  <button id="reject">Reject</button>
80860
81073
  </div>
@@ -80887,10 +81100,19 @@ const statusEl = document.getElementById("status");
80887
81100
  const requestEl = document.getElementById("request");
80888
81101
  const actionEl = document.getElementById("action");
80889
81102
  const cardEl = document.getElementById("card");
81103
+ const approveEl = document.getElementById("approve");
81104
+ const rejectEl = document.getElementById("reject");
81105
+ const deadlineEl = document.getElementById("deadline");
81106
+ let deadlineTimer = null;
80890
81107
  const walletEl = document.getElementById("wallet");
80891
81108
  let account = null;
80892
81109
  let chainId = null;
80893
81110
  let current = null;
81111
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
81112
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
81113
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
81114
+ // card the page never renders is one the human can neither read nor reject.
81115
+ const pending = new Map();
80894
81116
 
80895
81117
  function post(path, body) {
80896
81118
  return fetch(path, {
@@ -80953,43 +81175,135 @@ async function onAccountsChanged(accounts) {
80953
81175
  account = (accounts && accounts[0]) || null;
80954
81176
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80955
81177
  showWallet();
80956
- clearRequest("Wallet changed \u2014 pending request invalidated.");
81178
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
80957
81179
  }
80958
81180
 
80959
81181
  async function onChainChanged(cid) {
80960
81182
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
80961
81183
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80962
81184
  showWallet();
80963
- clearRequest("Network changed \u2014 pending request invalidated.");
81185
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
80964
81186
  }
80965
81187
 
80966
81188
  function listen() {
80967
81189
  const es = new EventSource(BASE + "events?s=" + SESSION);
80968
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
81190
+ es.onmessage = (ev) => {
81191
+ const next = JSON.parse(ev.data);
81192
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
81193
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
81194
+ pending.set(next.id, next);
81195
+ showPending();
81196
+ };
80969
81197
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
80970
81198
  }
80971
81199
 
81200
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
81201
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
81202
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
81203
+ // gets approved.
81204
+ function pickPending() {
81205
+ const held = current ? pending.get(current.id) : undefined;
81206
+ if (held && held.mirror !== true) return held;
81207
+ let best = held || null;
81208
+ pending.forEach((frame) => {
81209
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
81210
+ });
81211
+ return best;
81212
+ }
81213
+
81214
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
81215
+ function showPending(emptyText) {
81216
+ const next = pickPending();
81217
+ if (!next) {
81218
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
81219
+ // an expiry for a ceremony that is already decided.
81220
+ stopDeadline();
81221
+ current = null;
81222
+ requestEl.classList.add("hidden");
81223
+ if (emptyText) showStatus(emptyText);
81224
+ return;
81225
+ }
81226
+ current = next;
81227
+ renderRequest();
81228
+ }
81229
+
80972
81230
  function renderRequest() {
80973
81231
  actionEl.textContent = current.action;
80974
81232
  cardEl.textContent = current.card.join("\\n");
81233
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
81234
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
81235
+ // server-side, which is the actual boundary.
81236
+ const mirrored = current.mirror === true;
81237
+ approveEl.classList.toggle("hidden", mirrored);
81238
+ rejectEl.classList.remove("hidden");
80975
81239
  requestEl.classList.remove("hidden");
80976
- showStatus("Review the operation below. Nothing signs without your approval.");
81240
+ showStatus(mirrored
81241
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
81242
+ : "Review the operation below. Nothing signs without your approval.");
81243
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
81244
+ // card promoted after another settles gets its own clock, not the previous one's.
81245
+ startDeadline();
81246
+ }
81247
+
81248
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
81249
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
81250
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
81251
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
81252
+ // honest without it needing to know anything about quantum windows.
81253
+ function stopDeadline() {
81254
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81255
+ deadlineEl.classList.add("hidden");
81256
+ }
81257
+
81258
+ function startDeadline() {
81259
+ stopDeadline();
81260
+ if (!current || typeof current.expiresAtSec !== "number") return;
81261
+ const tick = () => {
81262
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
81263
+ if (left > 0) {
81264
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
81265
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
81266
+ } else {
81267
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
81268
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
81269
+ // after. The button is deliberately left enabled \u2014 declining is still the right
81270
+ // action and the page must not trap them.
81271
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
81272
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81273
+ }
81274
+ deadlineEl.classList.remove("hidden");
81275
+ };
81276
+ tick();
81277
+ deadlineTimer = setInterval(tick, 1000);
80977
81278
  }
80978
81279
 
81280
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
81281
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
81282
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
80979
81283
  function clearRequest(text) {
80980
- current = null;
80981
- requestEl.classList.add("hidden");
80982
- showStatus(text);
81284
+ if (current) pending.delete(current.id);
81285
+ showPending(text);
80983
81286
  }
80984
81287
 
80985
- document.getElementById("reject").onclick = async () => {
81288
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
81289
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
81290
+ // stays readable and rejectable.
81291
+ function invalidatePageRequests(text) {
81292
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
81293
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
81294
+ }
81295
+
81296
+ rejectEl.onclick = async () => {
80986
81297
  if (!current) return;
80987
81298
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
80988
81299
  clearRequest("Rejected. Waiting for the next request\u2026");
80989
81300
  };
80990
81301
 
80991
- document.getElementById("approve").onclick = async () => {
81302
+ approveEl.onclick = async () => {
80992
81303
  if (!current) return;
81304
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
81305
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
81306
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
80993
81307
  const req = current;
80994
81308
  try {
80995
81309
  if (req.kind === "transaction") {
@@ -81006,7 +81320,10 @@ document.getElementById("approve").onclick = async () => {
81006
81320
  const fbody = await fr.json();
81007
81321
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
81008
81322
  const fresh = fbody.request;
81009
- // \u2026re-render what will actually sign\u2026
81323
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
81324
+ // another card arriving while the wallet popup is open re-picks from there, and the
81325
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
81326
+ pending.set(fresh.id, fresh);
81010
81327
  current = fresh; renderRequest();
81011
81328
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
81012
81329
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -81189,9 +81506,6 @@ var SignatureBridge = class {
81189
81506
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81190
81507
  maxPending;
81191
81508
  attachGraceMs;
81192
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
81193
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
81194
- lastAttachedMs = 0;
81195
81509
  server = null;
81196
81510
  port = 0;
81197
81511
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -81302,7 +81616,7 @@ var SignatureBridge = class {
81302
81616
  connectedAccounts() {
81303
81617
  const seen = /* @__PURE__ */ new Map();
81304
81618
  for (const s of this.sessions.values()) {
81305
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81619
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81306
81620
  }
81307
81621
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
81308
81622
  return [...seen.values()];
@@ -81342,13 +81656,16 @@ var SignatureBridge = class {
81342
81656
  enqueuedMs: now,
81343
81657
  resolve,
81344
81658
  settled: false,
81345
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
81659
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
81660
+ owner: this.wcActive ? "wc" : "page",
81661
+ dispatched: false,
81662
+ lastAttachedMs: now
81346
81663
  };
81347
81664
  this.pending.set(request.id, entry);
81348
- if (this.wcActive) {
81665
+ if (entry.owner === "wc") {
81349
81666
  void this.driveWc(entry);
81350
81667
  } else {
81351
- this.push(request);
81668
+ this.pushEntry(entry);
81352
81669
  }
81353
81670
  });
81354
81671
  }
@@ -81369,10 +81686,16 @@ var SignatureBridge = class {
81369
81686
  enqueuedMs: now,
81370
81687
  resolve,
81371
81688
  settled: false,
81372
- collect
81689
+ collect,
81690
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
81691
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
81692
+ // ceremony could not reach quorum through the very pages it is broadcast to.
81693
+ owner: "both",
81694
+ dispatched: false,
81695
+ lastAttachedMs: now
81373
81696
  };
81374
81697
  this.pending.set(request.id, entry);
81375
- this.push(request);
81698
+ this.pushEntry(entry);
81376
81699
  if (this.wcActive) void this.driveWcCollection(entry);
81377
81700
  });
81378
81701
  }
@@ -81411,7 +81734,9 @@ var SignatureBridge = class {
81411
81734
  }
81412
81735
  try {
81413
81736
  if (req.kind === "transaction") {
81737
+ this.pushEntry(entry);
81414
81738
  const tx2 = req.tx;
81739
+ entry.dispatched = true;
81415
81740
  const txHash = await transport.request("eth_sendTransaction", [
81416
81741
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
81417
81742
  ]);
@@ -81423,11 +81748,22 @@ var SignatureBridge = class {
81423
81748
  req.card = fresh.card;
81424
81749
  }
81425
81750
  const ps = req.personalSign;
81751
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
81752
+ this.settle(entry, {
81753
+ status: "invalidated",
81754
+ 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)`
81755
+ });
81756
+ return;
81757
+ }
81758
+ this.pushEntry(entry);
81759
+ entry.dispatched = true;
81426
81760
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
81427
81761
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81428
81762
  } else {
81763
+ this.pushEntry(entry);
81429
81764
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
81430
81765
  const payload = withEip712DomainType2(req.typedData);
81766
+ entry.dispatched = true;
81431
81767
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
81432
81768
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81433
81769
  }
@@ -81447,30 +81783,55 @@ var SignatureBridge = class {
81447
81783
  * with a live attachment is in use and must never be evicted. */
81448
81784
  attachedNow() {
81449
81785
  if (this.wcActive) return true;
81450
- for (const s of this.sessions.values()) if (s.sse) return true;
81786
+ return this.pageAttached();
81787
+ }
81788
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
81789
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
81790
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
81791
+ * WalletConnect and must stay global for the connector's eviction predicate. */
81792
+ pageAttached() {
81793
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
81451
81794
  return false;
81452
81795
  }
81796
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
81797
+ * predicate said "a WC session is attached", which is true but irrelevant to a
81798
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
81799
+ * out the full expiry instead of failing fast at the grace. */
81800
+ attachedFor(entry) {
81801
+ if (entry.owner === "wc") return this.wcActive;
81802
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
81803
+ return this.pageAttached();
81804
+ }
81453
81805
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
81454
81806
  * interval; tests call it directly with the injected clock advanced. Order matters:
81455
81807
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
81456
81808
  sweep() {
81457
81809
  const now = this.clock();
81458
- const attached = this.attachedNow();
81459
- if (attached) this.lastAttachedMs = now;
81460
81810
  for (const entry of this.pending.values()) {
81461
81811
  if (entry.settled) continue;
81462
81812
  if (now >= entry.deadlineMs) {
81463
81813
  this.settle(entry, { status: "expired" });
81464
81814
  continue;
81465
81815
  }
81466
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
81467
- this.settle(entry, {
81468
- status: "invalidated",
81469
- 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`
81470
- });
81816
+ if (this.attachedFor(entry)) {
81817
+ entry.lastAttachedMs = now;
81818
+ continue;
81471
81819
  }
81820
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
81821
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
81472
81822
  }
81473
81823
  }
81824
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
81825
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
81826
+ unattendedReason(entry) {
81827
+ if (entry.dispatched && entry.request.kind === "transaction") {
81828
+ 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.";
81829
+ }
81830
+ if (entry.owner === "wc") {
81831
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
81832
+ }
81833
+ 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`;
81834
+ }
81474
81835
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
81475
81836
  walletConnectActive() {
81476
81837
  return this.wcActive;
@@ -81563,7 +81924,7 @@ var SignatureBridge = class {
81563
81924
  return;
81564
81925
  }
81565
81926
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81566
- this.sessions.set(sessionId, { wallet: null, sse: null });
81927
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81567
81928
  const page = htmlPageSecurityHeaders();
81568
81929
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81569
81930
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81593,7 +81954,8 @@ var SignatureBridge = class {
81593
81954
  const refusal = info ? this.accountRefusal(info.account) : null;
81594
81955
  if (info && refusal) {
81595
81956
  this.wcActive = false;
81596
- this.wallet = null;
81957
+ this.rebuildSharedWallet();
81958
+ this.demoteWcEntries();
81597
81959
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81598
81960
  `);
81599
81961
  return;
@@ -81603,7 +81965,10 @@ var SignatureBridge = class {
81603
81965
  if (info === null) {
81604
81966
  for (const entry of this.pending.values()) {
81605
81967
  if (!entry.settled && !entry.collect) {
81606
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
81968
+ this.settle(entry, {
81969
+ status: "invalidated",
81970
+ 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"
81971
+ });
81607
81972
  }
81608
81973
  }
81609
81974
  }
@@ -81675,9 +82040,7 @@ var SignatureBridge = class {
81675
82040
  session.sse?.end();
81676
82041
  session.sse = res;
81677
82042
  for (const entry of this.pending.values()) {
81678
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
81679
-
81680
- `);
82043
+ if (!entry.settled) res.write(this.wireFor(entry));
81681
82044
  }
81682
82045
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
81683
82046
  keepAlive.unref();
@@ -81697,6 +82060,7 @@ var SignatureBridge = class {
81697
82060
  }
81698
82061
  const refusal = this.accountRefusal(account);
81699
82062
  if (refusal) {
82063
+ this.quarantine(session, refusal);
81700
82064
  this.deny(res, 403, refusal);
81701
82065
  return;
81702
82066
  }
@@ -81735,10 +82099,15 @@ var SignatureBridge = class {
81735
82099
  const chainId = Number(body["chainId"]);
81736
82100
  const prev = session.wallet;
81737
82101
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81738
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
81739
- session.wallet = refusedSwitch ? null : offered;
81740
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81741
- this.wallet = session.wallet;
82102
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
82103
+ const refusedSwitch = switchRefusal !== null;
82104
+ if (refusedSwitch) {
82105
+ this.quarantine(session, switchRefusal);
82106
+ } else {
82107
+ session.wallet = offered;
82108
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
82109
+ this.wallet = session.wallet;
82110
+ }
81742
82111
  }
81743
82112
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81744
82113
  if (unchanged) {
@@ -81747,10 +82116,36 @@ var SignatureBridge = class {
81747
82116
  }
81748
82117
  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";
81749
82118
  for (const entry of this.pending.values()) {
81750
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
82119
+ if (entry.settled || entry.collect) continue;
82120
+ if (this.ownedByWc(entry)) continue;
82121
+ this.settle(entry, { status: "invalidated", reason });
81751
82122
  }
81752
82123
  this.ok(res);
81753
82124
  }
82125
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
82126
+ * session hands the request back to the page rather than stranding it. */
82127
+ ownedByWc(entry) {
82128
+ if (entry.owner !== "wc") return false;
82129
+ return this.wcActive || entry.dispatched;
82130
+ }
82131
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
82132
+ * them so the card stops rendering read-only. Collections are already `both`.
82133
+ *
82134
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
82135
+ * phone is still holding does not replace one wallet with another, it adds a second: the
82136
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
82137
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
82138
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
82139
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
82140
+ * false for them, and `unattendedReason` says plainly that the phone may already have
82141
+ * acted. */
82142
+ demoteWcEntries() {
82143
+ for (const entry of this.pending.values()) {
82144
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
82145
+ entry.owner = "page";
82146
+ this.pushEntry(entry);
82147
+ }
82148
+ }
81754
82149
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
81755
82150
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
81756
82151
  async onFinalize(body, res) {
@@ -81764,6 +82159,10 @@ var SignatureBridge = class {
81764
82159
  this.deny(res, 400, "finalize applies only to personal-sign requests");
81765
82160
  return;
81766
82161
  }
82162
+ if (this.ownedByWc(entry)) {
82163
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
82164
+ return;
82165
+ }
81767
82166
  if (entry.finalize) {
81768
82167
  let fresh;
81769
82168
  try {
@@ -81790,10 +82189,22 @@ var SignatureBridge = class {
81790
82189
  return;
81791
82190
  }
81792
82191
  if (body["approved"] !== true) {
82192
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
82193
+ this.settle(entry, {
82194
+ status: "invalidated",
82195
+ 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."
82196
+ });
82197
+ this.ok(res);
82198
+ return;
82199
+ }
81793
82200
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
81794
82201
  this.ok(res);
81795
82202
  return;
81796
82203
  }
82204
+ if (this.ownedByWc(entry)) {
82205
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
82206
+ return;
82207
+ }
81797
82208
  const account = String(body["account"] ?? "");
81798
82209
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
81799
82210
  this.deny(res, 400, "approved result requires the signing account");
@@ -81830,12 +82241,21 @@ var SignatureBridge = class {
81830
82241
  this.pending.delete(entry.request.id);
81831
82242
  entry.resolve(outcome);
81832
82243
  }
81833
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
81834
- push(request) {
81835
- const data = `data: ${JSON.stringify(request)}
82244
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
82245
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
82246
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
82247
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
82248
+ * a permanently read-only card that nobody is allowed to decide. */
82249
+ wireFor(entry) {
82250
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
82251
+ return `data: ${JSON.stringify(payload)}
81836
82252
 
81837
82253
  `;
81838
- for (const s of this.sessions.values()) s.sse?.write(data);
82254
+ }
82255
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
82256
+ pushEntry(entry) {
82257
+ const data = this.wireFor(entry);
82258
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81839
82259
  }
81840
82260
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81841
82261
  pushProgress(payload) {
@@ -81843,7 +82263,48 @@ var SignatureBridge = class {
81843
82263
  data: ${JSON.stringify(payload)}
81844
82264
 
81845
82265
  `;
81846
- for (const s of this.sessions.values()) s.sse?.write(data);
82266
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82267
+ }
82268
+ /**
82269
+ * C-47: `this.wallet` is DERIVED, never guessed.
82270
+ *
82271
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
82272
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
82273
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
82274
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
82275
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
82276
+ * wrong account into a disconnect for the legitimate user.
82277
+ *
82278
+ * Deriving it from live state removes the guess. Preference order matches
82279
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
82280
+ */
82281
+ rebuildSharedWallet() {
82282
+ if (this.wcActive && this.wcTransport) {
82283
+ const wc = this.wcTransport.active();
82284
+ if (wc && !this.accountRefusal(wc.account)) {
82285
+ this.wallet = { account: wc.account, chainId: wc.chainId };
82286
+ return;
82287
+ }
82288
+ }
82289
+ let latest = null;
82290
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
82291
+ this.wallet = latest;
82292
+ }
82293
+ /**
82294
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
82295
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
82296
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
82297
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
82298
+ * stream, and re-derive the shared view without it.
82299
+ */
82300
+ quarantine(session, reason) {
82301
+ session.refused = reason;
82302
+ session.wallet = null;
82303
+ if (session.sse) {
82304
+ session.sse.end();
82305
+ session.sse = null;
82306
+ }
82307
+ this.rebuildSharedWallet();
81847
82308
  }
81848
82309
  sessionOf(candidate, res) {
81849
82310
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81851,6 +82312,10 @@ data: ${JSON.stringify(payload)}
81851
82312
  this.deny(res, 403, "missing or wrong session");
81852
82313
  return null;
81853
82314
  }
82315
+ if (session.refused) {
82316
+ this.deny(res, 403, session.refused);
82317
+ return null;
82318
+ }
81854
82319
  return session;
81855
82320
  }
81856
82321
  checkSession(candidate, res) {
@@ -82272,7 +82737,7 @@ var FIELD_GLOSSARY = {
82272
82737
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
82273
82738
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
82274
82739
  // ---- psm quote ----
82275
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
82740
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
82276
82741
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
82277
82742
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
82278
82743
  amountInToken: "the token you pay with",
@@ -82370,11 +82835,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
82370
82835
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
82371
82836
  // on the real adapter these modes refuse") carry the narrower adapter axis.
82372
82837
  signerModes: GUIDE_SIGNER_MODES,
82373
- // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
82374
- // leg genuinely is not there until an operator configures it. The first draft of this line
82375
- // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
82376
- // about — the default rendering would have promised a QR that most installs cannot show.
82377
- // A live boot derives this from env either way (network-switch.ts).
82838
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
82839
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
82840
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
82841
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
82842
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
82843
+ // nobody supplied a deployment at all, and understating a capability there is the safe
82844
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
82845
+ // overclaim C-44 is about — promising a QR the build cannot show.
82378
82846
  walletConnect: false
82379
82847
  };
82380
82848
  function servedNetworks(d) {
@@ -82385,7 +82853,7 @@ function servedNetworks(d) {
82385
82853
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
82386
82854
  }
82387
82855
  if (mainnet) {
82388
- 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";
82856
+ 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";
82389
82857
  }
82390
82858
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
82391
82859
  }
@@ -82464,13 +82932,14 @@ function switchNetworkRules(d) {
82464
82932
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
82465
82933
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
82466
82934
  A sepolia position does not exist on mainnet and vice versa.
82467
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
82468
- and every one still requires the user's explicit confirmation plus the signer
82469
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
82935
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
82936
+ mainnet they move REAL money, and every one still requires the user's explicit
82937
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
82938
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
82939
+ signed.`;
82470
82940
  }
82471
82941
  const only = d.networks[0];
82472
82942
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82473
- 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.";
82474
82943
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
82475
82944
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
82476
82945
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -82479,7 +82948,9 @@ function switchNetworkRules(d) {
82479
82948
  belong to ${only} and would not exist anywhere else.
82480
82949
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
82481
82950
  confirmation plus the signer ceremony.
82482
- - ${psm}`;
82951
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
82952
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
82953
+ anything is signed.`;
82483
82954
  }
82484
82955
  function wrongNetworkTroubleshootingRow(d) {
82485
82956
  if (d.networks.length > 1) {
@@ -82499,14 +82970,18 @@ function switchNetworkIndexLine(d) {
82499
82970
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
82500
82971
  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`;
82501
82972
  }
82502
- function psmAvailabilityNote(d) {
82503
- if (d.networks.includes("sepolia")) return "";
82504
- return `**Not executable on this deployment.** The PSM write port refuses on every network
82505
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
82506
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
82507
- the mechanism, not an offer: say so before a user plans around it.
82508
-
82509
- `;
82973
+ function psmStablecoinRealityNote(d) {
82974
+ if (d.networks.includes("sepolia")) {
82975
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
82976
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
82977
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
82978
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
82979
+ }
82980
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
82981
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
82982
+ every swap executed on this deployment moves real Circle USDC and real UCD.
82983
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
82984
+ have to guess whether the money is real.`;
82510
82985
  }
82511
82986
  function authorizationModeBullets(d) {
82512
82987
  const bullets = [];
@@ -82620,7 +83095,7 @@ on the real adapter and the mock.
82620
83095
  **The walkthrough:**
82621
83096
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
82622
83097
  desktop browser; ${approvalPageLocation(d)}
82623
- 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) + "."}
83098
+ 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) + "."}
82624
83099
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
82625
83100
  login ceremony explicitly (one typed-data signature in the wallet).
82626
83101
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -82659,13 +83134,24 @@ on the real adapter and the mock.
82659
83134
  hash the SDK builds internally, which the approval page shows bare and says plainly it
82660
83135
  cannot decode (the production web app signs the same way). Tell the user before that
82661
83136
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
82662
- expect an unreadable card and click through the readable one.
83137
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
83138
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
83139
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
83140
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
83141
+ on the card, and the page is the only surface that shows it. With no page attached the
83142
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
83143
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
83144
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
82663
83145
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
82664
83146
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
82665
83147
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
82666
83148
  back. Warn the user: a second or third identical card is the retry, NOT a duplicate
82667
83149
  charge and NOT an attack \u2014 but they should still read it, and each attempt is a new
82668
- signature. The blind execute popup happens once.
83150
+ signature. The EXECUTE popup comes once PER ATTEMPT too, and \`loan_withdraw_retry\` raises
83151
+ it again \u2014 re-signing with a fresh stamp is the whole of what a retry does. What that popup
83152
+ LOOKS like depends on the adapter: on the real adapter it is the blind 32-byte hash above;
83153
+ in a practice world (adapter \`mock\`) every ceremony, retries included, is a readable
83154
+ typed-data card. Promise the unreadable one only where it is real.
82669
83155
  - **The allowlist delay is read LIVE from the chain.** A new BTC withdrawal destination
82670
83156
  (\`loan_allowlist_destination\`) becomes usable only after the chain's own delay \u2014 24
82671
83157
  hours on mainnet, so allowlisting and withdrawing happen on DIFFERENT DAYS there. The
@@ -82708,6 +83194,14 @@ Connections / Connected sites).`,
82708
83194
  \`loan_withdraw_retry {positionId, confirmed:true}\`, which re-runs that second step with a
82709
83195
  fresh stamp using the destination and amount the CHAIN already holds. Check
82710
83196
  \`position_pending_withdrawals\` first, and tell the user it re-sends real BTC.
83197
+ WARN THEM WHAT THEY WILL SEE: the retry raises the SAME popup the original attempt's
83198
+ execute step raised, on the same sub-minute clock \u2014 on the real adapter that is the opaque
83199
+ 32-byte hash the wallet cannot decode; in a practice world it is a readable typed-data card.
83200
+ Say which one before they open the page, not after the popup surprises them.
83201
+ A retry with nothing outstanding pops NO wallet at all: both adapters look the
83202
+ reservations up first and answer \`attempted: 0\` without ever asking for a signature.
83203
+ The fee is taken OUT of the already-authorized amount, so a retry can never send more than
83204
+ the original withdrawal authorized.
82711
83205
  7. **Watch it** \u2014 \`position_status\` (one), \`position_list\` (all),
82712
83206
  \`position_events\` (history), \`btc_price\`, \`protocol_status\`.
82713
83207
 
@@ -82728,9 +83222,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
82728
83222
 
82729
83223
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
82730
83224
  signed, amounts included. Read it back when the user asks what happened.`,
82731
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
83225
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
82732
83226
 
82733
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83227
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
82734
83228
  directions, in user words:
82735
83229
 
82736
83230
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -82738,20 +83232,27 @@ directions, in user words:
82738
83232
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
82739
83233
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
82740
83234
  and you receive 99 UCD.
82741
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
82742
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
82743
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
82744
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
82745
- shortfall refuses with both figures (available vs required).
83235
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
83236
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
83237
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
83238
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
83239
+ reserves, and a shortfall refuses with both figures (available vs required).
83240
+
83241
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
83242
+ default and that is deliberate: the PSM can carry several coins, each with its own
83243
+ reserves, fees and limits, so picking one silently would move someone's money through a
83244
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
83245
+ there rather than guessing one.
82746
83246
 
82747
83247
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
82748
83248
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
82749
83249
  1e18 = 1:1) and can be changed by protocol governance.
82750
83250
 
82751
83251
  **Limits and switches** (all visible in \`protocol://psm\`):
82752
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
82753
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
82754
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
83252
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
83253
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
83254
+ direction is DISABLED.
83255
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
82755
83256
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
82756
83257
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
82757
83258
 
@@ -82760,23 +83261,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
82760
83261
  change between your quote and execution; the floor makes a drifted execution REFUSE
82761
83262
  rather than silently deliver less than quoted.
82762
83263
 
82763
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
82764
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
82765
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
82766
- the money is real. On mainnet the stablecoin is real Circle USDC.
83264
+ ${psmStablecoinRealityNote(d)}
82767
83265
 
82768
83266
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
82769
83267
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
82770
83268
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
82771
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
82772
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
82773
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83269
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
83270
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
83271
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
82774
83272
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
82775
83273
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
82776
83274
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
82777
83275
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
82778
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
82779
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
83276
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
83277
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
83278
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
83279
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
83280
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
83281
+ per-operation and per-block limits,
83282
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
83283
+ mainnet swap, not after.`,
82780
83284
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
82781
83285
 
82782
83286
  Every fund-moving operation needs TWO things, always in this order:
@@ -83035,9 +83539,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
83035
83539
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
83036
83540
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
83037
83541
  the same way \u2014 reconnect on the user's word.`}
83038
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
83039
- 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
83040
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
83542
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
83543
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
83544
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
83545
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
83546
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
83041
83547
  ${wrongNetworkTroubleshootingRow(d)}
83042
83548
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
83043
83549
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -83195,12 +83701,13 @@ function guideDeployment(overrides, env) {
83195
83701
  tier: overrides?.bridgeMount ? "hosted" : "local",
83196
83702
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
83197
83703
  signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
83198
- // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
83199
- // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
83200
- // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
83201
- // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
83202
- // about the same server, which is exactly what they did before this line existed.
83203
- walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
83704
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
83705
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
83706
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
83707
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
83708
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
83709
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
83710
+ walletConnect: wcEnabled(env)
83204
83711
  };
83205
83712
  }
83206
83713
  function assembleWorld(opts) {
@@ -83840,39 +84347,45 @@ function registerPsmTools(server, getB) {
83840
84347
  server,
83841
84348
  "psm_quote",
83842
84349
  {
83843
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
83844
- 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.",
84350
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
84351
+ 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.",
83845
84352
  inputSchema: {
83846
- 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)"),
83847
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
84353
+ stablecoin: import_zod4.z.string().min(1).describe(
84354
+ "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."
84355
+ ),
84356
+ 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)"),
84357
+ 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.")
83848
84358
  },
83849
84359
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
83850
84360
  },
83851
- async ({ direction, amount }) => guarded(async () => {
83852
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
84361
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
84362
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
83853
84363
  const problem = checkUcdAmount(amount, label);
83854
84364
  if (problem) return validationFailed(problem);
83855
84365
  const b = getB();
83856
84366
  if (!b.ok) return renderError(b.error);
83857
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
84367
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
83858
84368
  })
83859
84369
  );
83860
84370
  registerBoundaryTool(
83861
84371
  server,
83862
84372
  "psm_swap",
83863
84373
  {
83864
- title: "Exchange UCD \u2194 USDC through the PSM",
83865
- 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).",
84374
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
84375
+ 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).",
83866
84376
  inputSchema: {
83867
- 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)"),
83868
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
84377
+ stablecoin: import_zod4.z.string().min(1).describe(
84378
+ "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."
84379
+ ),
84380
+ 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)"),
84381
+ 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."),
83869
84382
  confirmed: confirmedSchema2
83870
84383
  },
83871
84384
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
83872
84385
  },
83873
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
83874
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
83875
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
84386
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
84387
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
84388
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
83876
84389
  const gate = requireConfirmation(
83877
84390
  confirmed,
83878
84391
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -83882,7 +84395,7 @@ function registerPsmTools(server, getB) {
83882
84395
  if (problem) return validationFailed(problem);
83883
84396
  const b = getB();
83884
84397
  if (!b.ok) return renderError(b.error);
83885
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
84398
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
83886
84399
  })
83887
84400
  );
83888
84401
  }
@@ -84328,7 +84841,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
84328
84841
  "network_switch",
84329
84842
  {
84330
84843
  title: "Show or switch the active network",
84331
- 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.",
84844
+ 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.",
84332
84845
  inputSchema: {
84333
84846
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
84334
84847
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -84346,7 +84859,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
84346
84859
  lines.push(
84347
84860
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
84348
84861
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
84349
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
84862
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
84350
84863
  "Session-scoped: the configured default network returns when the server restarts."
84351
84864
  );
84352
84865
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -84452,13 +84965,26 @@ function registerProtocolResources(server, getB) {
84452
84965
  "protocol://psm",
84453
84966
  {
84454
84967
  title: "PSM status (UCD \u2194 USDC exchange)",
84455
- 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).",
84968
+ 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.",
84456
84969
  mimeType: "application/json"
84457
84970
  },
84458
84971
  async (uri) => {
84459
84972
  const b = getB();
84460
84973
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
84461
- const env = await b.boundary.getPsmStatus();
84974
+ const listed = await b.boundary.listPsmStablecoins();
84975
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
84976
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
84977
+ const failed = perCoin.find((s) => !s.ok);
84978
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
84979
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
84980
+ const head = coins[0];
84981
+ const env = {
84982
+ ...listed,
84983
+ data: {
84984
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
84985
+ stablecoins: coins
84986
+ }
84987
+ };
84462
84988
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
84463
84989
  }
84464
84990
  );
@@ -84501,7 +85027,7 @@ function registerBoundaryInfoResource(server, getB) {
84501
85027
  }
84502
85028
 
84503
85029
  // src/version.ts
84504
- var SERVER_VERSION = "0.5.13";
85030
+ var SERVER_VERSION = "0.5.15";
84505
85031
 
84506
85032
  // src/server.ts
84507
85033
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";
@@ -84546,14 +85072,17 @@ if (process.argv.includes("--version")) {
84546
85072
  process.exit(0);
84547
85073
  }
84548
85074
  async function main() {
84549
- const configResult = resolveBoundaryConfig(process.env);
85075
+ const localEnv = withLocalWcDefault(process.env);
85076
+ const configResult = resolveBoundaryConfig(localEnv);
84550
85077
  let boot = await buildBoundary(configResult);
84551
85078
  if (!boot.boundaryResult.ok) {
84552
85079
  process.stderr.write(`[dh-mcp] boundary not available: ${boot.boundaryResult.error.message}
84553
85080
  `);
84554
85081
  }
84555
85082
  const world = assembleWorld({
84556
- env: process.env,
85083
+ // The SAME resolved env the boundary booted from, so a `network_switch` rebuild does
85084
+ // not silently drop the phone-wallet leg the user started the session with.
85085
+ env: localEnv,
84557
85086
  configResult,
84558
85087
  boot,
84559
85088
  log: (line) => process.stderr.write(`[dh-mcp] ${line}