@gvnrdao/dh-mcp 0.5.14 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connector.js CHANGED
@@ -37,6 +37,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
37
37
  // src/boundary/upstream/shared/external-bridge/wc-transport.ts
38
38
  var wc_transport_exports = {};
39
39
  __export(wc_transport_exports, {
40
+ WC_DAPP_METADATA: () => WC_DAPP_METADATA,
40
41
  WC_SESSION_METHODS: () => WC_SESSION_METHODS,
41
42
  WcTransport: () => WcTransport,
42
43
  newIsolatedCore: () => newIsolatedCore,
@@ -72,7 +73,7 @@ function newIsolatedCore(cfg, label) {
72
73
  });
73
74
  return { core, scratch };
74
75
  }
75
- var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, EVENTS, WcTransport;
76
+ var import_core, import_sign_client, os, path, import_node_fs, WC_SESSION_METHODS, WC_DAPP_METADATA, EVENTS, WcTransport;
76
77
  var init_wc_transport = __esm({
77
78
  "src/boundary/upstream/shared/external-bridge/wc-transport.ts"() {
78
79
  "use strict";
@@ -82,6 +83,12 @@ var init_wc_transport = __esm({
82
83
  path = __toESM(require("path"));
83
84
  import_node_fs = require("fs");
84
85
  WC_SESSION_METHODS = ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"];
86
+ WC_DAPP_METADATA = {
87
+ name: "Diamond Hands MCP",
88
+ description: "Approve Diamond Hands loan operations \u2014 real funds move on your confirmation",
89
+ url: "https://app.diamondhands.credit",
90
+ icons: []
91
+ };
85
92
  EVENTS = ["accountsChanged", "chainChanged"];
86
93
  WcTransport = class _WcTransport {
87
94
  constructor(client, cfg, scratch) {
@@ -100,12 +107,7 @@ var init_wc_transport = __esm({
100
107
  const client = await import_sign_client.default.init({
101
108
  core,
102
109
  projectId: cfg.projectId,
103
- metadata: {
104
- name: "Diamond Hands MCP",
105
- description: "Human approval for Diamond Hands operations",
106
- url: "https://gvnr.xyz",
107
- icons: []
108
- }
110
+ metadata: WC_DAPP_METADATA
109
111
  });
110
112
  return new _WcTransport(client, cfg, scratch);
111
113
  }
@@ -15559,9 +15561,9 @@ ${errorReport}`);
15559
15561
  var MAX_BTC_AMOUNT = 25e6 * 1e8;
15560
15562
  var UTXO_QUERY_MAX_RETRIES = 3;
15561
15563
  var UTXO_QUERY_RETRY_DELAY_MS = 500;
15562
- var QUANTUM_WINDOW_SECONDS3 = 60;
15564
+ var QUANTUM_WINDOW_SECONDS4 = 60;
15563
15565
  var DEAD_ZONE_SECONDS2 = 16;
15564
- var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS3 - DEAD_ZONE_SECONDS2;
15566
+ var SAFE_EXECUTION_WINDOW_SECONDS = QUANTUM_WINDOW_SECONDS4 - DEAD_ZONE_SECONDS2;
15565
15567
  var SECONDS_PER_DAY = 86400;
15566
15568
  var DAYS_PER_MONTH = 30;
15567
15569
  var LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8e3;
@@ -41030,7 +41032,7 @@ function htmlPageSecurityHeaders(extra) {
41030
41032
  }
41031
41033
 
41032
41034
  // src/version.ts
41033
- var SERVER_VERSION = "0.5.14";
41035
+ var SERVER_VERSION = "0.5.15";
41034
41036
 
41035
41037
  // src/connector/siwe-oauth.ts
41036
41038
  var import_node_crypto2 = require("crypto");
@@ -41537,6 +41539,21 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
41537
41539
  var ADAPTERS = ["mock", "real"];
41538
41540
  var LATENCIES = ["zero", "realistic"];
41539
41541
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
41542
+ var WC_DISABLED = "off";
41543
+ function wcEnabled(env) {
41544
+ return resolvedWcProjectId(env) !== void 0;
41545
+ }
41546
+ function resolvedWcProjectId(env) {
41547
+ return resolveWcProjectId(env?.["DH_WC_PROJECT_ID"], []);
41548
+ }
41549
+ function resolveWcProjectId(raw, problems) {
41550
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
41551
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
41552
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
41553
+ return void 0;
41554
+ }
41555
+ return raw;
41556
+ }
41540
41557
  var NETWORK_DEFAULTS = {
41541
41558
  sepolia: {
41542
41559
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -41611,10 +41628,7 @@ function resolveBoundaryConfig(env) {
41611
41628
  }
41612
41629
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41613
41630
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41614
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41615
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41616
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41617
- }
41631
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41618
41632
  let bridgeOpenBrowser;
41619
41633
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41620
41634
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -41686,10 +41700,7 @@ function resolveRealConfig(env) {
41686
41700
  const stateDir = env["DH_STATE_DIR"];
41687
41701
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
41688
41702
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
41689
- const wcProjectId = env["DH_WC_PROJECT_ID"];
41690
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
41691
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
41692
- }
41703
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
41693
41704
  let bridgeOpenBrowser;
41694
41705
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
41695
41706
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -42129,8 +42140,15 @@ var BoundaryCore = class {
42129
42140
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
42130
42141
  }
42131
42142
  // ---- PSM reads (plan 08 Part B Phase R) ----
42132
- async getPsmStatus() {
42133
- const r = await this.deps.plugin.chain.getPsmStatus();
42143
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
42144
+ * names the coin, and this is how they learn what they may name. */
42145
+ async listPsmStablecoins() {
42146
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
42147
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
42148
+ return okEnvelope(r.value, r.source);
42149
+ }
42150
+ async getPsmStatus(p) {
42151
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
42134
42152
  if (!r.ok) return errEnvelope(failureToError(r.failure));
42135
42153
  return okEnvelope(this.psmStatusData(r.value), r.source);
42136
42154
  }
@@ -42141,7 +42159,7 @@ var BoundaryCore = class {
42141
42159
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
42142
42160
  * whenever `env.ok`. */
42143
42161
  async psmQuoteWithStatus(p) {
42144
- const statusR = await this.deps.plugin.chain.getPsmStatus();
42162
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
42145
42163
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
42146
42164
  const s = statusR.value;
42147
42165
  const toUcd = p.direction === "to-ucd";
@@ -42197,6 +42215,7 @@ var BoundaryCore = class {
42197
42215
  );
42198
42216
  }
42199
42217
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
42218
+ stablecoin: p.stablecoin,
42200
42219
  direction: toUcd ? "swap" : "redeem",
42201
42220
  amountIn: amountIn.toString()
42202
42221
  });
@@ -42263,6 +42282,7 @@ var BoundaryCore = class {
42263
42282
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
42264
42283
  if (floor === 0n) floor = 1n;
42265
42284
  const r = await this.deps.plugin.ops.psmSwap({
42285
+ stablecoin: p.stablecoin,
42266
42286
  direction: q.contractCall,
42267
42287
  amountIn: q.amountIn,
42268
42288
  minOut: floor.toString(),
@@ -42362,7 +42382,7 @@ var BoundaryCore = class {
42362
42382
  feeToken: "UCD",
42363
42383
  perBlockCap: s.maxSwapVolumePerBlock
42364
42384
  }),
42365
- toUsdc: direction({
42385
+ fromUcd: direction({
42366
42386
  minAmount: s.minRedeemAmount,
42367
42387
  maxAmount: s.maxRedeemAmount,
42368
42388
  amountUnit: ucdUnit,
@@ -44187,7 +44207,7 @@ var SINK_CONTRACTS = {
44187
44207
  PositionManager: sinkAddress("PositionManager"),
44188
44208
  UCDToken: sinkAddress("UCDToken"),
44189
44209
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
44190
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
44210
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
44191
44211
  SimplePSMV2: sinkAddress("SimplePSMV2"),
44192
44212
  UsdcToken: sinkAddress("UsdcToken"),
44193
44213
  UCDController: sinkAddress("UCDController")
@@ -44492,7 +44512,18 @@ var MockUpstreamPlugin = class {
44492
44512
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
44493
44513
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
44494
44514
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
44495
- getPsmStatus: () => this.read("mock-chain", () => {
44515
+ // The practice world models ONE stablecoin, and says so rather than implying a
44516
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
44517
+ // and naming anything but this one is refused the same way the real adapter refuses
44518
+ // an unsupported address — a mock that accepted any name would teach a habit the
44519
+ // real protocol punishes.
44520
+ listPsmStablecoins: () => this.read(
44521
+ "mock-chain",
44522
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
44523
+ ),
44524
+ getPsmStatus: (p) => this.read("mock-chain", () => {
44525
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44526
+ if (known) return known;
44496
44527
  const psm = this.world.psmSeed();
44497
44528
  return upOk(
44498
44529
  {
@@ -44517,6 +44548,8 @@ var MockUpstreamPlugin = class {
44517
44548
  );
44518
44549
  }),
44519
44550
  getPsmQuote: (p) => this.read("mock-chain", () => {
44551
+ const known = this.mockStablecoinRefusal(p.stablecoin);
44552
+ if (known) return known;
44520
44553
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
44521
44554
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
44522
44555
  })
@@ -44641,6 +44674,19 @@ var MockUpstreamPlugin = class {
44641
44674
  return apply();
44642
44675
  }
44643
44676
  /** Mode `none`: every write answers with the conversational setup invitation. */
44677
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
44678
+ * refused with the same shape the real adapter uses for an address the chain does not
44679
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
44680
+ * instead of silently succeeding and teaching that any name works. */
44681
+ mockStablecoinRefusal(stablecoin) {
44682
+ const chosen = stablecoin.trim().toLowerCase();
44683
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
44684
+ return upFail({
44685
+ kind: "rejected",
44686
+ source: "mock-chain",
44687
+ message: `'${stablecoin}' is not a PSM-supported stablecoin in this practice world \u2014 it supports 'USDC' only. Read protocol://psm for the coins a deployment actually supports; there is no default coin on any tier.`
44688
+ });
44689
+ }
44644
44690
  noneRefusal() {
44645
44691
  if (this.signer && this.signer.manager.mode() === "none") {
44646
44692
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -79524,6 +79570,19 @@ function listPositionsQuery(f) {
79524
79570
  }
79525
79571
  return { document: LIST_POSITIONS, variables: { first, skip } };
79526
79572
  }
79573
+ var SUPPORTED_STABLECOINS = `
79574
+ query SupportedStablecoins {
79575
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
79576
+ id
79577
+ address
79578
+ isSupported
79579
+ decimals
79580
+ entryFee
79581
+ exitFee
79582
+ reserves
79583
+ }
79584
+ }
79585
+ `;
79527
79586
 
79528
79587
  // src/boundary/upstream/real/psm-calls.ts
79529
79588
  var import_ethers32 = require("ethers");
@@ -79663,6 +79722,11 @@ var PsmCalls = class {
79663
79722
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
79664
79723
  });
79665
79724
  }
79725
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
79726
+ * so it must come from the token rather than from a per-network assumption. */
79727
+ symbol() {
79728
+ return this.deps.stablecoinSymbol;
79729
+ }
79666
79730
  async status() {
79667
79731
  return this.call(async () => {
79668
79732
  const s = this.deps.stablecoinAddress;
@@ -80122,13 +80186,6 @@ function buildValidationContext(network, chainId) {
80122
80186
  }
80123
80187
 
80124
80188
  // src/boundary/upstream/real/write-ops.ts
80125
- function psmMainnetWriteRefusal(network, chainId) {
80126
- return {
80127
- kind: "rejected",
80128
- source: SOURCE5,
80129
- 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.`
80130
- };
80131
- }
80132
80189
  var SOURCE5 = "real-ops";
80133
80190
  var OP_LAYOUT = "dh-op-envelope-v1";
80134
80191
  function randomNonceHex() {
@@ -80476,8 +80533,7 @@ function buildWriteOps(deps) {
80476
80533
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
80477
80534
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
80478
80535
  psmSwap: async (p) => {
80479
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
80480
- const pr = deps.psm();
80536
+ const pr = await deps.psm(p.stablecoin);
80481
80537
  if (!pr.ok) return upFail(pr.failure);
80482
80538
  const calls = pr.calls;
80483
80539
  const addr = calls.addresses();
@@ -80858,6 +80914,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80858
80914
  );
80859
80915
  }
80860
80916
  const hashHex = import_ethers38.ethers.hexlify(bytes).toLowerCase();
80917
+ const nowMs = (this.deps.clock ?? Date.now)();
80918
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
80919
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
80861
80920
  const outcome = await this.deps.bridge.requestSignature({
80862
80921
  id: (0, import_node_crypto7.randomUUID)(),
80863
80922
  kind: "personal-sign",
@@ -80869,15 +80928,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers38.ether
80869
80928
  "(identical to how diamondhands.credit signs withdrawals).",
80870
80929
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
80871
80930
  "",
80872
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
80873
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
80874
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
80875
- "itself allows. If it expires the signature is refused, the withdrawal does not",
80876
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
80877
- "start again rather than signing something you have not finished reading."
80931
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
80932
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
80933
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
80934
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
80935
+ "stay reserved until that is cleared. If the number above is already small, decline",
80936
+ "and start again rather than signing something you have not finished reading."
80878
80937
  ],
80879
80938
  expectedSigner: this.deps.borrower,
80880
80939
  chainId: this.deps.chainId,
80940
+ expiresAtSec,
80881
80941
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
80882
80942
  });
80883
80943
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -81081,13 +81141,27 @@ var RealUpstreamPlugin = class {
81081
81141
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
81082
81142
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
81083
81143
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
81084
- getPsmStatus: () => {
81085
- const r = this.psmCalls();
81086
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
81144
+ listPsmStablecoins: async () => {
81145
+ const listed = await this.listSupportedStablecoins();
81146
+ if (!listed.ok) return listed;
81147
+ const rows = await Promise.all(
81148
+ listed.rows.map(async (row) => {
81149
+ const built = await this.psmCallsFor(row.address);
81150
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
81151
+ })
81152
+ );
81153
+ return upOk(
81154
+ rows.filter((r) => r !== null),
81155
+ this.src("subgraph")
81156
+ );
81087
81157
  },
81088
- getPsmQuote: (p) => {
81089
- const r = this.psmCalls();
81090
- if (!r.ok) return Promise.resolve(upFail(r.failure));
81158
+ getPsmStatus: async (p) => {
81159
+ const r = await this.psmCallsFor(p.stablecoin);
81160
+ return r.ok ? r.calls.status() : upFail(r.failure);
81161
+ },
81162
+ getPsmQuote: async (p) => {
81163
+ const r = await this.psmCallsFor(p.stablecoin);
81164
+ if (!r.ok) return upFail(r.failure);
81091
81165
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
81092
81166
  }
81093
81167
  };
@@ -81155,12 +81229,13 @@ var RealUpstreamPlugin = class {
81155
81229
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
81156
81230
  delegationSetup: () => readOnly("delegationSetup"),
81157
81231
  delegationGrant: () => readOnly("delegationGrant"),
81158
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
81159
- // any non-sepolia network refuses typed — naming the network gate truthfully —
81160
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
81161
- // missing signer instead (the honest reason on that path).
81232
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
81233
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
81234
+ // signerless boot the honest refusal was always the missing signer; the network
81235
+ // gate sat in front of it and answered first. Now there is one reason left, and it
81236
+ // is the true one on this path.
81162
81237
  psmSwap: () => Promise.resolve(
81163
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
81238
+ upFail({
81164
81239
  kind: "signer-missing",
81165
81240
  source: "real-ops",
81166
81241
  message: "no signer configured \u2014 psmSwap signs two on-chain transactions (exact-amount approve, then swap/redeem) with the keystore signer. Set DH_KEYSTORE_PATH and DH_KEYSTORE_PASSWORD to enable it."
@@ -81277,7 +81352,7 @@ var RealUpstreamPlugin = class {
81277
81352
  session,
81278
81353
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81279
81354
  readDetails: (id) => this.readPositionDetails(id),
81280
- psm: () => this.psmCalls(),
81355
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81281
81356
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81282
81357
  });
81283
81358
  }
@@ -81411,7 +81486,7 @@ var RealUpstreamPlugin = class {
81411
81486
  session,
81412
81487
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
81413
81488
  readDetails: (id) => this.readPositionDetails(id),
81414
- psm: () => this.psmCalls(),
81489
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
81415
81490
  assertValidatorConfigured: () => this.assertValidatorConfigured()
81416
81491
  });
81417
81492
  this.opsGatewayCache.set(key, gateway);
@@ -81557,35 +81632,91 @@ var RealUpstreamPlugin = class {
81557
81632
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
81558
81633
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
81559
81634
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
81560
- psmWrapper = null;
81561
- psmCalls() {
81562
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
81635
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
81636
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
81637
+ psmWrappers = /* @__PURE__ */ new Map();
81638
+ /**
81639
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
81640
+ *
81641
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
81642
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
81643
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
81644
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
81645
+ * `getPSMStablecoins` reads the index for the same reason.
81646
+ */
81647
+ async listSupportedStablecoins() {
81648
+ const r = await this.graphProxy(
81649
+ SUPPORTED_STABLECOINS,
81650
+ {}
81651
+ );
81652
+ if (!r.ok) return r;
81653
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
81654
+ address: String(x.address).toLowerCase(),
81655
+ decimals: Number(x.decimals)
81656
+ }));
81657
+ return { ok: true, rows };
81658
+ }
81659
+ /**
81660
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
81661
+ *
81662
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
81663
+ * indexer is how the list is discovered and is not authority over it: it can lag a
81664
+ * governance removal, and acting on a stale list would build a swap the contract reverts
81665
+ * — after the user has approved it in their wallet. List from the index, verify on the
81666
+ * chain, then sign.
81667
+ */
81668
+ async psmCallsFor(stablecoinAddress) {
81669
+ const key = stablecoinAddress.toLowerCase();
81670
+ const cached = this.psmWrappers.get(key);
81671
+ if (cached) return { ok: true, calls: cached };
81563
81672
  const psmAddress = this.contracts["SimplePSMV2"];
81564
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
81565
- if (!psmAddress || !stablecoinAddress) {
81566
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
81673
+ if (!psmAddress) {
81567
81674
  return {
81568
81675
  ok: false,
81569
81676
  failure: {
81570
81677
  kind: "unavailable",
81571
81678
  source: "chain-rpc",
81572
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
81679
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
81573
81680
  }
81574
81681
  };
81575
81682
  }
81683
+ let supported;
81684
+ let symbol;
81685
+ try {
81686
+ const psm = new import_ethers39.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
81687
+ supported = await psm["supportedStablecoins"](key);
81688
+ const erc20 = new import_ethers39.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
81689
+ symbol = await erc20["symbol"]();
81690
+ } catch (e) {
81691
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
81692
+ }
81693
+ if (!supported) {
81694
+ return {
81695
+ ok: false,
81696
+ failure: {
81697
+ kind: "rejected",
81698
+ source: "chain-rpc",
81699
+ message: `${key} is not a PSM-supported stablecoin on ${this.config.network} (checked on-chain against SimplePSMV2.supportedStablecoins). Read protocol://psm for the coins this deployment actually supports.`
81700
+ }
81701
+ };
81702
+ }
81703
+ const stablecoinAddress2 = key;
81576
81704
  const ucdTokenAddress = this.contracts["UCDToken"];
81577
81705
  const ucdControllerAddress = this.contracts["UCDController"];
81578
- this.psmWrapper = new PsmCalls({
81706
+ const built = new PsmCalls({
81579
81707
  provider: this.provider,
81580
81708
  psmAddress,
81581
- stablecoinAddress,
81582
- stablecoinSymbol: "USDC",
81709
+ stablecoinAddress: stablecoinAddress2,
81710
+ // Read from the token, never assumed. The old value was the literal "USDC", which
81711
+ // stops being true the moment a second coin is supported.
81712
+ stablecoinSymbol: symbol,
81583
81713
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
81584
81714
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
81585
81715
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
81586
81716
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
81587
81717
  });
81588
- return { ok: true, calls: this.psmWrapper };
81718
+ this.psmWrappers.set(key, built);
81719
+ return { ok: true, calls: built };
81589
81720
  }
81590
81721
  src(id) {
81591
81722
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -81848,6 +81979,7 @@ function renderApprovalPage(sessionId, nonce) {
81848
81979
  <div id="request" class="hidden">
81849
81980
  <div id="action" class="action"></div>
81850
81981
  <div id="card" class="card"></div>
81982
+ <div id="deadline" class="status hidden"></div>
81851
81983
  <button id="approve">Approve in wallet</button>
81852
81984
  <button id="reject">Reject</button>
81853
81985
  </div>
@@ -81880,10 +82012,19 @@ const statusEl = document.getElementById("status");
81880
82012
  const requestEl = document.getElementById("request");
81881
82013
  const actionEl = document.getElementById("action");
81882
82014
  const cardEl = document.getElementById("card");
82015
+ const approveEl = document.getElementById("approve");
82016
+ const rejectEl = document.getElementById("reject");
82017
+ const deadlineEl = document.getElementById("deadline");
82018
+ let deadlineTimer = null;
81883
82019
  const walletEl = document.getElementById("wallet");
81884
82020
  let account = null;
81885
82021
  let chainId = null;
81886
82022
  let current = null;
82023
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
82024
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
82025
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
82026
+ // card the page never renders is one the human can neither read nor reject.
82027
+ const pending = new Map();
81887
82028
 
81888
82029
  function post(path, body) {
81889
82030
  return fetch(path, {
@@ -81946,43 +82087,135 @@ async function onAccountsChanged(accounts) {
81946
82087
  account = (accounts && accounts[0]) || null;
81947
82088
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81948
82089
  showWallet();
81949
- clearRequest("Wallet changed \u2014 pending request invalidated.");
82090
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
81950
82091
  }
81951
82092
 
81952
82093
  async function onChainChanged(cid) {
81953
82094
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
81954
82095
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
81955
82096
  showWallet();
81956
- clearRequest("Network changed \u2014 pending request invalidated.");
82097
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
81957
82098
  }
81958
82099
 
81959
82100
  function listen() {
81960
82101
  const es = new EventSource(BASE + "events?s=" + SESSION);
81961
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
82102
+ es.onmessage = (ev) => {
82103
+ const next = JSON.parse(ev.data);
82104
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
82105
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
82106
+ pending.set(next.id, next);
82107
+ showPending();
82108
+ };
81962
82109
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
81963
82110
  }
81964
82111
 
82112
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
82113
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
82114
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
82115
+ // gets approved.
82116
+ function pickPending() {
82117
+ const held = current ? pending.get(current.id) : undefined;
82118
+ if (held && held.mirror !== true) return held;
82119
+ let best = held || null;
82120
+ pending.forEach((frame) => {
82121
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
82122
+ });
82123
+ return best;
82124
+ }
82125
+
82126
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
82127
+ function showPending(emptyText) {
82128
+ const next = pickPending();
82129
+ if (!next) {
82130
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
82131
+ // an expiry for a ceremony that is already decided.
82132
+ stopDeadline();
82133
+ current = null;
82134
+ requestEl.classList.add("hidden");
82135
+ if (emptyText) showStatus(emptyText);
82136
+ return;
82137
+ }
82138
+ current = next;
82139
+ renderRequest();
82140
+ }
82141
+
81965
82142
  function renderRequest() {
81966
82143
  actionEl.textContent = current.action;
81967
82144
  cardEl.textContent = current.card.join("\\n");
82145
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
82146
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
82147
+ // server-side, which is the actual boundary.
82148
+ const mirrored = current.mirror === true;
82149
+ approveEl.classList.toggle("hidden", mirrored);
82150
+ rejectEl.classList.remove("hidden");
81968
82151
  requestEl.classList.remove("hidden");
81969
- showStatus("Review the operation below. Nothing signs without your approval.");
82152
+ showStatus(mirrored
82153
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
82154
+ : "Review the operation below. Nothing signs without your approval.");
82155
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
82156
+ // card promoted after another settles gets its own clock, not the previous one's.
82157
+ startDeadline();
82158
+ }
82159
+
82160
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
82161
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
82162
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
82163
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
82164
+ // honest without it needing to know anything about quantum windows.
82165
+ function stopDeadline() {
82166
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82167
+ deadlineEl.classList.add("hidden");
82168
+ }
82169
+
82170
+ function startDeadline() {
82171
+ stopDeadline();
82172
+ if (!current || typeof current.expiresAtSec !== "number") return;
82173
+ const tick = () => {
82174
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
82175
+ if (left > 0) {
82176
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
82177
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
82178
+ } else {
82179
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
82180
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
82181
+ // after. The button is deliberately left enabled \u2014 declining is still the right
82182
+ // action and the page must not trap them.
82183
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
82184
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
82185
+ }
82186
+ deadlineEl.classList.remove("hidden");
82187
+ };
82188
+ tick();
82189
+ deadlineTimer = setInterval(tick, 1000);
81970
82190
  }
81971
82191
 
82192
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
82193
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
82194
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
81972
82195
  function clearRequest(text) {
81973
- current = null;
81974
- requestEl.classList.add("hidden");
81975
- showStatus(text);
82196
+ if (current) pending.delete(current.id);
82197
+ showPending(text);
82198
+ }
82199
+
82200
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
82201
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
82202
+ // stays readable and rejectable.
82203
+ function invalidatePageRequests(text) {
82204
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
82205
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
81976
82206
  }
81977
82207
 
81978
- document.getElementById("reject").onclick = async () => {
82208
+ rejectEl.onclick = async () => {
81979
82209
  if (!current) return;
81980
82210
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
81981
82211
  clearRequest("Rejected. Waiting for the next request\u2026");
81982
82212
  };
81983
82213
 
81984
- document.getElementById("approve").onclick = async () => {
82214
+ approveEl.onclick = async () => {
81985
82215
  if (!current) return;
82216
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
82217
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
82218
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
81986
82219
  const req = current;
81987
82220
  try {
81988
82221
  if (req.kind === "transaction") {
@@ -81999,7 +82232,10 @@ document.getElementById("approve").onclick = async () => {
81999
82232
  const fbody = await fr.json();
82000
82233
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
82001
82234
  const fresh = fbody.request;
82002
- // \u2026re-render what will actually sign\u2026
82235
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
82236
+ // another card arriving while the wallet popup is open re-picks from there, and the
82237
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
82238
+ pending.set(fresh.id, fresh);
82003
82239
  current = fresh; renderRequest();
82004
82240
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
82005
82241
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -82154,9 +82390,6 @@ var SignatureBridge = class {
82154
82390
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
82155
82391
  maxPending;
82156
82392
  attachGraceMs;
82157
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
82158
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
82159
- lastAttachedMs = 0;
82160
82393
  server = null;
82161
82394
  port = 0;
82162
82395
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -82307,13 +82540,16 @@ var SignatureBridge = class {
82307
82540
  enqueuedMs: now,
82308
82541
  resolve,
82309
82542
  settled: false,
82310
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
82543
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
82544
+ owner: this.wcActive ? "wc" : "page",
82545
+ dispatched: false,
82546
+ lastAttachedMs: now
82311
82547
  };
82312
82548
  this.pending.set(request.id, entry);
82313
- if (this.wcActive) {
82549
+ if (entry.owner === "wc") {
82314
82550
  void this.driveWc(entry);
82315
82551
  } else {
82316
- this.push(request);
82552
+ this.pushEntry(entry);
82317
82553
  }
82318
82554
  });
82319
82555
  }
@@ -82334,10 +82570,16 @@ var SignatureBridge = class {
82334
82570
  enqueuedMs: now,
82335
82571
  resolve,
82336
82572
  settled: false,
82337
- collect
82573
+ collect,
82574
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
82575
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
82576
+ // ceremony could not reach quorum through the very pages it is broadcast to.
82577
+ owner: "both",
82578
+ dispatched: false,
82579
+ lastAttachedMs: now
82338
82580
  };
82339
82581
  this.pending.set(request.id, entry);
82340
- this.push(request);
82582
+ this.pushEntry(entry);
82341
82583
  if (this.wcActive) void this.driveWcCollection(entry);
82342
82584
  });
82343
82585
  }
@@ -82376,7 +82618,9 @@ var SignatureBridge = class {
82376
82618
  }
82377
82619
  try {
82378
82620
  if (req.kind === "transaction") {
82621
+ this.pushEntry(entry);
82379
82622
  const tx2 = req.tx;
82623
+ entry.dispatched = true;
82380
82624
  const txHash = await transport.request("eth_sendTransaction", [
82381
82625
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
82382
82626
  ]);
@@ -82388,11 +82632,22 @@ var SignatureBridge = class {
82388
82632
  req.card = fresh.card;
82389
82633
  }
82390
82634
  const ps = req.personalSign;
82635
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
82636
+ this.settle(entry, {
82637
+ status: "invalidated",
82638
+ reason: `this step signs a 32-byte hash your wallet cannot decode, and no approval page is open to show you what it authorizes \u2014 open ${this.url()} and re-run the withdrawal with loan_withdraw_retry (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`
82639
+ });
82640
+ return;
82641
+ }
82642
+ this.pushEntry(entry);
82643
+ entry.dispatched = true;
82391
82644
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
82392
82645
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82393
82646
  } else {
82647
+ this.pushEntry(entry);
82394
82648
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
82395
82649
  const payload = withEip712DomainType2(req.typedData);
82650
+ entry.dispatched = true;
82396
82651
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
82397
82652
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
82398
82653
  }
@@ -82412,30 +82667,55 @@ var SignatureBridge = class {
82412
82667
  * with a live attachment is in use and must never be evicted. */
82413
82668
  attachedNow() {
82414
82669
  if (this.wcActive) return true;
82415
- for (const s of this.sessions.values()) if (s.sse) return true;
82670
+ return this.pageAttached();
82671
+ }
82672
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
82673
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
82674
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
82675
+ * WalletConnect and must stay global for the connector's eviction predicate. */
82676
+ pageAttached() {
82677
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
82416
82678
  return false;
82417
82679
  }
82680
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
82681
+ * predicate said "a WC session is attached", which is true but irrelevant to a
82682
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
82683
+ * out the full expiry instead of failing fast at the grace. */
82684
+ attachedFor(entry) {
82685
+ if (entry.owner === "wc") return this.wcActive;
82686
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
82687
+ return this.pageAttached();
82688
+ }
82418
82689
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
82419
82690
  * interval; tests call it directly with the injected clock advanced. Order matters:
82420
82691
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
82421
82692
  sweep() {
82422
82693
  const now = this.clock();
82423
- const attached = this.attachedNow();
82424
- if (attached) this.lastAttachedMs = now;
82425
82694
  for (const entry of this.pending.values()) {
82426
82695
  if (entry.settled) continue;
82427
82696
  if (now >= entry.deadlineMs) {
82428
82697
  this.settle(entry, { status: "expired" });
82429
82698
  continue;
82430
82699
  }
82431
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
82432
- this.settle(entry, {
82433
- status: "invalidated",
82434
- 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`
82435
- });
82700
+ if (this.attachedFor(entry)) {
82701
+ entry.lastAttachedMs = now;
82702
+ continue;
82436
82703
  }
82704
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
82705
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
82437
82706
  }
82438
82707
  }
82708
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
82709
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
82710
+ unattendedReason(entry) {
82711
+ if (entry.dispatched && entry.request.kind === "transaction") {
82712
+ return "the mobile wallet holding this transaction went away before answering, but it was already asked to send it \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice.";
82713
+ }
82714
+ if (entry.owner === "wc") {
82715
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
82716
+ }
82717
+ return `no wallet approval page is attached to this bridge (it may have been closed) \u2014 open ${this.url()} in the browser, connect the wallet, and retry the operation`;
82718
+ }
82439
82719
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
82440
82720
  walletConnectActive() {
82441
82721
  return this.wcActive;
@@ -82559,6 +82839,7 @@ var SignatureBridge = class {
82559
82839
  if (info && refusal) {
82560
82840
  this.wcActive = false;
82561
82841
  this.rebuildSharedWallet();
82842
+ this.demoteWcEntries();
82562
82843
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
82563
82844
  `);
82564
82845
  return;
@@ -82568,7 +82849,10 @@ var SignatureBridge = class {
82568
82849
  if (info === null) {
82569
82850
  for (const entry of this.pending.values()) {
82570
82851
  if (!entry.settled && !entry.collect) {
82571
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
82852
+ this.settle(entry, {
82853
+ status: "invalidated",
82854
+ reason: entry.dispatched && entry.request.kind === "transaction" ? "the WalletConnect session disconnected after being asked to send this transaction \u2014 it may have broadcast. Check the chain (or your wallet's activity) before retrying, or you may pay twice." : "the WalletConnect session disconnected"
82855
+ });
82572
82856
  }
82573
82857
  }
82574
82858
  }
@@ -82640,9 +82924,7 @@ var SignatureBridge = class {
82640
82924
  session.sse?.end();
82641
82925
  session.sse = res;
82642
82926
  for (const entry of this.pending.values()) {
82643
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
82644
-
82645
- `);
82927
+ if (!entry.settled) res.write(this.wireFor(entry));
82646
82928
  }
82647
82929
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
82648
82930
  keepAlive.unref();
@@ -82718,10 +83000,36 @@ var SignatureBridge = class {
82718
83000
  }
82719
83001
  const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && session.wallet && prev.account.toLowerCase() !== session.wallet.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && session.wallet && prev.chainId !== session.wallet.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
82720
83002
  for (const entry of this.pending.values()) {
82721
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
83003
+ if (entry.settled || entry.collect) continue;
83004
+ if (this.ownedByWc(entry)) continue;
83005
+ this.settle(entry, { status: "invalidated", reason });
82722
83006
  }
82723
83007
  this.ok(res);
82724
83008
  }
83009
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
83010
+ * session hands the request back to the page rather than stranding it. */
83011
+ ownedByWc(entry) {
83012
+ if (entry.owner !== "wc") return false;
83013
+ return this.wcActive || entry.dispatched;
83014
+ }
83015
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
83016
+ * them so the card stops rendering read-only. Collections are already `both`.
83017
+ *
83018
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
83019
+ * phone is still holding does not replace one wallet with another, it adds a second: the
83020
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
83021
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
83022
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
83023
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
83024
+ * false for them, and `unattendedReason` says plainly that the phone may already have
83025
+ * acted. */
83026
+ demoteWcEntries() {
83027
+ for (const entry of this.pending.values()) {
83028
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
83029
+ entry.owner = "page";
83030
+ this.pushEntry(entry);
83031
+ }
83032
+ }
82725
83033
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
82726
83034
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
82727
83035
  async onFinalize(body, res) {
@@ -82735,6 +83043,10 @@ var SignatureBridge = class {
82735
83043
  this.deny(res, 400, "finalize applies only to personal-sign requests");
82736
83044
  return;
82737
83045
  }
83046
+ if (this.ownedByWc(entry)) {
83047
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
83048
+ return;
83049
+ }
82738
83050
  if (entry.finalize) {
82739
83051
  let fresh;
82740
83052
  try {
@@ -82761,10 +83073,22 @@ var SignatureBridge = class {
82761
83073
  return;
82762
83074
  }
82763
83075
  if (body["approved"] !== true) {
83076
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
83077
+ this.settle(entry, {
83078
+ status: "invalidated",
83079
+ reason: "cancelled on the approval page, but a mobile wallet was already asked to send this transaction \u2014 it may have broadcast already. Check the chain (or your wallet's activity) before retrying, or you may pay twice."
83080
+ });
83081
+ this.ok(res);
83082
+ return;
83083
+ }
82764
83084
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
82765
83085
  this.ok(res);
82766
83086
  return;
82767
83087
  }
83088
+ if (this.ownedByWc(entry)) {
83089
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
83090
+ return;
83091
+ }
82768
83092
  const account = String(body["account"] ?? "");
82769
83093
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
82770
83094
  this.deny(res, 400, "approved result requires the signing account");
@@ -82801,11 +83125,20 @@ var SignatureBridge = class {
82801
83125
  this.pending.delete(entry.request.id);
82802
83126
  entry.resolve(outcome);
82803
83127
  }
82804
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
82805
- push(request) {
82806
- const data = `data: ${JSON.stringify(request)}
83128
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
83129
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
83130
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
83131
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
83132
+ * a permanently read-only card that nobody is allowed to decide. */
83133
+ wireFor(entry) {
83134
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
83135
+ return `data: ${JSON.stringify(payload)}
82807
83136
 
82808
83137
  `;
83138
+ }
83139
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
83140
+ pushEntry(entry) {
83141
+ const data = this.wireFor(entry);
82809
83142
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82810
83143
  }
82811
83144
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -83288,7 +83621,7 @@ var FIELD_GLOSSARY = {
83288
83621
  originationFeeBps: "mint fee in basis points of the borrowed amount \u2014 ADDED TO DEBT (200 = 2%)",
83289
83622
  extensionFeeRateBps: "extension-fee CEILING in bps of current debt per renewal (unused origination credit reduces it)",
83290
83623
  // ---- psm quote ----
83291
- direction: "'to-ucd' = pay stablecoin, receive UCD; 'to-usdc' = pay UCD, receive stablecoin",
83624
+ direction: "'to-ucd' = pay stablecoin, receive UCD; 'from-ucd' = pay UCD, receive stablecoin",
83292
83625
  contractCall: "the on-chain function this direction maps to (swap | redeem) \u2014 vocabulary honesty",
83293
83626
  amountIn: "what you pay, in amountInUnit of amountInToken (smallest units)",
83294
83627
  amountInToken: "the token you pay with",
@@ -83386,11 +83719,14 @@ var LOCAL_GUIDE_DEPLOYMENT = {
83386
83719
  // speak the full vocabulary and let the existing adapter prose ("PRACTICE-ONLY today —
83387
83720
  // on the real adapter these modes refuse") carry the narrower adapter axis.
83388
83721
  signerModes: GUIDE_SIGNER_MODES,
83389
- // FALSE, because `DH_WC_PROJECT_ID` is unset in a default install and the WalletConnect
83390
- // leg genuinely is not there until an operator configures it. The first draft of this line
83391
- // said `true` "to keep the walkthrough complete", which is exactly the overclaim C-44 is
83392
- // about — the default rendering would have promised a QR that most installs cannot show.
83393
- // A live boot derives this from env either way (network-switch.ts).
83722
+ // FALSE as the FALLBACK, which is no longer the same statement as "a default install has
83723
+ // no WalletConnect". Since 2026-09-10 a local install ships a default project id
83724
+ // (`config.ts` DEFAULT_WC_PROJECT_ID), so the real answer for a real local boot is now
83725
+ // usually `true` — and a live boot derives exactly that, from the same resolution the
83726
+ // bridge uses (`network-switch.ts` → `wcEnabled`). This constant is only reached when
83727
+ // nobody supplied a deployment at all, and understating a capability there is the safe
83728
+ // direction: the first draft said `true` "to keep the walkthrough complete", which is the
83729
+ // overclaim C-44 is about — promising a QR the build cannot show.
83394
83730
  walletConnect: false
83395
83731
  };
83396
83732
  function servedNetworks(d) {
@@ -83401,7 +83737,7 @@ function servedNetworks(d) {
83401
83737
  return "sepolia (PRACTICE money) and mainnet (REAL MONEY) \u2014 `network_switch` moves between them, and every switch states which is live";
83402
83738
  }
83403
83739
  if (mainnet) {
83404
- return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing, and PSM swaps are refused on mainnet), and there is no practice network on this deployment to fall back to";
83740
+ return "mainnet ONLY \u2014 every fund-moving operation this deployment enables spends REAL MONEY (reads move nothing; PSM swaps are NOT an exception \u2014 they execute here and move real funds), and there is no practice network on this deployment to fall back to";
83405
83741
  }
83406
83742
  return "sepolia only \u2014 the real contracts on the test network, so the ceremonies are real and the money is PRACTICE";
83407
83743
  }
@@ -83480,13 +83816,14 @@ function switchNetworkRules(d) {
83480
83816
  the human approves the card. sepolia = practice funds; mainnet = REAL MONEY.
83481
83817
  - NOTHING carries across: positions, vaults, signer bindings, logins are per-network.
83482
83818
  A sepolia position does not exist on mainnet and vice versa.
83483
- - Fund-moving loan operations work on BOTH networks \u2014 on mainnet they move REAL money,
83484
- and every one still requires the user's explicit confirmation plus the signer
83485
- ceremony. The exception is PSM swaps: sepolia-only, refused on mainnet.`;
83819
+ - Fund-moving operations work on BOTH networks \u2014 loan operations AND PSM swaps alike. On
83820
+ mainnet they move REAL money, and every one still requires the user's explicit
83821
+ confirmation plus the signer ceremony. A PSM swap also requires the caller to NAME the
83822
+ stablecoin; that name is checked against the PSM's on-chain set before anything is
83823
+ signed.`;
83486
83824
  }
83487
83825
  const only = d.networks[0];
83488
83826
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83489
- 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.";
83490
83827
  return `- \`network_switch switch { network, confirmed: true }\` exists, but ${only} is the ONLY
83491
83828
  network this deployment is rolled out to \u2014 every other target is REFUSED with that
83492
83829
  rollout truth. There is nothing to switch TO here; never offer the user another world.
@@ -83495,7 +83832,9 @@ function switchNetworkRules(d) {
83495
83832
  belong to ${only} and would not exist anywhere else.
83496
83833
  - Fund-moving loan operations run on ${only}, each still requiring the user's explicit
83497
83834
  confirmation plus the signer ceremony.
83498
- - ${psm}`;
83835
+ - PSM swaps run on ${only} too, under that same confirmation and signer ceremony \u2014 and
83836
+ the caller must NAME the stablecoin, checked against the PSM's on-chain set before
83837
+ anything is signed.`;
83499
83838
  }
83500
83839
  function wrongNetworkTroubleshootingRow(d) {
83501
83840
  if (d.networks.length > 1) {
@@ -83515,14 +83854,18 @@ function switchNetworkIndexLine(d) {
83515
83854
  const money = d.networks.includes("mainnet") ? "REAL MONEY" : "PRACTICE funds";
83516
83855
  return `- switch-network \u2014 this deployment is rolled out to ${only} alone (${money}): \`network_switch status\` states the live world, and every other target is refused with that rollout truth`;
83517
83856
  }
83518
- function psmAvailabilityNote(d) {
83519
- if (d.networks.includes("sepolia")) return "";
83520
- return `**Not executable on this deployment.** The PSM write port refuses on every network
83521
- but sepolia, which this deployment is not rolled out to \u2014 quotes (\`psm_quote\`) and
83522
- \`protocol://psm\` reads still answer, but no swap can execute here. Everything below is
83523
- the mechanism, not an offer: say so before a user plans around it.
83524
-
83525
- `;
83857
+ function psmStablecoinRealityNote(d) {
83858
+ if (d.networks.includes("sepolia")) {
83859
+ return `**Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83860
+ \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83861
+ the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83862
+ the money is real. On mainnet the stablecoin is real Circle USDC.`;
83863
+ }
83864
+ return `**Real money, and no practice path from here.** This deployment is not rolled out to
83865
+ sepolia, so the self-mintable MOCK USDC that funds practice swaps there is out of reach \u2014
83866
+ every swap executed on this deployment moves real Circle USDC and real UCD.
83867
+ \`protocol://psm\` states the token's kind (\`mock\` vs \`circle\`) and address, so you never
83868
+ have to guess whether the money is real.`;
83526
83869
  }
83527
83870
  function authorizationModeBullets(d) {
83528
83871
  const bullets = [];
@@ -83636,7 +83979,7 @@ on the real adapter and the mock.
83636
83979
  **The walkthrough:**
83637
83980
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
83638
83981
  desktop browser; ${approvalPageLocation(d)}
83639
- 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code." : ". " + phoneWalletOffer(d) + "."}
83982
+ 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
83640
83983
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
83641
83984
  login ceremony explicitly (one typed-data signature in the wallet).
83642
83985
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -83675,7 +84018,14 @@ on the real adapter and the mock.
83675
84018
  hash the SDK builds internally, which the approval page shows bare and says plainly it
83676
84019
  cannot decode (the production web app signs the same way). Tell the user before that
83677
84020
  ONE popup. Do not describe the typed phase as blind: overstating it teaches them to
83678
- expect an unreadable card and click through the readable one.
84021
+ expect an unreadable card and click through the readable one.${d.walletConnect ? `
84022
+ - **On a PHONE wallet that EXECUTE step needs the approval page open, and refuses without
84023
+ it.** The phone can only render the bare 32 bytes; everything that makes them meaningful
84024
+ \u2014 which operation, that they cannot be decoded, that the window is under a minute \u2014 lives
84025
+ on the card, and the page is the only surface that shows it. With no page attached the
84026
+ step fails with that reason rather than asking anyone to sign blind. Nothing is lost: the
84027
+ coins stay in the vault and \`loan_withdraw_retry\` re-runs it with a fresh stamp. Tell a
84028
+ mobile user to keep the page open BEFORE they start a withdrawal, not after it refuses.` : ""}
83679
84029
  - **The READABLE phase can be asked for up to THREE times.** Its authorization is only
83680
84030
  valid inside a short protocol timing window, and the SDK re-signs on a miss \u2014 up to 3
83681
84031
  attempts, each a FRESH typed-data card. So a slow approval does not fail; it comes
@@ -83756,9 +84106,9 @@ State flow: ${STATE_FLOW_LINE} \u2014 see \`safety\`.`,
83756
84106
 
83757
84107
  Every fund-moving result carries an \`authorization.card\` \u2014 the exact text that was
83758
84108
  signed, amounts included. Read it back when the user asks what happened.`,
83759
- psm: (d) => `# PSM \u2014 exchanging UCD \u2194 USDC (the peg-stability module)
84109
+ psm: (d) => `# PSM \u2014 exchanging UCD \u2194 a stablecoin (the peg-stability module)
83760
84110
 
83761
- ${psmAvailabilityNote(d)}The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
84111
+ The PSM is the protocol's exchange window between UCD and USDC, near the peg. Two
83762
84112
  directions, in user words:
83763
84113
 
83764
84114
  - **"Get UCD for my USDC"** (\`psm_quote\` direction \`to-ucd\`): you pay USDC, the PSM
@@ -83766,20 +84116,27 @@ directions, in user words:
83766
84116
  The **entry fee is charged IN UCD**: a percentage (basis points) of the gross converted
83767
84117
  UCD, taken before it reaches you \u2014 e.g. at a 1% fee, 100 USDC converts to 100 UCD gross
83768
84118
  and you receive 99 UCD.
83769
- - **"Get USDC back"** (\`psm_quote\` direction \`to-usdc\`): you return UCD (it is burned)
83770
- and the PSM pays you USDC **from its live reserves**. The **exit fee is charged IN
83771
- USDC**, deducted from what you receive; the contract caps it at 10%. A redemption is
83772
- only possible while reserves cover the payout \u2014 the quote shows live reserves, and a
83773
- shortfall refuses with both figures (available vs required).
84119
+ - **"Get my stablecoin back"** (\`psm_quote\` direction \`from-ucd\`): you return UCD (it is
84120
+ burned) and the PSM pays you that stablecoin **from its live reserves**. The **exit fee
84121
+ is charged IN the stablecoin**, deducted from what you receive; the contract caps it at
84122
+ 10%. A redemption is only possible while reserves cover the payout \u2014 the quote shows live
84123
+ reserves, and a shortfall refuses with both figures (available vs required).
84124
+
84125
+ **Both tools REQUIRE a \`stablecoin\`** (symbol like \`USDC\`, or a 0x address). There is no
84126
+ default and that is deliberate: the PSM can carry several coins, each with its own
84127
+ reserves, fees and limits, so picking one silently would move someone's money through a
84128
+ token they never chose. \`protocol://psm\` lists every supported coin \u2014 read the names from
84129
+ there rather than guessing one.
83774
84130
 
83775
84131
  The two fees are independent and live in DIFFERENT tokens \u2014 always say which token a fee
83776
84132
  is in. Rates and fees are configuration (\`protocol://psm\` shows them; exchange rate
83777
84133
  1e18 = 1:1) and can be changed by protocol governance.
83778
84134
 
83779
84135
  **Limits and switches** (all visible in \`protocol://psm\`):
83780
- - Each direction has a min and max PER OPERATION. Unit trap: to-ucd limits are in USDC
83781
- units, to-usdc limits are in UCD. A max of 0 means that direction is DISABLED.
83782
- - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the to-usdc
84136
+ - Each direction has a min and max PER OPERATION, **per coin**. Unit trap: to-ucd limits
84137
+ are in the stablecoin's units, from-ucd limits are in UCD. A max of 0 means that
84138
+ direction is DISABLED.
84139
+ - \`paused\` kills BOTH directions; \`redeemEnabled = false\` kills ONLY the from-ucd
83783
84140
  direction (swaps to UCD keep working). These are different switches \u2014 name the right one.
83784
84141
  - Per-block volume caps may exist per direction ("uncapped" when none is set).
83785
84142
 
@@ -83788,23 +84145,26 @@ floor \u2014 submitting with a zero floor is refused by the contract. Fees or th
83788
84145
  change between your quote and execution; the floor makes a drifted execution REFUSE
83789
84146
  rather than silently deliver less than quoted.
83790
84147
 
83791
- **Practice funding (sepolia):** the sepolia stablecoin is a MOCK USDC with a public
83792
- \`mint\` \u2014 you can create practice USDC for yourself, self-serve. \`protocol://psm\` states
83793
- the token's kind (\`mock\` vs \`circle\`) and address so you never have to guess whether
83794
- the money is real. On mainnet the stablecoin is real Circle USDC.
84148
+ ${psmStablecoinRealityNote(d)}
83795
84149
 
83796
84150
  **Executing (\`psm_swap\`):** an exchange is TWO on-chain ceremonies, both shown in the
83797
84151
  result. (1) An **exact-amount approval** of the input token \u2014 never unlimited. The spender
83798
84152
  differs by direction, and that is contract truth, not a quirk: for **to-ucd** you approve
83799
- USDC to the **PSM contract** (it pulls the USDC it converts); for **to-usdc** you approve
83800
- UCD to the **UCDController** (the PSM burns your UCD through the controller). (2) The
83801
- swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
84153
+ the stablecoin to the **PSM contract** (it pulls the coin it converts); for **from-ucd**
84154
+ you approve UCD to the **UCDController** (the PSM burns your UCD through the
84155
+ controller). (2) The swap/redeem itself, carrying a minimum-out floor = the live quote minus a 100 bps
83802
84156
  tolerance; if fees or the rate drifted beyond that between quote and execution, the
83803
84157
  contract refuses \u2014 you never silently receive less. Output always lands at the signer's
83804
84158
  own address. If you approve step 1 but decline step 2, the exact-amount allowance remains
83805
84159
  standing \u2014 it authorizes only that amount and nothing else; the result says so plainly.
83806
- On the real protocol, PSM writes run on sepolia ONLY \u2014 mainnet PSM writes are refused
83807
- (the PSM-specific sepolia-only anchor; loan operations are not affected).`,
84160
+ PSM writes are wired on every real network \u2014 mainnet INCLUDED. On mainnet a swap moves
84161
+ REAL money \u2014 real Circle USDC and real UCD. What stands between the user and a
84162
+ wrong move is not a network gate: it is the stablecoin they NAMED (verified against the
84163
+ PSM's supported set on-chain before anything is signed), the explicit confirmation plus
84164
+ signer ceremony every fund-moving operation needs, and the contract's own bounds \u2014 the
84165
+ per-operation and per-block limits,
84166
+ \`paused\` / \`redeemEnabled\`, and live reserves. Say the money reality before the first
84167
+ mainnet swap, not after.`,
83808
84168
  authorization: (d) => `# Authorization \u2014 who signs, and what a signature means
83809
84169
 
83810
84170
  Every fund-moving operation needs TWO things, always in this order:
@@ -84063,9 +84423,11 @@ ${offers(d, "keystore") ? `- **SIGNER_UNAVAILABLE** \u2014 no authorization mode
84063
84423
  - **"Not logged in" on a read** \u2014 authenticated reads NEVER pop the wallet; the remedy is
84064
84424
  the same one: "connect my wallet" (\`signer_setup connect\`). An EXPIRED login refuses
84065
84425
  the same way \u2014 reconnect on the user's word.`}
84066
- ${d.networks.includes("mainnet") ? `- **PSM write refused on mainnet** \u2014 PSM swaps are sepolia-only (a deliberate anchor,
84067
- 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
84068
- anchor, not a bug); loan operations are unaffected. Reads keep working everywhere.`}
84426
+ - **PSM swap refused** \u2014 never a network gate any more: PSM writes run on every network
84427
+ this build serves. The message names the real cause \u2014 a \`stablecoin\` the PSM does not
84428
+ support (checked on-chain before signing), \`paused\` or \`redeemEnabled = false\`, a
84429
+ per-operation or per-block limit, reserves too thin for the redemption, or no signer.
84430
+ Fix the named cause; reads (\`psm_quote\`, \`protocol://psm\`) keep working regardless.
84069
84431
  ${wrongNetworkTroubleshootingRow(d)}
84070
84432
  - **External-mode withdraw shows a bare hash** \u2014 that is by design (site parity): the
84071
84433
  SDK builds the execute-phase hash internally, so the page cannot decode it. ONE blind
@@ -84223,12 +84585,13 @@ function guideDeployment(overrides, env) {
84223
84585
  tier: overrides?.bridgeMount ? "hosted" : "local",
84224
84586
  networks: overrides?.allowedNetworks ?? LOCAL_GUIDE_DEPLOYMENT.networks,
84225
84587
  signerModes: overrides?.externalOnly ? EXTERNAL_ONLY_SIGNER_MODES : LOCAL_GUIDE_DEPLOYMENT.signerModes,
84226
- // C-44 F8, the fourth derivation. Read from the SAME env var the bridge reads
84227
- // (boundary/config.ts `DH_WC_PROJECT_ID` → BridgeOptions.wc), so the guide cannot promise
84228
- // a phone-wallet QR that `/wc-pairing` would answer 404 for. Deriving it rather than
84229
- // hard-coding a tier default is what keeps the guide and `/auth.md` from disagreeing
84230
- // about the same server, which is exactly what they did before this line existed.
84231
- walletConnect: Boolean(env?.["DH_WC_PROJECT_ID"])
84588
+ // C-44 F8, the fourth derivation. Resolved through the SAME function the bridge's
84589
+ // config goes through (`wcEnabled` wraps it), so the guide cannot promise a phone-wallet
84590
+ // QR that `/wc-pairing` would answer 404 for. A bare `Boolean(env[...])` was that test
84591
+ // until the leg gained a shipped default and an `off` sentinel — after which absence no
84592
+ // longer means off, and "off" itself is truthy. Deriving rather than hard-coding a tier
84593
+ // default is what keeps the guide and `/auth.md` agreeing about the same server.
84594
+ walletConnect: wcEnabled(env)
84232
84595
  };
84233
84596
  }
84234
84597
  function assembleWorld(opts) {
@@ -84868,39 +85231,45 @@ function registerPsmTools(server, getB) {
84868
85231
  server,
84869
85232
  "psm_quote",
84870
85233
  {
84871
- title: "Quote a UCD \u2194 USDC exchange (peg-stability module)",
84872
- description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay USDC, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'to-usdc' = pay UCD, receive USDC back from the PSM's reserves; the EXIT fee is charged IN USDC and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). The result names both amounts, the fee WITH its token, and (to-usdc) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
85234
+ title: "Quote a UCD \u2194 stablecoin exchange (peg-stability module)",
85235
+ description: "Quote the PSM exchange (read-only, live on-chain views \u2014 never an indexer). direction 'to-ucd' = pay the stablecoin, receive UCD; the ENTRY fee is charged IN UCD on the gross converted amount. direction 'from-ucd' = pay UCD, receive the stablecoin back from the PSM's reserves; the EXIT fee is charged IN that stablecoin and deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). The result names both amounts, the fee WITH its token, and (from-ucd) the live reserves. Executing an exchange on-chain requires a minimum-out floor \u2014 a zero floor is refused \u2014 so a drifted quote refuses at execution instead of delivering less. Limits and kill-switches: protocol://psm.",
84873
85236
  inputSchema: {
84874
- 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)"),
84875
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals.")
85237
+ stablecoin: import_zod4.z.string().min(1).describe(
85238
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
85239
+ ),
85240
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
85241
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals.")
84876
85242
  },
84877
85243
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
84878
85244
  },
84879
- async ({ direction, amount }) => guarded(async () => {
84880
- const label = direction === "to-ucd" ? "Amount (USDC)" : "Amount (UCD)";
85245
+ async ({ stablecoin, direction, amount }) => guarded(async () => {
85246
+ const label = direction === "to-ucd" ? `Amount (${stablecoin})` : "Amount (UCD)";
84881
85247
  const problem = checkUcdAmount(amount, label);
84882
85248
  if (problem) return validationFailed(problem);
84883
85249
  const b = getB();
84884
85250
  if (!b.ok) return renderError(b.error);
84885
- return renderEnvelope(await b.boundary.getPsmQuote({ direction, amount: amount.toString() }));
85251
+ return renderEnvelope(await b.boundary.getPsmQuote({ stablecoin, direction, amount: amount.toString() }));
84886
85252
  })
84887
85253
  );
84888
85254
  registerBoundaryTool(
84889
85255
  server,
84890
85256
  "psm_swap",
84891
85257
  {
84892
- title: "Exchange UCD \u2194 USDC through the PSM",
84893
- description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay USDC, receive UCD; 'to-usdc' = pay UCD (burned), receive USDC from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves USDC to the PSM contract (the PSM pulls the USDC it converts); to-usdc approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; to-usdc charges the exit fee IN USDC, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: USDC; to-usdc: UCD). Requires human confirmation (confirmed: true).",
85258
+ title: "Exchange UCD \u2194 a stablecoin through the PSM",
85259
+ description: "Execute a PSM exchange (irreversible, fund-moving). direction 'to-ucd' = pay the stablecoin, receive UCD; 'from-ucd' = pay UCD (burned), receive the stablecoin from the PSM's reserves. Runs as TWO explicit on-chain ceremonies, both signed by the session signer and both reported in the result: (1) an EXACT-AMOUNT approval of the input token \u2014 to-ucd approves the stablecoin to the PSM contract (the PSM pulls the coin it converts); from-ucd approves UCD to the UCDController (the PSM burns UCD through the controller \u2014 a DIFFERENT spender, by design). Never an unlimited approval. (2) the swap/redeem itself, carrying a mandatory minimum-out floor set to the live quote minus a 100 bps tolerance \u2014 a zero floor is refused by the contract, and if the quote drifts beyond the floor the exchange REFUSES rather than delivering less. Output always goes to the signer's own address (the contract pays msg.sender only). Fees: to-ucd charges the entry fee IN UCD on the gross converted amount; from-ucd charges the exit fee IN the stablecoin, deducted from what you receive. amount is in the INPUT token's user units (to-ucd: the stablecoin; from-ucd: UCD). Requires human confirmation (confirmed: true).",
84894
85260
  inputSchema: {
84895
- 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)"),
84896
- amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: USDC; to-usdc: UCD). Max 6 decimals."),
85261
+ stablecoin: import_zod4.z.string().min(1).describe(
85262
+ "The stablecoin to exchange, by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address. REQUIRED and deliberately has NO DEFAULT: the PSM can support several coins, and choosing one for the user would move their money through a token they did not name. Read protocol://psm for the coins this deployment supports. The choice is verified against the PSM contract on-chain before anything signs."
85263
+ ),
85264
+ direction: import_zod4.z.enum(["to-ucd", "from-ucd"]).describe("'to-ucd' = pay the stablecoin, get UCD (contract swap); 'from-ucd' = pay UCD, get the stablecoin back (contract redeem)"),
85265
+ amount: import_zod4.z.number().positive().describe("Amount of the INPUT token in user units (to-ucd: the stablecoin; from-ucd: UCD). Max 6 decimals."),
84897
85266
  confirmed: confirmedSchema2
84898
85267
  },
84899
85268
  annotations: DESTRUCTIVE_WRITE_ANNOTATIONS2
84900
85269
  },
84901
- async ({ direction, amount, confirmed }) => guardedWrite(getB, async () => {
84902
- const inputToken = direction === "to-ucd" ? "USDC" : "UCD";
84903
- const outputToken = direction === "to-ucd" ? "UCD" : "USDC";
85270
+ async ({ stablecoin, direction, amount, confirmed }) => guardedWrite(getB, async () => {
85271
+ const inputToken = direction === "to-ucd" ? stablecoin : "UCD";
85272
+ const outputToken = direction === "to-ucd" ? "UCD" : stablecoin;
84904
85273
  const gate = requireConfirmation(
84905
85274
  confirmed,
84906
85275
  `exchange ${amount} ${inputToken} for ${outputToken} through the PSM (two ceremonies: exact-amount approve, then ${direction === "to-ucd" ? "swap" : "redeem"})`
@@ -84910,7 +85279,7 @@ function registerPsmTools(server, getB) {
84910
85279
  if (problem) return validationFailed(problem);
84911
85280
  const b = getB();
84912
85281
  if (!b.ok) return renderError(b.error);
84913
- return renderEnvelope(await b.boundary.psmSwap({ direction, amount: amount.toString() }));
85282
+ return renderEnvelope(await b.boundary.psmSwap({ stablecoin, direction, amount: amount.toString() }));
84914
85283
  })
84915
85284
  );
84916
85285
  }
@@ -85356,7 +85725,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85356
85725
  "network_switch",
85357
85726
  {
85358
85727
  title: "Show or switch the active network",
85359
- description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks (on mainnet they move REAL money; PSM swaps stay sepolia-only). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
85728
+ description: "Which world this server is on \u2014 and switching it by conversation (real adapter). 'status' states the active network and whether money is real. 'switch' moves this session between sepolia (practice funds) and mainnet (REAL MONEY) after an explicit human confirmation; positions, vaults, and signer bindings are per-network and do not carry across. Fund-moving operations work on BOTH networks \u2014 loan operations and PSM swaps alike (on mainnet they move REAL money). The switch lasts for this server session only; the configured default returns on restart. After a switch, re-read boundary://info and STATE the new environment to the user.",
85360
85729
  inputSchema: {
85361
85730
  action: import_zod8.z.enum(["status", "switch"]).describe("status = current world; switch = change network (needs confirmed:true)"),
85362
85731
  network: import_zod8.z.string().optional().describe("switch target: sepolia | mainnet"),
@@ -85374,7 +85743,7 @@ function registerNetworkSwitchTool(server, getB, runtime, getSigner) {
85374
85743
  lines.push(
85375
85744
  `Switchable networks: ${SWITCHABLE_NETWORKS.join(", ")} (action 'switch', confirmed:true after human approval).`,
85376
85745
  "A switch changes worlds entirely: positions, vaults, and signer bindings are per-network.",
85377
- "Fund-moving operations work on both networks \u2014 on mainnet they move REAL money (PSM swaps: sepolia-only).",
85746
+ "Fund-moving operations work on both networks, loan operations and PSM swaps alike \u2014 on mainnet they move REAL money.",
85378
85747
  "Session-scoped: the configured default network returns when the server restarts."
85379
85748
  );
85380
85749
  return { content: [{ type: "text", text: lines.join("\n") }] };
@@ -85480,13 +85849,26 @@ function registerProtocolResources(server, getB) {
85480
85849
  "protocol://psm",
85481
85850
  {
85482
85851
  title: "PSM status (UCD \u2194 USDC exchange)",
85483
- description: "Live SimplePSMV2 state as {data, warnings, source}: network + chainId + addresses (the money surface names its chain), stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in USDC smallest units, to-usdc caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0).",
85852
+ description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
85484
85853
  mimeType: "application/json"
85485
85854
  },
85486
85855
  async (uri) => {
85487
85856
  const b = getB();
85488
85857
  if (!b.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(b.error) }] };
85489
- const env = await b.boundary.getPsmStatus();
85858
+ const listed = await b.boundary.listPsmStablecoins();
85859
+ if (!listed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(listed) }] };
85860
+ const perCoin = await Promise.all(listed.data.map((coin) => b.boundary.getPsmStatus({ stablecoin: coin.address })));
85861
+ const failed = perCoin.find((s) => !s.ok);
85862
+ if (failed && !failed.ok) return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceErrorJson(failed.error) }] };
85863
+ const coins = perCoin.flatMap((s) => s.ok ? [s.data] : []);
85864
+ const head = coins[0];
85865
+ const env = {
85866
+ ...listed,
85867
+ data: {
85868
+ ...head ? { network: head.network, chainId: head.chainId, psmAddress: head.psmAddress } : {},
85869
+ stablecoins: coins
85870
+ }
85871
+ };
85490
85872
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: resourceJson(env) }] };
85491
85873
  }
85492
85874
  );
@@ -85699,12 +86081,15 @@ function composeConnector(opts, rawPublicOrigin) {
85699
86081
  for (const session of sessions.values()) held.add(session.tenant);
85700
86082
  return held;
85701
86083
  }
85702
- function isReclaimable(tenantKey, world, held) {
85703
- if (held.has(tenantKey)) return false;
86084
+ function isEvictable(world) {
85704
86085
  const bridge = world.deps.signer?.bridge;
85705
86086
  if (bridge && (bridge.pendingCount() > 0 || bridge.attachedNow())) return false;
85706
86087
  return true;
85707
86088
  }
86089
+ function isReclaimable(tenantKey, world, held) {
86090
+ if (held.has(tenantKey)) return false;
86091
+ return isEvictable(world);
86092
+ }
85708
86093
  function sweepService() {
85709
86094
  const now = clock();
85710
86095
  for (const [sid, session] of [...sessions]) {
@@ -85720,13 +86105,12 @@ function composeConnector(opts, rawPublicOrigin) {
85720
86105
  dropWorld(tenantKey, world, "idle eviction");
85721
86106
  }
85722
86107
  }
85723
- function reclaimIdleWorld() {
85724
- const held = tenantsWithSessions();
86108
+ function leastRecentlyActive(eligible) {
85725
86109
  let victimKey = null;
85726
86110
  let victim = null;
85727
86111
  let oldest = Number.POSITIVE_INFINITY;
85728
86112
  for (const [tenantKey, world] of readyWorlds) {
85729
- if (!isReclaimable(tenantKey, world, held)) continue;
86113
+ if (!eligible(tenantKey, world)) continue;
85730
86114
  const activeAt = lastActivity.get(tenantKey) ?? 0;
85731
86115
  if (activeAt < oldest) {
85732
86116
  oldest = activeAt;
@@ -85734,8 +86118,23 @@ function composeConnector(opts, rawPublicOrigin) {
85734
86118
  victim = world;
85735
86119
  }
85736
86120
  }
85737
- if (victimKey === null || victim === null) return false;
85738
- dropWorld(victimKey, victim, "capacity reclamation (least recently active idle world)");
86121
+ return victimKey !== null && victim !== null ? [victimKey, victim] : null;
86122
+ }
86123
+ function reclaimIdleWorld() {
86124
+ const held = tenantsWithSessions();
86125
+ const tier1 = leastRecentlyActive((k, w) => isReclaimable(k, w, held));
86126
+ if (tier1) {
86127
+ dropWorld(tier1[0], tier1[1], "capacity reclamation (least recently active idle world)");
86128
+ return true;
86129
+ }
86130
+ const tier2 = leastRecentlyActive((_k, w) => isEvictable(w));
86131
+ if (!tier2) return false;
86132
+ for (const [sid, session] of [...sessions]) {
86133
+ if (session.tenant !== tier2[0]) continue;
86134
+ sessions.delete(sid);
86135
+ void session.transport.close().catch(() => void 0);
86136
+ }
86137
+ dropWorld(tier2[0], tier2[1], "capacity eviction (least recently active world; its sessions were closed)");
85739
86138
  return true;
85740
86139
  }
85741
86140
  class TenantCapacityError extends Error {
@@ -85953,7 +86352,8 @@ function composeConnector(opts, rawPublicOrigin) {
85953
86352
  if (opts.auth) {
85954
86353
  authImpl = opts.auth;
85955
86354
  } else {
85956
- const wcLeg = opts.siweWc ?? (opts.env["DH_WC_PROJECT_ID"] ? { projectId: opts.env["DH_WC_PROJECT_ID"] } : void 0);
86355
+ const envWcProjectId = resolvedWcProjectId(opts.env);
86356
+ const wcLeg = opts.siweWc ?? (envWcProjectId !== void 0 ? { projectId: envWcProjectId } : void 0);
85957
86357
  const siwe = new SiweOAuthProvider({
85958
86358
  origin: () => publicOrigin,
85959
86359
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,