@gvnrdao/dh-mcp 0.5.14 → 0.5.16

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/boundary.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
  }
@@ -41014,8 +41016,15 @@ var BoundaryCore = class {
41014
41016
  return r.ok ? okEnvelope({ terms: r.value }, r.source) : errEnvelope(failureToError(r.failure));
41015
41017
  }
41016
41018
  // ---- PSM reads (plan 08 Part B Phase R) ----
41017
- async getPsmStatus() {
41018
- const r = await this.deps.plugin.chain.getPsmStatus();
41019
+ /** Which stablecoins this PSM supports. There is deliberately NO default: the caller
41020
+ * names the coin, and this is how they learn what they may name. */
41021
+ async listPsmStablecoins() {
41022
+ const r = await this.deps.plugin.chain.listPsmStablecoins();
41023
+ if (!r.ok) return errEnvelope(failureToError(r.failure));
41024
+ return okEnvelope(r.value, r.source);
41025
+ }
41026
+ async getPsmStatus(p) {
41027
+ const r = await this.deps.plugin.chain.getPsmStatus(p);
41019
41028
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41020
41029
  return okEnvelope(this.psmStatusData(r.value), r.source);
41021
41030
  }
@@ -41026,7 +41035,7 @@ var BoundaryCore = class {
41026
41035
  * refusal taxonomy and the decimals/fee identity for its cards). `status` is non-null
41027
41036
  * whenever `env.ok`. */
41028
41037
  async psmQuoteWithStatus(p) {
41029
- const statusR = await this.deps.plugin.chain.getPsmStatus();
41038
+ const statusR = await this.deps.plugin.chain.getPsmStatus({ stablecoin: p.stablecoin });
41030
41039
  if (!statusR.ok) return { env: errEnvelope(failureToError(statusR.failure)), status: null };
41031
41040
  const s = statusR.value;
41032
41041
  const toUcd = p.direction === "to-ucd";
@@ -41082,6 +41091,7 @@ var BoundaryCore = class {
41082
41091
  );
41083
41092
  }
41084
41093
  const quoteR = await this.deps.plugin.chain.getPsmQuote({
41094
+ stablecoin: p.stablecoin,
41085
41095
  direction: toUcd ? "swap" : "redeem",
41086
41096
  amountIn: amountIn.toString()
41087
41097
  });
@@ -41148,6 +41158,7 @@ var BoundaryCore = class {
41148
41158
  let floor = amountOut - amountOut * BigInt(PSM_FLOOR_TOLERANCE_BPS) / 10000n;
41149
41159
  if (floor === 0n) floor = 1n;
41150
41160
  const r = await this.deps.plugin.ops.psmSwap({
41161
+ stablecoin: p.stablecoin,
41151
41162
  direction: q.contractCall,
41152
41163
  amountIn: q.amountIn,
41153
41164
  minOut: floor.toString(),
@@ -41247,7 +41258,7 @@ var BoundaryCore = class {
41247
41258
  feeToken: "UCD",
41248
41259
  perBlockCap: s.maxSwapVolumePerBlock
41249
41260
  }),
41250
- toUsdc: direction({
41261
+ fromUcd: direction({
41251
41262
  minAmount: s.minRedeemAmount,
41252
41263
  maxAmount: s.maxRedeemAmount,
41253
41264
  amountUnit: ucdUnit,
@@ -43072,7 +43083,7 @@ var SINK_CONTRACTS = {
43072
43083
  PositionManager: sinkAddress("PositionManager"),
43073
43084
  UCDToken: sinkAddress("UCDToken"),
43074
43085
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
43075
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
43086
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
43076
43087
  SimplePSMV2: sinkAddress("SimplePSMV2"),
43077
43088
  UsdcToken: sinkAddress("UsdcToken"),
43078
43089
  UCDController: sinkAddress("UCDController")
@@ -43368,7 +43379,18 @@ var MockUpstreamPlugin = class {
43368
43379
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
43369
43380
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
43370
43381
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
43371
- getPsmStatus: () => this.read("mock-chain", () => {
43382
+ // The practice world models ONE stablecoin, and says so rather than implying a
43383
+ // choice it cannot honour: the caller must still NAME a coin (no default anywhere),
43384
+ // and naming anything but this one is refused the same way the real adapter refuses
43385
+ // an unsupported address — a mock that accepted any name would teach a habit the
43386
+ // real protocol punishes.
43387
+ listPsmStablecoins: () => this.read(
43388
+ "mock-chain",
43389
+ () => upOk([{ address: "mock-usdc", symbol: "USDC", decimals: this.world.psmSeed().stablecoinDecimals }], this.src("mock-chain"))
43390
+ ),
43391
+ getPsmStatus: (p) => this.read("mock-chain", () => {
43392
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43393
+ if (known) return known;
43372
43394
  const psm = this.world.psmSeed();
43373
43395
  return upOk(
43374
43396
  {
@@ -43393,6 +43415,8 @@ var MockUpstreamPlugin = class {
43393
43415
  );
43394
43416
  }),
43395
43417
  getPsmQuote: (p) => this.read("mock-chain", () => {
43418
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43419
+ if (known) return known;
43396
43420
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
43397
43421
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
43398
43422
  })
@@ -43517,6 +43541,19 @@ var MockUpstreamPlugin = class {
43517
43541
  return apply();
43518
43542
  }
43519
43543
  /** Mode `none`: every write answers with the conversational setup invitation. */
43544
+ /** The practice world supports exactly one PSM stablecoin. A name that is not it is
43545
+ * refused with the same shape the real adapter uses for an address the chain does not
43546
+ * list — so practising the choose-a-coin habit here fails the same way it would there,
43547
+ * instead of silently succeeding and teaching that any name works. */
43548
+ mockStablecoinRefusal(stablecoin) {
43549
+ const chosen = stablecoin.trim().toLowerCase();
43550
+ if (chosen === "mock-usdc" || chosen === "usdc") return null;
43551
+ return upFail({
43552
+ kind: "rejected",
43553
+ source: "mock-chain",
43554
+ 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.`
43555
+ });
43556
+ }
43520
43557
  noneRefusal() {
43521
43558
  if (this.signer && this.signer.manager.mode() === "none") {
43522
43559
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -78400,6 +78437,13 @@ function listPositionsQuery(f) {
78400
78437
  }
78401
78438
  return { document: LIST_POSITIONS, variables: { first, skip } };
78402
78439
  }
78440
+ var SUPPORTED_STABLECOINS = `
78441
+ query GetSupportedStablecoins {
78442
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
78443
+ id address isSupported exchangeRate entryFee exitFee reserves decimals
78444
+ totalSwapVolume totalRedeemVolume swapCount redeemCount addedAt lastUpdated
78445
+ }
78446
+ }`;
78403
78447
 
78404
78448
  // src/boundary/upstream/real/psm-calls.ts
78405
78449
  var import_ethers31 = require("ethers");
@@ -78539,6 +78583,11 @@ var PsmCalls = class {
78539
78583
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78540
78584
  });
78541
78585
  }
78586
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
78587
+ * so it must come from the token rather than from a per-network assumption. */
78588
+ symbol() {
78589
+ return this.deps.stablecoinSymbol;
78590
+ }
78542
78591
  async status() {
78543
78592
  return this.call(async () => {
78544
78593
  const s = this.deps.stablecoinAddress;
@@ -78998,13 +79047,6 @@ function buildValidationContext(network, chainId) {
78998
79047
  }
78999
79048
 
79000
79049
  // src/boundary/upstream/real/write-ops.ts
79001
- function psmMainnetWriteRefusal(network, chainId) {
79002
- return {
79003
- kind: "rejected",
79004
- source: SOURCE5,
79005
- 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.`
79006
- };
79007
- }
79008
79050
  var SOURCE5 = "real-ops";
79009
79051
  var OP_LAYOUT = "dh-op-envelope-v1";
79010
79052
  function randomNonceHex() {
@@ -79352,8 +79394,7 @@ function buildWriteOps(deps) {
79352
79394
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79353
79395
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
79354
79396
  psmSwap: async (p) => {
79355
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
79356
- const pr = deps.psm();
79397
+ const pr = await deps.psm(p.stablecoin);
79357
79398
  if (!pr.ok) return upFail(pr.failure);
79358
79399
  const calls = pr.calls;
79359
79400
  const addr = calls.addresses();
@@ -79371,7 +79412,7 @@ function buildWriteOps(deps) {
79371
79412
  const tokenAddress = isSwap ? addr.stablecoin : addr.ucdToken;
79372
79413
  const spenderAddress = isSwap ? addr.psm : addr.ucdController;
79373
79414
  const spenderContract = isSwap ? "SimplePSMV2" : "UCDController";
79374
- const tokenSymbol = isSwap ? "USDC" : "UCD";
79415
+ const tokenSymbol = isSwap ? calls.symbol() : "UCD";
79375
79416
  const quoteR = isSwap ? await calls.swapQuote(p.amountIn) : await calls.redemptionQuote(p.amountIn);
79376
79417
  if (!quoteR.ok) return upFail(quoteR.failure);
79377
79418
  const broadcast = async (leg, action, tx2) => {
@@ -79411,7 +79452,7 @@ function buildWriteOps(deps) {
79411
79452
  } catch (e) {
79412
79453
  return upFail({ kind: "rejected", source: SOURCE5, message: `PSM ${p.direction} tx failed the whitelist: ${e.message} \u2014 ${residualNote}` });
79413
79454
  }
79414
- const execCard = `${p.direction} ${p.amountIn} ${isSwap ? "USDC smallest units" : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
79455
+ const execCard = `${p.direction} ${p.amountIn} ${isSwap ? `${tokenSymbol} smallest units` : "UCD wei"} via the PSM: quote ${quoteR.value.amountOut} out (fee ${quoteR.value.feeAmount}), floor ${p.minOut} \u2014 output to ${p.borrower}`;
79415
79456
  const execHashR = await broadcast(`psmSwap (${p.direction})`, isSwap ? "psm-swap" : "psm-redeem", execTx);
79416
79457
  if (!execHashR.ok) {
79417
79458
  const f = execHashR.failure;
@@ -79734,6 +79775,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79734
79775
  );
79735
79776
  }
79736
79777
  const hashHex = import_ethers37.ethers.hexlify(bytes).toLowerCase();
79778
+ const nowMs = (this.deps.clock ?? Date.now)();
79779
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
79780
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
79737
79781
  const outcome = await this.deps.bridge.requestSignature({
79738
79782
  id: (0, import_node_crypto5.randomUUID)(),
79739
79783
  kind: "personal-sign",
@@ -79745,15 +79789,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79745
79789
  "(identical to how diamondhands.credit signs withdrawals).",
79746
79790
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79747
79791
  "",
79748
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
79749
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
79750
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
79751
- "itself allows. If it expires the signature is refused, the withdrawal does not",
79752
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
79753
- "start again rather than signing something you have not finished reading."
79792
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
79793
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
79794
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
79795
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
79796
+ "stay reserved until that is cleared. If the number above is already small, decline",
79797
+ "and start again rather than signing something you have not finished reading."
79754
79798
  ],
79755
79799
  expectedSigner: this.deps.borrower,
79756
79800
  chainId: this.deps.chainId,
79801
+ expiresAtSec,
79757
79802
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
79758
79803
  });
79759
79804
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -79957,13 +80002,18 @@ var RealUpstreamPlugin = class {
79957
80002
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
79958
80003
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
79959
80004
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
79960
- getPsmStatus: () => {
79961
- const r = this.psmCalls();
79962
- return r.ok ? r.calls.status() : Promise.resolve(upFail(r.failure));
79963
- },
79964
- getPsmQuote: (p) => {
79965
- const r = this.psmCalls();
79966
- if (!r.ok) return Promise.resolve(upFail(r.failure));
80005
+ listPsmStablecoins: async () => {
80006
+ const verified = await this.verifiedStablecoins();
80007
+ if (!verified.ok) return upFail(verified.failure);
80008
+ return upOk(verified.rows, this.src("subgraph"));
80009
+ },
80010
+ getPsmStatus: async (p) => {
80011
+ const r = await this.psmCallsForChoice(p.stablecoin);
80012
+ return r.ok ? r.calls.status() : upFail(r.failure);
80013
+ },
80014
+ getPsmQuote: async (p) => {
80015
+ const r = await this.psmCallsForChoice(p.stablecoin);
80016
+ if (!r.ok) return upFail(r.failure);
79967
80017
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
79968
80018
  }
79969
80019
  };
@@ -80031,12 +80081,13 @@ var RealUpstreamPlugin = class {
80031
80081
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
80032
80082
  delegationSetup: () => readOnly("delegationSetup"),
80033
80083
  delegationGrant: () => readOnly("delegationGrant"),
80034
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
80035
- // any non-sepolia network refuses typed — naming the network gate truthfully —
80036
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
80037
- // missing signer instead (the honest reason on that path).
80084
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
80085
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
80086
+ // signerless boot the honest refusal was always the missing signer; the network
80087
+ // gate sat in front of it and answered first. Now there is one reason left, and it
80088
+ // is the true one on this path.
80038
80089
  psmSwap: () => Promise.resolve(
80039
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
80090
+ upFail({
80040
80091
  kind: "signer-missing",
80041
80092
  source: "real-ops",
80042
80093
  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."
@@ -80153,7 +80204,7 @@ var RealUpstreamPlugin = class {
80153
80204
  session,
80154
80205
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80155
80206
  readDetails: (id) => this.readPositionDetails(id),
80156
- psm: () => this.psmCalls(),
80207
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80157
80208
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80158
80209
  });
80159
80210
  }
@@ -80287,7 +80338,7 @@ var RealUpstreamPlugin = class {
80287
80338
  session,
80288
80339
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80289
80340
  readDetails: (id) => this.readPositionDetails(id),
80290
- psm: () => this.psmCalls(),
80341
+ psm: (stablecoin) => this.psmCallsForChoice(stablecoin),
80291
80342
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80292
80343
  });
80293
80344
  this.opsGatewayCache.set(key, gateway);
@@ -80433,35 +80484,200 @@ var RealUpstreamPlugin = class {
80433
80484
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
80434
80485
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
80435
80486
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
80436
- psmWrapper = null;
80437
- psmCalls() {
80438
- if (this.psmWrapper) return { ok: true, calls: this.psmWrapper };
80487
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
80488
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
80489
+ psmWrappers = /* @__PURE__ */ new Map();
80490
+ /**
80491
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
80492
+ *
80493
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
80494
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
80495
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
80496
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
80497
+ * `getPSMStablecoins` reads the index for the same reason.
80498
+ */
80499
+ async listSupportedStablecoins() {
80500
+ const r = await this.graphProxy(
80501
+ SUPPORTED_STABLECOINS,
80502
+ {}
80503
+ );
80504
+ if (!r.ok) return r;
80505
+ const raw = r.value.data.supportedStablecoins ?? [];
80506
+ const bad = raw.find((x) => !import_ethers38.ethers.isAddress(String(x.address)) || !Number.isFinite(Number(x.decimals)));
80507
+ if (bad) {
80508
+ return {
80509
+ ok: false,
80510
+ failure: {
80511
+ kind: "malformed",
80512
+ source: "subgraph",
80513
+ message: `the indexer returned a PSM stablecoin row this build cannot read (address '${String(bad.address)}', decimals '${String(bad.decimals)}')`
80514
+ }
80515
+ };
80516
+ }
80517
+ const rows = raw.map((x) => ({
80518
+ address: String(x.address).toLowerCase(),
80519
+ decimals: Number(x.decimals)
80520
+ }));
80521
+ if (rows.length === 0) {
80522
+ return {
80523
+ ok: false,
80524
+ failure: {
80525
+ kind: "unavailable",
80526
+ source: "subgraph",
80527
+ message: `the indexer lists NO supported stablecoins for the PSM on ${this.config.network}. Either the subgraph has not indexed the StablecoinAdded events yet (check its start block against the block the coins were added at), or governance has removed every coin. PSM exchange is unavailable here until one of those is resolved \u2014 this is NOT "the PSM supports nothing".`
80528
+ }
80529
+ };
80530
+ }
80531
+ return { ok: true, rows };
80532
+ }
80533
+ /**
80534
+ * The supported set, verified — index rows each re-checked on-chain, carrying the symbol
80535
+ * read from the token itself. This is what `protocol://psm` lists and what a caller's
80536
+ * SYMBOL is resolved against.
80537
+ *
80538
+ * Rows are dropped ONLY for the one reason a drop is honest: the index still lists a coin
80539
+ * the chain no longer supports (index lag behind a governance removal). Any OTHER failure
80540
+ * — an RPC outage mid-loop — propagates, because a list that silently shrinks when the
80541
+ * chain is unreachable is the same silent-failure shape as the empty list above. If
80542
+ * nothing survives verification, that is a refusal too, and it says which side disagreed.
80543
+ */
80544
+ async verifiedStablecoins() {
80545
+ const listed = await this.listSupportedStablecoins();
80546
+ if (!listed.ok) return listed;
80547
+ const checked = await Promise.all(
80548
+ listed.rows.map(async (row) => ({ row, built: await this.psmCallsFor(row.address) }))
80549
+ );
80550
+ const transport = checked.find((c) => !c.built.ok && c.built.failure.kind !== "rejected");
80551
+ if (transport && !transport.built.ok) return { ok: false, failure: transport.built.failure };
80552
+ const rows = checked.flatMap(
80553
+ ({ row, built }) => built.ok ? [{ address: row.address, symbol: built.calls.symbol(), decimals: row.decimals }] : []
80554
+ );
80555
+ if (rows.length === 0) {
80556
+ return {
80557
+ ok: false,
80558
+ failure: {
80559
+ kind: "unavailable",
80560
+ source: "chain-rpc",
80561
+ message: `the indexer lists ${listed.rows.length} PSM stablecoin(s) on ${this.config.network}, and the PSM contract confirms none of them. The index is behind a governance removal, or it is indexing a different PSM than the one in this build's deployment table \u2014 verify before exchanging anything.`
80562
+ }
80563
+ };
80564
+ }
80565
+ return { ok: true, rows };
80566
+ }
80567
+ /**
80568
+ * Resolve what the CALLER named — a symbol or a 0x address — to a verified address.
80569
+ *
80570
+ * The tool schemas have always said "by SYMBOL (e.g. 'USDC', 'USDT') or by 0x address",
80571
+ * and the mock world accepts exactly that. The real adapter accepted only the address:
80572
+ * a symbol went straight into an address-typed `ethers.Contract`, which threw, and the
80573
+ * throw was caught as `kind: "unavailable"` → `UPSTREAM_UNAVAILABLE` — a code the guide
80574
+ * tells the model is "usually transient; retry once". So the documented input produced a
80575
+ * retry loop on the one deployment that moves real money, and a developer practising
80576
+ * against the mock never met it. Both halves are fixed here: the symbol resolves, and a
80577
+ * name that cannot resolve is `rejected` (the caller's input) rather than `unavailable`
80578
+ * (our upstream).
80579
+ */
80580
+ async psmCallsForChoice(chosen) {
80581
+ const raw = chosen.trim();
80582
+ if (raw.length === 0) {
80583
+ return {
80584
+ ok: false,
80585
+ failure: { kind: "rejected", source: "chain-rpc", message: "no stablecoin named \u2014 name one by symbol (e.g. 'USDC') or by 0x address; there is no default coin." }
80586
+ };
80587
+ }
80588
+ const symbol = raw.toLowerCase();
80589
+ if (import_ethers38.ethers.isAddress(raw)) return this.psmCallsFor(symbol);
80590
+ const verified = await this.verifiedStablecoins();
80591
+ if (!verified.ok) return { ok: false, failure: verified.failure };
80592
+ const hits = verified.rows.filter((r) => r.symbol.toLowerCase() === symbol);
80593
+ if (hits.length > 1) {
80594
+ return {
80595
+ ok: false,
80596
+ failure: {
80597
+ kind: "rejected",
80598
+ source: "chain-rpc",
80599
+ message: `'${raw}' names ${hits.length} different coins this PSM supports \u2014 ${hits.map((r) => r.address).join(", ")}. Symbols are self-declared and not unique, so this one cannot be resolved for you: name the 0x address of the one you mean.`
80600
+ }
80601
+ };
80602
+ }
80603
+ const hit = hits[0];
80604
+ if (!hit) {
80605
+ const names = verified.rows.map((r) => `${r.symbol} (${r.address})`).join(", ");
80606
+ return {
80607
+ ok: false,
80608
+ failure: {
80609
+ kind: "rejected",
80610
+ source: "chain-rpc",
80611
+ message: `'${raw}' is not a coin this PSM supports on ${this.config.network} \u2014 it supports ${names}. Name one of those by symbol or address. \`protocol://psm\` carries each one's fees, limits and reserves.`
80612
+ }
80613
+ };
80614
+ }
80615
+ return this.psmCallsFor(hit.address);
80616
+ }
80617
+ /**
80618
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
80619
+ *
80620
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
80621
+ * indexer is how the list is discovered and is not authority over it: it can lag a
80622
+ * governance removal, and acting on a stale list would build a swap the contract reverts
80623
+ * — after the user has approved it in their wallet. List from the index, verify on the
80624
+ * chain, then sign.
80625
+ */
80626
+ async psmCallsFor(stablecoinAddress) {
80627
+ if (!import_ethers38.ethers.isAddress(stablecoinAddress)) {
80628
+ throw new Error(`psmCallsFor requires a resolved 0x address, got '${stablecoinAddress}' \u2014 resolve through psmCallsForChoice`);
80629
+ }
80630
+ const key = stablecoinAddress.toLowerCase();
80631
+ const cached = this.psmWrappers.get(key);
80632
+ if (cached) return { ok: true, calls: cached };
80439
80633
  const psmAddress = this.contracts["SimplePSMV2"];
80440
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
80441
- if (!psmAddress || !stablecoinAddress) {
80442
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
80634
+ if (!psmAddress) {
80443
80635
  return {
80444
80636
  ok: false,
80445
80637
  failure: {
80446
80638
  kind: "unavailable",
80447
80639
  source: "chain-rpc",
80448
- message: `the bundled deployment table has no address for ${missing} on ${this.config.network} \u2014 PSM reads refuse rather than guess an address.`
80640
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
80449
80641
  }
80450
80642
  };
80451
80643
  }
80644
+ let supported;
80645
+ let symbol;
80646
+ try {
80647
+ const psm = new import_ethers38.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
80648
+ supported = await psm["supportedStablecoins"](key);
80649
+ const erc20 = new import_ethers38.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
80650
+ symbol = await erc20["symbol"]();
80651
+ } catch (e) {
80652
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
80653
+ }
80654
+ if (!supported) {
80655
+ return {
80656
+ ok: false,
80657
+ failure: {
80658
+ kind: "rejected",
80659
+ source: "chain-rpc",
80660
+ 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.`
80661
+ }
80662
+ };
80663
+ }
80664
+ const stablecoinAddress2 = key;
80452
80665
  const ucdTokenAddress = this.contracts["UCDToken"];
80453
80666
  const ucdControllerAddress = this.contracts["UCDController"];
80454
- this.psmWrapper = new PsmCalls({
80667
+ const built = new PsmCalls({
80455
80668
  provider: this.provider,
80456
80669
  psmAddress,
80457
- stablecoinAddress,
80458
- stablecoinSymbol: "USDC",
80670
+ stablecoinAddress: stablecoinAddress2,
80671
+ // Read from the token, never assumed. The old value was the literal "USDC", which
80672
+ // stops being true the moment a second coin is supported.
80673
+ stablecoinSymbol: symbol,
80459
80674
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
80460
80675
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
80461
80676
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
80462
80677
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
80463
80678
  });
80464
- return { ok: true, calls: this.psmWrapper };
80679
+ this.psmWrappers.set(key, built);
80680
+ return { ok: true, calls: built };
80465
80681
  }
80466
80682
  src(id) {
80467
80683
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -80724,6 +80940,7 @@ function renderApprovalPage(sessionId, nonce) {
80724
80940
  <div id="request" class="hidden">
80725
80941
  <div id="action" class="action"></div>
80726
80942
  <div id="card" class="card"></div>
80943
+ <div id="deadline" class="status hidden"></div>
80727
80944
  <button id="approve">Approve in wallet</button>
80728
80945
  <button id="reject">Reject</button>
80729
80946
  </div>
@@ -80756,10 +80973,19 @@ const statusEl = document.getElementById("status");
80756
80973
  const requestEl = document.getElementById("request");
80757
80974
  const actionEl = document.getElementById("action");
80758
80975
  const cardEl = document.getElementById("card");
80976
+ const approveEl = document.getElementById("approve");
80977
+ const rejectEl = document.getElementById("reject");
80978
+ const deadlineEl = document.getElementById("deadline");
80979
+ let deadlineTimer = null;
80759
80980
  const walletEl = document.getElementById("wallet");
80760
80981
  let account = null;
80761
80982
  let chainId = null;
80762
80983
  let current = null;
80984
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
80985
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
80986
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
80987
+ // card the page never renders is one the human can neither read nor reject.
80988
+ const pending = new Map();
80763
80989
 
80764
80990
  function post(path, body) {
80765
80991
  return fetch(path, {
@@ -80822,43 +81048,135 @@ async function onAccountsChanged(accounts) {
80822
81048
  account = (accounts && accounts[0]) || null;
80823
81049
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80824
81050
  showWallet();
80825
- clearRequest("Wallet changed \u2014 pending request invalidated.");
81051
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
80826
81052
  }
80827
81053
 
80828
81054
  async function onChainChanged(cid) {
80829
81055
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
80830
81056
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80831
81057
  showWallet();
80832
- clearRequest("Network changed \u2014 pending request invalidated.");
81058
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
80833
81059
  }
80834
81060
 
80835
81061
  function listen() {
80836
81062
  const es = new EventSource(BASE + "events?s=" + SESSION);
80837
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
81063
+ es.onmessage = (ev) => {
81064
+ const next = JSON.parse(ev.data);
81065
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
81066
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
81067
+ pending.set(next.id, next);
81068
+ showPending();
81069
+ };
80838
81070
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
80839
81071
  }
80840
81072
 
81073
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
81074
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
81075
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
81076
+ // gets approved.
81077
+ function pickPending() {
81078
+ const held = current ? pending.get(current.id) : undefined;
81079
+ if (held && held.mirror !== true) return held;
81080
+ let best = held || null;
81081
+ pending.forEach((frame) => {
81082
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
81083
+ });
81084
+ return best;
81085
+ }
81086
+
81087
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
81088
+ function showPending(emptyText) {
81089
+ const next = pickPending();
81090
+ if (!next) {
81091
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
81092
+ // an expiry for a ceremony that is already decided.
81093
+ stopDeadline();
81094
+ current = null;
81095
+ requestEl.classList.add("hidden");
81096
+ if (emptyText) showStatus(emptyText);
81097
+ return;
81098
+ }
81099
+ current = next;
81100
+ renderRequest();
81101
+ }
81102
+
80841
81103
  function renderRequest() {
80842
81104
  actionEl.textContent = current.action;
80843
81105
  cardEl.textContent = current.card.join("\\n");
81106
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
81107
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
81108
+ // server-side, which is the actual boundary.
81109
+ const mirrored = current.mirror === true;
81110
+ approveEl.classList.toggle("hidden", mirrored);
81111
+ rejectEl.classList.remove("hidden");
80844
81112
  requestEl.classList.remove("hidden");
80845
- showStatus("Review the operation below. Nothing signs without your approval.");
81113
+ showStatus(mirrored
81114
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
81115
+ : "Review the operation below. Nothing signs without your approval.");
81116
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
81117
+ // card promoted after another settles gets its own clock, not the previous one's.
81118
+ startDeadline();
80846
81119
  }
80847
81120
 
81121
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
81122
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
81123
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
81124
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
81125
+ // honest without it needing to know anything about quantum windows.
81126
+ function stopDeadline() {
81127
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81128
+ deadlineEl.classList.add("hidden");
81129
+ }
81130
+
81131
+ function startDeadline() {
81132
+ stopDeadline();
81133
+ if (!current || typeof current.expiresAtSec !== "number") return;
81134
+ const tick = () => {
81135
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
81136
+ if (left > 0) {
81137
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
81138
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
81139
+ } else {
81140
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
81141
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
81142
+ // after. The button is deliberately left enabled \u2014 declining is still the right
81143
+ // action and the page must not trap them.
81144
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
81145
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81146
+ }
81147
+ deadlineEl.classList.remove("hidden");
81148
+ };
81149
+ tick();
81150
+ deadlineTimer = setInterval(tick, 1000);
81151
+ }
81152
+
81153
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
81154
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
81155
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
80848
81156
  function clearRequest(text) {
80849
- current = null;
80850
- requestEl.classList.add("hidden");
80851
- showStatus(text);
81157
+ if (current) pending.delete(current.id);
81158
+ showPending(text);
81159
+ }
81160
+
81161
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
81162
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
81163
+ // stays readable and rejectable.
81164
+ function invalidatePageRequests(text) {
81165
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
81166
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
80852
81167
  }
80853
81168
 
80854
- document.getElementById("reject").onclick = async () => {
81169
+ rejectEl.onclick = async () => {
80855
81170
  if (!current) return;
80856
81171
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
80857
81172
  clearRequest("Rejected. Waiting for the next request\u2026");
80858
81173
  };
80859
81174
 
80860
- document.getElementById("approve").onclick = async () => {
81175
+ approveEl.onclick = async () => {
80861
81176
  if (!current) return;
81177
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
81178
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
81179
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
80862
81180
  const req = current;
80863
81181
  try {
80864
81182
  if (req.kind === "transaction") {
@@ -80875,7 +81193,10 @@ document.getElementById("approve").onclick = async () => {
80875
81193
  const fbody = await fr.json();
80876
81194
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
80877
81195
  const fresh = fbody.request;
80878
- // \u2026re-render what will actually sign\u2026
81196
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
81197
+ // another card arriving while the wallet popup is open re-picks from there, and the
81198
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
81199
+ pending.set(fresh.id, fresh);
80879
81200
  current = fresh; renderRequest();
80880
81201
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
80881
81202
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -81058,9 +81379,6 @@ var SignatureBridge = class {
81058
81379
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81059
81380
  maxPending;
81060
81381
  attachGraceMs;
81061
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
81062
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
81063
- lastAttachedMs = 0;
81064
81382
  server = null;
81065
81383
  port = 0;
81066
81384
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -81211,13 +81529,16 @@ var SignatureBridge = class {
81211
81529
  enqueuedMs: now,
81212
81530
  resolve,
81213
81531
  settled: false,
81214
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
81532
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
81533
+ owner: this.wcActive ? "wc" : "page",
81534
+ dispatched: false,
81535
+ lastAttachedMs: now
81215
81536
  };
81216
81537
  this.pending.set(request.id, entry);
81217
- if (this.wcActive) {
81538
+ if (entry.owner === "wc") {
81218
81539
  void this.driveWc(entry);
81219
81540
  } else {
81220
- this.push(request);
81541
+ this.pushEntry(entry);
81221
81542
  }
81222
81543
  });
81223
81544
  }
@@ -81238,10 +81559,16 @@ var SignatureBridge = class {
81238
81559
  enqueuedMs: now,
81239
81560
  resolve,
81240
81561
  settled: false,
81241
- collect
81562
+ collect,
81563
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
81564
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
81565
+ // ceremony could not reach quorum through the very pages it is broadcast to.
81566
+ owner: "both",
81567
+ dispatched: false,
81568
+ lastAttachedMs: now
81242
81569
  };
81243
81570
  this.pending.set(request.id, entry);
81244
- this.push(request);
81571
+ this.pushEntry(entry);
81245
81572
  if (this.wcActive) void this.driveWcCollection(entry);
81246
81573
  });
81247
81574
  }
@@ -81280,7 +81607,9 @@ var SignatureBridge = class {
81280
81607
  }
81281
81608
  try {
81282
81609
  if (req.kind === "transaction") {
81610
+ this.pushEntry(entry);
81283
81611
  const tx2 = req.tx;
81612
+ entry.dispatched = true;
81284
81613
  const txHash = await transport.request("eth_sendTransaction", [
81285
81614
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
81286
81615
  ]);
@@ -81292,11 +81621,22 @@ var SignatureBridge = class {
81292
81621
  req.card = fresh.card;
81293
81622
  }
81294
81623
  const ps = req.personalSign;
81624
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
81625
+ this.settle(entry, {
81626
+ status: "invalidated",
81627
+ 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)`
81628
+ });
81629
+ return;
81630
+ }
81631
+ this.pushEntry(entry);
81632
+ entry.dispatched = true;
81295
81633
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
81296
81634
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81297
81635
  } else {
81636
+ this.pushEntry(entry);
81298
81637
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
81299
81638
  const payload = withEip712DomainType2(req.typedData);
81639
+ entry.dispatched = true;
81300
81640
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
81301
81641
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81302
81642
  }
@@ -81316,30 +81656,55 @@ var SignatureBridge = class {
81316
81656
  * with a live attachment is in use and must never be evicted. */
81317
81657
  attachedNow() {
81318
81658
  if (this.wcActive) return true;
81319
- for (const s of this.sessions.values()) if (s.sse) return true;
81659
+ return this.pageAttached();
81660
+ }
81661
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
81662
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
81663
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
81664
+ * WalletConnect and must stay global for the connector's eviction predicate. */
81665
+ pageAttached() {
81666
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
81320
81667
  return false;
81321
81668
  }
81669
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
81670
+ * predicate said "a WC session is attached", which is true but irrelevant to a
81671
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
81672
+ * out the full expiry instead of failing fast at the grace. */
81673
+ attachedFor(entry) {
81674
+ if (entry.owner === "wc") return this.wcActive;
81675
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
81676
+ return this.pageAttached();
81677
+ }
81322
81678
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
81323
81679
  * interval; tests call it directly with the injected clock advanced. Order matters:
81324
81680
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
81325
81681
  sweep() {
81326
81682
  const now = this.clock();
81327
- const attached = this.attachedNow();
81328
- if (attached) this.lastAttachedMs = now;
81329
81683
  for (const entry of this.pending.values()) {
81330
81684
  if (entry.settled) continue;
81331
81685
  if (now >= entry.deadlineMs) {
81332
81686
  this.settle(entry, { status: "expired" });
81333
81687
  continue;
81334
81688
  }
81335
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
81336
- this.settle(entry, {
81337
- status: "invalidated",
81338
- 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`
81339
- });
81689
+ if (this.attachedFor(entry)) {
81690
+ entry.lastAttachedMs = now;
81691
+ continue;
81340
81692
  }
81693
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
81694
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
81341
81695
  }
81342
81696
  }
81697
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
81698
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
81699
+ unattendedReason(entry) {
81700
+ if (entry.dispatched && entry.request.kind === "transaction") {
81701
+ 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.";
81702
+ }
81703
+ if (entry.owner === "wc") {
81704
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
81705
+ }
81706
+ 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`;
81707
+ }
81343
81708
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
81344
81709
  walletConnectActive() {
81345
81710
  return this.wcActive;
@@ -81463,6 +81828,7 @@ var SignatureBridge = class {
81463
81828
  if (info && refusal) {
81464
81829
  this.wcActive = false;
81465
81830
  this.rebuildSharedWallet();
81831
+ this.demoteWcEntries();
81466
81832
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81467
81833
  `);
81468
81834
  return;
@@ -81472,7 +81838,10 @@ var SignatureBridge = class {
81472
81838
  if (info === null) {
81473
81839
  for (const entry of this.pending.values()) {
81474
81840
  if (!entry.settled && !entry.collect) {
81475
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
81841
+ this.settle(entry, {
81842
+ status: "invalidated",
81843
+ 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"
81844
+ });
81476
81845
  }
81477
81846
  }
81478
81847
  }
@@ -81544,9 +81913,7 @@ var SignatureBridge = class {
81544
81913
  session.sse?.end();
81545
81914
  session.sse = res;
81546
81915
  for (const entry of this.pending.values()) {
81547
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
81548
-
81549
- `);
81916
+ if (!entry.settled) res.write(this.wireFor(entry));
81550
81917
  }
81551
81918
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
81552
81919
  keepAlive.unref();
@@ -81622,10 +81989,36 @@ var SignatureBridge = class {
81622
81989
  }
81623
81990
  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";
81624
81991
  for (const entry of this.pending.values()) {
81625
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
81992
+ if (entry.settled || entry.collect) continue;
81993
+ if (this.ownedByWc(entry)) continue;
81994
+ this.settle(entry, { status: "invalidated", reason });
81626
81995
  }
81627
81996
  this.ok(res);
81628
81997
  }
81998
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
81999
+ * session hands the request back to the page rather than stranding it. */
82000
+ ownedByWc(entry) {
82001
+ if (entry.owner !== "wc") return false;
82002
+ return this.wcActive || entry.dispatched;
82003
+ }
82004
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
82005
+ * them so the card stops rendering read-only. Collections are already `both`.
82006
+ *
82007
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
82008
+ * phone is still holding does not replace one wallet with another, it adds a second: the
82009
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
82010
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
82011
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
82012
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
82013
+ * false for them, and `unattendedReason` says plainly that the phone may already have
82014
+ * acted. */
82015
+ demoteWcEntries() {
82016
+ for (const entry of this.pending.values()) {
82017
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
82018
+ entry.owner = "page";
82019
+ this.pushEntry(entry);
82020
+ }
82021
+ }
81629
82022
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
81630
82023
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
81631
82024
  async onFinalize(body, res) {
@@ -81639,6 +82032,10 @@ var SignatureBridge = class {
81639
82032
  this.deny(res, 400, "finalize applies only to personal-sign requests");
81640
82033
  return;
81641
82034
  }
82035
+ if (this.ownedByWc(entry)) {
82036
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
82037
+ return;
82038
+ }
81642
82039
  if (entry.finalize) {
81643
82040
  let fresh;
81644
82041
  try {
@@ -81665,10 +82062,22 @@ var SignatureBridge = class {
81665
82062
  return;
81666
82063
  }
81667
82064
  if (body["approved"] !== true) {
82065
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
82066
+ this.settle(entry, {
82067
+ status: "invalidated",
82068
+ 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."
82069
+ });
82070
+ this.ok(res);
82071
+ return;
82072
+ }
81668
82073
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
81669
82074
  this.ok(res);
81670
82075
  return;
81671
82076
  }
82077
+ if (this.ownedByWc(entry)) {
82078
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
82079
+ return;
82080
+ }
81672
82081
  const account = String(body["account"] ?? "");
81673
82082
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
81674
82083
  this.deny(res, 400, "approved result requires the signing account");
@@ -81705,11 +82114,20 @@ var SignatureBridge = class {
81705
82114
  this.pending.delete(entry.request.id);
81706
82115
  entry.resolve(outcome);
81707
82116
  }
81708
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
81709
- push(request) {
81710
- const data = `data: ${JSON.stringify(request)}
82117
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
82118
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
82119
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
82120
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
82121
+ * a permanently read-only card that nobody is allowed to decide. */
82122
+ wireFor(entry) {
82123
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
82124
+ return `data: ${JSON.stringify(payload)}
81711
82125
 
81712
82126
  `;
82127
+ }
82128
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
82129
+ pushEntry(entry) {
82130
+ const data = this.wireFor(entry);
81713
82131
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81714
82132
  }
81715
82133
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -81817,6 +82235,15 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
81817
82235
  var ADAPTERS = ["mock", "real"];
81818
82236
  var LATENCIES = ["zero", "realistic"];
81819
82237
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
82238
+ var WC_DISABLED = "off";
82239
+ function resolveWcProjectId(raw, problems) {
82240
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
82241
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
82242
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
82243
+ return void 0;
82244
+ }
82245
+ return raw;
82246
+ }
81820
82247
  var NETWORK_DEFAULTS = {
81821
82248
  sepolia: {
81822
82249
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -81891,10 +82318,7 @@ function resolveBoundaryConfig(env) {
81891
82318
  }
81892
82319
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81893
82320
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
81894
- const wcProjectId = env["DH_WC_PROJECT_ID"];
81895
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
81896
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
81897
- }
82321
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81898
82322
  let bridgeOpenBrowser;
81899
82323
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81900
82324
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -81966,10 +82390,7 @@ function resolveRealConfig(env) {
81966
82390
  const stateDir = env["DH_STATE_DIR"];
81967
82391
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81968
82392
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
81969
- const wcProjectId = env["DH_WC_PROJECT_ID"];
81970
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
81971
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
81972
- }
82393
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81973
82394
  let bridgeOpenBrowser;
81974
82395
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81975
82396
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {