@gvnrdao/dh-mcp 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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,
@@ -41379,7 +41390,10 @@ var BoundaryCore = class {
41379
41390
  borrower: auth.borrower
41380
41391
  });
41381
41392
  if (!r.ok) return errEnvelope(failureToError(r.failure));
41382
- return okEnvelope({ attempted: r.value.attempted, transfers: r.value.transfers }, r.source);
41393
+ return okEnvelope(
41394
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...r.value.authorization ? { authorization: r.value.authorization } : {} },
41395
+ r.source
41396
+ );
41383
41397
  }
41384
41398
  // ---- meta ----
41385
41399
  world() {
@@ -42226,20 +42240,56 @@ var World = class {
42226
42240
  if (pos.borrower.toLowerCase() !== p.borrower.toLowerCase()) {
42227
42241
  return { ok: false, reason: `caller ${p.borrower} is not the borrower of this position` };
42228
42242
  }
42229
- const c = this.state.collateral[p.positionId];
42230
- const pending = (c?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42231
- const transfers = pending.map((spend) => {
42243
+ const fee = BigInt(p.networkFeeSats);
42244
+ const transfers = this.pendingSpends(p.positionId).map((spend) => {
42245
+ const utxoIdentifier = `${spend.txid}:${spend.vout}`;
42246
+ const refusal = this.retryFeeRefusal(spend, p.networkFeeSats);
42247
+ if (refusal) return { utxoIdentifier, ok: false, error: refusal };
42232
42248
  const { hash: txid } = this.nextId("btc-withdraw-retry");
42233
42249
  return {
42234
- utxoIdentifier: `${spend.txid}:${spend.vout}`,
42250
+ utxoIdentifier,
42235
42251
  ok: true,
42236
42252
  txid,
42237
- amountSentSats: spend.satoshis,
42253
+ // NET of the fee: what the destination actually receives. The fee is carved OUT of
42254
+ // the authorized amount, never added on top — the same semantics `withdraw` above
42255
+ // models and `IBTCSpendAuthorizer` enforces (the recipient receives
42256
+ // targetAmount − networkFee). Reporting the gross figure as "sent" would hide
42257
+ // whether the fee was honoured at all.
42258
+ amountSentSats: (BigInt(spend.satoshis) - fee).toString(),
42238
42259
  destination: spend.targetAddress
42239
42260
  };
42240
42261
  });
42241
42262
  return { ok: true, value: { attempted: transfers.length, transfers } };
42242
42263
  }
42264
+ /** Reservations whose coins have not been observed moving — the set phase 2 re-executes. */
42265
+ pendingSpends(positionId) {
42266
+ return (this.state.collateral[positionId]?.authorizedSpends ?? []).filter((s) => s.consumed === null);
42267
+ }
42268
+ /**
42269
+ * The fee cap the SDK applies to a reservation BEFORE it signs anything
42270
+ * (`diamond-hands-sdk.ts` `executeBTCWithdrawal`, above `buildBtcExecuteEnvelope`):
42271
+ *
42272
+ * if (request.networkFee * 2 >= request.targetAmount) { … refuse … }
42273
+ *
42274
+ * — audit M-E, a griefing cap, deliberately far tighter than "leaves something to send".
42275
+ * A reservation's `satoshis` here IS the authorized `targetAmount`, so the same arithmetic
42276
+ * applies per reservation. Returns the refusal, or null when phase 2 would proceed.
42277
+ */
42278
+ retryFeeRefusal(spend, networkFeeSats) {
42279
+ const target = BigInt(spend.satoshis);
42280
+ if (BigInt(networkFeeSats) * 2n >= target) {
42281
+ return `network fee ${networkFeeSats} sats is \u2265 50% of the ${target.toString()}-sat authorized amount on ${spend.txid}:${spend.vout} \u2014 the fee comes OUT of the authorized amount, and the protocol refuses to broadcast above that cap (real Bitcoin fees are typically <1% of value)`;
42282
+ }
42283
+ return null;
42284
+ }
42285
+ /**
42286
+ * How many of this position's outstanding reservations phase 2 would actually attempt at
42287
+ * this fee. Zero means the SDK never reaches `executeBTCWithdrawal`'s signing step, so the
42288
+ * wallet is never opened — which is what the mock's ceremony gate reads.
42289
+ */
42290
+ retryExecutableCount(positionId, networkFeeSats) {
42291
+ return this.pendingSpends(positionId).filter((s) => this.retryFeeRefusal(s, networkFeeSats) === null).length;
42292
+ }
42243
42293
  // ---- Mock Safes (plan 06): REAL verification semantics, no fakes (M6-21/27) ----
42244
42294
  safesMap() {
42245
42295
  return this.state.safes;
@@ -43033,7 +43083,7 @@ var SINK_CONTRACTS = {
43033
43083
  PositionManager: sinkAddress("PositionManager"),
43034
43084
  UCDToken: sinkAddress("UCDToken"),
43035
43085
  // PSM pair (plan 08 W1): the exchange's asymmetric approval targets/spenders —
43036
- // to-ucd approves UsdcToken → SimplePSMV2; to-usdc approves UCDToken → UCDController.
43086
+ // to-ucd approves UsdcToken → SimplePSMV2; from-ucd approves UCDToken → UCDController.
43037
43087
  SimplePSMV2: sinkAddress("SimplePSMV2"),
43038
43088
  UsdcToken: sinkAddress("UsdcToken"),
43039
43089
  UCDController: sinkAddress("UCDController")
@@ -43329,7 +43379,18 @@ var MockUpstreamPlugin = class {
43329
43379
  getHead: () => this.read("mock-chain", () => upOk({ height: this.world.state.events.length }, this.src("mock-chain"))),
43330
43380
  // PSM sim (plan 08 Part B Phase R): seeded from the sepolia fixture snapshot; the
43331
43381
  // mock's addresses are honest labels — the mock never fabricates chain-looking values.
43332
- 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;
43333
43394
  const psm = this.world.psmSeed();
43334
43395
  return upOk(
43335
43396
  {
@@ -43354,6 +43415,8 @@ var MockUpstreamPlugin = class {
43354
43415
  );
43355
43416
  }),
43356
43417
  getPsmQuote: (p) => this.read("mock-chain", () => {
43418
+ const known = this.mockStablecoinRefusal(p.stablecoin);
43419
+ if (known) return known;
43357
43420
  const q = p.direction === "swap" ? this.world.psmSwapQuote(BigInt(p.amountIn)) : this.world.psmRedeemQuote(BigInt(p.amountIn));
43358
43421
  return upOk({ amountOut: q.out.toString(), feeAmount: q.fee.toString() }, this.src("mock-chain"));
43359
43422
  })
@@ -43426,11 +43489,7 @@ var MockUpstreamPlugin = class {
43426
43489
  if (!r.ok) return this.rejected("recoverStaleSpend", r.reason);
43427
43490
  return upOk({ txRef: this.world.nextTxRef(), releasedSats: r.value.releasedSats }, this.src("mock-ops"));
43428
43491
  }),
43429
- retryWithdrawExecute: (p) => this.write("retryWithdrawExecute", () => {
43430
- const r = this.world.retryWithdrawExecute({ positionId: p.positionId, borrower: p.borrower });
43431
- if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43432
- return upOk({ attempted: r.value.attempted, transfers: r.value.transfers }, this.src("mock-ops"));
43433
- })
43492
+ retryWithdrawExecute: (p) => this.opRetryWithdrawExecute(p)
43434
43493
  };
43435
43494
  }
43436
43495
  indexer;
@@ -43482,6 +43541,19 @@ var MockUpstreamPlugin = class {
43482
43541
  return apply();
43483
43542
  }
43484
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
+ }
43485
43557
  noneRefusal() {
43486
43558
  if (this.signer && this.signer.manager.mode() === "none") {
43487
43559
  return upFail({ kind: "signer-missing", source: "signer-setup", message: this.signer.manager.invitation() });
@@ -43705,6 +43777,46 @@ var MockUpstreamPlugin = class {
43705
43777
  );
43706
43778
  });
43707
43779
  }
43780
+ /**
43781
+ * C-46 retry, and it takes the SAME ceremony `opWithdraw` takes.
43782
+ *
43783
+ * The first version of this op skipped all three gates: no `noneRefusal`, no wallet
43784
+ * ceremony, no `applyAuthorized`. It moved mock BTC on nothing but `confirmed: true`, so a
43785
+ * user who DECLINED in their wallet still saw the retry succeed. The real adapter does sign
43786
+ * — the SDK's phase 2 raises the blind-hash card before it broadcasts — so the mock was
43787
+ * passing requests the real protocol would refuse, which is the one thing a practice world
43788
+ * must never do.
43789
+ *
43790
+ * The ceremony is nonetheless PREFLIGHTED, because the SDK signs strictly less often than
43791
+ * "once per call": `executePendingBtcTransfers` reads the authorizer and `return []`s on an
43792
+ * empty set without entering `executeBTCWithdrawal` at all, and `executeBTCWithdrawal`'s own
43793
+ * fee cap refuses above `buildBtcExecuteEnvelope` — the only thing that touches the signer.
43794
+ * So a retry with nothing executable opens NO wallet on the real adapter, and a mock that
43795
+ * raised a ceremony there would teach a user to approve a popup the protocol never shows.
43796
+ */
43797
+ async opRetryWithdrawExecute(p) {
43798
+ const none = this.noneRefusal();
43799
+ if (none) return none;
43800
+ const executable = this.world.retryExecutableCount(p.positionId, p.networkFeeSats);
43801
+ const card = `re-run the BTC withdrawal EXECUTE step for ${executable} outstanding reservation(s) on ${p.positionId}`;
43802
+ const cer = executable > 0 ? this.ceremonyNow() : null;
43803
+ const auth = cer ? await cer.authorizeTypedData({ action: "withdraw", borrower: p.borrower, detail: card }) : null;
43804
+ if (auth && !auth.ok) return auth.failure;
43805
+ if (auth?.ok) this.bindIfDiscovering(auth.authorization);
43806
+ return this.write("retryWithdrawExecute", () => {
43807
+ const sig = executable === 0 ? null : auth ?? this.sign("withdraw", p.borrower, card);
43808
+ if (sig && !sig.ok) return sig.failure;
43809
+ const r = this.applyAuthorized(
43810
+ sig ? sig.authorization : void 0,
43811
+ () => this.world.retryWithdrawExecute({ positionId: p.positionId, networkFeeSats: p.networkFeeSats, borrower: p.borrower })
43812
+ );
43813
+ if (!r.ok) return this.rejected("retryWithdrawExecute", r.reason);
43814
+ return upOk(
43815
+ { attempted: r.value.attempted, transfers: r.value.transfers, ...sig ? { authorization: sig.authorization } : {} },
43816
+ this.src("mock-ops")
43817
+ );
43818
+ });
43819
+ }
43708
43820
  /** BWAR mirror ceremony (plan 06 E3): a SAFE borrower allowlists a BTC destination via
43709
43821
  * a Safe transaction (owner signatures, durable — async collection is honest here). On
43710
43822
  * mock, EOA borrowers have no allowlist gate; refusing beats faking success. */
@@ -78325,6 +78437,19 @@ function listPositionsQuery(f) {
78325
78437
  }
78326
78438
  return { document: LIST_POSITIONS, variables: { first, skip } };
78327
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
+ `;
78328
78453
 
78329
78454
  // src/boundary/upstream/real/psm-calls.ts
78330
78455
  var import_ethers31 = require("ethers");
@@ -78464,6 +78589,11 @@ var PsmCalls = class {
78464
78589
  return { ucdWei: ucdWei.toString(), stablecoinUnits: stablecoinUnits.toString() };
78465
78590
  });
78466
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
+ }
78467
78597
  async status() {
78468
78598
  return this.call(async () => {
78469
78599
  const s = this.deps.stablecoinAddress;
@@ -78923,13 +79053,6 @@ function buildValidationContext(network, chainId) {
78923
79053
  }
78924
79054
 
78925
79055
  // src/boundary/upstream/real/write-ops.ts
78926
- function psmMainnetWriteRefusal(network, chainId) {
78927
- return {
78928
- kind: "rejected",
78929
- source: SOURCE5,
78930
- 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.`
78931
- };
78932
- }
78933
79056
  var SOURCE5 = "real-ops";
78934
79057
  var OP_LAYOUT = "dh-op-envelope-v1";
78935
79058
  function randomNonceHex() {
@@ -79277,8 +79400,7 @@ function buildWriteOps(deps) {
79277
79400
  * keystore-signed and broadcast through `/api/lit/broadcast` (the existing sepolia
79278
79401
  * write pattern). NOT live-run in this delivery — Phase S is Master-gated. */
79279
79402
  psmSwap: async (p) => {
79280
- if (config.network !== "sepolia") return upFail(psmMainnetWriteRefusal(config.network, chainId));
79281
- const pr = deps.psm();
79403
+ const pr = await deps.psm(p.stablecoin);
79282
79404
  if (!pr.ok) return upFail(pr.failure);
79283
79405
  const calls = pr.calls;
79284
79406
  const addr = calls.addresses();
@@ -79659,6 +79781,9 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79659
79781
  );
79660
79782
  }
79661
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));
79662
79787
  const outcome = await this.deps.bridge.requestSignature({
79663
79788
  id: (0, import_node_crypto5.randomUUID)(),
79664
79789
  kind: "personal-sign",
@@ -79670,15 +79795,16 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers37.ether
79670
79795
  "(identical to how diamondhands.credit signs withdrawals).",
79671
79796
  "Approve ONLY if you initiated this exact BTC withdrawal in the conversation.",
79672
79797
  "",
79673
- "SIGN NOW \u2014 this one is on a clock. The payload was stamped before this card was",
79674
- `raised and is only valid inside a single ${QUANTUM_WINDOW_SECONDS}-second window, so the time left is`,
79675
- "under a minute and often nearer twenty seconds \u2014 far less than the approval page",
79676
- "itself allows. If it expires the signature is refused, the withdrawal does not",
79677
- "complete, and the reserved coins stay reserved until that is cleared. Decline and",
79678
- "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."
79679
79804
  ],
79680
79805
  expectedSigner: this.deps.borrower,
79681
79806
  chainId: this.deps.chainId,
79807
+ expiresAtSec,
79682
79808
  personalSign: { layout: RAW_HASH_LAYOUT, fields: { hash: hashHex }, hashHex }
79683
79809
  });
79684
79810
  if (outcome.status !== "approved" || !outcome.signature) {
@@ -79882,13 +80008,27 @@ var RealUpstreamPlugin = class {
79882
80008
  getHead: () => this.chainRead(async () => ({ height: await this.provider.getBlockNumber() })),
79883
80009
  // PSM reads (plan 08 Part B Phase R): on-chain views ONLY, through the dedicated
79884
80010
  // wrapper (NOT chainRead) so custom-error refusals decode WITH their figures.
79885
- getPsmStatus: () => {
79886
- const r = this.psmCalls();
79887
- 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
+ );
80024
+ },
80025
+ getPsmStatus: async (p) => {
80026
+ const r = await this.psmCallsFor(p.stablecoin);
80027
+ return r.ok ? r.calls.status() : upFail(r.failure);
79888
80028
  },
79889
- getPsmQuote: (p) => {
79890
- const r = this.psmCalls();
79891
- if (!r.ok) return Promise.resolve(upFail(r.failure));
80029
+ getPsmQuote: async (p) => {
80030
+ const r = await this.psmCallsFor(p.stablecoin);
80031
+ if (!r.ok) return upFail(r.failure);
79892
80032
  return p.direction === "swap" ? r.calls.swapQuote(p.amountIn) : r.calls.redemptionQuote(p.amountIn);
79893
80033
  }
79894
80034
  };
@@ -79956,12 +80096,13 @@ var RealUpstreamPlugin = class {
79956
80096
  allowlistWithdrawalAddress: () => readOnly("allowlistWithdrawalAddress"),
79957
80097
  delegationSetup: () => readOnly("delegationSetup"),
79958
80098
  delegationGrant: () => readOnly("delegationGrant"),
79959
- // THE mainnet standing block, anchored at the PSM write port (plan 08 M8-7/M8-14):
79960
- // any non-sepolia network refuses typed — naming the network gate truthfully —
79961
- // BEFORE any ceremony or signer touch. A signerless sepolia boot refuses on the
79962
- // 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.
79963
80104
  psmSwap: () => Promise.resolve(
79964
- this.config.network !== "sepolia" ? upFail(psmMainnetWriteRefusal(this.config.network, this.config.chainId)) : upFail({
80105
+ upFail({
79965
80106
  kind: "signer-missing",
79966
80107
  source: "real-ops",
79967
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."
@@ -80078,7 +80219,7 @@ var RealUpstreamPlugin = class {
80078
80219
  session,
80079
80220
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80080
80221
  readDetails: (id) => this.readPositionDetails(id),
80081
- psm: () => this.psmCalls(),
80222
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80082
80223
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80083
80224
  });
80084
80225
  }
@@ -80212,7 +80353,7 @@ var RealUpstreamPlugin = class {
80212
80353
  session,
80213
80354
  getWriteSdk: () => this.sdkCache.get(key) ?? null,
80214
80355
  readDetails: (id) => this.readPositionDetails(id),
80215
- psm: () => this.psmCalls(),
80356
+ psm: (stablecoin) => this.psmCallsFor(stablecoin),
80216
80357
  assertValidatorConfigured: () => this.assertValidatorConfigured()
80217
80358
  });
80218
80359
  this.opsGatewayCache.set(key, gateway);
@@ -80358,35 +80499,91 @@ var RealUpstreamPlugin = class {
80358
80499
  * (never invented): sepolia runs the self-mintable mock USDC; the MAINNET table carries
80359
80500
  * SimplePSMV2 but NO stablecoin address — mainnet PSM reads refuse typed rather than
80360
80501
  * guess the Circle USDC address (reads-verify only, and only once the table names it). */
80361
- psmWrapper = null;
80362
- psmCalls() {
80363
- 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 };
80364
80539
  const psmAddress = this.contracts["SimplePSMV2"];
80365
- const stablecoinAddress = this.config.network === "sepolia" ? this.contracts["mockUsdcToken"] : this.contracts["usdcToken"];
80366
- if (!psmAddress || !stablecoinAddress) {
80367
- const missing = [!psmAddress ? "SimplePSMV2" : null, !stablecoinAddress ? "the PSM stablecoin (USDC)" : null].filter((x) => x !== null).join(" and ");
80540
+ if (!psmAddress) {
80368
80541
  return {
80369
80542
  ok: false,
80370
80543
  failure: {
80371
80544
  kind: "unavailable",
80372
80545
  source: "chain-rpc",
80373
- 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.`
80374
80547
  }
80375
80548
  };
80376
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;
80377
80571
  const ucdTokenAddress = this.contracts["UCDToken"];
80378
80572
  const ucdControllerAddress = this.contracts["UCDController"];
80379
- this.psmWrapper = new PsmCalls({
80573
+ const built = new PsmCalls({
80380
80574
  provider: this.provider,
80381
80575
  psmAddress,
80382
- stablecoinAddress,
80383
- 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,
80384
80580
  // Write plane (plan 08 W1): the redeem approve leg's spender is the UCDController
80385
80581
  // (the PSM burns via controller.burnFromPsm) — table-sourced, never invented.
80386
80582
  ...ucdTokenAddress ? { ucdTokenAddress } : {},
80387
80583
  ...ucdControllerAddress ? { ucdControllerAddress } : {}
80388
80584
  });
80389
- return { ok: true, calls: this.psmWrapper };
80585
+ this.psmWrappers.set(key, built);
80586
+ return { ok: true, calls: built };
80390
80587
  }
80391
80588
  src(id) {
80392
80589
  const kind = id === "subgraph" ? "subgraph" : id === "chain-rpc" ? "chain" : "lit-ops";
@@ -80649,6 +80846,7 @@ function renderApprovalPage(sessionId, nonce) {
80649
80846
  <div id="request" class="hidden">
80650
80847
  <div id="action" class="action"></div>
80651
80848
  <div id="card" class="card"></div>
80849
+ <div id="deadline" class="status hidden"></div>
80652
80850
  <button id="approve">Approve in wallet</button>
80653
80851
  <button id="reject">Reject</button>
80654
80852
  </div>
@@ -80681,10 +80879,19 @@ const statusEl = document.getElementById("status");
80681
80879
  const requestEl = document.getElementById("request");
80682
80880
  const actionEl = document.getElementById("action");
80683
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;
80684
80886
  const walletEl = document.getElementById("wallet");
80685
80887
  let account = null;
80686
80888
  let chainId = null;
80687
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();
80688
80895
 
80689
80896
  function post(path, body) {
80690
80897
  return fetch(path, {
@@ -80747,43 +80954,135 @@ async function onAccountsChanged(accounts) {
80747
80954
  account = (accounts && accounts[0]) || null;
80748
80955
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80749
80956
  showWallet();
80750
- clearRequest("Wallet changed \u2014 pending request invalidated.");
80957
+ invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
80751
80958
  }
80752
80959
 
80753
80960
  async function onChainChanged(cid) {
80754
80961
  chainId = typeof cid === "string" ? parseInt(cid, 16) : Number(cid);
80755
80962
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
80756
80963
  showWallet();
80757
- clearRequest("Network changed \u2014 pending request invalidated.");
80964
+ invalidatePageRequests("Network changed \u2014 pending request invalidated.");
80758
80965
  }
80759
80966
 
80760
80967
  function listen() {
80761
80968
  const es = new EventSource(BASE + "events?s=" + SESSION);
80762
- 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
+ };
80763
80976
  es.onerror = () => showStatus("Bridge connection lost \u2014 the MCP process may have exited.");
80764
80977
  }
80765
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
+
80766
81009
  function renderRequest() {
80767
81010
  actionEl.textContent = current.action;
80768
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");
80769
81018
  requestEl.classList.remove("hidden");
80770
- 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");
81035
+ }
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);
80771
81057
  }
80772
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.
80773
81062
  function clearRequest(text) {
80774
- current = null;
80775
- requestEl.classList.add("hidden");
80776
- 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
80777
81073
  }
80778
81074
 
80779
- document.getElementById("reject").onclick = async () => {
81075
+ rejectEl.onclick = async () => {
80780
81076
  if (!current) return;
80781
81077
  await post(BASE + "result", { requestId: current.id, approved: false, reason: "user declined on the approval page" });
80782
81078
  clearRequest("Rejected. Waiting for the next request\u2026");
80783
81079
  };
80784
81080
 
80785
- document.getElementById("approve").onclick = async () => {
81081
+ approveEl.onclick = async () => {
80786
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; }
80787
81086
  const req = current;
80788
81087
  try {
80789
81088
  if (req.kind === "transaction") {
@@ -80800,7 +81099,10 @@ document.getElementById("approve").onclick = async () => {
80800
81099
  const fbody = await fr.json();
80801
81100
  if (!fr.ok) { showStatus("Cannot prepare the signature right now: " + (fbody.error || "finalize failed") + " \u2014 retry the operation."); return; }
80802
81101
  const fresh = fbody.request;
80803
- // \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);
80804
81106
  current = fresh; renderRequest();
80805
81107
  // \u2026and A0.4: recompute the hash from the DISPLAYED fields. No match, no button.
80806
81108
  const recomputed = dhPageCrypto.packAndHash(fresh.personalSign.layout, fresh.personalSign.fields);
@@ -80983,9 +81285,6 @@ var SignatureBridge = class {
80983
81285
  /** Plan 17 E2: single-decision concurrency cap (null = unbounded, the loopback tier). */
80984
81286
  maxPending;
80985
81287
  attachGraceMs;
80986
- /** Last sweep tick that saw a live attachment — the unattended grace measures from
80987
- * max(enqueue, this), so a page closed mid-wait gets the same grace as never-opened. */
80988
- lastAttachedMs = 0;
80989
81288
  server = null;
80990
81289
  port = 0;
80991
81290
  /** Started state independent of the transport binding (mounted bridges own no server). */
@@ -81096,7 +81395,7 @@ var SignatureBridge = class {
81096
81395
  connectedAccounts() {
81097
81396
  const seen = /* @__PURE__ */ new Map();
81098
81397
  for (const s of this.sessions.values()) {
81099
- if (s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81398
+ if (!s.refused && s.wallet) seen.set(s.wallet.account.toLowerCase(), s.wallet.account);
81100
81399
  }
81101
81400
  if (this.wcActive && this.wallet) seen.set(this.wallet.account.toLowerCase(), this.wallet.account);
81102
81401
  return [...seen.values()];
@@ -81136,13 +81435,16 @@ var SignatureBridge = class {
81136
81435
  enqueuedMs: now,
81137
81436
  resolve,
81138
81437
  settled: false,
81139
- ...handlers?.finalize ? { finalize: handlers.finalize } : {}
81438
+ ...handlers?.finalize ? { finalize: handlers.finalize } : {},
81439
+ owner: this.wcActive ? "wc" : "page",
81440
+ dispatched: false,
81441
+ lastAttachedMs: now
81140
81442
  };
81141
81443
  this.pending.set(request.id, entry);
81142
- if (this.wcActive) {
81444
+ if (entry.owner === "wc") {
81143
81445
  void this.driveWc(entry);
81144
81446
  } else {
81145
- this.push(request);
81447
+ this.pushEntry(entry);
81146
81448
  }
81147
81449
  });
81148
81450
  }
@@ -81163,10 +81465,16 @@ var SignatureBridge = class {
81163
81465
  enqueuedMs: now,
81164
81466
  resolve,
81165
81467
  settled: false,
81166
- 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
81167
81475
  };
81168
81476
  this.pending.set(request.id, entry);
81169
- this.push(request);
81477
+ this.pushEntry(entry);
81170
81478
  if (this.wcActive) void this.driveWcCollection(entry);
81171
81479
  });
81172
81480
  }
@@ -81205,7 +81513,9 @@ var SignatureBridge = class {
81205
81513
  }
81206
81514
  try {
81207
81515
  if (req.kind === "transaction") {
81516
+ this.pushEntry(entry);
81208
81517
  const tx2 = req.tx;
81518
+ entry.dispatched = true;
81209
81519
  const txHash = await transport.request("eth_sendTransaction", [
81210
81520
  { from: account, to: tx2.to, data: tx2.data, value: tx2.value, ...tx2.gas ? { gas: tx2.gas } : {} }
81211
81521
  ]);
@@ -81217,11 +81527,22 @@ var SignatureBridge = class {
81217
81527
  req.card = fresh.card;
81218
81528
  }
81219
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;
81220
81539
  const signature = await transport.request("personal_sign", [ps.hashHex, account]);
81221
81540
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81222
81541
  } else {
81542
+ this.pushEntry(entry);
81223
81543
  const { withEip712DomainType: withEip712DomainType2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
81224
81544
  const payload = withEip712DomainType2(req.typedData);
81545
+ entry.dispatched = true;
81225
81546
  const signature = await transport.request("eth_signTypedData_v4", [account, JSON.stringify(payload)]);
81226
81547
  if (!entry.settled) this.settle(entry, { status: "approved", account, signature });
81227
81548
  }
@@ -81241,29 +81562,54 @@ var SignatureBridge = class {
81241
81562
  * with a live attachment is in use and must never be evicted. */
81242
81563
  attachedNow() {
81243
81564
  if (this.wcActive) return true;
81244
- 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;
81245
81573
  return false;
81246
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
+ }
81247
81584
  /** Expire overdue requests; fail UNATTENDED requests fast. Runs on a real-time
81248
81585
  * interval; tests call it directly with the injected clock advanced. Order matters:
81249
81586
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
81250
81587
  sweep() {
81251
81588
  const now = this.clock();
81252
- const attached = this.attachedNow();
81253
- if (attached) this.lastAttachedMs = now;
81254
81589
  for (const entry of this.pending.values()) {
81255
81590
  if (entry.settled) continue;
81256
81591
  if (now >= entry.deadlineMs) {
81257
81592
  this.settle(entry, { status: "expired" });
81258
81593
  continue;
81259
81594
  }
81260
- if (!attached && now - Math.max(entry.enqueuedMs, this.lastAttachedMs) >= this.attachGraceMs) {
81261
- this.settle(entry, {
81262
- status: "invalidated",
81263
- 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`
81264
- });
81595
+ if (this.attachedFor(entry)) {
81596
+ entry.lastAttachedMs = now;
81597
+ continue;
81265
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";
81266
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`;
81267
81613
  }
81268
81614
  /** A live WalletConnect session exists right now (disconnect reports it truthfully). */
81269
81615
  walletConnectActive() {
@@ -81357,7 +81703,7 @@ var SignatureBridge = class {
81357
81703
  return;
81358
81704
  }
81359
81705
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
81360
- this.sessions.set(sessionId, { wallet: null, sse: null });
81706
+ this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
81361
81707
  const page = htmlPageSecurityHeaders();
81362
81708
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
81363
81709
  res.end(renderApprovalPage(sessionId, page.nonce));
@@ -81387,7 +81733,8 @@ var SignatureBridge = class {
81387
81733
  const refusal = info ? this.accountRefusal(info.account) : null;
81388
81734
  if (info && refusal) {
81389
81735
  this.wcActive = false;
81390
- this.wallet = null;
81736
+ this.rebuildSharedWallet();
81737
+ this.demoteWcEntries();
81391
81738
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
81392
81739
  `);
81393
81740
  return;
@@ -81397,7 +81744,10 @@ var SignatureBridge = class {
81397
81744
  if (info === null) {
81398
81745
  for (const entry of this.pending.values()) {
81399
81746
  if (!entry.settled && !entry.collect) {
81400
- 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
+ });
81401
81751
  }
81402
81752
  }
81403
81753
  }
@@ -81469,9 +81819,7 @@ var SignatureBridge = class {
81469
81819
  session.sse?.end();
81470
81820
  session.sse = res;
81471
81821
  for (const entry of this.pending.values()) {
81472
- if (!entry.settled) res.write(`data: ${JSON.stringify(entry.request)}
81473
-
81474
- `);
81822
+ if (!entry.settled) res.write(this.wireFor(entry));
81475
81823
  }
81476
81824
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
81477
81825
  keepAlive.unref();
@@ -81491,6 +81839,7 @@ var SignatureBridge = class {
81491
81839
  }
81492
81840
  const refusal = this.accountRefusal(account);
81493
81841
  if (refusal) {
81842
+ this.quarantine(session, refusal);
81494
81843
  this.deny(res, 403, refusal);
81495
81844
  return;
81496
81845
  }
@@ -81529,10 +81878,15 @@ var SignatureBridge = class {
81529
81878
  const chainId = Number(body["chainId"]);
81530
81879
  const prev = session.wallet;
81531
81880
  const offered = /^0x[0-9a-fA-F]{40}$/.test(account) && Number.isInteger(chainId) ? { account, chainId } : null;
81532
- const refusedSwitch = offered !== null && this.accountRefusal(offered.account) !== null;
81533
- session.wallet = refusedSwitch ? null : offered;
81534
- if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81535
- this.wallet = session.wallet;
81881
+ const switchRefusal = offered !== null ? this.accountRefusal(offered.account) : null;
81882
+ const refusedSwitch = switchRefusal !== null;
81883
+ if (refusedSwitch) {
81884
+ this.quarantine(session, switchRefusal);
81885
+ } else {
81886
+ session.wallet = offered;
81887
+ if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
81888
+ this.wallet = session.wallet;
81889
+ }
81536
81890
  }
81537
81891
  const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
81538
81892
  if (unchanged) {
@@ -81541,10 +81895,36 @@ var SignatureBridge = class {
81541
81895
  }
81542
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";
81543
81897
  for (const entry of this.pending.values()) {
81544
- 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 });
81545
81901
  }
81546
81902
  this.ok(res);
81547
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
+ }
81548
81928
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
81549
81929
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
81550
81930
  async onFinalize(body, res) {
@@ -81558,6 +81938,10 @@ var SignatureBridge = class {
81558
81938
  this.deny(res, 400, "finalize applies only to personal-sign requests");
81559
81939
  return;
81560
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
+ }
81561
81945
  if (entry.finalize) {
81562
81946
  let fresh;
81563
81947
  try {
@@ -81584,10 +81968,22 @@ var SignatureBridge = class {
81584
81968
  return;
81585
81969
  }
81586
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
+ }
81587
81979
  this.settle(entry, { status: "rejected", reason: String(body["reason"] ?? "user declined in wallet") });
81588
81980
  this.ok(res);
81589
81981
  return;
81590
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
+ }
81591
81987
  const account = String(body["account"] ?? "");
81592
81988
  if (!/^0x[0-9a-fA-F]{40}$/.test(account)) {
81593
81989
  this.deny(res, 400, "approved result requires the signing account");
@@ -81624,12 +82020,21 @@ var SignatureBridge = class {
81624
82020
  this.pending.delete(entry.request.id);
81625
82021
  entry.resolve(outcome);
81626
82022
  }
81627
- /** Broadcast a request to EVERY open page (multi-owner links — plan 06 §1.5). */
81628
- push(request) {
81629
- 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)}
81630
82031
 
81631
82032
  `;
81632
- for (const s of this.sessions.values()) s.sse?.write(data);
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);
82037
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
81633
82038
  }
81634
82039
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
81635
82040
  pushProgress(payload) {
@@ -81637,7 +82042,48 @@ var SignatureBridge = class {
81637
82042
  data: ${JSON.stringify(payload)}
81638
82043
 
81639
82044
  `;
81640
- for (const s of this.sessions.values()) s.sse?.write(data);
82045
+ for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
82046
+ }
82047
+ /**
82048
+ * C-47: `this.wallet` is DERIVED, never guessed.
82049
+ *
82050
+ * It is the shared last-wallet view `candidate()` reads, and an earlier fix decided its
82051
+ * ownership from the `wcActive` flag — "while that is true the wallet came from
82052
+ * WalletConnect". That is false: an approval page can say hello AFTER a WC session is
82053
+ * live, so the page owned the wallet while the flag still said WC did. A refused pairing
82054
+ * then blanked a perfectly good page session, turning someone scanning the QR with the
82055
+ * wrong account into a disconnect for the legitimate user.
82056
+ *
82057
+ * Deriving it from live state removes the guess. Preference order matches
82058
+ * `requestSignature`, which routes to WalletConnect ahead of the page.
82059
+ */
82060
+ rebuildSharedWallet() {
82061
+ if (this.wcActive && this.wcTransport) {
82062
+ const wc = this.wcTransport.active();
82063
+ if (wc && !this.accountRefusal(wc.account)) {
82064
+ this.wallet = { account: wc.account, chainId: wc.chainId };
82065
+ return;
82066
+ }
82067
+ }
82068
+ let latest = null;
82069
+ for (const s of this.sessions.values()) if (!s.refused && s.wallet) latest = s.wallet;
82070
+ this.wallet = latest;
82071
+ }
82072
+ /**
82073
+ * C-47: the ONE way a page session is refused. Setting `refused` alone was not enough —
82074
+ * an ALREADY-ADMITTED session that later offers a wrong account kept its `wallet`, so it
82075
+ * still answered `connectedAccounts()` for quorum and could still be the shared candidate.
82076
+ * Quarantine therefore does all four things together: mark it, drop its wallet, close its
82077
+ * stream, and re-derive the shared view without it.
82078
+ */
82079
+ quarantine(session, reason) {
82080
+ session.refused = reason;
82081
+ session.wallet = null;
82082
+ if (session.sse) {
82083
+ session.sse.end();
82084
+ session.sse = null;
82085
+ }
82086
+ this.rebuildSharedWallet();
81641
82087
  }
81642
82088
  sessionOf(candidate, res) {
81643
82089
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
@@ -81645,6 +82091,10 @@ data: ${JSON.stringify(payload)}
81645
82091
  this.deny(res, 403, "missing or wrong session");
81646
82092
  return null;
81647
82093
  }
82094
+ if (session.refused) {
82095
+ this.deny(res, 403, session.refused);
82096
+ return null;
82097
+ }
81648
82098
  return session;
81649
82099
  }
81650
82100
  checkSession(candidate, res) {
@@ -81691,6 +82141,15 @@ var NETWORKS = { sepolia: 11155111, mainnet: 1 };
81691
82141
  var ADAPTERS = ["mock", "real"];
81692
82142
  var LATENCIES = ["zero", "realistic"];
81693
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
+ }
81694
82153
  var NETWORK_DEFAULTS = {
81695
82154
  sepolia: {
81696
82155
  rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
@@ -81765,10 +82224,7 @@ function resolveBoundaryConfig(env) {
81765
82224
  }
81766
82225
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81767
82226
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
81768
- const wcProjectId = env["DH_WC_PROJECT_ID"];
81769
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
81770
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
81771
- }
82227
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81772
82228
  let bridgeOpenBrowser;
81773
82229
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81774
82230
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {
@@ -81840,10 +82296,7 @@ function resolveRealConfig(env) {
81840
82296
  const stateDir = env["DH_STATE_DIR"];
81841
82297
  const bridgeUrlFile = env["DH_BRIDGE_URL_FILE"];
81842
82298
  const bridgeOpenRaw = env["DH_BRIDGE_OPEN"];
81843
- const wcProjectId = env["DH_WC_PROJECT_ID"];
81844
- if (wcProjectId !== void 0 && wcProjectId !== "" && !/^[0-9a-f]{32}$/.test(wcProjectId)) {
81845
- problems.push("DH_WC_PROJECT_ID must be a 32-char hex WalletConnect project id.");
81846
- }
82299
+ const wcProjectId = resolveWcProjectId(env["DH_WC_PROJECT_ID"], problems);
81847
82300
  let bridgeOpenBrowser;
81848
82301
  if (bridgeOpenRaw !== void 0 && bridgeOpenRaw !== "") {
81849
82302
  if (bridgeOpenRaw !== "0" && bridgeOpenRaw !== "1") {