@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/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,19 @@ function listPositionsQuery(f) {
78400
78437
  }
78401
78438
  return { document: LIST_POSITIONS, variables: { first, skip } };
78402
78439
  }
78440
+ var SUPPORTED_STABLECOINS = `
78441
+ query SupportedStablecoins {
78442
+ supportedStablecoins(where: { isSupported: true }, orderBy: addedAt, orderDirection: desc) {
78443
+ id
78444
+ address
78445
+ isSupported
78446
+ decimals
78447
+ entryFee
78448
+ exitFee
78449
+ reserves
78450
+ }
78451
+ }
78452
+ `;
78403
78453
 
78404
78454
  // src/boundary/upstream/real/psm-calls.ts
78405
78455
  var import_ethers31 = require("ethers");
@@ -78539,6 +78589,11 @@ var PsmCalls = class {
78539
78589
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78540
78590
  });
78541
78591
  }
78592
+ /** The token's own symbol, read at construction. The caller names the coin by this word,
78593
+ * so it must come from the token rather than from a per-network assumption. */
78594
+ symbol() {
78595
+ return this.deps.stablecoinSymbol;
78596
+ }
78542
78597
  async status() {
78543
78598
  return this.call(async () => {
78544
78599
  const s = this.deps.stablecoinAddress;
@@ -78998,13 +79053,6 @@ function buildValidationContext(network, chainId) {
78998
79053
  }
78999
79054
 
79000
79055
  // 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
79056
  var SOURCE5 = "real-ops";
79009
79057
  var OP_LAYOUT = "dh-op-envelope-v1";
79010
79058
  function randomNonceHex() {
@@ -79352,8 +79400,7 @@ function buildWriteOps(deps) {
79352
79400
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79353
79401
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
79354
79402
  psmSwap: async (p) => {
79355
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
79356
- const pr = deps.psm();
79403
+ const pr = await deps.psm(p.stablecoin);
79357
79404
  if (!pr.ok) return upFail(pr.failure);
79358
79405
  const calls = pr.calls;
79359
79406
  const addr = calls.addresses();
@@ -79734,6 +79781,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79734
79781
  );
79735
79782
  }
79736
79783
  const hashHex = import_ethers37.ethers.hexlify(bytes).toLowerCase();
79784
+ const nowMs = (this.deps.clock ?? Date.now)();
79785
+ const expiresAtSec = nextQuantumTimestamp(nowMs);
79786
+ const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
79737
79787
  const outcome = await this.deps.bridge.requestSignature({
79738
79788
  id: (0, import_node_crypto5.randomUUID)(),
79739
79789
  kind: "personal-sign",
@@ -79745,15 +79795,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79745
79795
  "(identical to how diamondhands.credit signs withdrawals).",
79746
79796
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79747
79797
  "",
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."
79798
+ "SIGN NOW \u2014 this one is on a clock, and here is the actual deadline:",
79799
+ ` expires at ${new Date(expiresAtSec * 1e3).toISOString().slice(11, 19)} UTC \u2014 ${secondsLeft} second${secondsLeft === 1 ? "" : "s"} from when this card was raised`,
79800
+ "The approval page allows far longer than this; the PAYLOAD does not. If it expires",
79801
+ "the signature is refused, the withdrawal does not complete, and the reserved coins",
79802
+ "stay reserved until that is cleared. If the number above is already small, decline",
79803
+ "and start again rather than signing something you have not finished reading."
79754
79804
  ],
79755
79805
  expectedSigner: this.deps.borrower,
79756
79806
  chainId: this.deps.chainId,
79807
+ expiresAtSec,
79757
79808
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
79758
79809
  });
79759
79810
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -79957,13 +80008,27 @@ var RealUpstreamPlugin = class {
79957
80008
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
79958
80009
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
79959
80010
  // 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));
80011
+ listPsmStablecoins: async () => {
80012
+ const listed = await this.listSupportedStablecoins();
80013
+ if (!listed.ok) return listed;
80014
+ const rows = await Promise.all(
80015
+ listed.rows.map(async (row) => {
80016
+ const built = await this.psmCallsFor(row.address);
80017
+ return built.ok ? { address: row.address, symbol: built.calls.symbol(), decimals: row.decimals } : null;
80018
+ })
80019
+ );
80020
+ return upOk(
80021
+ rows.filter((r) => r !== null),
80022
+ this.src("subgraph")
80023
+ );
79963
80024
  },
79964
- getPsmQuote: (p) => {
79965
- const r = this.psmCalls();
79966
- if (!r.ok) return Promise.resolve(upFail(r.failure));
80025
+ getPsmStatus: async (p) => {
80026
+ const r = await this.psmCallsFor(p.stablecoin);
80027
+ return r.ok ? r.calls.status() : upFail(r.failure);
80028
+ },
80029
+ getPsmQuote: async (p) => {
80030
+ const r = await this.psmCallsFor(p.stablecoin);
80031
+ if (!r.ok) return upFail(r.failure);
79967
80032
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
79968
80033
  }
79969
80034
  };
@@ -80031,12 +80096,13 @@ var RealUpstreamPlugin = class {
80031
80096
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
80032
80097
  delegationSetup: () => readOnly("delegationSetup"),
80033
80098
  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).
80099
+ // The plan-08 M8-7/M8-14 mainnet standing block was anchored here too, and is
80100
+ // removed with its twin in write-ops.ts (2026-09-10, Master's instruction). On a
80101
+ // signerless boot the honest refusal was always the missing signer; the network
80102
+ // gate sat in front of it and answered first. Now there is one reason left, and it
80103
+ // is the true one on this path.
80038
80104
  psmSwap: () => Promise.resolve(
80039
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
80105
+ upFail({
80040
80106
  kind: "signer-missing",
80041
80107
  source: "real-ops",
80042
80108
  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 +80219,7 @@ var RealUpstreamPlugin = class {
80153
80219
  session,
80154
80220
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80155
80221
  readDetails: (id) => this.readPositionDetails(id),
80156
- psm: () => this.psmCalls(),
80222
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80157
80223
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80158
80224
  });
80159
80225
  }
@@ -80287,7 +80353,7 @@ var RealUpstreamPlugin = class {
80287
80353
  session,
80288
80354
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80289
80355
  readDetails: (id) => this.readPositionDetails(id),
80290
- psm: () => this.psmCalls(),
80356
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80291
80357
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80292
80358
  });
80293
80359
  this.opsGatewayCache.set(key, gateway);
@@ -80433,35 +80499,91 @@ var RealUpstreamPlugin = class {
80433
80499
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
80434
80500
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
80435
80501
  * 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 };
80502
+ /** One wrapper per stablecoin — the PSM supports several and each has its own decimals,
80503
+ * fees and reserves, so a single cached wrapper would answer for the wrong coin. */
80504
+ psmWrappers = /* @__PURE__ */ new Map();
80505
+ /**
80506
+ * The PSM's supported stablecoins, from the indexer (2026-09-10, mainnet PSM enablement).
80507
+ *
80508
+ * This replaced a deployment-table lookup that hardcoded ONE coin per network — sepolia's
80509
+ * mock USDC, and on mainnet an address the table did not carry at all, so mainnet PSM
80510
+ * refused before it ever reached the write gate. Which coins the PSM supports is on-chain
80511
+ * STATE that governance changes, not a constant a package can ship: the SDK's own
80512
+ * `getPSMStablecoins` reads the index for the same reason.
80513
+ */
80514
+ async listSupportedStablecoins() {
80515
+ const r = await this.graphProxy(
80516
+ SUPPORTED_STABLECOINS,
80517
+ {}
80518
+ );
80519
+ if (!r.ok) return r;
80520
+ const rows = (r.value.data.supportedStablecoins ?? []).map((x) => ({
80521
+ address: String(x.address).toLowerCase(),
80522
+ decimals: Number(x.decimals)
80523
+ }));
80524
+ return { ok: true, rows };
80525
+ }
80526
+ /**
80527
+ * Build the PSM wrapper for ONE caller-chosen stablecoin.
80528
+ *
80529
+ * The choice is re-checked against `supportedStablecoins(address)` on-chain first. The
80530
+ * indexer is how the list is discovered and is not authority over it: it can lag a
80531
+ * governance removal, and acting on a stale list would build a swap the contract reverts
80532
+ * — after the user has approved it in their wallet. List from the index, verify on the
80533
+ * chain, then sign.
80534
+ */
80535
+ async psmCallsFor(stablecoinAddress) {
80536
+ const key = stablecoinAddress.toLowerCase();
80537
+ const cached = this.psmWrappers.get(key);
80538
+ if (cached) return { ok: true, calls: cached };
80439
80539
  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 ");
80540
+ if (!psmAddress) {
80443
80541
  return {
80444
80542
  ok: false,
80445
80543
  failure: {
80446
80544
  kind: "unavailable",
80447
80545
  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.`
80546
+ message: `the bundled deployment table has no SimplePSMV2 address on ${this.config.network} \u2014 PSM refuses rather than guess an address.`
80449
80547
  }
80450
80548
  };
80451
80549
  }
80550
+ let supported;
80551
+ let symbol;
80552
+ try {
80553
+ const psm = new import_ethers38.ethers.Contract(psmAddress, ["function supportedStablecoins(address) view returns (bool)"], this.provider);
80554
+ supported = await psm["supportedStablecoins"](key);
80555
+ const erc20 = new import_ethers38.ethers.Contract(key, ["function symbol() view returns (string)"], this.provider);
80556
+ symbol = await erc20["symbol"]();
80557
+ } catch (e) {
80558
+ return { ok: false, failure: { kind: "unavailable", source: "chain-rpc", message: `PSM stablecoin check failed for ${key}: ${e.message}` } };
80559
+ }
80560
+ if (!supported) {
80561
+ return {
80562
+ ok: false,
80563
+ failure: {
80564
+ kind: "rejected",
80565
+ source: "chain-rpc",
80566
+ 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.`
80567
+ }
80568
+ };
80569
+ }
80570
+ const stablecoinAddress2 = key;
80452
80571
  const ucdTokenAddress = this.contracts["UCDToken"];
80453
80572
  const ucdControllerAddress = this.contracts["UCDController"];
80454
- this.psmWrapper = new PsmCalls({
80573
+ const built = new PsmCalls({
80455
80574
  provider: this.provider,
80456
80575
  psmAddress,
80457
- stablecoinAddress,
80458
- stablecoinSymbol: "USDC",
80576
+ stablecoinAddress: stablecoinAddress2,
80577
+ // Read from the token, never assumed. The old value was the literal "USDC", which
80578
+ // stops being true the moment a second coin is supported.
80579
+ stablecoinSymbol: symbol,
80459
80580
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
80460
80581
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
80461
80582
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
80462
80583
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
80463
80584
  });
80464
- return { ok: true, calls: this.psmWrapper };
80585
+ this.psmWrappers.set(key, built);
80586
+ return { ok: true, calls: built };
80465
80587
  }
80466
80588
  src(id) {
80467
80589
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -80724,6 +80846,7 @@ function renderApprovalPage(sessionId, nonce) {
80724
80846
  <div id="request" class="hidden">
80725
80847
  <div id="action" class="action"></div>
80726
80848
  <div id="card" class="card"></div>
80849
+ <div id="deadline" class="status hidden"></div>
80727
80850
  <button id="approve">Approve in wallet</button>
80728
80851
  <button id="reject">Reject</button>
80729
80852
  </div>
@@ -80756,10 +80879,19 @@ const statusEl = document.getElementById("status");
80756
80879
  const requestEl = document.getElementById("request");
80757
80880
  const actionEl = document.getElementById("action");
80758
80881
  const cardEl = document.getElementById("card");
80882
+ const approveEl = document.getElementById("approve");
80883
+ const rejectEl = document.getElementById("reject");
80884
+ const deadlineEl = document.getElementById("deadline");
80885
+ let deadlineTimer = null;
80759
80886
  const walletEl = document.getElementById("wallet");
80760
80887
  let account = null;
80761
80888
  let chainId = null;
80762
80889
  let current = null;
80890
+ // EVERY pending ceremony, by id \u2014 not just the displayed one. A loopback bridge caps
80891
+ // nothing, so a k-of-n collection and a WalletConnect request can be live at once and
80892
+ // "events" replays both on attach; with a single slot the loser was gone for good, and a
80893
+ // card the page never renders is one the human can neither read nor reject.
80894
+ const pending = new Map();
80763
80895
 
80764
80896
  function post(path, body) {
80765
80897
  return fetch(path, {
@@ -80822,43 +80954,135 @@ async function onAccountsChanged(accounts) {
80822
80954
  account = (accounts && accounts[0]) || null;
80823
80955
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80824
80956
  showWallet();
80825
- clearRequest("Wallet changed \u2014 pending request invalidated.");
80957
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
80826
80958
  }
80827
80959
 
80828
80960
  async function onChainChanged(cid) {
80829
80961
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
80830
80962
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80831
80963
  showWallet();
80832
- clearRequest("Network changed \u2014 pending request invalidated.");
80964
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
80833
80965
  }
80834
80966
 
80835
80967
  function listen() {
80836
80968
  const es = new EventSource(BASE + "events?s=" + SESSION);
80837
- es.onmessage = (ev) => { current = JSON.parse(ev.data); renderRequest(); };
80969
+ es.onmessage = (ev) => {
80970
+ const next = JSON.parse(ev.data);
80971
+ // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
80972
+ // payload in place and re-pushes it, so the older frame carries a dead hash.
80973
+ pending.set(next.id, next);
80974
+ showPending();
80975
+ };
80838
80976
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
80839
80977
  }
80840
80978
 
80979
+ // A read-only mirror must never displace a card this page can actually decide \u2014 but it
80980
+ // must not be thrown away either, so it waits its turn instead. Among equals the card
80981
+ // already on screen keeps it: reshuffling under a moving cursor is how the wrong thing
80982
+ // gets approved.
80983
+ function pickPending() {
80984
+ const held = current ? pending.get(current.id) : undefined;
80985
+ if (held && held.mirror !== true) return held;
80986
+ let best = held || null;
80987
+ pending.forEach((frame) => {
80988
+ if (!best || (best.mirror === true && frame.mirror !== true)) best = frame;
80989
+ });
80990
+ return best;
80991
+ }
80992
+
80993
+ // "current" stays the DISPLAYED frame \u2014 renderRequest and both click handlers read it.
80994
+ function showPending(emptyText) {
80995
+ const next = pickPending();
80996
+ if (!next) {
80997
+ // The queue drained, so no card owns the clock \u2014 leaving it running would tick down
80998
+ // an expiry for a ceremony that is already decided.
80999
+ stopDeadline();
81000
+ current = null;
81001
+ requestEl.classList.add("hidden");
81002
+ if (emptyText) showStatus(emptyText);
81003
+ return;
81004
+ }
81005
+ current = next;
81006
+ renderRequest();
81007
+ }
81008
+
80841
81009
  function renderRequest() {
80842
81010
  actionEl.textContent = current.action;
80843
81011
  cardEl.textContent = current.card.join("\\n");
81012
+ // Visibility is set on BOTH branches, always. A hidden button is still in the DOM and
81013
+ // still wired, so this is presentation only \u2014 the bridge refuses a mirrored approval
81014
+ // server-side, which is the actual boundary.
81015
+ const mirrored = current.mirror === true;
81016
+ approveEl.classList.toggle("hidden", mirrored);
81017
+ rejectEl.classList.remove("hidden");
80844
81018
  requestEl.classList.remove("hidden");
80845
- showStatus("Review the operation below. Nothing signs without your approval.");
81019
+ showStatus(mirrored
81020
+ ? "Your mobile wallet is holding this one \u2014 read it here, then approve or decline in the wallet. Reject cancels it from this page."
81021
+ : "Review the operation below. Nothing signs without your approval.");
81022
+ // The countdown belongs to the DISPLAYED card, so it restarts on every render \u2014 a queued
81023
+ // card promoted after another settles gets its own clock, not the previous one's.
81024
+ startDeadline();
81025
+ }
81026
+
81027
+ // C-46: the card's deadline is computed when the card is RAISED, so by the time a human
81028
+ // has read it the number is already wrong. On the BTC-withdraw execute leg the whole
81029
+ // window is under a minute, which makes a stale figure worse than none \u2014 it implies time
81030
+ // the payload does not have. Counting down from the server-supplied instant keeps the page
81031
+ // honest without it needing to know anything about quantum windows.
81032
+ function stopDeadline() {
81033
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81034
+ deadlineEl.classList.add("hidden");
80846
81035
  }
80847
81036
 
81037
+ function startDeadline() {
81038
+ stopDeadline();
81039
+ if (!current || typeof current.expiresAtSec !== "number") return;
81040
+ const tick = () => {
81041
+ const left = current.expiresAtSec - Math.floor(Date.now() / 1000);
81042
+ if (left > 0) {
81043
+ deadlineEl.textContent = "This payload expires in " + left + " second" + (left === 1 ? "" : "s") +
81044
+ " \u2014 after that the signature is refused and the withdrawal does not complete.";
81045
+ } else {
81046
+ // Say EXPIRED rather than hiding the line: a user who signs now gets a refusal from
81047
+ // the protocol, and the honest thing is to tell them before the wallet opens, not
81048
+ // after. The button is deliberately left enabled \u2014 declining is still the right
81049
+ // action and the page must not trap them.
81050
+ deadlineEl.textContent = "EXPIRED \u2014 this payload is past its window. Decline and start the withdrawal again.";
81051
+ if (deadlineTimer !== null) { clearInterval(deadlineTimer); deadlineTimer = null; }
81052
+ }
81053
+ deadlineEl.classList.remove("hidden");
81054
+ };
81055
+ tick();
81056
+ deadlineTimer = setInterval(tick, 1000);
81057
+ }
81058
+
81059
+ // Only the ceremony this page just decided leaves the queue. The bridge never announces a
81060
+ // settlement, so anything else it pushed is still live as far as the page can know \u2014 and
81061
+ // blanking the panel over it stranded a phone ceremony with no card and no Reject.
80848
81062
  function clearRequest(text) {
80849
- current = null;
80850
- requestEl.classList.add("hidden");
80851
- showStatus(text);
81063
+ if (current) pending.delete(current.id);
81064
+ showPending(text);
81065
+ }
81066
+
81067
+ // A wallet or network change settles every ceremony THIS page could decide, and the bridge
81068
+ // deliberately spares the ones a phone is holding. Drop what died; the mirror that survived
81069
+ // stays readable and rejectable.
81070
+ function invalidatePageRequests(text) {
81071
+ pending.forEach((frame, id) => { if (frame.mirror !== true) pending.delete(id); });
81072
+ showPending(text); // NOT clearRequest \u2014 that would drop a displayed mirror the bridge kept
80852
81073
  }
80853
81074
 
80854
- document.getElementById("reject").onclick = async () => {
81075
+ rejectEl.onclick = async () => {
80855
81076
  if (!current) return;
80856
81077
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
80857
81078
  clearRequest("Rejected. Waiting for the next request\u2026");
80858
81079
  };
80859
81080
 
80860
- document.getElementById("approve").onclick = async () => {
81081
+ approveEl.onclick = async () => {
80861
81082
  if (!current) return;
81083
+ // Re-checked at the click, not just at render: hiding a button is CSS, and a stale
81084
+ // request or a DOM poke must not open a wallet for a ceremony the phone owns.
81085
+ if (current.mirror === true) { showStatus("This approval belongs to your mobile wallet \u2014 approve it there."); return; }
80862
81086
  const req = current;
80863
81087
  try {
80864
81088
  if (req.kind === "transaction") {
@@ -80875,7 +81099,10 @@ document.getElementById("approve").onclick = async () => {
80875
81099
  const fbody = await fr.json();
80876
81100
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
80877
81101
  const fresh = fbody.request;
80878
- // \u2026re-render what will actually sign\u2026
81102
+ // \u2026re-render what will actually sign, and put the re-stamped frame in the queue too:
81103
+ // another card arriving while the wallet popup is open re-picks from there, and the
81104
+ // pre-finalize frame would put the OLD hash's card back under an open wallet.
81105
+ pending.set(fresh.id, fresh);
80879
81106
  current = fresh; renderRequest();
80880
81107
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
80881
81108
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -81058,9 +81285,6 @@ var SignatureBridge = class {
81058
81285
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
81059
81286
  maxPending;
81060
81287
  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
81288
  server = null;
81065
81289
  port = 0;
81066
81290
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -81211,13 +81435,16 @@ var SignatureBridge = class {
81211
81435
  enqueuedMs: now,
81212
81436
  resolve,
81213
81437
  settled: false,
81214
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
81438
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
81439
+ owner: this.wcActive ? "wc" : "page",
81440
+ dispatched: false,
81441
+ lastAttachedMs: now
81215
81442
  };
81216
81443
  this.pending.set(request.id, entry);
81217
- if (this.wcActive) {
81444
+ if (entry.owner === "wc") {
81218
81445
  void this.driveWc(entry);
81219
81446
  } else {
81220
- this.push(request);
81447
+ this.pushEntry(entry);
81221
81448
  }
81222
81449
  });
81223
81450
  }
@@ -81238,10 +81465,16 @@ var SignatureBridge = class {
81238
81465
  enqueuedMs: now,
81239
81466
  resolve,
81240
81467
  settled: false,
81241
- collect
81468
+ collect,
81469
+ // A collection asks the page AND (below) WalletConnect at once, so it is owned by
81470
+ // BOTH: the read-only card and the `/result` gate must never fire here, or a k-of-n
81471
+ // ceremony could not reach quorum through the very pages it is broadcast to.
81472
+ owner: "both",
81473
+ dispatched: false,
81474
+ lastAttachedMs: now
81242
81475
  };
81243
81476
  this.pending.set(request.id, entry);
81244
- this.push(request);
81477
+ this.pushEntry(entry);
81245
81478
  if (this.wcActive) void this.driveWcCollection(entry);
81246
81479
  });
81247
81480
  }
@@ -81280,7 +81513,9 @@ var SignatureBridge = class {
81280
81513
  }
81281
81514
  try {
81282
81515
  if (req.kind === "transaction") {
81516
+ this.pushEntry(entry);
81283
81517
  const tx2 = req.tx;
81518
+ entry.dispatched = true;
81284
81519
  const txHash = await transport.request("eth_sendTransaction", [
81285
81520
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
81286
81521
  ]);
@@ -81292,11 +81527,22 @@ var SignatureBridge = class {
81292
81527
  req.card = fresh.card;
81293
81528
  }
81294
81529
  const ps = req.personalSign;
81530
+ if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
81531
+ this.settle(entry, {
81532
+ status: "invalidated",
81533
+ 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)`
81534
+ });
81535
+ return;
81536
+ }
81537
+ this.pushEntry(entry);
81538
+ entry.dispatched = true;
81295
81539
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
81296
81540
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81297
81541
  } else {
81542
+ this.pushEntry(entry);
81298
81543
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
81299
81544
  const payload = withEip712DomainType2(req.typedData);
81545
+ entry.dispatched = true;
81300
81546
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
81301
81547
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81302
81548
  }
@@ -81316,29 +81562,54 @@ var SignatureBridge = class {
81316
81562
  * with a live attachment is in use and must never be evicted. */
81317
81563
  attachedNow() {
81318
81564
  if (this.wcActive) return true;
81319
- for (const s of this.sessions.values()) if (s.sse) return true;
81565
+ return this.pageAttached();
81566
+ }
81567
+ /** A live approval PAGE specifically — the only surface that can render a card. Excludes
81568
+ * quarantined sessions, which `push` already refuses to write to (C-47): a page that
81569
+ * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
81570
+ * WalletConnect and must stay global for the connector's eviction predicate. */
81571
+ pageAttached() {
81572
+ for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
81320
81573
  return false;
81321
81574
  }
81575
+ /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
81576
+ * predicate said "a WC session is attached", which is true but irrelevant to a
81577
+ * page-owned request, and vice versa: an entry whose own wallet has gone silently sat
81578
+ * out the full expiry instead of failing fast at the grace. */
81579
+ attachedFor(entry) {
81580
+ if (entry.owner === "wc") return this.wcActive;
81581
+ if (entry.owner === "both") return this.wcActive || this.pageAttached();
81582
+ return this.pageAttached();
81583
+ }
81322
81584
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
81323
81585
  * interval; tests call it directly with the injected clock advanced. Order matters:
81324
81586
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
81325
81587
  sweep() {
81326
81588
  const now = this.clock();
81327
- const attached = this.attachedNow();
81328
- if (attached) this.lastAttachedMs = now;
81329
81589
  for (const entry of this.pending.values()) {
81330
81590
  if (entry.settled) continue;
81331
81591
  if (now >= entry.deadlineMs) {
81332
81592
  this.settle(entry, { status: "expired" });
81333
81593
  continue;
81334
81594
  }
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
- });
81595
+ if (this.attachedFor(entry)) {
81596
+ entry.lastAttachedMs = now;
81597
+ continue;
81340
81598
  }
81599
+ if (now - Math.max(entry.enqueuedMs, entry.lastAttachedMs) < this.attachGraceMs) continue;
81600
+ this.settle(entry, { status: "invalidated", reason: this.unattendedReason(entry) });
81601
+ }
81602
+ }
81603
+ /** Why an unattended ceremony was cut loose — and, for a transaction already sitting on
81604
+ * a phone, the warning that giving up here is not the same as nothing having happened. */
81605
+ unattendedReason(entry) {
81606
+ if (entry.dispatched && entry.request.kind === "transaction") {
81607
+ 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.";
81608
+ }
81609
+ if (entry.owner === "wc") {
81610
+ return "the mobile wallet holding this approval went away before answering \u2014 reconnect it, or use the approval page, and retry the operation";
81341
81611
  }
81612
+ 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`;
81342
81613
  }
81343
81614
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
81344
81615
  walletConnectActive() {
@@ -81463,6 +81734,7 @@ var SignatureBridge = class {
81463
81734
  if (info && refusal) {
81464
81735
  this.wcActive = false;
81465
81736
  this.rebuildSharedWallet();
81737
+ this.demoteWcEntries();
81466
81738
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81467
81739
  `);
81468
81740
  return;
@@ -81472,7 +81744,10 @@ var SignatureBridge = class {
81472
81744
  if (info === null) {
81473
81745
  for (const entry of this.pending.values()) {
81474
81746
  if (!entry.settled && !entry.collect) {
81475
- this.settle(entry, { status: "invalidated", reason: "the WalletConnect session disconnected" });
81747
+ this.settle(entry, {
81748
+ status: "invalidated",
81749
+ 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"
81750
+ });
81476
81751
  }
81477
81752
  }
81478
81753
  }
@@ -81544,9 +81819,7 @@ var SignatureBridge = class {
81544
81819
  session.sse?.end();
81545
81820
  session.sse = res;
81546
81821
  for (const entry of this.pending.values()) {
81547
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
81548
-
81549
- `);
81822
+ if (!entry.settled) res.write(this.wireFor(entry));
81550
81823
  }
81551
81824
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
81552
81825
  keepAlive.unref();
@@ -81622,10 +81895,36 @@ var SignatureBridge = class {
81622
81895
  }
81623
81896
  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
81897
  for (const entry of this.pending.values()) {
81625
- if (!entry.settled && !entry.collect) this.settle(entry, { status: "invalidated", reason });
81898
+ if (entry.settled || entry.collect) continue;
81899
+ if (this.ownedByWc(entry)) continue;
81900
+ this.settle(entry, { status: "invalidated", reason });
81626
81901
  }
81627
81902
  this.ok(res);
81628
81903
  }
81904
+ /** Is this ceremony the PHONE's to decide? False once the WC leg is gone, so a dropped
81905
+ * session hands the request back to the page rather than stranding it. */
81906
+ ownedByWc(entry) {
81907
+ if (entry.owner !== "wc") return false;
81908
+ return this.wcActive || entry.dispatched;
81909
+ }
81910
+ /** Give the approval page back the ceremonies a departed WC leg was holding, and re-push
81911
+ * them so the card stops rendering read-only. Collections are already `both`.
81912
+ *
81913
+ * DISPATCHED entries are deliberately left where they are. Handing back a ceremony the
81914
+ * phone is still holding does not replace one wallet with another, it adds a second: the
81915
+ * outstanding `transport.request` is not cancelled by a refused pairing (the refusal path
81916
+ * keeps the transport alive on purpose), so an actionable page card alongside it means
81917
+ * both can approve — and for a transaction that is two broadcasts of the same operation.
81918
+ * Those entries instead fail fast at the per-entry grace, since `attachedFor` now reads
81919
+ * false for them, and `unattendedReason` says plainly that the phone may already have
81920
+ * acted. */
81921
+ demoteWcEntries() {
81922
+ for (const entry of this.pending.values()) {
81923
+ if (entry.settled || entry.owner !== "wc" || entry.dispatched) continue;
81924
+ entry.owner = "page";
81925
+ this.pushEntry(entry);
81926
+ }
81927
+ }
81629
81928
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
81630
81929
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
81631
81930
  async onFinalize(body, res) {
@@ -81639,6 +81938,10 @@ var SignatureBridge = class {
81639
81938
  this.deny(res, 400, "finalize applies only to personal-sign requests");
81640
81939
  return;
81641
81940
  }
81941
+ if (this.ownedByWc(entry)) {
81942
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
81943
+ return;
81944
+ }
81642
81945
  if (entry.finalize) {
81643
81946
  let fresh;
81644
81947
  try {
@@ -81665,10 +81968,22 @@ var SignatureBridge = class {
81665
81968
  return;
81666
81969
  }
81667
81970
  if (body["approved"] !== true) {
81971
+ if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
81972
+ this.settle(entry, {
81973
+ status: "invalidated",
81974
+ 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."
81975
+ });
81976
+ this.ok(res);
81977
+ return;
81978
+ }
81668
81979
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
81669
81980
  this.ok(res);
81670
81981
  return;
81671
81982
  }
81983
+ if (this.ownedByWc(entry)) {
81984
+ this.deny(res, 409, "a mobile wallet is holding this approval \u2014 approve it there; this page is read-only for it");
81985
+ return;
81986
+ }
81672
81987
  const account = String(body["account"] ?? "");
81673
81988
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
81674
81989
  this.deny(res, 400, "approved result requires the signing account");
@@ -81705,11 +82020,20 @@ var SignatureBridge = class {
81705
82020
  this.pending.delete(entry.request.id);
81706
82021
  entry.resolve(outcome);
81707
82022
  }
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)}
82023
+ /** The wire form of a pending entry. `mirror` is DERIVED here, every time, and never
82024
+ * written back onto `entry.request`: ownership is mutable (a WC drop demotes to `page`),
82025
+ * `onFinalize` echoes the request object back to the caller, and `driveWc` mutates that
82026
+ * same object in place — a stored flag would leak into all three and go sticky, leaving
82027
+ * a permanently read-only card that nobody is allowed to decide. */
82028
+ wireFor(entry) {
82029
+ const payload = entry.owner === "wc" ? { ...entry.request, mirror: true } : entry.request;
82030
+ return `data: ${JSON.stringify(payload)}
81711
82031
 
81712
82032
  `;
82033
+ }
82034
+ /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
82035
+ pushEntry(entry) {
82036
+ const data = this.wireFor(entry);
81713
82037
  for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81714
82038
  }
81715
82039
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
@@ -81817,6 +82141,15 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
81817
82141
  var ADAPTERS = ["mock", "real"];
81818
82142
  var LATENCIES = ["zero", "realistic"];
81819
82143
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
82144
+ var WC_DISABLED = "off";
82145
+ function resolveWcProjectId(raw, problems) {
82146
+ if (raw === void 0 || raw === "" || raw === WC_DISABLED) return void 0;
82147
+ if (!/^[0-9a-f]{32}$/.test(raw)) {
82148
+ problems.push(`DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id, or '${WC_DISABLED}' to disable WalletConnect.`);
82149
+ return void 0;
82150
+ }
82151
+ return raw;
82152
+ }
81820
82153
  var NETWORK_DEFAULTS = {
81821
82154
  sepolia: {
81822
82155
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -81891,10 +82224,7 @@ function resolveBoundaryConfig(env) {
81891
82224
  }
81892
82225
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81893
82226
  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
- }
82227
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81898
82228
  let bridgeOpenBrowser;
81899
82229
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81900
82230
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -81966,10 +82296,7 @@ function resolveRealConfig(env) {
81966
82296
  const stateDir = env["DH_STATE_DIR"];
81967
82297
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81968
82298
  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
- }
82299
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81973
82300
  let bridgeOpenBrowser;
81974
82301
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81975
82302
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {