@gvnrdao/dh-mcp 0.5.19 → 0.5.21

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.
@@ -95,7 +95,8 @@ var init_wc_transport = __esm({
95
95
  this.client = client;
96
96
  this.cfg = cfg;
97
97
  this.scratch = scratch;
98
- client.on("session_delete", () => {
98
+ client.on("session_delete", ({ topic }) => {
99
+ if (this.session === null || this.session.topic !== topic) return;
99
100
  this.session = null;
100
101
  this.sessionListener?.(null);
101
102
  });
@@ -107,7 +108,7 @@ var init_wc_transport = __esm({
107
108
  const client = await import_sign_client.default.init({
108
109
  core,
109
110
  projectId: cfg.projectId,
110
- metadata: WC_DAPP_METADATA
111
+ metadata: cfg.metadata ?? WC_DAPP_METADATA
111
112
  });
112
113
  return new _WcTransport(client, cfg, scratch);
113
114
  }
@@ -125,14 +126,21 @@ var init_wc_transport = __esm({
125
126
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
126
127
  });
127
128
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
129
+ const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
130
+ if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
128
131
  void approval().then((session) => {
129
132
  const first = session.namespaces["eip155"]?.accounts[0];
130
133
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
131
134
  const [, chainIdStr, account] = first.split(":");
135
+ const previous = this.session;
132
136
  this.session = { topic: session.topic, account, chainId: Number(chainIdStr) };
133
- this.sessionListener?.(this.active());
137
+ const verdict = this.sessionListener?.({ ...this.active(), pairingId });
138
+ if (verdict === false) {
139
+ this.session = previous;
140
+ void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
141
+ }
134
142
  }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
135
- return { uri };
143
+ return { uri, pairingId };
136
144
  }
137
145
  /** Route one wallet request over the active session. Throws on user rejection. */
138
146
  async request(method, params) {
@@ -13543,6 +13551,12 @@ var require_follow_redirects = __commonJS({
13543
13551
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
13544
13552
  if (!options.headers) {
13545
13553
  options.headers = {};
13554
+ } else if (Array.isArray(options.headers)) {
13555
+ var headerList = options.headers;
13556
+ options.headers = {};
13557
+ for (var i = 0; i < headerList.length; i += 2) {
13558
+ options.headers[headerList[i]] = headerList[i + 1];
13559
+ }
13546
13560
  }
13547
13561
  if (!isArray2(options.sensitiveHeaders)) {
13548
13562
  options.sensitiveHeaders = [];
@@ -13817,7 +13831,7 @@ var require_follow_redirects = __commonJS({
13817
13831
  return URL3 && value instanceof URL3;
13818
13832
  }
13819
13833
  function escapeRegex(regex) {
13820
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
13834
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
13821
13835
  }
13822
13836
  module2.exports = wrap({ http: http4, https: https2 });
13823
13837
  module2.exports.wrap = wrap;
@@ -14571,113 +14585,113 @@ var require_pkg_src = __commonJS({
14571
14585
  deployedAt: 1784569687492,
14572
14586
  size: 4140,
14573
14587
  hash: "4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b",
14574
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
14588
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
14575
14589
  pkp: {
14576
14590
  publicKey: "0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f",
14577
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14591
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14578
14592
  }
14579
14593
  },
14580
14594
  btcTransactionSigner: {
14581
- cid: "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf",
14595
+ cid: "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U",
14582
14596
  authorizedCidHex: cidToHex(
14583
- "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf"
14597
+ "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U"
14584
14598
  ),
14585
14599
  name: "Btc Transaction Signer",
14586
14600
  description: "Production Btc Transaction Signer",
14587
14601
  version: "1.1.1",
14588
14602
  deployed: true,
14589
- deployedAt: 1787923905597,
14590
- size: 70646,
14591
- hash: "37c3bb72a660c8275d92e1b73f9482742d86b64789480b9246304c0ca1bab47a"
14603
+ deployedAt: 1790246185256,
14604
+ size: 73313,
14605
+ hash: "d8b6bc646ba33fee7d46c8e9b281de776081ea6f182f56fd15d4c52aaf3dd030"
14592
14606
  },
14593
14607
  ucdMintValidator: {
14594
- cid: "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc",
14608
+ cid: "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe",
14595
14609
  authorizedCidHex: cidToHex(
14596
- "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc"
14610
+ "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe"
14597
14611
  ),
14598
14612
  name: "Ucd Mint Validator",
14599
14613
  description: "Production Ucd Mint Validator",
14600
- version: "1.2.1",
14614
+ version: "1.3.0",
14601
14615
  deployed: true,
14602
- deployedAt: 1787923919527,
14603
- size: 86197,
14604
- hash: "c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf",
14605
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14616
+ deployedAt: 1790246219868,
14617
+ size: 90022,
14618
+ hash: "65e8cb778c2b767ae6eb37cb5db7b4c5a3f2468d508463c847c83c1b6825fadd",
14619
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14606
14620
  pkp: {
14607
14621
  publicKey: "0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb",
14608
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14622
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14609
14623
  }
14610
14624
  },
14611
14625
  processPaymentValidator: {
14612
- cid: "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF",
14626
+ cid: "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8",
14613
14627
  authorizedCidHex: cidToHex(
14614
- "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF"
14628
+ "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8"
14615
14629
  ),
14616
14630
  name: "Process Payment Validator",
14617
14631
  description: "Production Process Payment Validator",
14618
14632
  version: "1.2.1",
14619
14633
  deployed: true,
14620
- deployedAt: 1787923987153,
14621
- size: 82217,
14622
- hash: "13defa19614215ab3b1fe88955d69e530d13a09475396af932fe0e213637da2f",
14623
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14634
+ deployedAt: 1790246225795,
14635
+ size: 85107,
14636
+ hash: "25ecf952c4c44c40b0920b92d57906e7010ed9a38e2ba41ccdee6d3377c2b596",
14637
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14624
14638
  pkp: {
14625
14639
  publicKey: "0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad",
14626
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14640
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14627
14641
  }
14628
14642
  },
14629
14643
  extendPositionValidator: {
14630
- cid: "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m",
14644
+ cid: "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX",
14631
14645
  authorizedCidHex: cidToHex(
14632
- "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m"
14646
+ "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX"
14633
14647
  ),
14634
14648
  name: "Extend Position Validator",
14635
14649
  description: "Production Extend Position Validator",
14636
14650
  version: "1.2.1",
14637
14651
  deployed: true,
14638
- deployedAt: 1787923999294,
14639
- size: 79975,
14640
- hash: "31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a",
14641
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14652
+ deployedAt: 1790246231975,
14653
+ size: 82853,
14654
+ hash: "25d4887b7f646649db2bb7f2bfb77d039db83228a6c454377ca26c779b0903cc",
14655
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14642
14656
  pkp: {
14643
14657
  publicKey: "0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836",
14644
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14658
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14645
14659
  }
14646
14660
  },
14647
14661
  btcWithdrawal: {
14648
- cid: "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY",
14662
+ cid: "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP",
14649
14663
  authorizedCidHex: cidToHex(
14650
- "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY"
14664
+ "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP"
14651
14665
  ),
14652
14666
  name: "Btc Withdrawal",
14653
14667
  description: "Production Btc Withdrawal",
14654
14668
  version: "1.2.7",
14655
14669
  deployed: true,
14656
- deployedAt: 1787924017769,
14657
- size: 100069,
14658
- hash: "4f8e27414e4da235e63d6ae1325c63f3d2fb956464515a21aa007a99935f0f13",
14659
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14670
+ deployedAt: 1790246239599,
14671
+ size: 101228,
14672
+ hash: "2ed25eca6cc80a43061b7ad119737af48158fdb61d59f10cd06cea51b607f112",
14673
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14660
14674
  pkp: {
14661
14675
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
14662
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14676
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14663
14677
  }
14664
14678
  },
14665
14679
  liquidationValidator: {
14666
- cid: "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx",
14680
+ cid: "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb",
14667
14681
  authorizedCidHex: cidToHex(
14668
- "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx"
14682
+ "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb"
14669
14683
  ),
14670
14684
  name: "Liquidation Validator",
14671
14685
  description: "Production Liquidation Validator",
14672
14686
  version: "1.2.1",
14673
14687
  deployed: true,
14674
- deployedAt: 1785173262533,
14675
- size: 66846,
14676
- hash: "b35ee7706d733d625faa4dbe37f73c8e20f0c1befa897cd7875e827de52003de",
14677
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14688
+ deployedAt: 1790246247904,
14689
+ size: 70308,
14690
+ hash: "582ccf0ec7f715195e20fdc885996743cb42125b64173424e360ee63db62bbd8",
14691
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14678
14692
  pkp: {
14679
14693
  publicKey: "0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8",
14680
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14694
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14681
14695
  }
14682
14696
  },
14683
14697
  priceOracle: {
@@ -14692,28 +14706,28 @@ var require_pkg_src = __commonJS({
14692
14706
  deployedAt: 1781116663270,
14693
14707
  size: 8695,
14694
14708
  hash: "ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74",
14695
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
14709
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
14696
14710
  pkp: {
14697
14711
  publicKey: "0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b",
14698
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14712
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14699
14713
  }
14700
14714
  },
14701
14715
  loanVaultBtcBalance: {
14702
- cid: "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4",
14716
+ cid: "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W",
14703
14717
  authorizedCidHex: cidToHex(
14704
- "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4"
14718
+ "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W"
14705
14719
  ),
14706
14720
  name: "Loan Vault Btc Balance",
14707
14721
  description: "Production Loan Vault Btc Balance",
14708
14722
  version: "1.2.1",
14709
14723
  deployed: true,
14710
- deployedAt: 1785173271802,
14711
- size: 56800,
14712
- hash: "a059133214e6ba0a73d655a15600c4b33e361fb340c98f8eecaf8ab7b95aaf83",
14713
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14724
+ deployedAt: 1790179961079,
14725
+ size: 60046,
14726
+ hash: "922e86c0a667fe0c0945771f84aa6b9fe08be9c96dd2f73a9c5cb257d24e22b0",
14727
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14714
14728
  pkp: {
14715
14729
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
14716
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14730
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14717
14731
  }
14718
14732
  },
14719
14733
  // btc-address-balance (Option B) — address-only signed total balance via
@@ -14723,21 +14737,21 @@ var require_pkg_src = __commonJS({
14723
14737
  // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))
14724
14738
  // on each target chain (the action decrypts registry slots). No OAR entry.
14725
14739
  btcAddressBalance: {
14726
- cid: "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj",
14740
+ cid: "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN",
14727
14741
  authorizedCidHex: cidToHex(
14728
- "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj"
14742
+ "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN"
14729
14743
  ),
14730
14744
  name: "Btc Address Balance",
14731
14745
  description: "Address-only signed total BTC balance via registry consensus (no positionId, no price)",
14732
14746
  version: "0.2.1",
14733
14747
  deployed: true,
14734
- deployedAt: 1785173280221,
14735
- size: 27309,
14736
- hash: "f0d08938713d9d89a56a3a386cacbc2b57afd5ad367ea82d827d40e1bfc70989",
14737
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14748
+ deployedAt: 1790179971315,
14749
+ size: 30295,
14750
+ hash: "2c67d9cfa4d50e835fbb28ae50e80217ceb2be3bb862c89290aadf43fdc739c9",
14751
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14738
14752
  pkp: {
14739
14753
  publicKey: "0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd",
14740
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14754
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14741
14755
  }
14742
14756
  },
14743
14757
  alwaysSigner: {
@@ -14767,48 +14781,74 @@ var require_pkg_src = __commonJS({
14767
14781
  hash: "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72"
14768
14782
  },
14769
14783
  agentModuleExecutor: {
14770
- cid: "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf",
14784
+ cid: "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX",
14771
14785
  authorizedCidHex: cidToHex(
14772
- "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf"
14786
+ "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX"
14773
14787
  ),
14774
14788
  name: "Agent Module Executor",
14775
14789
  description: "Production Agent Module Executor",
14776
14790
  version: "1.1.1",
14777
14791
  deployed: true,
14778
- deployedAt: 1787924032013,
14779
- size: 13878,
14780
- hash: "a7f0204700912e26e5a354bee13a1242a2baa218643b3bb22d28481f67f9baf4"
14792
+ deployedAt: 1790179978959,
14793
+ size: 14688,
14794
+ hash: "8edb9b12c784c8d7d153cce97235584c24665a788767ae68713dce91109ab35e"
14781
14795
  },
14782
14796
  staleSpendRecoveryValidator: {
14783
- cid: "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8",
14797
+ cid: "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz",
14784
14798
  authorizedCidHex: cidToHex(
14785
- "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8"
14799
+ "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz"
14786
14800
  ),
14787
14801
  name: "Stale Spend Recovery Validator",
14788
14802
  description: "Production Stale Spend Recovery Validator",
14789
14803
  version: "1.1.2",
14790
14804
  deployed: true,
14791
- deployedAt: 1787924048772,
14792
- size: 41424,
14793
- hash: "3c5f028d2bef4344768462993616d45e30d9d44ef126e04d6eb579821d57d99c",
14794
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14805
+ deployedAt: 1790246256280,
14806
+ size: 48143,
14807
+ hash: "ec9236bcbe0af24d3e1844791fc8fe37371bbecd8ce95d02e13f7c6e1fc7d94c",
14808
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14795
14809
  pkp: {
14796
14810
  publicKey: "0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21",
14797
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14811
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14798
14812
  }
14799
14813
  },
14800
14814
  btcUtxoInvalidator: {
14801
- cid: "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf",
14815
+ cid: "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX",
14802
14816
  authorizedCidHex: cidToHex(
14803
- "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf"
14817
+ "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX"
14804
14818
  ),
14805
14819
  name: "Btc Utxo Invalidator",
14806
14820
  description: "Production Btc Utxo Invalidator",
14807
14821
  version: "1.0.0",
14808
14822
  deployed: true,
14809
- deployedAt: 1787924133241,
14810
- size: 66026,
14811
- hash: "603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9"
14823
+ deployedAt: 1790246264563,
14824
+ size: 69219,
14825
+ hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
14826
+ },
14827
+ carryCollateralAttestation: {
14828
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
14829
+ authorizedCidHex: cidToHex(
14830
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
14831
+ ),
14832
+ name: "Carry Collateral Attestation",
14833
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
14834
+ version: "1.0.0",
14835
+ deployed: true,
14836
+ deployedAt: 1790927734070,
14837
+ size: 21156,
14838
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
14839
+ },
14840
+ carryFundingAttestation: {
14841
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
14842
+ authorizedCidHex: cidToHex(
14843
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
14844
+ ),
14845
+ name: "Carry Funding Attestation",
14846
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
14847
+ version: "1.0.0",
14848
+ deployed: true,
14849
+ deployedAt: 1790925699980,
14850
+ size: 7193,
14851
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
14812
14852
  }
14813
14853
  };
14814
14854
  function getDeploymentsForNetwork(network) {
@@ -15552,7 +15592,7 @@ ${errorReport}`);
15552
15592
  }
15553
15593
  init_debug_logger();
15554
15594
  init_session_signature_cache();
15555
- var import_ethers54 = require("ethers");
15595
+ var import_ethers56 = require("ethers");
15556
15596
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15557
15597
  var GRACE_PERIOD_DAYS = 30;
15558
15598
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -15574,7 +15614,10 @@ ${errorReport}`);
15574
15614
  BTCSpendAuthorizer: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
15575
15615
  BitcoinProviderRegistry: "0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",
15576
15616
  LITActionValidator: "0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",
15577
- PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"
15617
+ PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",
15618
+ TermManagerModule: "0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",
15619
+ UCDController: "0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",
15620
+ LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9"
15578
15621
  },
15579
15622
  11155111: {
15580
15623
  PositionManager: "0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",
@@ -15582,7 +15625,10 @@ ${errorReport}`);
15582
15625
  BTCSpendAuthorizer: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
15583
15626
  BitcoinProviderRegistry: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
15584
15627
  LITActionValidator: "0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",
15585
- PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9"
15628
+ PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
15629
+ TermManagerModule: "0x94Adc6F9558368B1482197584f1fc7133Ecf835b",
15630
+ UCDController: "0x360Bde4e489ee94E26601B206932De09EE60FF04",
15631
+ LiquidationManagerModule: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"
15586
15632
  }
15587
15633
  };
15588
15634
  function getPinnedContractAddresses(chainId) {
@@ -15768,10 +15814,10 @@ ${errorReport}`);
15768
15814
  };
15769
15815
  }
15770
15816
  const ratioBigInt = collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n / ucdDebt;
15771
- const collateralRatioBps = Number(ratioBigInt);
15817
+ const collateralRatioBps2 = Number(ratioBigInt);
15772
15818
  return {
15773
15819
  collateralValueUsd,
15774
- collateralRatioBps
15820
+ collateralRatioBps: collateralRatioBps2
15775
15821
  };
15776
15822
  }
15777
15823
  function hasSufficientCollateralForDebt(collateralValueUsd, currentDebt, additionalDebt, requiredRatioBps) {
@@ -16616,6 +16662,17 @@ ${auth.clientId}`;
16616
16662
  );
16617
16663
  }
16618
16664
  }
16665
+ var TIP_READ_FAILURE_PREFIX = "Bitcoin tip-height read failed";
16666
+ var BitcoinTipUnreadableError = class extends Error {
16667
+ constructor(message) {
16668
+ super(message);
16669
+ this.isBitcoinTipUnreadable = true;
16670
+ this.name = "BitcoinTipUnreadableError";
16671
+ }
16672
+ };
16673
+ function isBitcoinTipUnreadableError(error) {
16674
+ return typeof error === "object" && error !== null && error.isBitcoinTipUnreadable === true;
16675
+ }
16619
16676
  var BitcoinDataProvider = class {
16620
16677
  constructor(config) {
16621
16678
  this.config = config;
@@ -17067,27 +17124,12 @@ ${auth.clientId}`;
17067
17124
  if (!data.status.confirmed || !data.status.block_height) {
17068
17125
  return { txid: data.txid ?? txid, confirmations: 0 };
17069
17126
  }
17070
- try {
17071
- const tipResp = await fetch(
17072
- `${this.config.providerUrl}/blocks/tip/height`,
17073
- { signal: controller.signal, headers: await this.withAuth() }
17074
- );
17075
- if (!tipResp.ok) {
17076
- return { txid: data.txid ?? txid, confirmations: 1 };
17077
- }
17078
- const tipBody = (await tipResp.text()).trim();
17079
- const tipHeight = Number.parseInt(tipBody, 10);
17080
- if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
17081
- return { txid: data.txid ?? txid, confirmations: 1 };
17082
- }
17083
- const depth = tipHeight - data.status.block_height + 1;
17084
- return {
17085
- txid: data.txid ?? txid,
17086
- confirmations: depth > 0 ? depth : 0
17087
- };
17088
- } catch {
17089
- return { txid: data.txid ?? txid, confirmations: 1 };
17090
- }
17127
+ const tipHeight = await this.fetchTipHeight(controller.signal);
17128
+ const depth = tipHeight - data.status.block_height + 1;
17129
+ return {
17130
+ txid: data.txid ?? txid,
17131
+ confirmations: depth > 0 ? depth : 0
17132
+ };
17091
17133
  }
17092
17134
  return null;
17093
17135
  } catch (error) {
@@ -17095,12 +17137,55 @@ ${auth.clientId}`;
17095
17137
  if (isAbortError(error)) {
17096
17138
  throw new Error(`Request timeout after ${this.timeout}ms`);
17097
17139
  }
17140
+ if (isBitcoinTipUnreadableError(error)) {
17141
+ throw error;
17142
+ }
17098
17143
  if (getUnknownErrorMessage(error).includes("404")) {
17099
17144
  return null;
17100
17145
  }
17101
17146
  throw error;
17102
17147
  }
17103
17148
  }
17149
+ /**
17150
+ * Current chain tip height from THIS provider — or throw.
17151
+ *
17152
+ * Every exit is a throw naming the provider and the precise failure, because
17153
+ * the only alternative is inventing a confirmation depth (see the call site).
17154
+ * The single `try` exists solely to attach that name to a transport-level
17155
+ * rejection (DNS, TLS, connection reset, abort); it re-throws the cause
17156
+ * verbatim inside the message and never substitutes a value — authorized for
17157
+ * this case by the Batch 2 plan, §C2.
17158
+ *
17159
+ * @param signal - The caller's AbortSignal, so this read shares the same
17160
+ * timeout budget as the transaction fetch it serves.
17161
+ */
17162
+ async fetchTipHeight(signal) {
17163
+ const endpoint = `${this.config.providerUrl}/blocks/tip/height`;
17164
+ let tipResp;
17165
+ try {
17166
+ tipResp = await fetch(endpoint, {
17167
+ signal,
17168
+ headers: await this.withAuth()
17169
+ });
17170
+ } catch (error) {
17171
+ throw new BitcoinTipUnreadableError(
17172
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`
17173
+ );
17174
+ }
17175
+ if (!tipResp.ok) {
17176
+ throw new BitcoinTipUnreadableError(
17177
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`
17178
+ );
17179
+ }
17180
+ const tipBody = (await tipResp.text()).trim();
17181
+ const tipHeight = Number.parseInt(tipBody, 10);
17182
+ if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
17183
+ throw new BitcoinTipUnreadableError(
17184
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height "${tipBody.slice(0, 64)}"`
17185
+ );
17186
+ }
17187
+ return tipHeight;
17188
+ }
17104
17189
  /**
17105
17190
  * Get outputs (vouts) of a Bitcoin transaction
17106
17191
  *
@@ -17735,10 +17820,13 @@ ${auth.clientId}`;
17735
17820
  * only on unanimity. The confirmed-balance consensus the validators run
17736
17821
  * covers `chain_stats` only, so without this the primary provider alone
17737
17822
  * could fabricate an unconfirmed UTXO plus a self-consistent parent proof
17738
- * and inflate the signed balance. Any provider failure or verdict
17739
- * disagreement THROWS (fail-closed) — exclusion on a suppressed proof
17740
- * would deflate the balance and open a wrongful-liquidation window, so
17741
- * neither direction may proceed without agreement.
17823
+ * and inflate the signed balance. Any verdict disagreement THROWS
17824
+ * (fail-closed) — exclusion on a suppressed proof would deflate the balance
17825
+ * and open a wrongful-liquidation window, so neither direction may proceed
17826
+ * without agreement. A provider that cannot state the chain tip — and only
17827
+ * that failure — is dropped from the quorum rather than aborting the read (it
17828
+ * never counts as agreeing), and falling below `minConsensusProviders`
17829
+ * survivors throws — see `verifyParentIsSelfSpendConsensus`.
17742
17830
  *
17743
17831
  * The same per-provider `/tx` fetch also returns the parent's outputs, and
17744
17832
  * every provider must corroborate each claimed UTXO (index, vault address,
@@ -17833,10 +17921,26 @@ ${auth.clientId}`;
17833
17921
  }
17834
17922
  /**
17835
17923
  * Run the self-spend proof against every configured provider and require
17836
- * unanimity. Fail-closed: a provider request failure or a verdict
17837
- * disagreement throws and aborts the balance calculation — see
17924
+ * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:
17925
+ * a verdict mismatch throws and aborts the balance calculation — see
17838
17926
  * classifySelfChange for why exclusion is not a safe fallback here.
17839
17927
  *
17928
+ * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a
17929
+ * provider that could not state the chain tip (`BitcoinTipUnreadableError`).
17930
+ * It is ABSENT from the quorum — never counted as agreeing, never allowed to
17931
+ * decide the verdict — and the policy floor, not "at least one", decides when
17932
+ * that absence is fatal: below `minConsensusProviders` surviving readings
17933
+ * there is no cross-check left to trust, and the read fails loudly naming
17934
+ * every provider that dropped out.
17935
+ *
17936
+ * Why only that class. `getTransaction` now throws on an unreadable tip
17937
+ * instead of fabricating `confirmations: 1`; without this carve-out one flaky
17938
+ * `/blocks/tip/height` endpoint would take every balance and spend path down
17939
+ * with it. Every OTHER failure remains fatal, as before: a provider that
17940
+ * answers "I have never seen that transaction" is making a claim about the
17941
+ * chain rather than suffering an outage, and that shape is precisely the
17942
+ * fabricated-UTXO signature the fail-closed rule exists to catch.
17943
+ *
17840
17944
  * When the parent IS a unanimous self-spend, every provider's view of the
17841
17945
  * parent's OUTPUTS must additionally corroborate the primary's claimed
17842
17946
  * UTXOs (index exists, pays the vault, exact value). Without this, a
@@ -17861,32 +17965,52 @@ ${auth.clientId}`;
17861
17965
  )
17862
17966
  )
17863
17967
  );
17864
- const failures = settled.map((r, i) => ({ r, name: providerName(i) })).filter(
17865
- (x) => x.r.status === "rejected"
17866
- ).map(
17867
- ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`
17868
- );
17968
+ const answered = [];
17969
+ const absences = [];
17970
+ const failures = [];
17971
+ settled.forEach((result, i) => {
17972
+ if (result.status === "fulfilled") {
17973
+ answered.push({ index: i, evaluation: result.value });
17974
+ return;
17975
+ }
17976
+ const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;
17977
+ if (isBitcoinTipUnreadableError(result.reason)) {
17978
+ absences.push(described);
17979
+ return;
17980
+ }
17981
+ failures.push(described);
17982
+ });
17869
17983
  if (failures.length > 0) {
17870
17984
  throw new Error(
17871
17985
  `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join("; ")}`
17872
17986
  );
17873
17987
  }
17874
- const evaluations = settled.map(
17875
- (r) => r.value
17876
- );
17877
- const votes = evaluations.map((e) => e.selfSpend);
17878
- const disagreements = votes.map((vote, i) => ({ vote, name: providerName(i) })).filter((x) => x.vote !== votes[0]).map(
17879
- (x) => `${providerName(0)}=${votes[0]} vs ${x.name}=${x.vote}`
17988
+ const floor = Math.max(1, this.minConsensusProviders);
17989
+ if (answered.length < floor) {
17990
+ throw new Error(
17991
+ `Self-change classification for tx ${parentTxid}: only ${answered.length}/${providerConfigs.length} provider(s) could state a confirmation depth, below this chain's floor of ${floor}. Unreadable tips: ${absences.join("; ")}`
17992
+ );
17993
+ }
17994
+ if (absences.length > 0) {
17995
+ litDebugLog(
17996
+ `[VaultBalance] self-change: tx ${parentTxid} classified on a reduced quorum \u2014 ${answered.length}/${providerConfigs.length} provider(s) answered (floor ${floor}); dropped for an unreadable chain tip: ${absences.join("; ")}`
17997
+ );
17998
+ }
17999
+ const first = answered[0];
18000
+ const disagreements = answered.slice(1).filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend).map(
18001
+ (a) => `${providerName(first.index)}=${first.evaluation.selfSpend} vs ${providerName(a.index)}=${a.evaluation.selfSpend}`
17880
18002
  );
17881
18003
  if (disagreements.length > 0) {
17882
18004
  throw new Error(
17883
18005
  `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`
17884
18006
  );
17885
18007
  }
17886
- if (!votes[0]) {
18008
+ if (!first.evaluation.selfSpend) {
17887
18009
  return false;
17888
18010
  }
17889
- const outputMismatches = evaluations.map((e, i) => e.outputMismatch ? `${providerName(i)} \u2192 ${e.outputMismatch}` : null).filter((m) => m !== null);
18011
+ const outputMismatches = answered.map(
18012
+ (a) => a.evaluation.outputMismatch ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}` : null
18013
+ ).filter((m) => m !== null);
17890
18014
  if (outputMismatches.length > 0) {
17891
18015
  throw new Error(
17892
18016
  `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`
@@ -18129,16 +18253,6 @@ ${auth.clientId}`;
18129
18253
  minConfirmations
18130
18254
  );
18131
18255
  const authorizedSpends = await this.getAuthorizedSpendsFromContract(positionId);
18132
- for (const spend of authorizedSpends) {
18133
- const utxoStillExists = utxoSet.utxos.some(
18134
- (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout
18135
- );
18136
- if (utxoStillExists) {
18137
- throw new Error(
18138
- `Authorized UTXO ${spend.txid}:${spend.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`
18139
- );
18140
- }
18141
- }
18142
18256
  const authorizedBalance = authorizedSpends.reduce(
18143
18257
  (sum, spend) => sum + spend.satoshis,
18144
18258
  0n
@@ -18434,7 +18548,13 @@ ${auth.clientId}`;
18434
18548
  allowDevSinglePriceProvider: false,
18435
18549
  minBitcoinBalanceConfirmations: 1,
18436
18550
  minBitcoinSpendConfirmations: 1,
18437
- minConsensusProviders: 1
18551
+ // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider
18552
+ // "by design", so the consensus floor was documented as a mainnet-only
18553
+ // guarantee. The registry now holds two, and leaving the floor at 1 meant
18554
+ // Sepolia could never exercise the multi-provider agreement the stale-spend
18555
+ // and balance paths rely on — the one environment where that logic is
18556
+ // supposed to be proved before mainnet.
18557
+ minConsensusProviders: 2
18438
18558
  },
18439
18559
  [
18440
18560
  "ethereum"
@@ -18468,12 +18588,12 @@ ${auth.clientId}`;
18468
18588
  }
18469
18589
  async function executeVaultSnapshot(params) {
18470
18590
  global.ethers = {
18471
- ...import_ethers54.ethers,
18591
+ ...import_ethers56.ethers,
18472
18592
  providers: {
18473
- StaticJsonRpcProvider: import_ethers54.ethers.JsonRpcProvider
18593
+ StaticJsonRpcProvider: import_ethers56.ethers.JsonRpcProvider
18474
18594
  },
18475
- Contract: import_ethers54.ethers.Contract,
18476
- utils: import_ethers54.ethers
18595
+ Contract: import_ethers56.ethers.Contract,
18596
+ utils: import_ethers56.ethers
18477
18597
  // v6 moved utils to top level
18478
18598
  };
18479
18599
  global.Lit = {
@@ -24043,9 +24163,35 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
24043
24163
  return mod && mod.__esModule ? mod : { "default": mod };
24044
24164
  };
24045
24165
  Object.defineProperty(exports2, "__esModule", { value: true });
24166
+ exports2.computeCidV0 = computeCidV0;
24046
24167
  exports2.fetchLitActionCodeFromIpfs = fetchLitActionCodeFromIpfs;
24047
24168
  var axios_1 = __importDefault(require_axios());
24169
+ var ethers_1 = require("ethers");
24048
24170
  var ipfsCodeCache = /* @__PURE__ */ new Map();
24171
+ var CIDV0 = /^Qm[1-9A-HJ-NP-Za-km-z]{44}$/;
24172
+ var SINGLE_BLOCK_MAX_BYTES = 262144;
24173
+ function varint(n) {
24174
+ const out = [];
24175
+ while (n >= 128) {
24176
+ out.push(n & 127 | 128);
24177
+ n >>>= 7;
24178
+ }
24179
+ out.push(n);
24180
+ return out;
24181
+ }
24182
+ function computeCidV0(content) {
24183
+ const n = varint(content.length);
24184
+ const unixfs = new Uint8Array([8, 2, 18, ...n, ...content, 24, ...n]);
24185
+ const node = new Uint8Array([10, ...varint(unixfs.length), ...unixfs]);
24186
+ return (0, ethers_1.encodeBase58)(new Uint8Array([18, 32, ...(0, ethers_1.getBytes)((0, ethers_1.sha256)(node))]));
24187
+ }
24188
+ function responseBytes(data) {
24189
+ if (data instanceof Uint8Array)
24190
+ return data;
24191
+ if (data instanceof ArrayBuffer)
24192
+ return new Uint8Array(data);
24193
+ return null;
24194
+ }
24049
24195
  var GATEWAY_TIMEOUT_MS = 2e4;
24050
24196
  var buildGatewayList = (cid, pinataJwt) => {
24051
24197
  const gateways = [];
@@ -24066,6 +24212,9 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
24066
24212
  }
24067
24213
  return cached;
24068
24214
  }
24215
+ if (!CIDV0.test(cid)) {
24216
+ throw new Error(`Refusing to fetch LIT Action for ${cid}: only CIDv0 (Qm\u2026) content can be verified`);
24217
+ }
24069
24218
  const pinataJwt = options.pinataJwt ?? process.env.PINATA_JWT;
24070
24219
  const extraGateways = options.extraGateways?.map((t) => ({ url: t.replace("{cid}", cid) })) ?? [];
24071
24220
  const gateways = [...extraGateways, ...buildGatewayList(cid, pinataJwt)];
@@ -24077,19 +24226,32 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
24077
24226
  }
24078
24227
  const response = await axios_1.default.get(gateway.url, {
24079
24228
  timeout: GATEWAY_TIMEOUT_MS,
24229
+ responseType: "arraybuffer",
24080
24230
  headers: {
24081
24231
  Accept: "text/plain, application/javascript, text/javascript",
24082
24232
  ...gateway.headers
24083
24233
  }
24084
24234
  });
24085
- if (response.data && typeof response.data === "string") {
24086
- if (options.debug) {
24087
- console.log(`\u2705 [fetchLitActionCodeFromIpfs] Fetched from ${gateway.url}`);
24088
- }
24089
- ipfsCodeCache.set(cid, response.data);
24090
- return response.data;
24235
+ const bytes = responseBytes(response.data);
24236
+ if (!bytes || bytes.length === 0) {
24237
+ failures.push(`${gateway.url}: HTTP ${response.status} returned ${bytes ? "an empty body" : typeof response.data}, expected bytes`);
24238
+ continue;
24239
+ }
24240
+ if (bytes.length > SINGLE_BLOCK_MAX_BYTES) {
24241
+ failures.push(`${gateway.url}: ${bytes.length} bytes exceeds the single-block CIDv0 limit (${SINGLE_BLOCK_MAX_BYTES}); content cannot be verified`);
24242
+ continue;
24243
+ }
24244
+ const actualCid = computeCidV0(bytes);
24245
+ if (actualCid !== cid) {
24246
+ failures.push(`${gateway.url}: content hashes to ${actualCid}, not the requested CID`);
24247
+ continue;
24091
24248
  }
24092
- failures.push(`${gateway.url}: HTTP ${response.status} returned ${typeof response.data}, expected string`);
24249
+ const code = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
24250
+ if (options.debug) {
24251
+ console.log(`\u2705 [fetchLitActionCodeFromIpfs] Fetched and verified from ${gateway.url}`);
24252
+ }
24253
+ ipfsCodeCache.set(cid, code);
24254
+ return code;
24093
24255
  } catch (error) {
24094
24256
  const message = error instanceof Error ? error.message : String(error);
24095
24257
  failures.push(`${gateway.url}: ${message}`);
@@ -25577,6 +25739,53 @@ var require_pkp_signer_module = __commonJS({
25577
25739
  }
25578
25740
  });
25579
25741
 
25742
+ // node_modules/@gvnrdao/dh-lit-ops/dist/modules/mainnet-validator-wallets.js
25743
+ var require_mainnet_validator_wallets = __commonJS({
25744
+ "node_modules/@gvnrdao/dh-lit-ops/dist/modules/mainnet-validator-wallets.js"(exports2) {
25745
+ "use strict";
25746
+ Object.defineProperty(exports2, "__esModule", { value: true });
25747
+ exports2.MAINNET_OP_VALIDATOR_WALLETS = exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET = exports2.NON_MAINNET_CHAIN_IDS = void 0;
25748
+ exports2.resolveMainnetValidatorWallet = resolveMainnetValidatorWallet;
25749
+ exports2.NON_MAINNET_CHAIN_IDS = /* @__PURE__ */ new Set([
25750
+ 11155111,
25751
+ // Sepolia
25752
+ 1337,
25753
+ // Hardhat (DH local deployment chainId)
25754
+ 31337
25755
+ // Hardhat (default)
25756
+ ]);
25757
+ exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET = "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c";
25758
+ exports2.MAINNET_OP_VALIDATOR_WALLETS = {
25759
+ ucdMintValidator: "0x19C8FeE0f8f4b6F9Aa8e521D4CC62F4697CF85af",
25760
+ processPaymentValidator: "0x01480725c1fA026fd4A6bfA3100c691aeC955135",
25761
+ extendPositionValidator: "0xcE08AF213D8d95ad3dD317276F9e93Ab2eD75030",
25762
+ btcWithdrawal: "0x69dCd1204CDB31437CaF7114f74422390b472d3A",
25763
+ loanVaultBtcBalance: "0xc3d549EEb62721750Ff6518f6730Ab0e8D0Fea97",
25764
+ liquidationValidator: "0x66B30C19173005A51f21e2e4180FD7BC8c1d485b",
25765
+ // Non-OAR: verified on-chain by BTCSpendAuthorizer.staleSpendValidatorAddress (set via
25766
+ // AdminModule to this PKP's derived signer). Self-deriving Safe-owned PKP; seed == signer.
25767
+ staleSpendRecoveryValidator: "0x58F9144cF9781c15C061ba86901905a5a19F7661",
25768
+ // Non-OAR: no on-chain consumer verifies these signatures. The Sepolia seed has no key
25769
+ // derivation registered on the mainnet Lit account, so they reuse the Safe-owned
25770
+ // pkp-validator PKP (live derivation, group 2). See
25771
+ // docs/INCIDENT_2026-09-21_MAINNET_PKP_DERIVATION_DECRYPT.md.
25772
+ btcAddressBalance: "0x19524aE4e514a0f08A542596c2DA0B2262c61f48",
25773
+ priceOracle: "0x19524aE4e514a0f08A542596c2DA0B2262c61f48"
25774
+ };
25775
+ function resolveMainnetValidatorWallet(args) {
25776
+ const { registryKey, chainId, wallet } = args;
25777
+ const isNonMainnetChain = Number.isFinite(chainId) && exports2.NON_MAINNET_CHAIN_IDS.has(chainId);
25778
+ if (isNonMainnetChain || !wallet || wallet.toLowerCase() !== exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET) {
25779
+ return wallet;
25780
+ }
25781
+ if (!registryKey || !Object.prototype.hasOwnProperty.call(exports2.MAINNET_OP_VALIDATOR_WALLETS, registryKey)) {
25782
+ return wallet;
25783
+ }
25784
+ return exports2.MAINNET_OP_VALIDATOR_WALLETS[registryKey];
25785
+ }
25786
+ }
25787
+ });
25788
+
25580
25789
  // node_modules/@gvnrdao/dh-lit-ops/dist/utils/async-request.util.js
25581
25790
  var require_async_request_util = __commonJS({
25582
25791
  "node_modules/@gvnrdao/dh-lit-ops/dist/utils/async-request.util.js"(exports2) {
@@ -25604,7 +25813,9 @@ var require_async_request_util = __commonJS({
25604
25813
  });
25605
25814
  if (!submitResponse.ok) {
25606
25815
  const errorText = await submitResponse.text();
25607
- throw new Error(`Failed to submit request (${submitResponse.status}): ${errorText}`);
25816
+ const retryAfter = submitResponse.status === 429 ? submitResponse.headers.get("retry-after") : null;
25817
+ const retryHint = retryAfter && /^\d+$/.test(retryAfter.trim()) ? ` Retry after ${retryAfter.trim()}s.` : "";
25818
+ throw new Error(`Failed to submit request (${submitResponse.status}): ${errorText}${retryHint}`);
25608
25819
  }
25609
25820
  const submitEnvelope = await submitResponse.json();
25610
25821
  if (!submitEnvelope.success || !submitEnvelope.data?.ticketId) {
@@ -25882,6 +26093,7 @@ var require_lit_ops_module = __commonJS({
25882
26093
  var pkp_manager_module_1 = require_pkp_manager_module();
25883
26094
  var pkp_minter_module_1 = require_pkp_minter_module();
25884
26095
  var pkp_signer_module_1 = require_pkp_signer_module();
26096
+ var mainnet_validator_wallets_1 = require_mainnet_validator_wallets();
25885
26097
  var async_request_util_1 = require_async_request_util();
25886
26098
  var crypto_1 = require("crypto");
25887
26099
  var lit_core_lit_action_client_1 = require_lit_core_lit_action_client();
@@ -25894,26 +26106,6 @@ var require_lit_ops_module = __commonJS({
25894
26106
  { name: "borrower", type: "address" }
25895
26107
  ]
25896
26108
  };
25897
- var NON_MAINNET_CHAIN_IDS = /* @__PURE__ */ new Set([
25898
- 11155111,
25899
- // Sepolia
25900
- 1337,
25901
- // Hardhat (DH local deployment chainId)
25902
- 31337
25903
- // Hardhat (default)
25904
- ]);
25905
- var SEPOLIA_DEFAULT_VALIDATOR_WALLET = "0x82db9f515957aa380b596c6ea2bd30cef181f236";
25906
- var MAINNET_OP_VALIDATOR_WALLETS = {
25907
- ucdMintValidator: "0x19C8FeE0f8f4b6F9Aa8e521D4CC62F4697CF85af",
25908
- processPaymentValidator: "0x01480725c1fA026fd4A6bfA3100c691aeC955135",
25909
- extendPositionValidator: "0xcE08AF213D8d95ad3dD317276F9e93Ab2eD75030",
25910
- btcWithdrawal: "0x69dCd1204CDB31437CaF7114f74422390b472d3A",
25911
- loanVaultBtcBalance: "0xc3d549EEb62721750Ff6518f6730Ab0e8D0Fea97",
25912
- liquidationValidator: "0x66B30C19173005A51f21e2e4180FD7BC8c1d485b",
25913
- // Non-OAR: verified on-chain by BTCSpendAuthorizer.staleSpendValidatorAddress (set via
25914
- // AdminModule to this PKP's derived signer). Self-deriving Safe-owned PKP; seed == signer.
25915
- staleSpendRecoveryValidator: "0x58F9144cF9781c15C061ba86901905a5a19F7661"
25916
- };
25917
26109
  function resolvePkpValidationRegistryAddress(config) {
25918
26110
  const fromConfig = config.pkpValidationRegistryAddress;
25919
26111
  return fromConfig || process.env.PKP_VALIDATION_REGISTRY_ADDRESS || process.env.PKP_VALIDATION_REGISTRY;
@@ -27154,17 +27346,18 @@ var require_lit_ops_module = __commonJS({
27154
27346
  let effectiveValidatorWallet = litActionInfo.validatorWalletAddress;
27155
27347
  const jp = jsParams;
27156
27348
  const resolvedChainId = Number(jp.chainId ?? jp.auth?.chainId ?? jp.authMessage?.chainId ?? this.config.chainId);
27157
- const isNonMainnetChain = Number.isFinite(resolvedChainId) && NON_MAINNET_CHAIN_IDS.has(resolvedChainId);
27158
- if (!isNonMainnetChain && effectiveValidatorWallet && effectiveValidatorWallet.toLowerCase() === SEPOLIA_DEFAULT_VALIDATOR_WALLET) {
27159
- const reg = (0, dh_lit_actions_1.getDeploymentsForNetwork)(this.config.network);
27160
- const registryKey = Object.keys(reg).find((k) => reg[k]?.cid === litActionInfo.cid);
27161
- const mainnetWallet = registryKey ? MAINNET_OP_VALIDATOR_WALLETS[registryKey] : void 0;
27162
- if (mainnetWallet) {
27163
- if (this.config.debug) {
27164
- console.log(`[${label}] mainnet validator remap (${registryKey}, chainId=${Number.isFinite(resolvedChainId) ? resolvedChainId : "unknown\u2192mainnet"}): ${effectiveValidatorWallet} -> ${mainnetWallet}`);
27165
- }
27166
- effectiveValidatorWallet = mainnetWallet;
27349
+ const reg = (0, dh_lit_actions_1.getDeploymentsForNetwork)(this.config.network);
27350
+ const registryKey = Object.keys(reg).find((k) => reg[k]?.cid === litActionInfo.cid);
27351
+ const mainnetWallet = (0, mainnet_validator_wallets_1.resolveMainnetValidatorWallet)({
27352
+ registryKey,
27353
+ chainId: resolvedChainId,
27354
+ wallet: effectiveValidatorWallet
27355
+ });
27356
+ if (mainnetWallet !== effectiveValidatorWallet) {
27357
+ if (this.config.debug) {
27358
+ console.log(`[${label}] mainnet validator remap (${registryKey}, chainId=${Number.isFinite(resolvedChainId) ? resolvedChainId : "unknown\u2192mainnet"}): ${effectiveValidatorWallet} -> ${mainnetWallet}`);
27167
27359
  }
27360
+ effectiveValidatorWallet = mainnetWallet;
27168
27361
  }
27169
27362
  if (process.env.LIT_LANE_VALIDATOR_WALLET_OVERRIDE) {
27170
27363
  if (process.env.LIT_LANE_GUARD !== "1") {
@@ -27280,7 +27473,7 @@ var require_lit_ops_module = __commonJS({
27280
27473
  break;
27281
27474
  case 11155111:
27282
27475
  chain = "sepolia";
27283
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27476
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27284
27477
  break;
27285
27478
  case 1337:
27286
27479
  // Hardhat local testnet (actual deployment chainId)
@@ -27469,7 +27662,7 @@ var require_lit_ops_module = __commonJS({
27469
27662
  break;
27470
27663
  case 11155111:
27471
27664
  chain = "sepolia";
27472
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27665
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27473
27666
  break;
27474
27667
  case 1337:
27475
27668
  // Hardhat local testnet (actual deployment chainId)
@@ -27660,7 +27853,7 @@ var require_lit_ops_module = __commonJS({
27660
27853
  break;
27661
27854
  case 11155111:
27662
27855
  chain = "sepolia";
27663
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27856
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27664
27857
  break;
27665
27858
  case 1337:
27666
27859
  case 31337:
@@ -27808,7 +28001,7 @@ var require_lit_ops_module = __commonJS({
27808
28001
  break;
27809
28002
  case 11155111:
27810
28003
  chain = "sepolia";
27811
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28004
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27812
28005
  break;
27813
28006
  case 1337:
27814
28007
  // Hardhat local testnet (actual deployment chainId)
@@ -28028,7 +28221,7 @@ var require_lit_ops_module = __commonJS({
28028
28221
  bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://mempool.space/api";
28029
28222
  break;
28030
28223
  case 11155111:
28031
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28224
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
28032
28225
  break;
28033
28226
  case 1337:
28034
28227
  // Hardhat local testnet (actual deployment chainId)
@@ -28331,7 +28524,11 @@ var require_lit_ops_module = __commonJS({
28331
28524
  error: "sign=true requires price oracle PKP in registry (ethAddress/publicKey) or options.pkpId (Lit jsParams pkpId)"
28332
28525
  };
28333
28526
  }
28334
- priceOracleParams.pkpId = resolvedPkpId;
28527
+ priceOracleParams.pkpId = (0, mainnet_validator_wallets_1.resolveMainnetValidatorWallet)({
28528
+ registryKey: "priceOracle",
28529
+ chainId: Number(this.config.chainId),
28530
+ wallet: resolvedPkpId
28531
+ });
28335
28532
  }
28336
28533
  if (this.config.debug) {
28337
28534
  console.log("\u{1F4B0} Calling Price Oracle LIT Action:");
@@ -40556,7 +40753,7 @@ var require_dist3 = __commonJS({
40556
40753
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
40557
40754
  };
40558
40755
  Object.defineProperty(exports2, "__esModule", { value: true });
40559
- exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40756
+ exports2.default = exports2.broadcastSignedBitcoinTransaction = exports2.convertEthereumSignatureToBitcoinDER = exports2.CORE_API_TRANSPORT_FAILURE_MARKER = exports2.isCoreApiTransportError = exports2.describeErrorWithCause = exports2.normalizeCoreLitActionResult = exports2.executeLitActionViaCoreApi = exports2.fetchLitActionCodeFromIpfs = exports2.redactPositionIdForLog = exports2.asyncRequest = exports2.TaskQueue = exports2.TicketManager = exports2.PKPSigner = exports2.PKPAuthorizerUtils = exports2.PKPAuthorizer = exports2.PKPMinterUtils = exports2.PKPMinter = exports2.PKPManager = exports2.LitActionExecutor = exports2.LitAuthManager = exports2.resolveMainnetValidatorWallet = exports2.LitOps = exports2.cidToHex = exports2.getDeploymentsForNetwork = void 0;
40560
40757
  __exportStar(require_interfaces(), exports2);
40561
40758
  var dh_lit_actions_1 = require_pkg_src();
40562
40759
  Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
@@ -40569,6 +40766,10 @@ var require_dist3 = __commonJS({
40569
40766
  Object.defineProperty(exports2, "LitOps", { enumerable: true, get: function() {
40570
40767
  return lit_ops_module_1.LitOps;
40571
40768
  } });
40769
+ var mainnet_validator_wallets_1 = require_mainnet_validator_wallets();
40770
+ Object.defineProperty(exports2, "resolveMainnetValidatorWallet", { enumerable: true, get: function() {
40771
+ return mainnet_validator_wallets_1.resolveMainnetValidatorWallet;
40772
+ } });
40572
40773
  var auth_manager_module_1 = require_auth_manager_module();
40573
40774
  Object.defineProperty(exports2, "LitAuthManager", { enumerable: true, get: function() {
40574
40775
  return auth_manager_module_1.LitAuthManager;
@@ -40661,7 +40862,7 @@ module.exports = __toCommonJS(connector_embed_exports);
40661
40862
 
40662
40863
  // src/connector/service.ts
40663
40864
  var import_node_http = require("http");
40664
- var import_node_crypto10 = require("crypto");
40865
+ var import_node_crypto11 = require("crypto");
40665
40866
  var import_express = __toESM(require("express"));
40666
40867
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40667
40868
  var import_router = require("@modelcontextprotocol/sdk/server/auth/router.js");
@@ -40669,7 +40870,7 @@ var import_types4 = require("@modelcontextprotocol/sdk/types.js");
40669
40870
 
40670
40871
  // src/connector/auth-md.ts
40671
40872
  var CHAIN_IDS = { mainnet: 1, sepolia: 11155111 };
40672
- function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled }) {
40873
+ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled, grants }) {
40673
40874
  const origin2 = publicOrigin.replace(/\/+$/, "");
40674
40875
  const launchNetwork = networks2[0];
40675
40876
  if (launchNetwork === void 0) {
@@ -40682,6 +40883,7 @@ function renderAuthMd({ publicOrigin, networks: networks2, walletConnectEnabled
40682
40883
  );
40683
40884
  }
40684
40885
  const isMainnet = launchNetwork === "mainnet";
40886
+ const grantsLine = (grants.durable ? "- Clients and grants are stored durably, so a service restart does not sign anyone\n out: your client refreshes. Access tokens, sign-in flows and codes stay in memory." : "- All authorization state is held **in memory**. A service restart ends every session\n and the user signs in again. Nothing is persisted at rest.") + (grants.accountApi ? "\n- The wallet owner can see and **revoke** every grant from the Diamond Hands web app\n (Connect \u2192 Connections). A revoked grant stops working within about 30 seconds and\n its refresh token is refused with that reason." : "");
40685
40887
  const wcLine = walletConnectEnabled ? "" : " **Mobile WalletConnect sign-in is not enabled on this deployment** \u2014 browser extension or own-key only.";
40686
40888
  const agentAuth = {
40687
40889
  agent_auth: {
@@ -40770,9 +40972,11 @@ ${JSON.stringify(agentAuth, null, 2)}
40770
40972
 
40771
40973
  ### What the credential is, and is not
40772
40974
 
40773
- The **wallet address is the account.** There are no passwords, no email addresses, and
40774
- no user database. Registration creates an OAuth client, not a Diamond Hands account \u2014
40775
- there is nothing to delete, and no personal data is collected.
40975
+ The **wallet address is the account.** There are no passwords and no email addresses.
40976
+ Registration creates an OAuth client, not a Diamond Hands account. No password or email
40977
+ address is collected. Each completed sign-in is a **grant** that is stored: the wallet
40978
+ address, the client's id and self-declared name, the redirect host, timestamps, and a
40979
+ SHA-256 of the refresh token \u2014 never a token itself.
40776
40980
 
40777
40981
  The access token proves **session identity only**. It can read what that address could
40778
40982
  already read, and it can *stage* a fund-moving operation \u2014 arm a mint, a repayment, a
@@ -40781,8 +40985,7 @@ signature over that specific operation, which the token cannot produce. So it is
40781
40985
  read-only credential, and it is not a spending one either. A stolen token cannot spend.
40782
40986
 
40783
40987
  - Access token: ~1 hour. Refresh token: rotating, expires after inactivity.
40784
- - All authorization state is held **in memory**. A service restart ends every session
40785
- and the user signs in again. Nothing is persisted at rest.
40988
+ ${grantsLine}
40786
40989
  - \`scopes_supported\` is empty and tokens are minted with no scopes \u2014 this
40787
40990
  authorization server does not implement scoped access. Do not request a scope; you
40788
40991
  will not receive one.
@@ -40856,9 +41059,12 @@ source of truth.
40856
41059
  `;
40857
41060
  }
40858
41061
 
40859
- // src/connector/landing-page.ts
41062
+ // src/util/brand-assets.ts
40860
41063
  var FAVICON_SVG = `<svg width="512" height="512" viewBox="-6 -11 88 88" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Diamond Hands"><path d="M1.08325 20.7041L37.9038 64.4967L74.2886 20.7041L61.8699 0.877686H13.502L1.08325 20.7041Z" fill="#C9F284" stroke="#34440E" stroke-width="1.75559"/><path d="M13.9385 0.877441L37.9045 64.2785" stroke="#34440E" stroke-width="1.75559"/><path d="M61.6553 0.877441L37.9071 64.4964" stroke="#34440E" stroke-width="1.75559"/><path d="M1.08276 20.7029H74.2882" stroke="#34440E" stroke-width="1.75559"/></svg>`;
40861
41064
  var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).replace(/'/g, "%27")}`;
41065
+ var GVNR_PILL_LOGO_DATA_URI = "data:image/png;base64,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";
41066
+
41067
+ // src/connector/landing-page.ts
40862
41068
  var BACKGROUND_IMAGE_ORIGIN = "https://images.gvnr.xyz";
40863
41069
  var BACKGROUND_IMAGE_URL = `${BACKGROUND_IMAGE_ORIGIN}/images/layout/backgroundCorleoneb.jpg`;
40864
41070
  var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -40925,6 +41131,7 @@ function renderLandingPage(input) {
40925
41131
 
40926
41132
  // src/util/page-headers.ts
40927
41133
  var import_node_crypto = require("crypto");
41134
+ var STRICT_TRANSPORT_SECURITY = { name: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" };
40928
41135
  function htmlPageSecurityHeaders(extra) {
40929
41136
  const nonce = (0, import_node_crypto.randomBytes)(16).toString("base64");
40930
41137
  const base = [
@@ -40952,16 +41159,86 @@ function htmlPageSecurityHeaders(extra) {
40952
41159
  }
40953
41160
 
40954
41161
  // src/version.ts
40955
- var SERVER_VERSION = "0.5.19";
41162
+ var SERVER_VERSION = "0.5.21";
40956
41163
 
40957
41164
  // src/connector/siwe-oauth.ts
40958
- var import_node_crypto2 = require("crypto");
41165
+ var import_node_crypto3 = require("crypto");
40959
41166
  var import_ethers = require("ethers");
40960
41167
  var import_errors = require("@modelcontextprotocol/sdk/server/auth/errors.js");
40961
41168
 
41169
+ // src/util/house-style.ts
41170
+ var APP_BACKGROUND_ORIGIN = "https://images.diamondhands.credit";
41171
+ var APP_BACKGROUND_URL = `${APP_BACKGROUND_ORIGIN}/bg-diamond-hands.png`;
41172
+ var FONT_ORIGIN = "https://images.gvnr.xyz";
41173
+ var MANROPE_BASE = `${FONT_ORIGIN}/fonts/manrope`;
41174
+ var HOUSE_CSP_EXTRA = {
41175
+ "img-src": [APP_BACKGROUND_ORIGIN, "data:"],
41176
+ "font-src": [FONT_ORIGIN]
41177
+ };
41178
+ var HOUSE_HEAD_LINKS = `<link rel="icon" type="image/svg+xml" href="${FAVICON_DATA_URI}">
41179
+ <link rel="apple-touch-icon" href="${FAVICON_DATA_URI}">`;
41180
+ var MANROPE_WEIGHTS = [
41181
+ [300, "Light"],
41182
+ [400, "Regular"],
41183
+ [500, "Medium"],
41184
+ [600, "SemiBold"],
41185
+ [700, "Bold"]
41186
+ ];
41187
+ var HOUSE_BASE_CSS = `
41188
+ ${MANROPE_WEIGHTS.map(([w, n]) => `@font-face { font-family: "Manrope"; font-weight: ${w}; font-display: swap; src: url("${MANROPE_BASE}/Manrope-${n}.ttf") format("truetype"); }`).join("\n")}
41189
+ * { box-sizing: border-box; }
41190
+ html { min-height: 100%; background: #000006; }
41191
+ body { margin: 0; min-height: 100vh; color: #fff; font: 14px/1.5 "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
41192
+ background: #000006 url("${APP_BACKGROUND_URL}") center / cover no-repeat fixed; }
41193
+ .house-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem; }
41194
+ @media (min-width: 768px) { .house-header { padding: 1rem 2.5rem; } }
41195
+ .house-header > img { height: 1.92rem; width: auto; display: block; flex: none; }
41196
+ /* Narrow viewports: the chip may shrink (its label ellipsises), and below 400px the label
41197
+ is dropped so logo + chip icon always fit a 320px phone with no horizontal page scroll. */
41198
+ .house-header .chip { min-width: 0; }
41199
+ .chip-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
41200
+ /* ".house-header .chip", not ".chip": the base .chip rule below declares padding too, and at
41201
+ equal specificity the LATER rule wins regardless of the media query; this selector outranks it. */
41202
+ @media (max-width: 400px) { .chip-label { display: none; } .house-header .chip { padding: 0.4rem 0.6rem; } }
41203
+ .chip { display: inline-flex; align-items: center; gap: 0.45rem; padding: 0.4rem 0.85rem; border-radius: 999px;
41204
+ background: rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.1); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
41205
+ font-size: 0.8rem; font-weight: 600; color: #dbff91; white-space: nowrap; }
41206
+ .chip img { height: 1rem; }
41207
+ main { max-width: 34rem; margin: 2.5rem auto 3rem; padding: 0 1rem; }
41208
+ .panel { background: #121212; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 1rem;
41209
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); }
41210
+ @media (min-width: 768px) { .panel { padding: 1.25rem; } }
41211
+ h1 { font-size: 1.25rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 1rem; }
41212
+ @media (min-width: 768px) { h1 { font-size: 1.5rem; margin-bottom: 1.25rem; } }
41213
+ h2 { font-size: 1rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 0.75rem; }
41214
+ p { margin: 0 0 1rem; color: #e5e5e5; font-size: 0.875rem; font-weight: 300; line-height: 1.5; }
41215
+ button { font: inherit; font-size: 0.875rem; cursor: pointer; border: 0; display: inline-flex; align-items: center; justify-content: center;
41216
+ min-height: 2.75rem; padding: 0.65rem 1.25rem; transition: opacity 0.2s, background-color 0.2s; }
41217
+ button:focus-visible { outline: 2px solid #84cc16; outline-offset: 2px; }
41218
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
41219
+ /* Primary = lime-700 (#4d7c0f): white 14px text on it is 4.99:1 (WCAG AA needs 4.5:1; the
41220
+ brighter #65a30d was 3.09:1). Hover = lime-800 (#3f6212), 7.08:1. A test recomputes both. */
41221
+ .btn-primary { background: #4d7c0f; color: #fff; font-weight: 700; letter-spacing: 0.025em; border-radius: 12px; box-shadow: 0 4px 18px rgba(74, 222, 128, 0.2); }
41222
+ .btn-primary:hover:not(:disabled) { background: #3f6212; }
41223
+ .btn-secondary { background: #34440e; color: #dbff91; font-weight: 500; border-radius: 20px; }
41224
+ .btn-secondary:hover:not(:disabled) { background: #3d5210; }
41225
+ .btn-danger { background: transparent; color: #fca5a5; font-weight: 600; border-radius: 12px; border: 1px solid rgba(248, 113, 113, 0.45); }
41226
+ .btn-danger:hover:not(:disabled) { background: rgba(220, 38, 38, 0.15); }
41227
+ /* A QR needs dark-on-light to scan: it keeps a white plate on the dark page. */
41228
+ .qr-plate { max-width: 16rem; margin-top: 1rem; background: #fff; border-radius: 12px; padding: 0.5rem; }
41229
+ .qr-plate svg { width: 100%; height: auto; display: block; }
41230
+ `;
41231
+ function houseHeader(label) {
41232
+ return `<header class="house-header">
41233
+ <img src="${GVNR_PILL_LOGO_DATA_URI}" alt="GVNR">
41234
+ <span class="chip"><img src="${FAVICON_DATA_URI}" alt=""><span class="chip-label">${label}</span></span>
41235
+ </header>`;
41236
+ }
41237
+
40962
41238
  // src/connector/siwe-page.ts
41239
+ var SIWE_PAGE_CSP_EXTRA = HOUSE_CSP_EXTRA;
40963
41240
  function renderSiwePage(opts) {
40964
- const { flowId, redirectHost, nonce } = opts;
41241
+ const { flowId, redirectHost, nonce, walletConnectEnabled } = opts;
40965
41242
  const clientName = clampClientName(opts.clientName);
40966
41243
  return `<!DOCTYPE html>
40967
41244
  <html>
@@ -40969,54 +41246,63 @@ function renderSiwePage(opts) {
40969
41246
  <meta charset="utf-8">
40970
41247
  <meta name="viewport" content="width=device-width, initial-scale=1">
40971
41248
  <title>Diamond Hands \u2014 sign in with your wallet</title>
41249
+ ${HOUSE_HEAD_LINKS}
40972
41250
  <style>
40973
- body { font-family: system-ui, sans-serif; max-width: 30rem; margin: 3rem auto; padding: 0 1rem; color: #1a1a1a; }
40974
- h1 { font-size: 1.2rem; }
40975
- button { font-size: 1rem; padding: 0.6rem 1.2rem; cursor: pointer; margin-right: 0.5rem; }
40976
- #status { margin-top: 1rem; color: #444; min-height: 1.5rem; }
40977
- .err { color: #b00020; }
40978
- .note { font-size: 0.85rem; color: #666; margin-top: 2rem; }
41251
+ ${HOUSE_BASE_CSS}
41252
+ /* \u2500\u2500 sign-in page only \u2500\u2500 */
41253
+ .actions { display: flex; flex-wrap: wrap; gap: 0.75rem; margin-top: 1.25rem; }
41254
+ #qr:empty { display: none; }
41255
+ #status { margin-top: 1rem; color: #a1a1a1; font-size: 0.875rem; font-weight: 400; }
41256
+ #status:empty, #wc-uri:empty { display: none; }
41257
+ .err { color: #f87171; }
41258
+ .note { font-size: 0.75rem; color: #a1a1a1; margin: 1.25rem 0 0; padding-top: 1rem; border-top: 1px solid rgba(255, 255, 255, 0.06); }
40979
41259
  /* "position: relative" is load-bearing, not cosmetic: it puts the consent box in its
40980
41260
  own stacking context so it paints ABOVE the inline content of the paragraph before
40981
41261
  it. Without it, a client name built from stacked combining marks overflows its line
40982
41262
  box downward and paints over this text \u2014 the CSS painting order draws every block
40983
41263
  background first, then all inline content in tree order. */
40984
- .dest { background: #fff8e1; border-left: 3px solid #c77700; padding: 0.7rem 0.9rem; font-size: 0.9rem; position: relative; }
41264
+ .dest { background: rgba(245, 158, 11, 0.12); border-left: 3px solid #f59e0b; border-radius: 0 10px 10px 0; padding: 0.75rem 0.95rem; font-size: 0.875rem; font-weight: 400; color: #f5f5f5; position: relative; }
40985
41265
  /* The destination must stay legible under a host the attacker chose the length of:
40986
41266
  "overflow-wrap: anywhere" lets it wrap mid-label (a dot is not a break opportunity),
40987
41267
  and the isolate keeps any bidi control inside from reordering the sentence around
40988
41268
  it. splitRedirectHost has already bounded the length; this bounds the geometry. */
40989
- .dest code { font-family: ui-monospace, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
40990
- .dest .host-head { color: #5a5a5a; }
40991
- .dest .host-tail { font-weight: 700; color: #000; }
41269
+ .dest code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 1rem; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; }
41270
+ .dest .host-head { color: #a3a3a3; }
41271
+ .dest .host-tail { font-weight: 700; color: #fff; }
40992
41272
  /* The elision is NOT decoration \u2014 it is the page admitting it withheld characters, so
40993
41273
  it must be as visible as the text it replaced. */
40994
- .dest .host-cut { color: #c77700; font-weight: 700; font-style: normal; }
41274
+ .dest .host-cut { color: #fbbf24; font-weight: 700; font-style: normal; }
40995
41275
  /* The attacker-chosen name is clipped to a fixed box: bounded characters alone do not
40996
41276
  bound HEIGHT (combining marks stack vertically), and an isolate stops an unpaired
40997
41277
  RTL override inside the name from reversing the rest of the sentence. */
40998
- .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 700; }
40999
- #qr { max-width: 16rem; margin-top: 1rem; }
41000
- #qr svg { width: 100%; height: auto; }
41001
- #wc-uri { font-size: 0.7rem; word-break: break-all; color: #888; }
41278
+ .cname { display: inline-block; max-width: 100%; max-height: 4.5em; overflow: hidden; vertical-align: bottom; word-break: break-all; overflow-wrap: anywhere; unicode-bidi: isolate; font-weight: 600; color: #fafafa; }
41279
+ #wc-uri { font-size: 0.7rem; word-break: break-all; color: #a1a1a1; }
41002
41280
  </style>
41003
41281
  </head>
41004
41282
  <body>
41283
+ ${houseHeader("Diamond Hands \xB7 wallet sign-in")}
41284
+ <main>
41005
41285
  <h1>Sign in to Diamond Hands</h1>
41286
+ <div class="panel">
41287
+ <h2>Connect your wallet</h2>
41006
41288
  <p><span class="cname" dir="ltr">${escapeHtml2(clientName)}</span> is asking to connect. Signing in proves you own a wallet address \u2014 it authorizes nothing on-chain and can never move funds.</p>
41007
41289
  <p class="dest">When you sign, this connection is handed to <code dir="ltr">${renderRedirectHost(redirectHost)}</code>. Anyone can register a client under any name, so read the host, not the name \u2014 and read it from the <b>bold end</b>, which is the part that decides who actually owns it. If you do not recognize it, close this page; nothing has happened yet.</p>
41008
- <button id="connect">Browser wallet</button>
41009
- <button id="wc">Mobile wallet (QR)</button>
41290
+ <div class="actions">
41291
+ <button id="connect" class="btn-primary">Browser wallet</button>
41292
+ ${walletConnectEnabled ? `<button id="wc" class="btn-secondary">Mobile wallet (QR)</button>
41293
+ ` : ""}</div>
41010
41294
  <div id="status"></div>
41011
- <div id="qr"></div>
41295
+ <div id="qr" class="qr-plate"></div>
41012
41296
  <p id="wc-uri"></p>
41013
- <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect).</p>
41297
+ <p class="note">Every future operation that moves funds will still ask for its own approval in your wallet. ${walletConnectEnabled ? "Two ways in: a browser wallet extension on this device, or scan the QR with a mobile wallet (WalletConnect)." : "Sign in with a browser wallet extension on this device."}</p>
41298
+ </div>
41299
+ </main>
41014
41300
  <script nonce="${nonce}">
41015
41301
  const FLOW = ${JSON.stringify(flowId)};
41016
41302
  const statusEl = document.getElementById("status");
41017
41303
  function show(text, isErr) { statusEl.textContent = text; statusEl.className = isErr ? "err" : ""; }
41018
41304
  document.getElementById("connect").addEventListener("click", async () => {
41019
- if (!window.ethereum) { show("No browser wallet found - install a wallet extension and reload, or use the mobile QR path.", true); return; }
41305
+ if (!window.ethereum) { show(${JSON.stringify(walletConnectEnabled ? "No browser wallet found - install a wallet extension and reload, or use the mobile QR path." : "No browser wallet found - install a wallet extension and reload.")}, true); return; }
41020
41306
  try {
41021
41307
  const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
41022
41308
  const address = accounts[0];
@@ -41042,7 +41328,7 @@ document.getElementById("connect").addEventListener("click", async () => {
41042
41328
  show(e && e.code === 4001 ? "You declined in the wallet - nothing was connected." : String(e && e.message || e), true);
41043
41329
  }
41044
41330
  });
41045
- let wcPoll = null;
41331
+ ${walletConnectEnabled ? `let wcPoll = null;
41046
41332
  document.getElementById("wc").addEventListener("click", async () => {
41047
41333
  try {
41048
41334
  show("Creating a WalletConnect pairing\u2026");
@@ -41075,6 +41361,7 @@ document.getElementById("wc").addEventListener("click", async () => {
41075
41361
  show(String(e && e.message || e), true);
41076
41362
  }
41077
41363
  });
41364
+ ` : ""}
41078
41365
  </script>
41079
41366
  </body>
41080
41367
  </html>`;
@@ -41102,51 +41389,138 @@ function renderRedirectHost(host) {
41102
41389
  const cut = elided === 0 ? "" : `<span class="host-cut">\u2026+${elided} chars\u2026</span>`;
41103
41390
  return `<span class="host-head">${escapeHtml2(head)}</span>${cut}<span class="host-tail">${escapeHtml2(tail)}</span>`;
41104
41391
  }
41392
+ function redirectHostForStatement(host) {
41393
+ const { head, elided, tail } = splitRedirectHost(host);
41394
+ return elided === 0 ? `${head}${tail}` : `${head}\u2026+${elided} chars\u2026${tail}`;
41395
+ }
41105
41396
  function clampClientName(name) {
41106
41397
  const points = [...name];
41107
41398
  if (points.length <= MAX_CLIENT_NAME_CHARS) return name;
41108
41399
  return `${points.slice(0, MAX_CLIENT_NAME_CHARS - 1).join("")}\u2026`;
41109
41400
  }
41110
41401
 
41402
+ // src/connector/oauth-store.ts
41403
+ var import_node_crypto2 = require("crypto");
41404
+ function hashToken(token) {
41405
+ return (0, import_node_crypto2.createHash)("sha256").update(token, "utf8").digest("hex");
41406
+ }
41407
+ var DEFAULT_MAX_CLIENTS = 1e3;
41408
+ function memoryOAuthStateStore(opts) {
41409
+ const maxClients = opts?.maxClients ?? DEFAULT_MAX_CLIENTS;
41410
+ const clients = /* @__PURE__ */ new Map();
41411
+ const grants = /* @__PURE__ */ new Map();
41412
+ return {
41413
+ async getClient(clientId, now) {
41414
+ const entry = clients.get(clientId);
41415
+ if (!entry) return null;
41416
+ if (entry.expireAt <= now) {
41417
+ clients.delete(clientId);
41418
+ return null;
41419
+ }
41420
+ return entry.client;
41421
+ },
41422
+ async putClient(client, _now, expireAt) {
41423
+ if (!clients.has(client.client_id)) {
41424
+ while (clients.size >= maxClients) {
41425
+ let victim;
41426
+ let earliest = Infinity;
41427
+ for (const [id, entry] of clients) {
41428
+ if (entry.expireAt < earliest) {
41429
+ victim = id;
41430
+ earliest = entry.expireAt;
41431
+ }
41432
+ }
41433
+ if (victim === void 0) break;
41434
+ clients.delete(victim);
41435
+ }
41436
+ }
41437
+ clients.set(client.client_id, { client, expireAt });
41438
+ },
41439
+ async extendClient(clientId, expireAt) {
41440
+ const entry = clients.get(clientId);
41441
+ if (entry && entry.expireAt < expireAt) entry.expireAt = expireAt;
41442
+ },
41443
+ async createGrant(grant) {
41444
+ grants.set(grant.grantId, { ...grant });
41445
+ },
41446
+ async getGrant(grantId) {
41447
+ const g = grants.get(grantId);
41448
+ return g ? { ...g } : null;
41449
+ },
41450
+ async findGrantByRefreshHash(refreshHash) {
41451
+ for (const g of grants.values()) if (g.refreshHash === refreshHash) return { ...g };
41452
+ return null;
41453
+ },
41454
+ async rotateGrant(grantId, expectedHash, next) {
41455
+ const g = grants.get(grantId);
41456
+ if (!g || g.revokedAt !== null || g.refreshHash !== expectedHash) return false;
41457
+ grants.set(grantId, { ...g, ...next });
41458
+ return true;
41459
+ },
41460
+ async revokeGrant(grantId, now) {
41461
+ const g = grants.get(grantId);
41462
+ if (g && g.revokedAt === null) grants.set(grantId, { ...g, revokedAt: now });
41463
+ },
41464
+ async listGrants(address) {
41465
+ const a = address.toLowerCase();
41466
+ return [...grants.values()].filter((g) => g.address === a).map((g) => ({ ...g }));
41467
+ },
41468
+ async sweep(now) {
41469
+ for (const [id, c] of clients) if (c.expireAt <= now) clients.delete(id);
41470
+ for (const [id, g] of grants) if (g.expireAt <= now) grants.delete(id);
41471
+ }
41472
+ };
41473
+ }
41474
+
41111
41475
  // src/connector/siwe-oauth.ts
41112
41476
  var FLOW_TTL_MS = 10 * 60 * 1e3;
41113
41477
  var CODE_TTL_MS = 60 * 1e3;
41114
41478
  var ACCESS_TTL_S = 3600;
41115
41479
  var DEFAULT_REFRESH_IDLE_MS = 30 * 24 * 60 * 60 * 1e3;
41116
- var DEFAULT_MAX_CLIENTS = 1e3;
41480
+ var UNCLAIMED_CLIENT_TTL_MS = 24 * 60 * 60 * 1e3;
41481
+ var GRANT_RECHECK_MS = 30 * 1e3;
41482
+ var DEFAULT_WC_MAX_GLOBAL_PAIRINGS = 50;
41483
+ var DEFAULT_WC_MAX_PAIRINGS_PER_IP = 3;
41484
+ function resolveWcLimits(limits) {
41485
+ const maxGlobal = limits?.maxGlobal ?? DEFAULT_WC_MAX_GLOBAL_PAIRINGS;
41486
+ const maxPerIp = limits?.maxPerIp ?? DEFAULT_WC_MAX_PAIRINGS_PER_IP;
41487
+ for (const [name, v] of [["wcLimits.maxGlobal", maxGlobal], ["wcLimits.maxPerIp", maxPerIp]]) {
41488
+ if (!Number.isSafeInteger(v) || v < 1) throw new Error(`${name} must be a positive integer, got ${String(v)}`);
41489
+ }
41490
+ return { maxGlobal, maxPerIp };
41491
+ }
41117
41492
  var SiweOAuthProvider = class {
41118
41493
  constructor(opts) {
41119
41494
  this.opts = opts;
41120
41495
  this.clock = opts.clock ?? Date.now;
41121
- this.maxClients = opts.bounds?.maxClients ?? DEFAULT_MAX_CLIENTS;
41122
41496
  this.refreshIdleMs = opts.bounds?.refreshIdleMs ?? DEFAULT_REFRESH_IDLE_MS;
41497
+ const limits = resolveWcLimits(opts.wcLimits);
41498
+ this.wcMaxGlobal = limits.maxGlobal;
41499
+ this.wcMaxPerIp = limits.maxPerIp;
41500
+ this.store = opts.store ?? memoryOAuthStateStore(opts.bounds?.maxClients !== void 0 ? { maxClients: opts.bounds.maxClients } : void 0);
41123
41501
  }
41124
- clients = /* @__PURE__ */ new Map();
41125
41502
  flows = /* @__PURE__ */ new Map();
41126
41503
  codes = /* @__PURE__ */ new Map();
41127
41504
  access = /* @__PURE__ */ new Map();
41128
- refresh = /* @__PURE__ */ new Map();
41505
+ store;
41129
41506
  clock;
41130
- maxClients;
41131
41507
  refreshIdleMs;
41508
+ wcMaxGlobal;
41509
+ wcMaxPerIp;
41132
41510
  get clientsStore() {
41133
- const clients = this.clients;
41134
- const maxClients = this.maxClients;
41511
+ const store = this.store;
41512
+ const clock = this.clock;
41135
41513
  return {
41136
- getClient: (clientId) => clients.get(clientId),
41137
- registerClient: (client) => {
41514
+ getClient: async (clientId) => await store.getClient(clientId, clock()) ?? void 0,
41515
+ registerClient: async (client) => {
41138
41516
  const name = client.client_name;
41139
41517
  if (name !== void 0 && [...name].length > MAX_CLIENT_NAME_CHARS) {
41140
41518
  throw new import_errors.InvalidClientMetadataError(
41141
41519
  `client_name is ${[...name].length} characters \u2014 this authorization server displays it on a consent screen and accepts at most ${MAX_CLIENT_NAME_CHARS}`
41142
41520
  );
41143
41521
  }
41144
- while (clients.size >= maxClients) {
41145
- const oldest = clients.keys().next().value;
41146
- if (oldest === void 0) break;
41147
- clients.delete(oldest);
41148
- }
41149
- clients.set(client.client_id, client);
41522
+ const now = clock();
41523
+ await store.putClient(client, now, now + UNCLAIMED_CLIENT_TTL_MS);
41150
41524
  return client;
41151
41525
  }
41152
41526
  };
@@ -41157,11 +41531,12 @@ var SiweOAuthProvider = class {
41157
41531
  * response carries its own security headers, and the page names the redirect HOST —
41158
41532
  * the consent fact that open registration makes `client_name` unable to carry. */
41159
41533
  async authorize(client, params, res) {
41160
- this.sweep();
41161
- const flowId = (0, import_node_crypto2.randomBytes)(16).toString("hex");
41534
+ await this.sweep();
41535
+ const flowId = (0, import_node_crypto3.randomBytes)(16).toString("hex");
41162
41536
  this.flows.set(flowId, { clientId: client.client_id, params, createdAt: this.clock() });
41163
- const page = htmlPageSecurityHeaders();
41537
+ const page = htmlPageSecurityHeaders(SIWE_PAGE_CSP_EXTRA);
41164
41538
  for (const [name, value] of Object.entries(page.headers)) res.setHeader(name, value);
41539
+ res.setHeader(STRICT_TRANSPORT_SECURITY.name, STRICT_TRANSPORT_SECURITY.value);
41165
41540
  res.status(200).type("html").send(
41166
41541
  renderSiwePage({
41167
41542
  flowId,
@@ -41170,7 +41545,8 @@ var SiweOAuthProvider = class {
41170
41545
  // redirect_uri (SafeUrlSchema) and, for a request-supplied one, URL.canParse
41171
41546
  // plus a registered-URI match — so this constructor cannot throw here.
41172
41547
  redirectHost: new URL(params.redirectUri).host,
41173
- nonce: page.nonce
41548
+ nonce: page.nonce,
41549
+ walletConnectEnabled: this.opts.wc !== void 0
41174
41550
  })
41175
41551
  );
41176
41552
  }
@@ -41183,17 +41559,22 @@ var SiweOAuthProvider = class {
41183
41559
  if (!flow) return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41184
41560
  if (!import_ethers.ethers.isAddress(address)) return { ok: false, status: 400, reason: "not a valid wallet address" };
41185
41561
  const checksummed = import_ethers.ethers.getAddress(address);
41186
- flow.siwe = { address: checksummed, message: this.mintSiweMessage(checksummed) };
41562
+ flow.siwe = { address: checksummed, message: this.mintSiweMessage(checksummed, flow) };
41187
41563
  return { ok: true, message: flow.siwe.message };
41188
41564
  }
41189
- mintSiweMessage(checksummedAddress) {
41565
+ /** S1-C — the statement carries the redirect HOST (bounded like the sign-in page bounds
41566
+ * it; never the attacker-chosen client name), because on the WalletConnect leg the phone
41567
+ * shows only this text and a relayed pairing QR would otherwise hide where the grant goes.
41568
+ * One line, no newline: EIP-4361 statements cannot contain one, and a URL host cannot. */
41569
+ mintSiweMessage(checksummedAddress, flow) {
41570
+ const redirectHost = redirectHostForStatement(new URL(flow.params.redirectUri).host);
41190
41571
  const origin2 = this.opts.origin();
41191
41572
  const domain = new URL(origin2).host;
41192
- const nonce = (0, import_node_crypto2.randomBytes)(8).toString("hex");
41573
+ const nonce = (0, import_node_crypto3.randomBytes)(8).toString("hex");
41193
41574
  return `${domain} wants you to sign in with your Ethereum account:
41194
41575
  ${checksummedAddress}
41195
41576
 
41196
- Connect Diamond Hands to your AI assistant. This signature only proves you own this wallet - it authorizes nothing on-chain and can never move funds.
41577
+ Connect Diamond Hands to your AI assistant. After you sign, this connection is handed to ${redirectHost}. This signature only proves you own this wallet - it authorizes nothing on-chain and can never move funds.
41197
41578
 
41198
41579
  URI: ${origin2}/authorize
41199
41580
  Version: 1
@@ -41204,12 +41585,42 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41204
41585
  /** Plan 17 A1 — start the mobile (WalletConnect) leg for a flow: one ISOLATED
41205
41586
  * transport per flow, a fresh pairing URI + QR. A re-call replaces the flow's
41206
41587
  * previous pairing (dispose first — no orphaned transports). */
41207
- async wcPairing(flowId) {
41588
+ async wcPairing(flowId, requesterIp) {
41208
41589
  const wcOpts = this.opts.wc;
41209
41590
  if (!wcOpts) return { ok: false, status: 404, reason: "mobile wallet sign-in is not enabled on this deployment" };
41210
41591
  const flow = this.liveFlow(flowId);
41211
41592
  if (!flow) return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41593
+ if (flow.wcSetupInFlight) {
41594
+ return { ok: false, status: 409, reason: "a mobile wallet pairing for this sign-in is already being set up - wait for it to finish" };
41595
+ }
41596
+ let global2 = 0;
41597
+ let perIp = 0;
41598
+ for (const f of this.flows.values()) {
41599
+ if (f === flow || f.wcSlotIp === void 0) continue;
41600
+ global2 += 1;
41601
+ if (f.wcSlotIp === requesterIp) perIp += 1;
41602
+ }
41603
+ if (global2 >= this.wcMaxGlobal) {
41604
+ return { ok: false, status: 429, reason: `mobile wallet sign-in is at capacity (${this.wcMaxGlobal} pairings open on this server) - try again in a few minutes, or sign in with a browser wallet` };
41605
+ }
41606
+ if (perIp >= this.wcMaxPerIp) {
41607
+ return { ok: false, status: 429, reason: `too many mobile wallet sign-ins are pending from your network address (at most ${this.wcMaxPerIp} at once) - finish one, or wait up to 10 minutes for it to expire` };
41608
+ }
41212
41609
  if (flow.wc) this.disposeFlowTransport(flow);
41610
+ flow.wcSlotIp = requesterIp;
41611
+ flow.wcSetupInFlight = true;
41612
+ try {
41613
+ return await this.buildWcPairing(flowId, flow, wcOpts);
41614
+ } catch (e) {
41615
+ this.disposeFlowTransport(flow);
41616
+ throw e;
41617
+ } finally {
41618
+ delete flow.wcSetupInFlight;
41619
+ }
41620
+ }
41621
+ /** The setup steps of `wcPairing` — runs only under that method's slot reservation and
41622
+ * in-flight mark, which also own the failure cleanup. */
41623
+ async buildWcPairing(flowId, flow, wcOpts) {
41213
41624
  const factory2 = wcOpts.transportFactory ?? (async (cfg) => {
41214
41625
  const { WcTransport: WcTransport2 } = await Promise.resolve().then(() => (init_wc_transport(), wc_transport_exports));
41215
41626
  return WcTransport2.create(cfg);
@@ -41217,8 +41628,21 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41217
41628
  const transport = await factory2({
41218
41629
  projectId: wcOpts.projectId,
41219
41630
  chainId: this.opts.chainId,
41220
- ...wcOpts.relayUrl ? { relayUrl: wcOpts.relayUrl } : {}
41631
+ ...wcOpts.relayUrl ? { relayUrl: wcOpts.relayUrl } : {},
41632
+ // L-2: the wallet is asked to sign an EIP-4361 message whose domain is THIS origin,
41633
+ // so the dapp it is told it is talking to must be this origin too — a mismatch makes
41634
+ // domain-binding wallets warn on every honest sign-in.
41635
+ metadata: {
41636
+ name: "Diamond Hands \u2014 sign in",
41637
+ description: "Sign in to the Diamond Hands connector \u2014 proves wallet ownership, moves no funds",
41638
+ url: this.opts.origin(),
41639
+ icons: []
41640
+ }
41221
41641
  });
41642
+ if (this.flows.get(flowId) !== flow) {
41643
+ void transport.close().catch(() => void 0);
41644
+ return { ok: false, status: 404, reason: "unknown or expired sign-in flow \u2014 restart the connection from claude.ai" };
41645
+ }
41222
41646
  const record = { transport, uri: "", state: "pairing" };
41223
41647
  flow.wc = record;
41224
41648
  transport.onSession((info) => {
@@ -41261,7 +41685,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41261
41685
  return;
41262
41686
  }
41263
41687
  const checksummed = import_ethers.ethers.getAddress(account);
41264
- const message = this.mintSiweMessage(checksummed);
41688
+ const message = this.mintSiweMessage(checksummed, flow);
41265
41689
  flow.siwe = { address: checksummed, message };
41266
41690
  flow.wc.state = "awaiting-signature";
41267
41691
  let signature;
@@ -41288,11 +41712,12 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41288
41712
  void transport.close().catch(() => void 0);
41289
41713
  return;
41290
41714
  }
41291
- const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
41715
+ const code = (0, import_node_crypto3.randomBytes)(24).toString("hex");
41292
41716
  this.codes.set(code, {
41293
41717
  clientId: flow.clientId,
41294
41718
  address: checksummed,
41295
41719
  codeChallenge: flow.params.codeChallenge,
41720
+ redirectHost: new URL(flow.params.redirectUri).host,
41296
41721
  createdAt: this.clock()
41297
41722
  });
41298
41723
  const redirect = new URL(flow.params.redirectUri);
@@ -41334,6 +41759,7 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41334
41759
  /** Close a flow's WC transport (idempotent). `keepState` preserves the wc state
41335
41760
  * machine for the page's poll — only the TRANSPORT is released. */
41336
41761
  disposeFlowTransport(flow, keepState = false) {
41762
+ delete flow.wcSlotIp;
41337
41763
  const wc = flow.wc;
41338
41764
  if (!wc) return;
41339
41765
  void wc.transport.close().catch(() => void 0);
@@ -41355,11 +41781,12 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41355
41781
  return { ok: false, status: 401, reason: "the signature does not match the connected wallet address" };
41356
41782
  }
41357
41783
  this.deleteFlow(flowId, flow);
41358
- const code = (0, import_node_crypto2.randomBytes)(24).toString("hex");
41784
+ const code = (0, import_node_crypto3.randomBytes)(24).toString("hex");
41359
41785
  this.codes.set(code, {
41360
41786
  clientId: flow.clientId,
41361
41787
  address: flow.siwe.address,
41362
41788
  codeChallenge: flow.params.codeChallenge,
41789
+ redirectHost: new URL(flow.params.redirectUri).host,
41363
41790
  createdAt: this.clock()
41364
41791
  });
41365
41792
  const redirect = new URL(flow.params.redirectUri);
@@ -41376,28 +41803,61 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41376
41803
  const record = this.liveCode(authorizationCode);
41377
41804
  if (!record || record.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown, expired, or foreign authorization code");
41378
41805
  this.codes.delete(authorizationCode);
41379
- return this.mintTokens(record.address, client.client_id);
41806
+ const now = this.clock();
41807
+ const refreshToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41808
+ const grant = {
41809
+ grantId: (0, import_node_crypto3.randomBytes)(16).toString("hex"),
41810
+ address: record.address.toLowerCase(),
41811
+ clientId: client.client_id,
41812
+ clientName: client.client_name ?? null,
41813
+ redirectHost: record.redirectHost,
41814
+ createdAt: now,
41815
+ lastUsedAt: now,
41816
+ refreshHash: hashToken(refreshToken),
41817
+ revokedAt: null,
41818
+ expireAt: now + this.refreshIdleMs
41819
+ };
41820
+ await this.store.createGrant(grant);
41821
+ await this.store.extendClient(client.client_id, grant.expireAt);
41822
+ return this.mintAccess(grant, refreshToken);
41380
41823
  }
41381
41824
  async exchangeRefreshToken(client, refreshToken) {
41382
- const record = this.refresh.get(refreshToken);
41383
- if (!record || record.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown or foreign refresh token");
41384
- if (this.clock() - record.lastUsed > this.refreshIdleMs) {
41385
- this.refresh.delete(refreshToken);
41825
+ const oldHash = hashToken(refreshToken);
41826
+ const grant = await this.store.findGrantByRefreshHash(oldHash);
41827
+ if (!grant || grant.clientId !== client.client_id) throw new import_errors.InvalidGrantError("unknown or foreign refresh token");
41828
+ if (grant.revokedAt !== null) throw new import_errors.InvalidGrantError("this connection was revoked by the wallet owner \u2014 reconnect with a fresh wallet sign-in");
41829
+ const now = this.clock();
41830
+ if (now - grant.lastUsedAt > this.refreshIdleMs) {
41386
41831
  throw new import_errors.InvalidGrantError("refresh token expired after inactivity \u2014 reconnect with a fresh wallet sign-in");
41387
41832
  }
41388
- this.refresh.delete(refreshToken);
41389
- return this.mintTokens(record.address, client.client_id);
41833
+ const nextToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41834
+ const next = { refreshHash: hashToken(nextToken), lastUsedAt: now, expireAt: now + this.refreshIdleMs };
41835
+ await this.store.extendClient(client.client_id, next.expireAt);
41836
+ if (!await this.store.rotateGrant(grant.grantId, oldHash, next)) {
41837
+ throw new import_errors.InvalidGrantError("refresh token already used or revoked \u2014 reconnect with a fresh wallet sign-in");
41838
+ }
41839
+ return this.mintAccess({ ...grant, ...next }, nextToken);
41390
41840
  }
41391
41841
  /** SDK contract: throws InvalidTokenError on anything not live. */
41392
41842
  async verifyAccessToken(token) {
41393
- const info = this.lookupAccessToken(token);
41843
+ const info = await this.lookupAccessToken(token);
41394
41844
  if (!info) throw new import_errors.InvalidTokenError("unknown or expired access token");
41395
41845
  return info;
41396
41846
  }
41397
- /** Non-throwing lookup for the connector's own request path (null = 401). */
41398
- lookupAccessToken(token) {
41847
+ /** Non-throwing lookup for the connector's own request path (null = 401). The grant
41848
+ * behind the token is re-confirmed live when the last check is older than D6's bound. */
41849
+ async lookupAccessToken(token) {
41399
41850
  const record = this.access.get(token);
41400
- if (!record || record.expiresAt * 1e3 <= this.clock()) return null;
41851
+ const now = this.clock();
41852
+ if (!record || record.expiresAt * 1e3 <= now) return null;
41853
+ if (now - record.checkedAt > GRANT_RECHECK_MS) {
41854
+ const grant = await this.store.getGrant(record.grantId);
41855
+ if (!grant || !this.grantLive(grant, now)) {
41856
+ this.access.delete(token);
41857
+ return null;
41858
+ }
41859
+ record.checkedAt = now;
41860
+ }
41401
41861
  return {
41402
41862
  token,
41403
41863
  clientId: record.clientId,
@@ -41409,14 +41869,46 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41409
41869
  async revokeToken(client, request) {
41410
41870
  const a = this.access.get(request.token);
41411
41871
  if (a && a.clientId === client.client_id) this.access.delete(request.token);
41412
- const r = this.refresh.get(request.token);
41413
- if (r && r.clientId === client.client_id) this.refresh.delete(request.token);
41414
- }
41415
- mintTokens(address, clientId) {
41416
- const accessToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41417
- const refreshToken = (0, import_node_crypto2.randomBytes)(32).toString("hex");
41418
- this.access.set(accessToken, { address, clientId, expiresAt: Math.floor(this.clock() / 1e3) + ACCESS_TTL_S });
41419
- this.refresh.set(refreshToken, { address, clientId, lastUsed: this.clock() });
41872
+ const grant = await this.store.findGrantByRefreshHash(hashToken(request.token));
41873
+ if (grant && grant.clientId === client.client_id) await this.revokeGrantRecord(grant.grantId);
41874
+ }
41875
+ /** Plan 18 — the account API's list: the address's LIVE grants, most recently used first. */
41876
+ async listGrants(address) {
41877
+ const now = this.clock();
41878
+ return (await this.store.listGrants(address.toLowerCase())).filter((g) => this.grantLive(g, now)).sort((x, y) => y.lastUsedAt - x.lastUsedAt).map((g) => ({
41879
+ id: g.grantId,
41880
+ clientId: g.clientId,
41881
+ clientName: g.clientName,
41882
+ redirectHost: g.redirectHost,
41883
+ createdAt: new Date(g.createdAt).toISOString(),
41884
+ lastUsedAt: new Date(g.lastUsedAt).toISOString()
41885
+ }));
41886
+ }
41887
+ /** Plan 18 — the wallet owner revokes one grant. False when the grant is unknown, not
41888
+ * live, or ANOTHER address's: the caller cannot tell those apart (no existence oracle). */
41889
+ async revokeGrantForAddress(address, grantId) {
41890
+ const grant = await this.store.getGrant(grantId);
41891
+ if (!grant || grant.address !== address.toLowerCase() || !this.grantLive(grant, this.clock())) return false;
41892
+ await this.revokeGrantRecord(grantId);
41893
+ return true;
41894
+ }
41895
+ async revokeGrantRecord(grantId) {
41896
+ await this.store.revokeGrant(grantId, this.clock());
41897
+ for (const [t, a] of this.access) if (a.grantId === grantId) this.access.delete(t);
41898
+ }
41899
+ grantLive(grant, now) {
41900
+ return grant.revokedAt === null && now - grant.lastUsedAt <= this.refreshIdleMs;
41901
+ }
41902
+ mintAccess(grant, refreshToken) {
41903
+ const accessToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
41904
+ const now = this.clock();
41905
+ this.access.set(accessToken, {
41906
+ address: grant.address,
41907
+ clientId: grant.clientId,
41908
+ grantId: grant.grantId,
41909
+ expiresAt: Math.floor(now / 1e3) + ACCESS_TTL_S,
41910
+ checkedAt: now
41911
+ });
41420
41912
  return { access_token: accessToken, token_type: "bearer", expires_in: ACCESS_TTL_S, refresh_token: refreshToken };
41421
41913
  }
41422
41914
  liveFlow(flowId) {
@@ -41438,17 +41930,53 @@ Issued At: ${new Date(this.clock()).toISOString()}`;
41438
41930
  return record;
41439
41931
  }
41440
41932
  /** Expired flows/codes/tokens are dropped opportunistically — no timers to leak. An
41441
- * expired flow's WC transport is DISPOSED with it (M17-3); idle refresh tokens die
41442
- * here too (M17-9 — nothing grows forever). */
41443
- sweep() {
41933
+ * expired flow's WC transport is DISPOSED with it (M17-3); expired clients and grants
41934
+ * leave the store here too (M17-9 — nothing grows forever). */
41935
+ async sweep() {
41444
41936
  const now = this.clock();
41445
41937
  for (const [id, f] of this.flows) if (now - f.createdAt > FLOW_TTL_MS) this.deleteFlow(id, f);
41446
41938
  for (const [c, r] of this.codes) if (now - r.createdAt > CODE_TTL_MS) this.codes.delete(c);
41447
41939
  for (const [t, a] of this.access) if (a.expiresAt * 1e3 <= now) this.access.delete(t);
41448
- for (const [t, r] of this.refresh) if (now - r.lastUsed > this.refreshIdleMs) this.refresh.delete(t);
41940
+ await this.store.sweep(now);
41449
41941
  }
41450
41942
  };
41451
41943
 
41944
+ // src/connector/wc-min-version.ts
41945
+ var WC_MIN_SAFE_VERSION = "0.5.21";
41946
+ function parseVersion(label, v) {
41947
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(v);
41948
+ if (!m) throw new Error(`${label} '${v}' is not a MAJOR.MINOR.PATCH[-prerelease] version`);
41949
+ return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split(".") : [] };
41950
+ }
41951
+ function compareVersions(a, b) {
41952
+ for (let i = 0; i < 3; i++) {
41953
+ const d = a.core[i] - b.core[i];
41954
+ if (d !== 0) return d;
41955
+ }
41956
+ if (a.pre.length === 0 || b.pre.length === 0) return b.pre.length - a.pre.length;
41957
+ for (let i = 0; i < Math.min(a.pre.length, b.pre.length); i++) {
41958
+ const x = a.pre[i];
41959
+ const y = b.pre[i];
41960
+ if (x === y) continue;
41961
+ const xNum = /^\d+$/.test(x);
41962
+ const yNum = /^\d+$/.test(y);
41963
+ if (xNum && yNum) return Number(x) - Number(y);
41964
+ if (xNum !== yNum) return xNum ? -1 : 1;
41965
+ return x < y ? -1 : 1;
41966
+ }
41967
+ return a.pre.length - b.pre.length;
41968
+ }
41969
+ function assertWcMinSafeVersion(version2, wcArmed) {
41970
+ if (!wcArmed) return;
41971
+ const have = parseVersion("connector version", version2);
41972
+ const need = parseVersion("WC_MIN_SAFE_VERSION", WC_MIN_SAFE_VERSION);
41973
+ if (compareVersions(have, need) < 0) {
41974
+ throw new Error(
41975
+ `refusing to boot: the WalletConnect leg is armed (DH_WC_PROJECT_ID) but this connector is v${version2}, below WC_MIN_SAFE_VERSION v${WC_MIN_SAFE_VERSION} \u2014 the first release carrying the plan-19 WalletConnect fixes. Roll forward, or unset DH_WC_PROJECT_ID.`
41976
+ );
41977
+ }
41978
+ }
41979
+
41452
41980
  // src/boundary/errors.ts
41453
41981
  function boundaryError(code, message, extra) {
41454
41982
  return { code, message, ...extra?.source && { source: extra.source }, ...extra?.details && { details: extra.details } };
@@ -41672,13 +42200,14 @@ function resolveRealConfig(env) {
41672
42200
 
41673
42201
  // src/boot.ts
41674
42202
  var fs6 = __toESM(require("fs"));
41675
- var import_ethers51 = require("ethers");
42203
+ var import_ethers53 = require("ethers");
41676
42204
 
41677
42205
  // src/boundary/index.ts
41678
- var import_node_crypto9 = require("crypto");
42206
+ var import_node_crypto10 = require("crypto");
41679
42207
  var fs5 = __toESM(require("fs"));
41680
42208
  var os2 = __toESM(require("os"));
41681
42209
  var path4 = __toESM(require("path"));
42210
+ var import_ethers52 = require("ethers");
41682
42211
 
41683
42212
  // src/boundary/envelope.ts
41684
42213
  function okEnvelope(data, source, warnings = []) {
@@ -41762,8 +42291,13 @@ function iso(sec) {
41762
42291
  return new Date(sec * 1e3).toISOString();
41763
42292
  }
41764
42293
  var PSM_FLOOR_TOLERANCE_BPS = 100;
42294
+ var CANONICAL_MAINNET_USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
42295
+ function stablecoinKindFor(network, stablecoinAddress) {
42296
+ if (network !== "mainnet") return "mock";
42297
+ return stablecoinAddress.toLowerCase() === CANONICAL_MAINNET_USDC.toLowerCase() ? "circle" : "onchain";
42298
+ }
41765
42299
  function failureToError(f) {
41766
- const code = f.kind === "signer-missing" ? "SIGNER_UNAVAILABLE" : f.kind === "unavailable" ? "UPSTREAM_UNAVAILABLE" : f.kind === "not-found" ? "NOT_FOUND" : "UPSTREAM_REJECTED";
42300
+ const code = f.kind === "signer-missing" ? "SIGNER_UNAVAILABLE" : f.kind === "unavailable" ? "UPSTREAM_UNAVAILABLE" : f.kind === "unsupported" ? "NOT_IMPLEMENTED" : f.kind === "not-found" ? "NOT_FOUND" : "UPSTREAM_REJECTED";
41767
42301
  const message = f.kind === "malformed" ? `${f.message} (upstream response failed integrity checks)` : f.message;
41768
42302
  return boundaryError(code, message, {
41769
42303
  source: f.source,
@@ -42239,7 +42773,7 @@ var BoundaryCore = class {
42239
42773
  tokenAddress: a.tokenAddress,
42240
42774
  spenderAddress: a.spenderAddress,
42241
42775
  spenderContract: a.spenderContract,
42242
- spenderReason: a.spenderContract === "SimplePSMV2" ? "the PSM contract itself pulls the USDC it converts (transferFrom), so the USDC allowance goes to the PSM" : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
42776
+ spenderReason: a.spenderContract === "SimplePSMV2" ? `the PSM contract itself pulls the ${a.tokenSymbol} it converts (transferFrom), so the ${a.tokenSymbol} allowance goes to the PSM` : "the PSM burns your UCD THROUGH the UCDController (controller.burnFromPsm), so the UCD allowance goes to the UCDController \u2014 a different contract than the PSM, by design",
42243
42777
  before: a.before,
42244
42778
  amountUnit: q.amountInUnit,
42245
42779
  basis: "approvals are planned against the allowance read before signing: none when it already covers the amount; an exact approve when it is 0; a partial allowance is reset to 0 first (some tokens refuse a non-zero \u2192 non-zero approve). Every approve is EXACTLY the input amount \u2014 never unlimited."
@@ -42298,9 +42832,10 @@ var BoundaryCore = class {
42298
42832
  chainId: this.deps.chainId,
42299
42833
  psmAddress: s.psmAddress,
42300
42834
  stablecoinAddress: s.stablecoinAddress,
42301
- // Only mainnet runs real Circle USDC; the mock world and sepolia both run a
42302
- // practice stablecoin with a public self-serve mint.
42303
- stablecoinKind: this.deps.network === "mainnet" ? "circle" : "mock",
42835
+ // Labelled by the ACTUAL coin, not the network (C-49): `circle` only for canonical
42836
+ // mainnet USDC, `mock` for the practice token, `onchain` for any other real coin
42837
+ // (e.g. mainnet USDT) — a USDT swap must never render as "real USDC".
42838
+ stablecoinKind: stablecoinKindFor(this.deps.network, s.stablecoinAddress),
42304
42839
  stablecoinSymbol: s.stablecoinSymbol,
42305
42840
  stablecoinDecimals: s.stablecoinDecimals,
42306
42841
  exchangeRate: s.exchangeRate,
@@ -42735,7 +43270,7 @@ var DEFAULT_SEED = {
42735
43270
  };
42736
43271
 
42737
43272
  // src/boundary/upstream/mock/world.ts
42738
- var import_node_crypto3 = require("crypto");
43273
+ var import_node_crypto4 = require("crypto");
42739
43274
  var import_ethers3 = require("ethers");
42740
43275
 
42741
43276
  // src/signer/safe.ts
@@ -42939,7 +43474,7 @@ var World = class {
42939
43474
  nextId(prefix) {
42940
43475
  this.state.counter += 1;
42941
43476
  const n = this.state.counter;
42942
- const hash = (0, import_node_crypto3.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
43477
+ const hash = (0, import_node_crypto4.createHash)("sha256").update(`${this.state.seed.namespace}:${prefix}:${n}`).digest("hex");
42943
43478
  return { n, hash };
42944
43479
  }
42945
43480
  nextTxRef() {
@@ -43890,7 +44425,7 @@ var WorldStore = class {
43890
44425
  };
43891
44426
 
43892
44427
  // src/boundary/upstream/mock/signer.ts
43893
- var import_node_crypto4 = require("crypto");
44428
+ var import_node_crypto5 = require("crypto");
43894
44429
  function mockSign(op, borrower, stance) {
43895
44430
  if (stance === "decline") {
43896
44431
  return {
@@ -43905,7 +44440,7 @@ function mockSign(op, borrower, stance) {
43905
44440
  signer: borrower,
43906
44441
  action: op.action,
43907
44442
  card: op.card,
43908
- digest: (0, import_node_crypto4.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
44443
+ digest: (0, import_node_crypto5.createHash)("sha256").update(`${borrower}:${op.card}`).digest("hex")
43909
44444
  }
43910
44445
  };
43911
44446
  }
@@ -44175,8 +44710,13 @@ var SignerManager = class {
44175
44710
  mode: deps.initialMode,
44176
44711
  borrower: deps.configuredBorrower ?? null
44177
44712
  };
44713
+ if (deps.authenticatedBorrower) this.state = { ...this.state, borrower: deps.authenticatedBorrower };
44178
44714
  }
44179
44715
  state;
44716
+ /** True when the borrower is the signed-in identity and cannot be swapped. */
44717
+ identityPinned() {
44718
+ return this.deps.authenticatedBorrower !== void 0;
44719
+ }
44180
44720
  mode() {
44181
44721
  return this.state.mode;
44182
44722
  }
@@ -44216,7 +44756,7 @@ var SignerManager = class {
44216
44756
  this.deps.persistence.save(this.state);
44217
44757
  }
44218
44758
  resetBorrower() {
44219
- this.state = { ...this.state, borrower: null };
44759
+ this.state = { ...this.state, borrower: this.deps.authenticatedBorrower ?? null };
44220
44760
  this.deps.persistence.save(this.state);
44221
44761
  }
44222
44762
  async use(mode, opts) {
@@ -45284,13 +45824,42 @@ var MockUpstreamPlugin = class {
45284
45824
  };
45285
45825
 
45286
45826
  // src/boundary/upstream/mock/external-ceremony.ts
45287
- var import_node_crypto5 = require("crypto");
45827
+ var import_node_crypto6 = require("crypto");
45288
45828
  var import_node_child_process = require("child_process");
45289
45829
  var import_ethers10 = require("ethers");
45290
45830
 
45291
45831
  // src/boundary/upstream/shared/external-bridge/card.ts
45292
45832
  var import_ethers8 = require("ethers");
45293
45833
  init_tx_validator();
45834
+
45835
+ // src/boundary/upstream/shared/external-bridge/card-escape.ts
45836
+ var MAX_VALUE_CHARS = 200;
45837
+ function mustEscape(code) {
45838
+ if (code <= 31 || code === 127) return true;
45839
+ if (code >= 128 && code <= 159) return true;
45840
+ if (code === 8232 || code === 8233) return true;
45841
+ if (code >= 8234 && code <= 8238) return true;
45842
+ if (code >= 8294 && code <= 8297) return true;
45843
+ return false;
45844
+ }
45845
+ function safeValue(raw) {
45846
+ let out = "";
45847
+ for (const ch of String(raw)) {
45848
+ const code = ch.codePointAt(0);
45849
+ out += mustEscape(code) ? `\\u${code.toString(16).padStart(4, "0")}` : ch;
45850
+ if (out.length > MAX_VALUE_CHARS) return `${out.slice(0, MAX_VALUE_CHARS)}\u2026[truncated]`;
45851
+ }
45852
+ return out;
45853
+ }
45854
+
45855
+ // src/boundary/upstream/shared/external-bridge/card.ts
45856
+ function formatBtc(sats) {
45857
+ const negative = sats < 0n;
45858
+ const abs = negative ? -sats : sats;
45859
+ const whole = abs / 10n ** 8n;
45860
+ const frac = (abs % 10n ** 8n).toString().padStart(8, "0").replace(/0+$/, "");
45861
+ return `${negative ? "-" : ""}${whole}${frac ? "." + frac : ""}`;
45862
+ }
45294
45863
  function formatUcd(wei) {
45295
45864
  const negative = wei < 0n;
45296
45865
  const abs = negative ? -wei : wei;
@@ -45336,15 +45905,15 @@ function cardForTx(tx2) {
45336
45905
  "Operation: create a new borrowing position (your wallet is the borrower)",
45337
45906
  `Term: ${Number(args[4])} months`,
45338
45907
  `Position key (PKP id): ${String(args[0])}`,
45339
- `BTC vault (mainnet form): ${String(args[2])}`,
45340
- `BTC vault (regtest form): ${String(args[3])}`,
45908
+ `BTC vault (mainnet form): ${safeValue(args[2])}`,
45909
+ `BTC vault (regtest form): ${safeValue(args[3])}`,
45341
45910
  `Validator generation: ${Number(args[5])}`,
45342
45911
  ...head
45343
45912
  ];
45344
45913
  case "addAddress":
45345
45914
  return [
45346
45915
  "Operation: allowlist a Bitcoin withdrawal destination for YOUR account",
45347
- `BTC address to allowlist: ${String(args[0])}`,
45916
+ `BTC address to allowlist: ${safeValue(args[0])}`,
45348
45917
  "Withdrawals to this address become possible only after the registry's on-chain delay",
45349
45918
  ...head
45350
45919
  ];
@@ -45372,15 +45941,40 @@ function cardForTx(tx2) {
45372
45941
  `Minimum stablecoin out \u2014 the slippage floor (smallest units): ${String(args[2])}`,
45373
45942
  ...head
45374
45943
  ];
45944
+ case "withdrawBTC": {
45945
+ const p = args[0];
45946
+ return [
45947
+ "Operation: withdraw BTC from your vault \u2014 THIS MOVES BITCOIN OUT",
45948
+ `Position: ${safeValue(p.positionId)}`,
45949
+ // The destination is the whole security question of this card. It is a caller-
45950
+ // supplied string, hence safeValue: see the escaping note above.
45951
+ `BTC sent to: ${safeValue(p.withdrawalAddress)}`,
45952
+ `Leaves the vault (fee included): ${formatBtc(BigInt(p.totalDeduction))} BTC (${BigInt(p.totalDeduction)} sats)`,
45953
+ `Collateral remaining after this: ${formatBtc(BigInt(p.newCollateral))} BTC (${BigInt(p.newCollateral)} sats)`,
45954
+ `Spending vault UTXO: ${safeValue(p.utxoTxid)}:${Number(p.utxoVout)}`,
45955
+ ...head
45956
+ ];
45957
+ }
45958
+ case "setPositionDelegate":
45959
+ return [
45960
+ "Operation: set the DELEGATE for this position \u2014 this address may act on the position on your behalf",
45961
+ `Position: ${safeValue(args[0])}`,
45962
+ `Delegate address: ${safeValue(args[1])}`,
45963
+ "Setting the zero address removes the current delegate",
45964
+ ...head
45965
+ ];
45375
45966
  default:
45376
- return [`Operation: ${name}`, ...args.map((a, i) => `arg[${i}]: ${String(a)}`), ...head];
45967
+ throw new Error(
45968
+ `no approval card is defined for the signable function "${name}" \u2014 add a case to cardForTx before this operation can be approved`
45969
+ );
45377
45970
  }
45378
45971
  }
45379
45972
  function cardForTypedData(action, payload) {
45380
45973
  const m = payload.message;
45381
45974
  return [
45382
45975
  `Operation: ${action} \u2014 this signature AUTHORIZES the operation described below; the protocol executes it after your approval`,
45383
- ...Object.entries(m).map(([k, v]) => `${k}: ${String(v)}`),
45976
+ // `detail` here is a server-composed string — same escaping rule as the tx card.
45977
+ ...Object.entries(m).map(([k, v]) => `${safeValue(k)}: ${safeValue(v)}`),
45384
45978
  `Signing domain: ${String(payload.domain["name"])} v${String(payload.domain["version"])} \xB7 chain ${String(payload.domain["chainId"])}`
45385
45979
  ];
45386
45980
  }
@@ -45477,7 +46071,7 @@ var ExternalCeremony = class {
45477
46071
  validateUnsignedTx({ ...p.tx }, p.expected, this.deps.vctx);
45478
46072
  const card = cardForTx(p.tx);
45479
46073
  const outcome = await this.request({
45480
- id: (0, import_node_crypto5.randomUUID)(),
46074
+ id: (0, import_node_crypto6.randomUUID)(),
45481
46075
  kind: "transaction",
45482
46076
  action: p.action,
45483
46077
  card,
@@ -45522,7 +46116,7 @@ var ExternalCeremony = class {
45522
46116
  message
45523
46117
  };
45524
46118
  const outcome = await this.request({
45525
- id: (0, import_node_crypto5.randomUUID)(),
46119
+ id: (0, import_node_crypto6.randomUUID)(),
45526
46120
  kind: "typed-data",
45527
46121
  action: "login",
45528
46122
  card: cardForTypedData("login", typedData),
@@ -45550,7 +46144,7 @@ var ExternalCeremony = class {
45550
46144
  });
45551
46145
  const card = cardForTypedData(p.action, typedData);
45552
46146
  const outcome = await this.request({
45553
- id: (0, import_node_crypto5.randomUUID)(),
46147
+ id: (0, import_node_crypto6.randomUUID)(),
45554
46148
  kind: "typed-data",
45555
46149
  action: p.action,
45556
46150
  card,
@@ -45725,18 +46319,16 @@ var KeystoreCeremony = class {
45725
46319
  };
45726
46320
 
45727
46321
  // src/boundary/upstream/mock/safe-ceremony.ts
45728
- var import_node_crypto6 = require("crypto");
46322
+ var import_node_crypto7 = require("crypto");
45729
46323
  var import_ethers12 = require("ethers");
45730
46324
  init_tx_validator();
45731
46325
 
45732
46326
  // src/boundary/upstream/shared/quantum.ts
45733
46327
  var QUANTUM_WINDOW_SECONDS = 60;
45734
- var AUTH_VALIDITY_WINDOWS = 3;
45735
- function authValiditySec() {
45736
- return QUANTUM_WINDOW_SECONDS * AUTH_VALIDITY_WINDOWS;
45737
- }
45738
46328
  function isAuthFresh(issuedAtSec, nowSec) {
45739
- return issuedAtSec <= nowSec && nowSec - issuedAtSec < authValiditySec();
46329
+ const sq = Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS;
46330
+ const cq = Math.floor(nowSec / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS;
46331
+ return sq === cq - QUANTUM_WINDOW_SECONDS || sq === cq || sq === cq + QUANTUM_WINDOW_SECONDS;
45740
46332
  }
45741
46333
  function isStrictCurrentQuantum(issuedAtSec, nowSec) {
45742
46334
  return issuedAtSec <= nowSec && Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) === Math.floor(nowSec / QUANTUM_WINDOW_SECONDS);
@@ -45777,7 +46369,7 @@ var SafeCeremony = class {
45777
46369
  if (!auth.ok) return auth.refusal;
45778
46370
  if (!isAuthFresh(issuedAtSec, surface.nowSec())) {
45779
46371
  return this.refuse(
45780
- `${p.action}: the owners' authorization expired \u2014 issued in a past quantum window (validity ${3 * QUANTUM_WINDOW_SECONDS}s); gather the owners and sign again`
46372
+ `${p.action}: the owners' authorization expired \u2014 issued outside the past/current/next quantum window (${QUANTUM_WINDOW_SECONDS}s quanta); gather the owners and sign again`
45781
46373
  );
45782
46374
  }
45783
46375
  const raw = await executor.signTransaction({
@@ -46026,7 +46618,7 @@ var SafeCeremony = class {
46026
46618
  const primaryType = Object.keys(build.payload.types)[0];
46027
46619
  const outcome = await bridge.requestSignatureCollection(
46028
46620
  {
46029
- id: (0, import_node_crypto6.randomUUID)(),
46621
+ id: (0, import_node_crypto7.randomUUID)(),
46030
46622
  kind: "typed-data",
46031
46623
  action,
46032
46624
  card: build.card,
@@ -52496,7 +53088,6 @@ var init_deployment_addresses = __esm2({
52496
53088
  PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
52497
53089
  FeeRecipientRegistry: "0x95795F8403DDb629E8527B2934C4e71f5fC0C374",
52498
53090
  BitcoinWithdrawalAddressRegistry: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
52499
- CarryAgentRegistry: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
52500
53091
  AgentDelegationRegistry: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
52501
53092
  DHAgentDelegate: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF",
52502
53093
  AgentModuleFactory: "0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5"
@@ -52545,11 +53136,11 @@ var init_deployment_addresses = __esm2({
52545
53136
  reason: "Shared upgrade script: AdminModule implementation update"
52546
53137
  },
52547
53138
  PositionManagerViews: {
52548
- previousImplementation: "0x1EB2B1d058006ACd9033E01e846D73eDE686b620",
52549
- newImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
52550
- upgradedAt: "2026-07-03T20:11:25.817Z",
52551
- upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
52552
- reason: "Shared upgrade script: PositionManagerViews implementation update"
53139
+ previousImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
53140
+ newImplementation: "0x8cEB3F1c07fDB3301f55b96a5B9aDb33C8d36Da3",
53141
+ upgradedAt: "2026-10-02T17:04:25.853Z",
53142
+ upgradedBy: "0x0f8f23674cc90Ef7107930a4437341fD8B460362",
53143
+ reason: "1.1.2: getBackingVaults (PoR backing set) + implementation lock (constructor)"
52553
53144
  },
52554
53145
  TestPositionManager: {
52555
53146
  previousImplementation: "0x0B46Ee1a9C6b42559758B7FF78294Cd867BB08f8",
@@ -52766,8 +53357,6 @@ var init_deployment_addresses = __esm2({
52766
53357
  OPERATION_AUTHORIZATION_REGISTRY_IMPL: "0xe0D981B60351f0f8fFDA2b50C8180Fb37CeF3883",
52767
53358
  BITCOIN_WITHDRAWAL_ADDRESS_REGISTRY: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
52768
53359
  BITCOIN_WITHDRAWAL_ADDRESS_REGISTRY_IMPL: "0x76E0a2c9d89562fD7c50b5f554d7fa25957e39Db",
52769
- CARRY_AGENT_REGISTRY: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
52770
- CARRY_AGENT_REGISTRY_IMPL: "0x1b11a3D5e46F3672E643c997f0d569DFf0b64a01",
52771
53360
  AGENT_DELEGATION_REGISTRY: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
52772
53361
  AGENT_DELEGATION_REGISTRY_IMPL: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
52773
53362
  DH_AGENT_DELEGATE: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF"
@@ -52799,7 +53388,6 @@ var init_deployment_addresses = __esm2({
52799
53388
  PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
52800
53389
  FeeRecipientRegistry: "0x95795F8403DDb629E8527B2934C4e71f5fC0C374",
52801
53390
  BitcoinWithdrawalAddressRegistry: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
52802
- CarryAgentRegistry: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
52803
53391
  AgentDelegationRegistry: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
52804
53392
  DHAgentDelegate: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF",
52805
53393
  AgentModuleFactory: "0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5"
@@ -53774,113 +54362,113 @@ var require_pkg_src2 = __commonJS2({
53774
54362
  deployedAt: 1784569687492,
53775
54363
  size: 4140,
53776
54364
  hash: "4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b",
53777
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
54365
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
53778
54366
  pkp: {
53779
54367
  publicKey: "0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f",
53780
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54368
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53781
54369
  }
53782
54370
  },
53783
54371
  btcTransactionSigner: {
53784
- cid: "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf",
54372
+ cid: "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U",
53785
54373
  authorizedCidHex: cidToHex(
53786
- "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf"
54374
+ "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U"
53787
54375
  ),
53788
54376
  name: "Btc Transaction Signer",
53789
54377
  description: "Production Btc Transaction Signer",
53790
54378
  version: "1.1.1",
53791
54379
  deployed: true,
53792
- deployedAt: 1787923905597,
53793
- size: 70646,
53794
- hash: "37c3bb72a660c8275d92e1b73f9482742d86b64789480b9246304c0ca1bab47a"
54380
+ deployedAt: 1790246185256,
54381
+ size: 73313,
54382
+ hash: "d8b6bc646ba33fee7d46c8e9b281de776081ea6f182f56fd15d4c52aaf3dd030"
53795
54383
  },
53796
54384
  ucdMintValidator: {
53797
- cid: "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc",
54385
+ cid: "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe",
53798
54386
  authorizedCidHex: cidToHex(
53799
- "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc"
54387
+ "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe"
53800
54388
  ),
53801
54389
  name: "Ucd Mint Validator",
53802
54390
  description: "Production Ucd Mint Validator",
53803
- version: "1.2.1",
54391
+ version: "1.3.0",
53804
54392
  deployed: true,
53805
- deployedAt: 1787923919527,
53806
- size: 86197,
53807
- hash: "c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf",
53808
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54393
+ deployedAt: 1790246219868,
54394
+ size: 90022,
54395
+ hash: "65e8cb778c2b767ae6eb37cb5db7b4c5a3f2468d508463c847c83c1b6825fadd",
54396
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53809
54397
  pkp: {
53810
54398
  publicKey: "0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb",
53811
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54399
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53812
54400
  }
53813
54401
  },
53814
54402
  processPaymentValidator: {
53815
- cid: "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF",
54403
+ cid: "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8",
53816
54404
  authorizedCidHex: cidToHex(
53817
- "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF"
54405
+ "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8"
53818
54406
  ),
53819
54407
  name: "Process Payment Validator",
53820
54408
  description: "Production Process Payment Validator",
53821
54409
  version: "1.2.1",
53822
54410
  deployed: true,
53823
- deployedAt: 1787923987153,
53824
- size: 82217,
53825
- hash: "13defa19614215ab3b1fe88955d69e530d13a09475396af932fe0e213637da2f",
53826
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54411
+ deployedAt: 1790246225795,
54412
+ size: 85107,
54413
+ hash: "25ecf952c4c44c40b0920b92d57906e7010ed9a38e2ba41ccdee6d3377c2b596",
54414
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53827
54415
  pkp: {
53828
54416
  publicKey: "0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad",
53829
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54417
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53830
54418
  }
53831
54419
  },
53832
54420
  extendPositionValidator: {
53833
- cid: "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m",
54421
+ cid: "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX",
53834
54422
  authorizedCidHex: cidToHex(
53835
- "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m"
54423
+ "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX"
53836
54424
  ),
53837
54425
  name: "Extend Position Validator",
53838
54426
  description: "Production Extend Position Validator",
53839
54427
  version: "1.2.1",
53840
54428
  deployed: true,
53841
- deployedAt: 1787923999294,
53842
- size: 79975,
53843
- hash: "31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a",
53844
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54429
+ deployedAt: 1790246231975,
54430
+ size: 82853,
54431
+ hash: "25d4887b7f646649db2bb7f2bfb77d039db83228a6c454377ca26c779b0903cc",
54432
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53845
54433
  pkp: {
53846
54434
  publicKey: "0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836",
53847
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54435
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53848
54436
  }
53849
54437
  },
53850
54438
  btcWithdrawal: {
53851
- cid: "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY",
54439
+ cid: "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP",
53852
54440
  authorizedCidHex: cidToHex(
53853
- "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY"
54441
+ "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP"
53854
54442
  ),
53855
54443
  name: "Btc Withdrawal",
53856
54444
  description: "Production Btc Withdrawal",
53857
54445
  version: "1.2.7",
53858
54446
  deployed: true,
53859
- deployedAt: 1787924017769,
53860
- size: 100069,
53861
- hash: "4f8e27414e4da235e63d6ae1325c63f3d2fb956464515a21aa007a99935f0f13",
53862
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54447
+ deployedAt: 1790246239599,
54448
+ size: 101228,
54449
+ hash: "2ed25eca6cc80a43061b7ad119737af48158fdb61d59f10cd06cea51b607f112",
54450
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53863
54451
  pkp: {
53864
54452
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
53865
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54453
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53866
54454
  }
53867
54455
  },
53868
54456
  liquidationValidator: {
53869
- cid: "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx",
54457
+ cid: "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb",
53870
54458
  authorizedCidHex: cidToHex(
53871
- "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx"
54459
+ "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb"
53872
54460
  ),
53873
54461
  name: "Liquidation Validator",
53874
54462
  description: "Production Liquidation Validator",
53875
54463
  version: "1.2.1",
53876
54464
  deployed: true,
53877
- deployedAt: 1785173262533,
53878
- size: 66846,
53879
- hash: "b35ee7706d733d625faa4dbe37f73c8e20f0c1befa897cd7875e827de52003de",
53880
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54465
+ deployedAt: 1790246247904,
54466
+ size: 70308,
54467
+ hash: "582ccf0ec7f715195e20fdc885996743cb42125b64173424e360ee63db62bbd8",
54468
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53881
54469
  pkp: {
53882
54470
  publicKey: "0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8",
53883
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54471
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53884
54472
  }
53885
54473
  },
53886
54474
  priceOracle: {
@@ -53895,28 +54483,28 @@ var require_pkg_src2 = __commonJS2({
53895
54483
  deployedAt: 1781116663270,
53896
54484
  size: 8695,
53897
54485
  hash: "ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74",
53898
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
54486
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
53899
54487
  pkp: {
53900
54488
  publicKey: "0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b",
53901
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54489
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53902
54490
  }
53903
54491
  },
53904
54492
  loanVaultBtcBalance: {
53905
- cid: "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4",
54493
+ cid: "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W",
53906
54494
  authorizedCidHex: cidToHex(
53907
- "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4"
54495
+ "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W"
53908
54496
  ),
53909
54497
  name: "Loan Vault Btc Balance",
53910
54498
  description: "Production Loan Vault Btc Balance",
53911
54499
  version: "1.2.1",
53912
54500
  deployed: true,
53913
- deployedAt: 1785173271802,
53914
- size: 56800,
53915
- hash: "a059133214e6ba0a73d655a15600c4b33e361fb340c98f8eecaf8ab7b95aaf83",
53916
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54501
+ deployedAt: 1790179961079,
54502
+ size: 60046,
54503
+ hash: "922e86c0a667fe0c0945771f84aa6b9fe08be9c96dd2f73a9c5cb257d24e22b0",
54504
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53917
54505
  pkp: {
53918
54506
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
53919
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54507
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53920
54508
  }
53921
54509
  },
53922
54510
  // btc-address-balance (Option B) — address-only signed total balance via
@@ -53926,21 +54514,21 @@ var require_pkg_src2 = __commonJS2({
53926
54514
  // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))
53927
54515
  // on each target chain (the action decrypts registry slots). No OAR entry.
53928
54516
  btcAddressBalance: {
53929
- cid: "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj",
54517
+ cid: "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN",
53930
54518
  authorizedCidHex: cidToHex(
53931
- "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj"
54519
+ "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN"
53932
54520
  ),
53933
54521
  name: "Btc Address Balance",
53934
54522
  description: "Address-only signed total BTC balance via registry consensus (no positionId, no price)",
53935
54523
  version: "0.2.1",
53936
54524
  deployed: true,
53937
- deployedAt: 1785173280221,
53938
- size: 27309,
53939
- hash: "f0d08938713d9d89a56a3a386cacbc2b57afd5ad367ea82d827d40e1bfc70989",
53940
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54525
+ deployedAt: 1790179971315,
54526
+ size: 30295,
54527
+ hash: "2c67d9cfa4d50e835fbb28ae50e80217ceb2be3bb862c89290aadf43fdc739c9",
54528
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53941
54529
  pkp: {
53942
54530
  publicKey: "0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd",
53943
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54531
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53944
54532
  }
53945
54533
  },
53946
54534
  alwaysSigner: {
@@ -53970,48 +54558,74 @@ var require_pkg_src2 = __commonJS2({
53970
54558
  hash: "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72"
53971
54559
  },
53972
54560
  agentModuleExecutor: {
53973
- cid: "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf",
54561
+ cid: "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX",
53974
54562
  authorizedCidHex: cidToHex(
53975
- "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf"
54563
+ "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX"
53976
54564
  ),
53977
54565
  name: "Agent Module Executor",
53978
54566
  description: "Production Agent Module Executor",
53979
54567
  version: "1.1.1",
53980
54568
  deployed: true,
53981
- deployedAt: 1787924032013,
53982
- size: 13878,
53983
- hash: "a7f0204700912e26e5a354bee13a1242a2baa218643b3bb22d28481f67f9baf4"
54569
+ deployedAt: 1790179978959,
54570
+ size: 14688,
54571
+ hash: "8edb9b12c784c8d7d153cce97235584c24665a788767ae68713dce91109ab35e"
53984
54572
  },
53985
54573
  staleSpendRecoveryValidator: {
53986
- cid: "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8",
54574
+ cid: "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz",
53987
54575
  authorizedCidHex: cidToHex(
53988
- "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8"
54576
+ "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz"
53989
54577
  ),
53990
54578
  name: "Stale Spend Recovery Validator",
53991
54579
  description: "Production Stale Spend Recovery Validator",
53992
54580
  version: "1.1.2",
53993
54581
  deployed: true,
53994
- deployedAt: 1787924048772,
53995
- size: 41424,
53996
- hash: "3c5f028d2bef4344768462993616d45e30d9d44ef126e04d6eb579821d57d99c",
53997
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
54582
+ deployedAt: 1790246256280,
54583
+ size: 48143,
54584
+ hash: "ec9236bcbe0af24d3e1844791fc8fe37371bbecd8ce95d02e13f7c6e1fc7d94c",
54585
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53998
54586
  pkp: {
53999
54587
  publicKey: "0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21",
54000
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
54588
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
54001
54589
  }
54002
54590
  },
54003
54591
  btcUtxoInvalidator: {
54004
- cid: "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf",
54592
+ cid: "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX",
54005
54593
  authorizedCidHex: cidToHex(
54006
- "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf"
54594
+ "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX"
54007
54595
  ),
54008
54596
  name: "Btc Utxo Invalidator",
54009
54597
  description: "Production Btc Utxo Invalidator",
54010
54598
  version: "1.0.0",
54011
54599
  deployed: true,
54012
- deployedAt: 1787924133241,
54013
- size: 66026,
54014
- hash: "603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9"
54600
+ deployedAt: 1790246264563,
54601
+ size: 69219,
54602
+ hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
54603
+ },
54604
+ carryCollateralAttestation: {
54605
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
54606
+ authorizedCidHex: cidToHex(
54607
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
54608
+ ),
54609
+ name: "Carry Collateral Attestation",
54610
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
54611
+ version: "1.0.0",
54612
+ deployed: true,
54613
+ deployedAt: 1790927734070,
54614
+ size: 21156,
54615
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
54616
+ },
54617
+ carryFundingAttestation: {
54618
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
54619
+ authorizedCidHex: cidToHex(
54620
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
54621
+ ),
54622
+ name: "Carry Funding Attestation",
54623
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
54624
+ version: "1.0.0",
54625
+ deployed: true,
54626
+ deployedAt: 1790925699980,
54627
+ size: 7193,
54628
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
54015
54629
  }
54016
54630
  };
54017
54631
  function getDeploymentsForNetwork(network) {
@@ -54779,7 +55393,10 @@ ${errorReport}`);
54779
55393
  BTCSpendAuthorizer: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
54780
55394
  BitcoinProviderRegistry: "0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",
54781
55395
  LITActionValidator: "0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",
54782
- PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"
55396
+ PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",
55397
+ TermManagerModule: "0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",
55398
+ UCDController: "0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",
55399
+ LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9"
54783
55400
  },
54784
55401
  11155111: {
54785
55402
  PositionManager: "0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",
@@ -54787,7 +55404,10 @@ ${errorReport}`);
54787
55404
  BTCSpendAuthorizer: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
54788
55405
  BitcoinProviderRegistry: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
54789
55406
  LITActionValidator: "0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",
54790
- PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9"
55407
+ PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
55408
+ TermManagerModule: "0x94Adc6F9558368B1482197584f1fc7133Ecf835b",
55409
+ UCDController: "0x360Bde4e489ee94E26601B206932De09EE60FF04",
55410
+ LiquidationManagerModule: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"
54791
55411
  }
54792
55412
  };
54793
55413
  function getPinnedContractAddresses(chainId) {
@@ -54973,10 +55593,10 @@ ${errorReport}`);
54973
55593
  };
54974
55594
  }
54975
55595
  const ratioBigInt = collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n / ucdDebt;
54976
- const collateralRatioBps = Number(ratioBigInt);
55596
+ const collateralRatioBps2 = Number(ratioBigInt);
54977
55597
  return {
54978
55598
  collateralValueUsd,
54979
- collateralRatioBps
55599
+ collateralRatioBps: collateralRatioBps2
54980
55600
  };
54981
55601
  }
54982
55602
  function hasSufficientCollateralForDebt(collateralValueUsd, currentDebt, additionalDebt, requiredRatioBps) {
@@ -55830,6 +56450,17 @@ ${auth.clientId}`;
55830
56450
  );
55831
56451
  }
55832
56452
  }
56453
+ var TIP_READ_FAILURE_PREFIX = "Bitcoin tip-height read failed";
56454
+ var BitcoinTipUnreadableError = class extends Error {
56455
+ constructor(message) {
56456
+ super(message);
56457
+ this.isBitcoinTipUnreadable = true;
56458
+ this.name = "BitcoinTipUnreadableError";
56459
+ }
56460
+ };
56461
+ function isBitcoinTipUnreadableError(error) {
56462
+ return typeof error === "object" && error !== null && error.isBitcoinTipUnreadable === true;
56463
+ }
55833
56464
  var BitcoinDataProvider = class {
55834
56465
  constructor(config) {
55835
56466
  this.config = config;
@@ -56281,27 +56912,12 @@ ${auth.clientId}`;
56281
56912
  if (!data.status.confirmed || !data.status.block_height) {
56282
56913
  return { txid: data.txid ?? txid, confirmations: 0 };
56283
56914
  }
56284
- try {
56285
- const tipResp = await fetch(
56286
- `${this.config.providerUrl}/blocks/tip/height`,
56287
- { signal: controller.signal, headers: await this.withAuth() }
56288
- );
56289
- if (!tipResp.ok) {
56290
- return { txid: data.txid ?? txid, confirmations: 1 };
56291
- }
56292
- const tipBody = (await tipResp.text()).trim();
56293
- const tipHeight = Number.parseInt(tipBody, 10);
56294
- if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
56295
- return { txid: data.txid ?? txid, confirmations: 1 };
56296
- }
56297
- const depth = tipHeight - data.status.block_height + 1;
56298
- return {
56299
- txid: data.txid ?? txid,
56300
- confirmations: depth > 0 ? depth : 0
56301
- };
56302
- } catch {
56303
- return { txid: data.txid ?? txid, confirmations: 1 };
56304
- }
56915
+ const tipHeight = await this.fetchTipHeight(controller.signal);
56916
+ const depth = tipHeight - data.status.block_height + 1;
56917
+ return {
56918
+ txid: data.txid ?? txid,
56919
+ confirmations: depth > 0 ? depth : 0
56920
+ };
56305
56921
  }
56306
56922
  return null;
56307
56923
  } catch (error) {
@@ -56309,12 +56925,55 @@ ${auth.clientId}`;
56309
56925
  if (isAbortError(error)) {
56310
56926
  throw new Error(`Request timeout after ${this.timeout}ms`);
56311
56927
  }
56928
+ if (isBitcoinTipUnreadableError(error)) {
56929
+ throw error;
56930
+ }
56312
56931
  if (getUnknownErrorMessage(error).includes("404")) {
56313
56932
  return null;
56314
56933
  }
56315
56934
  throw error;
56316
56935
  }
56317
56936
  }
56937
+ /**
56938
+ * Current chain tip height from THIS provider — or throw.
56939
+ *
56940
+ * Every exit is a throw naming the provider and the precise failure, because
56941
+ * the only alternative is inventing a confirmation depth (see the call site).
56942
+ * The single `try` exists solely to attach that name to a transport-level
56943
+ * rejection (DNS, TLS, connection reset, abort); it re-throws the cause
56944
+ * verbatim inside the message and never substitutes a value — authorized for
56945
+ * this case by the Batch 2 plan, §C2.
56946
+ *
56947
+ * @param signal - The caller's AbortSignal, so this read shares the same
56948
+ * timeout budget as the transaction fetch it serves.
56949
+ */
56950
+ async fetchTipHeight(signal) {
56951
+ const endpoint = `${this.config.providerUrl}/blocks/tip/height`;
56952
+ let tipResp;
56953
+ try {
56954
+ tipResp = await fetch(endpoint, {
56955
+ signal,
56956
+ headers: await this.withAuth()
56957
+ });
56958
+ } catch (error) {
56959
+ throw new BitcoinTipUnreadableError(
56960
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`
56961
+ );
56962
+ }
56963
+ if (!tipResp.ok) {
56964
+ throw new BitcoinTipUnreadableError(
56965
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`
56966
+ );
56967
+ }
56968
+ const tipBody = (await tipResp.text()).trim();
56969
+ const tipHeight = Number.parseInt(tipBody, 10);
56970
+ if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
56971
+ throw new BitcoinTipUnreadableError(
56972
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height "${tipBody.slice(0, 64)}"`
56973
+ );
56974
+ }
56975
+ return tipHeight;
56976
+ }
56318
56977
  /**
56319
56978
  * Get outputs (vouts) of a Bitcoin transaction
56320
56979
  *
@@ -56952,10 +57611,13 @@ ${auth.clientId}`;
56952
57611
  * only on unanimity. The confirmed-balance consensus the validators run
56953
57612
  * covers `chain_stats` only, so without this the primary provider alone
56954
57613
  * could fabricate an unconfirmed UTXO plus a self-consistent parent proof
56955
- * and inflate the signed balance. Any provider failure or verdict
56956
- * disagreement THROWS (fail-closed) — exclusion on a suppressed proof
56957
- * would deflate the balance and open a wrongful-liquidation window, so
56958
- * neither direction may proceed without agreement.
57614
+ * and inflate the signed balance. Any verdict disagreement THROWS
57615
+ * (fail-closed) — exclusion on a suppressed proof would deflate the balance
57616
+ * and open a wrongful-liquidation window, so neither direction may proceed
57617
+ * without agreement. A provider that cannot state the chain tip — and only
57618
+ * that failure — is dropped from the quorum rather than aborting the read (it
57619
+ * never counts as agreeing), and falling below `minConsensusProviders`
57620
+ * survivors throws — see `verifyParentIsSelfSpendConsensus`.
56959
57621
  *
56960
57622
  * The same per-provider `/tx` fetch also returns the parent's outputs, and
56961
57623
  * every provider must corroborate each claimed UTXO (index, vault address,
@@ -57050,10 +57712,26 @@ ${auth.clientId}`;
57050
57712
  }
57051
57713
  /**
57052
57714
  * Run the self-spend proof against every configured provider and require
57053
- * unanimity. Fail-closed: a provider request failure or a verdict
57054
- * disagreement throws and aborts the balance calculation — see
57715
+ * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:
57716
+ * a verdict mismatch throws and aborts the balance calculation — see
57055
57717
  * classifySelfChange for why exclusion is not a safe fallback here.
57056
57718
  *
57719
+ * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a
57720
+ * provider that could not state the chain tip (`BitcoinTipUnreadableError`).
57721
+ * It is ABSENT from the quorum — never counted as agreeing, never allowed to
57722
+ * decide the verdict — and the policy floor, not "at least one", decides when
57723
+ * that absence is fatal: below `minConsensusProviders` surviving readings
57724
+ * there is no cross-check left to trust, and the read fails loudly naming
57725
+ * every provider that dropped out.
57726
+ *
57727
+ * Why only that class. `getTransaction` now throws on an unreadable tip
57728
+ * instead of fabricating `confirmations: 1`; without this carve-out one flaky
57729
+ * `/blocks/tip/height` endpoint would take every balance and spend path down
57730
+ * with it. Every OTHER failure remains fatal, as before: a provider that
57731
+ * answers "I have never seen that transaction" is making a claim about the
57732
+ * chain rather than suffering an outage, and that shape is precisely the
57733
+ * fabricated-UTXO signature the fail-closed rule exists to catch.
57734
+ *
57057
57735
  * When the parent IS a unanimous self-spend, every provider's view of the
57058
57736
  * parent's OUTPUTS must additionally corroborate the primary's claimed
57059
57737
  * UTXOs (index exists, pays the vault, exact value). Without this, a
@@ -57078,32 +57756,52 @@ ${auth.clientId}`;
57078
57756
  )
57079
57757
  )
57080
57758
  );
57081
- const failures = settled.map((r, i) => ({ r, name: providerName(i) })).filter(
57082
- (x) => x.r.status === "rejected"
57083
- ).map(
57084
- ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`
57085
- );
57759
+ const answered = [];
57760
+ const absences = [];
57761
+ const failures = [];
57762
+ settled.forEach((result, i) => {
57763
+ if (result.status === "fulfilled") {
57764
+ answered.push({ index: i, evaluation: result.value });
57765
+ return;
57766
+ }
57767
+ const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;
57768
+ if (isBitcoinTipUnreadableError(result.reason)) {
57769
+ absences.push(described);
57770
+ return;
57771
+ }
57772
+ failures.push(described);
57773
+ });
57086
57774
  if (failures.length > 0) {
57087
57775
  throw new Error(
57088
57776
  `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join("; ")}`
57089
57777
  );
57090
57778
  }
57091
- const evaluations = settled.map(
57092
- (r) => r.value
57093
- );
57094
- const votes = evaluations.map((e) => e.selfSpend);
57095
- const disagreements = votes.map((vote, i) => ({ vote, name: providerName(i) })).filter((x) => x.vote !== votes[0]).map(
57096
- (x) => `${providerName(0)}=${votes[0]} vs ${x.name}=${x.vote}`
57779
+ const floor = Math.max(1, this.minConsensusProviders);
57780
+ if (answered.length < floor) {
57781
+ throw new Error(
57782
+ `Self-change classification for tx ${parentTxid}: only ${answered.length}/${providerConfigs.length} provider(s) could state a confirmation depth, below this chain's floor of ${floor}. Unreadable tips: ${absences.join("; ")}`
57783
+ );
57784
+ }
57785
+ if (absences.length > 0) {
57786
+ litDebugLog(
57787
+ `[VaultBalance] self-change: tx ${parentTxid} classified on a reduced quorum \u2014 ${answered.length}/${providerConfigs.length} provider(s) answered (floor ${floor}); dropped for an unreadable chain tip: ${absences.join("; ")}`
57788
+ );
57789
+ }
57790
+ const first = answered[0];
57791
+ const disagreements = answered.slice(1).filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend).map(
57792
+ (a) => `${providerName(first.index)}=${first.evaluation.selfSpend} vs ${providerName(a.index)}=${a.evaluation.selfSpend}`
57097
57793
  );
57098
57794
  if (disagreements.length > 0) {
57099
57795
  throw new Error(
57100
57796
  `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`
57101
57797
  );
57102
57798
  }
57103
- if (!votes[0]) {
57799
+ if (!first.evaluation.selfSpend) {
57104
57800
  return false;
57105
57801
  }
57106
- const outputMismatches = evaluations.map((e, i) => e.outputMismatch ? `${providerName(i)} \u2192 ${e.outputMismatch}` : null).filter((m) => m !== null);
57802
+ const outputMismatches = answered.map(
57803
+ (a) => a.evaluation.outputMismatch ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}` : null
57804
+ ).filter((m) => m !== null);
57107
57805
  if (outputMismatches.length > 0) {
57108
57806
  throw new Error(
57109
57807
  `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`
@@ -57346,16 +58044,6 @@ ${auth.clientId}`;
57346
58044
  minConfirmations
57347
58045
  );
57348
58046
  const authorizedSpends = await this.getAuthorizedSpendsFromContract(positionId);
57349
- for (const spend of authorizedSpends) {
57350
- const utxoStillExists = utxoSet.utxos.some(
57351
- (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout
57352
- );
57353
- if (utxoStillExists) {
57354
- throw new Error(
57355
- `Authorized UTXO ${spend.txid}:${spend.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`
57356
- );
57357
- }
57358
- }
57359
58047
  const authorizedBalance = authorizedSpends.reduce(
57360
58048
  (sum, spend) => sum + spend.satoshis,
57361
58049
  0n
@@ -57651,7 +58339,13 @@ ${auth.clientId}`;
57651
58339
  allowDevSinglePriceProvider: false,
57652
58340
  minBitcoinBalanceConfirmations: 1,
57653
58341
  minBitcoinSpendConfirmations: 1,
57654
- minConsensusProviders: 1
58342
+ // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider
58343
+ // "by design", so the consensus floor was documented as a mainnet-only
58344
+ // guarantee. The registry now holds two, and leaving the floor at 1 meant
58345
+ // Sepolia could never exercise the multi-provider agreement the stale-spend
58346
+ // and balance paths rely on — the one environment where that logic is
58347
+ // supposed to be proved before mainnet.
58348
+ minConsensusProviders: 2
57655
58349
  },
57656
58350
  [
57657
58351
  "ethereum"
@@ -57960,7 +58654,6 @@ function getSepoliaConfig() {
57960
58654
  feeRecipientRegistry: SEPOLIA_CONTRACTS.FeeRecipientRegistry || "",
57961
58655
  positionDelegateRegistry: SEPOLIA_CONTRACTS.PositionDelegateRegistry || "",
57962
58656
  bitcoinWithdrawalAddressRegistry: SEPOLIA_CONTRACTS.BitcoinWithdrawalAddressRegistry || "",
57963
- carryAgentRegistry: SEPOLIA_CONTRACTS.CarryAgentRegistry || "",
57964
58657
  agentDelegationRegistry: SEPOLIA_CONTRACTS.AgentDelegationRegistry || "",
57965
58658
  dhAgentDelegate: SEPOLIA_CONTRACTS.DHAgentDelegate || "",
57966
58659
  agentModuleFactory: SEPOLIA_CONTRACTS.AgentModuleFactory || ""
@@ -58014,7 +58707,6 @@ function getMainnetConfig() {
58014
58707
  feeRecipientRegistry: MAINNET_CONTRACTS.FeeRecipientRegistry || "",
58015
58708
  positionDelegateRegistry: MAINNET_CONTRACTS.PositionDelegateRegistry || "",
58016
58709
  bitcoinWithdrawalAddressRegistry: MAINNET_CONTRACTS.BitcoinWithdrawalAddressRegistry || "",
58017
- carryAgentRegistry: MAINNET_CONTRACTS.CarryAgentRegistry || "",
58018
58710
  agentDelegationRegistry: MAINNET_CONTRACTS.AgentDelegationRegistry || "",
58019
58711
  dhAgentDelegate: MAINNET_CONTRACTS.DHAgentDelegate || "",
58020
58712
  // Empty on mainnet until the factory is deployed there — the ceremony is Sepolia-only.
@@ -59087,6 +59779,51 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
59087
59779
  }
59088
59780
  return { timestamp: result.timestamp, signature: result.signature };
59089
59781
  }
59782
+ var BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
59783
+ function segwitProgramShape(address) {
59784
+ const lower2 = address.trim().toLowerCase();
59785
+ if (!/^(bc1|tb1|bcrt1)/.test(lower2))
59786
+ return null;
59787
+ const sep = lower2.lastIndexOf("1");
59788
+ const data = lower2.slice(sep + 1);
59789
+ if (data.length < 8)
59790
+ return null;
59791
+ const version2 = BECH32_CHARSET.indexOf(data[0]);
59792
+ if (version2 < 0)
59793
+ return null;
59794
+ const programChars = data.length - 1 - 6;
59795
+ return { version: version2, programBytes: Math.floor(programChars * 5 / 8) };
59796
+ }
59797
+ function dustLimitForAddress(address) {
59798
+ const shape = segwitProgramShape(address);
59799
+ if (shape === null)
59800
+ return 546;
59801
+ if (shape.version === 0 && shape.programBytes === 20)
59802
+ return 294;
59803
+ if (shape.version === 0 && shape.programBytes === 32)
59804
+ return 330;
59805
+ if (shape.version === 1 && shape.programBytes === 32)
59806
+ return 330;
59807
+ return 546;
59808
+ }
59809
+ function destinationDustShortfall(targetAmount, networkFee, destination) {
59810
+ const limit = dustLimitForAddress(destination);
59811
+ return targetAmount - networkFee < limit ? limit : null;
59812
+ }
59813
+ function calculateMintFee(params) {
59814
+ const { mintAmount, mintTimestamp, originationFeeBps, previousExpiryAt, selectedTerm, totalTerm } = params;
59815
+ let mintFee = mintAmount * BigInt(originationFeeBps) / 10000n;
59816
+ if (previousExpiryAt > 0 && mintTimestamp < previousExpiryAt) {
59817
+ const tailSeconds = BigInt(previousExpiryAt) - BigInt(mintTimestamp);
59818
+ const originalTermMonths = totalTerm - selectedTerm;
59819
+ const originalTermSeconds = BigInt(
59820
+ originalTermMonths === 12 ? 365 * 86400 : originalTermMonths * 30 * 86400
59821
+ );
59822
+ const tailFee = tailSeconds * BigInt(originationFeeBps) * mintAmount / (10000n * originalTermSeconds);
59823
+ mintFee = mintFee + tailFee;
59824
+ }
59825
+ return mintFee;
59826
+ }
59090
59827
  function baseMintFeeWei(mintAmountWei, originationFeeBps) {
59091
59828
  if (mintAmountWei < 0n)
59092
59829
  throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
@@ -59105,20 +59842,34 @@ function debtAfterMintExceedsLoanCap(params) {
59105
59842
  }
59106
59843
  return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
59107
59844
  }
59108
- function maxPrincipalWithinLoanCap(params) {
59109
- const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
59110
- if (maxLoanWei < 0n || currentDebtWei < 0n) {
59111
- throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
59845
+ function collateralRatioBps(sats, price8, debtWei) {
59846
+ if (sats < 0n || price8 < 0n) {
59847
+ throw new Error("collateralRatioBps: sats and price cannot be negative");
59112
59848
  }
59113
- if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
59114
- throw new Error(
59115
- `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
59116
- );
59849
+ if (debtWei <= 0n) {
59850
+ throw new Error("collateralRatioBps: debt must be positive");
59117
59851
  }
59118
- const room = maxLoanWei - currentDebtWei;
59119
- if (room <= 0n)
59120
- return 0n;
59121
- return room * 10000n / (10000n + BigInt(originationFeeBps));
59852
+ return sats * price8 * 100n * 10000n / debtWei;
59853
+ }
59854
+ function collateralRatioPercentString(sats, price8, debtWei) {
59855
+ const bps = collateralRatioBps(sats, price8, debtWei);
59856
+ return `${bps / 100n}.${(bps % 100n).toString().padStart(2, "0")}`;
59857
+ }
59858
+ function maxPrincipalForFee(room, fee) {
59859
+ if (room < 0n)
59860
+ throw new Error("maxPrincipalForFee: room cannot be negative");
59861
+ if (fee(0n) !== 0n)
59862
+ throw new Error("maxPrincipalForFee: fee(0) must be 0");
59863
+ let lo = 0n;
59864
+ let hi = room;
59865
+ while (lo < hi) {
59866
+ const mid = (lo + hi + 1n) / 2n;
59867
+ if (mid + fee(mid) <= room)
59868
+ lo = mid;
59869
+ else
59870
+ hi = mid - 1n;
59871
+ }
59872
+ return lo;
59122
59873
  }
59123
59874
  function buildLoginDomain(chainId) {
59124
59875
  return {
@@ -71281,9 +72032,17 @@ async function mintAgentPkp(params) {
71281
72032
  }
71282
72033
  var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
71283
72034
  function planAgentBinding(params) {
71284
- const { isActive, record, nowSeconds } = params;
72035
+ const { isActive, paused, record, nowSeconds } = params;
72036
+ if (typeof paused !== "boolean") {
72037
+ throw new Error("planAgentBinding: `paused` must be read from the registry (boolean required)");
72038
+ }
71285
72039
  if (isActive)
71286
72040
  return { kind: "reuse", agent: record.agent };
72041
+ if (paused) {
72042
+ throw new Error(
72043
+ "AgentDelegationRegistry is paused \u2014 agent delegation cannot be changed until it is unpaused."
72044
+ );
72045
+ }
71287
72046
  const status = Number(record.status);
71288
72047
  if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
71289
72048
  return { kind: "register" };
@@ -71293,7 +72052,7 @@ function planAgentBinding(params) {
71293
72052
  }
71294
72053
  if (Number(record.validUntil) > nowSeconds) {
71295
72054
  throw new Error(
71296
- "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
72055
+ "AgentDelegationRegistry returned an inconsistent read (an unexpired, unpaused Active agent reported inactive); retry."
71297
72056
  );
71298
72057
  }
71299
72058
  return { kind: "rotate" };
@@ -72462,7 +73221,7 @@ function normalizeBigNumberish(value) {
72462
73221
  }
72463
73222
  return value;
72464
73223
  }
72465
- if (typeof value === "object" && value !== null && "toString" in value && typeof value.toString === "function") {
73224
+ if (typeof value === "object" && value !== null && "toString" in value && typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
72466
73225
  const result = value.toString();
72467
73226
  if (typeof result === "object" && result !== null && "_hex" in result) {
72468
73227
  const resultObj = result;
@@ -73884,12 +74643,21 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
73884
74643
  maxLoanWei: maxLoanValueWei
73885
74644
  })) {
73886
74645
  const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
74646
+ const suggestionStamp = calculateNextQuantumTimestamp();
74647
+ const room = maxLoanValueWei > currentDebtWei ? maxLoanValueWei - currentDebtWei : 0n;
73887
74648
  const maxPrincipalUcd = Number(
73888
- maxPrincipalWithinLoanCap({
73889
- maxLoanWei: maxLoanValueWei,
73890
- currentDebtWei,
73891
- originationFeeBps: positionTerm.originationFeeBps
73892
- }) / BigInt(10 ** 18)
74649
+ maxPrincipalForFee(
74650
+ room,
74651
+ (principal) => calculateMintFee({
74652
+ mintAmount: principal,
74653
+ mintTimestamp: suggestionStamp,
74654
+ originationFeeBps: positionTerm.originationFeeBps,
74655
+ expiryAt: Number(position2.expiryAt),
74656
+ previousExpiryAt: Number(position2.previousExpiryAt),
74657
+ selectedTerm: Number(position2.selectedTerm),
74658
+ totalTerm: Number(position2.totalTerm)
74659
+ })
74660
+ ) / BigInt(10 ** 18)
73893
74661
  );
73894
74662
  return {
73895
74663
  success: false,
@@ -74967,11 +75735,7 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
74967
75735
  const debt = positionDetails.debt || positionDetails.ucdDebt || "0";
74968
75736
  const btcPrice2 = litActionResult.btcPrice || "0";
74969
75737
  const btcVaultBalance = litActionResult.btcAmountSats || positionDetails.btcVaultBalance || "0";
74970
- const usdPricePerBTC = Number(btcPrice2) / 1e8;
74971
- const btcAmount = Number(btcVaultBalance) / 1e8;
74972
- const btcValueUSD = btcAmount * usdPricePerBTC;
74973
- const debtUSD = Number(debt) / 1e18;
74974
- const ratio = debtUSD > 0 ? (btcValueUSD / debtUSD * 100).toFixed(2) : "0.00";
75738
+ const ratio = BigInt(debt) > 0n ? collateralRatioPercentString(BigInt(btcVaultBalance), BigInt(btcPrice2), BigInt(debt)) : "0.00";
74975
75739
  const message = formatLiquidationSkippedMessage(
74976
75740
  request.positionId,
74977
75741
  ratio,
@@ -75460,14 +76224,15 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
75460
76224
  }
75461
76225
  const debt = positionDetails.debt || positionDetails.ucdDebt || "0";
75462
76226
  const btcPrice2 = litActionResult.btcPrice || "0";
75463
- const ratio = debt !== "0" ? (Number(positionDetails.btcVaultBalance || "0") * Number(btcPrice2) / Number(debt) * 100 / 1e8).toFixed(2) : "0.00";
76227
+ const btcVaultBalance = litActionResult.btcAmountSats || positionDetails.btcVaultBalance || "0";
76228
+ const ratio = BigInt(debt) > 0n ? collateralRatioPercentString(BigInt(btcVaultBalance), BigInt(btcPrice2), BigInt(debt)) : "0.00";
75464
76229
  const message = formatLiquidationSuccessMessage(
75465
76230
  request.positionId,
75466
76231
  ratio,
75467
76232
  `${liquidationThreshold / 100}`,
75468
76233
  // Convert to percentage
75469
76234
  positionDetails.btcVault || "unknown",
75470
- positionDetails.btcVaultBalance || "0",
76235
+ btcVaultBalance,
75471
76236
  debt,
75472
76237
  btcPrice2
75473
76238
  );
@@ -77951,6 +78716,17 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
77951
78716
  error: `networkFee=${request.networkFee} is \u2265 50% of targetAmount=${request.targetAmount}. Refusing to broadcast \u2014 real Bitcoin fees are typically <1% of value.`
77952
78717
  };
77953
78718
  }
78719
+ const destinationDustLimit = destinationDustShortfall(
78720
+ request.targetAmount,
78721
+ request.networkFee,
78722
+ request.destination
78723
+ );
78724
+ if (destinationDustLimit !== null) {
78725
+ return {
78726
+ success: false,
78727
+ error: `Destination would receive ${request.targetAmount - request.networkFee} sats (targetAmount=${request.targetAmount} \u2212 networkFee=${request.networkFee}), below the ${destinationDustLimit}-sat dust limit for ${request.destination}; the transaction would not relay.`
78728
+ };
78729
+ }
77954
78730
  const [txid, voutStr] = request.utxoIdentifier.split(":");
77955
78731
  const vout = parseInt(voutStr || "0", 10);
77956
78732
  if (!txid || isNaN(vout)) {
@@ -79426,8 +80202,9 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
79426
80202
  const user = await signer.getAddress();
79427
80203
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
79428
80204
  let agentAddress;
79429
- const [isActive, record, latestBlock] = await Promise.all([
80205
+ const [isActive, paused, record, latestBlock] = await Promise.all([
79430
80206
  registry.isAgentActive(user),
80207
+ registry.paused(),
79431
80208
  registry.agentOf(user),
79432
80209
  this.getProviderOrThrow().getBlock("latest")
79433
80210
  ]);
@@ -79439,7 +80216,7 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
79439
80216
  /* HIGH */
79440
80217
  });
79441
80218
  }
79442
- const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
80219
+ const plan = planAgentBinding({ isActive, paused, record, nowSeconds: latestBlock.timestamp });
79443
80220
  if (plan.kind === "reuse") {
79444
80221
  agentAddress = plan.agent;
79445
80222
  } else {
@@ -82536,7 +83313,7 @@ var EoaDHSigner = class {
82536
83313
  };
82537
83314
 
82538
83315
  // src/signer/external-eoa.ts
82539
- var import_node_crypto7 = require("crypto");
83316
+ var import_node_crypto8 = require("crypto");
82540
83317
  var import_ethers49 = require("ethers");
82541
83318
 
82542
83319
  // src/boundary/upstream/shared/external-bridge/verify-landed-tx.ts
@@ -82630,7 +83407,7 @@ var ExternalEoaDHSigner = class {
82630
83407
  let used = { quantumTs: initialTs, fields: initial.fields };
82631
83408
  const outcome = await this.deps.bridge.requestSignature(
82632
83409
  {
82633
- id: (0, import_node_crypto7.randomUUID)(),
83410
+ id: (0, import_node_crypto8.randomUUID)(),
82634
83411
  kind: "personal-sign",
82635
83412
  action: spec.action,
82636
83413
  card: initial.card,
@@ -82664,7 +83441,7 @@ var ExternalEoaDHSigner = class {
82664
83441
  const approved = toApprovedTx(outerTx, this.deps.chainId);
82665
83442
  const gas = outerTx.gasLimit != null ? import_ethers49.ethers.toBeHex(BigInt(String(outerTx.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, ctx.action);
82666
83443
  const outcome = await this.deps.bridge.requestSignature({
82667
- id: (0, import_node_crypto7.randomUUID)(),
83444
+ id: (0, import_node_crypto8.randomUUID)(),
82668
83445
  kind: "transaction",
82669
83446
  action: ctx.action,
82670
83447
  card: ctx.card,
@@ -82718,7 +83495,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
82718
83495
  const expiresAtSec = nextQuantumTimestamp(nowMs);
82719
83496
  const secondsLeft = Math.max(0, expiresAtSec - Math.floor(nowMs / 1e3));
82720
83497
  const outcome = await this.deps.bridge.requestSignature({
82721
- id: (0, import_node_crypto7.randomUUID)(),
83498
+ id: (0, import_node_crypto8.randomUUID)(),
82722
83499
  kind: "personal-sign",
82723
83500
  action: "btc-withdrawal EXECUTE step (blind hash)",
82724
83501
  card: [
@@ -82757,7 +83534,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
82757
83534
  message: value
82758
83535
  };
82759
83536
  const outcome = await this.deps.bridge.requestSignature({
82760
- id: (0, import_node_crypto7.randomUUID)(),
83537
+ id: (0, import_node_crypto8.randomUUID)(),
82761
83538
  kind: "typed-data",
82762
83539
  action: "login",
82763
83540
  card: cardForTypedData("login", typedData),
@@ -82783,7 +83560,7 @@ var BridgeEthersSigner = class _BridgeEthersSigner extends import_ethers49.ether
82783
83560
  const card = cardForTx(approved);
82784
83561
  const gas = tx2.gasLimit != null ? import_ethers49.ethers.toBeHex(BigInt(String(tx2.gasLimit))) : await gasHintAcrossBlocks(this.deps.provider, this.deps.borrower, approved, describeFn(approved.data));
82785
83562
  const outcome = await this.deps.bridge.requestSignature({
82786
- id: (0, import_node_crypto7.randomUUID)(),
83563
+ id: (0, import_node_crypto8.randomUUID)(),
82787
83564
  kind: "transaction",
82788
83565
  action: describeFn(approved.data),
82789
83566
  card,
@@ -82904,11 +83681,16 @@ var RealUpstreamPlugin = class {
82904
83681
  this.src("subgraph")
82905
83682
  );
82906
83683
  },
82907
- getPositionEvents: async () => upFail({
82908
- kind: "unavailable",
82909
- source: "subgraph",
82910
- message: "event history is not mapped in this delivery of the real adapter (indexer projection pending)"
82911
- })
83684
+ getPositionEvents: async () => (
83685
+ // PERMANENT capability gap, not a transient outage: the real adapter has no indexer
83686
+ // projection for event history, and this build never will. `unsupported` →
83687
+ // NOT_IMPLEMENTED so the guide does not tell the model to retry it (C-44).
83688
+ upFail({
83689
+ kind: "unsupported",
83690
+ source: "subgraph",
83691
+ message: "event history is not implemented on the real adapter in this build (no indexer projection) \u2014 this is a permanent capability gap, not a transient outage; do not retry"
83692
+ })
83693
+ )
82912
83694
  };
82913
83695
  this.chain = {
82914
83696
  getPositionDetails: (id) => this.chainRead(() => this.readPositionDetails(id)),
@@ -83254,7 +84036,7 @@ var RealUpstreamPlugin = class {
83254
84036
  }
83255
84037
  if (mode === "external") {
83256
84038
  const borrower = await rt.manager.resolveBorrowerForWrite();
83257
- if (!borrower) {
84039
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: false })) {
83258
84040
  return {
83259
84041
  ok: false,
83260
84042
  failure: {
@@ -83304,6 +84086,20 @@ var RealUpstreamPlugin = class {
83304
84086
  }
83305
84087
  };
83306
84088
  }
84089
+ /** Hosted tier: the SIWE borrower is bound from boot, so "bound" no longer implies a
84090
+ * wallet can sign. Refuse as "no wallet is connected" instead of starting a ceremony
84091
+ * nobody can answer.
84092
+ *
84093
+ * `allowCachedLogin` is for `connectExternal` ONLY: a still-valid lit-ops login lets it
84094
+ * succeed without a wallet (it signs nothing). A WRITE always needs a fresh wallet
84095
+ * signature (ExternalEoaDHSigner), so a cached JWT must not admit it — that would queue
84096
+ * an approval with no wallet attached to sign it. */
84097
+ pinnedWalletUnreachable(borrower, opts) {
84098
+ if (!this.runtime?.manager.identityPinned()) return false;
84099
+ if (this.runtime.bridge.walletState() !== null) return false;
84100
+ if (!opts.allowCachedLogin) return true;
84101
+ return !this.sessionCache.get(`external:${borrower.toLowerCase()}`)?.hasValidToken();
84102
+ }
83307
84103
  /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
83308
84104
  * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
83309
84105
  * the first verified ceremony fixes the identity. */
@@ -83314,7 +84110,7 @@ var RealUpstreamPlugin = class {
83314
84110
  return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
83315
84111
  }
83316
84112
  const borrower = manager.borrowerForWrite();
83317
- if (!borrower) {
84113
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: true })) {
83318
84114
  return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
83319
84115
  }
83320
84116
  const key = `external:${borrower.toLowerCase()}`;
@@ -83850,7 +84646,8 @@ var RealUpstreamPlugin = class {
83850
84646
  // src/boundary/upstream/shared/external-bridge/bridge.ts
83851
84647
  var fs4 = __toESM(require("fs"));
83852
84648
  var http3 = __toESM(require("http"));
83853
- var import_node_crypto8 = require("crypto");
84649
+ var import_node_crypto9 = require("crypto");
84650
+ var import_ethers51 = require("ethers");
83854
84651
 
83855
84652
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
83856
84653
  function renderApprovalPage(sessionId, nonce) {
@@ -83860,46 +84657,47 @@ function renderApprovalPage(sessionId, nonce) {
83860
84657
  <meta charset="utf-8">
83861
84658
  <meta name="viewport" content="width=device-width, initial-scale=1">
83862
84659
  <title>Diamond Hands \u2014 signature approval</title>
84660
+ ${HOUSE_HEAD_LINKS}
83863
84661
  <style>
83864
- :root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --text:#e6edf3; --dim:#8b949e;
83865
- --accent:#58a6ff; --approve:#238636; --reject:#da3633; }
83866
- * { box-sizing:border-box; }
83867
- body { margin:0; font:15px/1.5 system-ui,sans-serif; background:var(--bg); color:var(--text);
83868
- display:flex; min-height:100vh; align-items:center; justify-content:center; }
83869
- main { width:min(560px,94vw); }
83870
- h1 { font-size:18px; font-weight:600; letter-spacing:.02em; }
83871
- h1 span { color:var(--accent); }
83872
- .panel { background:var(--panel); border:1px solid var(--line); border-radius:10px; padding:20px; margin-top:12px; }
83873
- .status { color:var(--dim); font-size:13px; }
83874
- .card { white-space:pre-wrap; font-family:ui-monospace,monospace; font-size:14px;
83875
- background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:14px; margin:14px 0; }
83876
- .action { text-transform:uppercase; letter-spacing:.08em; font-size:12px; color:var(--accent); }
83877
- button { border:0; border-radius:8px; padding:10px 22px; font-size:15px; color:#fff; cursor:pointer; }
83878
- #approve { background:var(--approve); margin-right:10px; }
83879
- #reject { background:var(--reject); }
83880
- #wallet { font-family:ui-monospace,monospace; font-size:12px; color:var(--dim); margin-top:10px; }
84662
+ ${HOUSE_BASE_CSS}
84663
+ /* \u2500\u2500 approval page only \u2500\u2500 */
84664
+ main { max-width: 36rem; }
84665
+ .status { color:#a1a1a1; font-size:0.875rem; }
84666
+ .action { text-transform:uppercase; letter-spacing:.08em; font-size:0.75rem; font-weight:600; color:#dbff91; margin-top:0.25rem; }
84667
+ /* The decoded card IS the operation (decode-equivalence): kept monospace and pre-wrapped
84668
+ exactly as the server rendered it, on an inset well darker than the panel. */
84669
+ .card { white-space:pre-wrap; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.875rem; color:#fafafa;
84670
+ background:#0a0a0a; border:1px solid rgba(255,255,255,0.1); border-radius:10px; padding:14px; margin:0.75rem 0 1rem; }
84671
+ .actions { display:flex; flex-wrap:wrap; gap:0.75rem; }
84672
+ #deadline { margin-bottom:1rem; }
84673
+ #wallet { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.75rem; color:#a1a1a1; margin-top:1rem; }
84674
+ #wallet:empty { display:none; }
84675
+ #wc { margin-top:1.25rem; border-top:1px solid rgba(255,255,255,0.06); padding-top:1rem; }
84676
+ #wc-uri { user-select:all; word-break:break-all; font-size:0.75rem; }
84677
+ #wc-hint { margin-top:0.75rem; }
83881
84678
  .hidden { display:none; }
83882
84679
  </style>
83883
84680
  </head>
83884
84681
  <body>
84682
+ ${houseHeader("Diamond Hands \xB7 signature approval")}
83885
84683
  <main>
83886
- <h1><span>\u25C6</span> Diamond Hands \u2014 signature approval</h1>
84684
+ <h1>Signature approval</h1>
83887
84685
  <div class="panel">
83888
84686
  <div id="status" class="status">Connecting to your wallet\u2026</div>
83889
84687
  <div id="request" class="hidden">
83890
84688
  <div id="action" class="action"></div>
83891
84689
  <div id="card" class="card"></div>
83892
84690
  <div id="deadline" class="status hidden"></div>
83893
- <button id="approve">Approve in wallet</button>
83894
- <button id="reject">Reject</button>
84691
+ <div class="actions">
84692
+ <button id="approve" class="btn-primary">Approve in wallet</button>
84693
+ <button id="reject" class="btn-danger">Reject</button>
84694
+ </div>
83895
84695
  </div>
83896
84696
  <div id="wallet"></div>
83897
- <div id="wc" style="margin-top:14px; border-top:1px solid var(--line); padding-top:12px;">
83898
- <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
83899
- Use a mobile wallet instead (WalletConnect)
83900
- </button>
83901
- <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
83902
- <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
84697
+ <div id="wc">
84698
+ <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
84699
+ <div id="wc-qr" class="qr-plate hidden"></div>
84700
+ <div id="wc-uri" class="card hidden"></div>
83903
84701
  <div id="wc-hint" class="status hidden">Scan the QR with your wallet app (or open the app \u2192 WalletConnect \u2192 paste the pairing code). Approvals then happen on your phone.</div>
83904
84702
  </div>
83905
84703
  </div>
@@ -83974,21 +84772,63 @@ async function healChain() {
83974
84772
  }).catch(() => undefined);
83975
84773
  }
83976
84774
  await readWallet();
83977
- await post(BASE + "hello", { account: account, chainId: chainId });
84775
+ await sayHello();
83978
84776
  showWallet();
83979
84777
  }
83980
84778
 
84779
+ function utf8Hex(text) {
84780
+ return "0x" + Array.from(new TextEncoder().encode(text)).map((b) => b.toString(16).padStart(2, "0")).join("");
84781
+ }
84782
+
84783
+ // Presence proof: the bridge only believes a wallet is at this page once the wallet has
84784
+ // SIGNED a short statement naming this page's origin, the chain and a per-page nonce. Saying
84785
+ // an address proves nothing (it is public); signing proves the key is here. One prompt per
84786
+ // page session: once this account has proven itself the bridge accepts later hellos for it
84787
+ // (a chain switch) without asking the wallet again.
84788
+ let provenFor = null;
84789
+ async function sayHello() {
84790
+ let signature;
84791
+ if (provenFor === null || provenFor.toLowerCase() !== String(account).toLowerCase()) {
84792
+ const ch = await fetch(BASE + "challenge?s=" + SESSION + "&chainId=" + chainId).then((r) => r.json());
84793
+ showIdleStatus("Sign the short statement in your wallet to prove it is yours \u2014 it moves no funds.");
84794
+ signature = await window.ethereum.request({ method: "personal_sign", params: [utf8Hex(ch.statement), account] });
84795
+ }
84796
+ const r = await post(BASE + "hello", { account: account, chainId: chainId, signature: signature });
84797
+ if (!r.ok) {
84798
+ const b = await r.json().catch(() => ({}));
84799
+ showStatus("This wallet was not accepted: " + (b.error || "HTTP " + r.status));
84800
+ return false;
84801
+ }
84802
+ provenFor = account;
84803
+ return true;
84804
+ }
84805
+
84806
+ // The stream opens at load, so a card can be on screen BEFORE connect() finishes. The status
84807
+ // line then belongs to that card (its review / mobile-wallet guidance), and connection
84808
+ // progress must not overwrite it. Connection progress lines (idle / "sign the statement", whose
84809
+ // wallet popup is self-explanatory) go through here; failures (a refused hello, a lost
84810
+ // stream, a wrong network) still show unconditionally.
84811
+ function showIdleStatus(text) {
84812
+ if (current !== null) return;
84813
+ showStatus(text);
84814
+ }
84815
+
83981
84816
  async function connect() {
83982
- if (!window.ethereum) { showStatus("No wallet detected \u2014 install MetaMask (or open this page in a wallet browser)."); return; }
84817
+ if (!window.ethereum) {
84818
+ // The event stream is already open (see the bottom of this script) \u2014 a phone paired
84819
+ // below still mirrors its cards here.
84820
+ showIdleStatus("No browser wallet detected \u2014 use the mobile wallet option below, or install MetaMask (or open this page in a wallet browser).");
84821
+ return;
84822
+ }
83983
84823
  await window.ethereum.request({ method: "eth_requestAccounts" });
83984
84824
  await readWallet();
83985
- await post(BASE + "hello", { account: account, chainId: chainId });
84825
+ const accepted = await sayHello();
83986
84826
  showWallet();
83987
84827
  window.ethereum.on("accountsChanged", onAccountsChanged);
83988
84828
  window.ethereum.on("chainChanged", onChainChanged);
84829
+ if (!accepted) return;
83989
84830
  await healChain();
83990
- showStatus("Connected. Waiting for a signature request\u2026");
83991
- listen();
84831
+ showIdleStatus("Connected. Waiting for a signature request\u2026");
83992
84832
  }
83993
84833
 
83994
84834
  // Handlers trust the EVENT payloads \u2014 re-reading eth_accounts/eth_chainId here races the
@@ -83998,6 +84838,8 @@ async function onAccountsChanged(accounts) {
83998
84838
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
83999
84839
  showWallet();
84000
84840
  invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
84841
+ // The bridge adopts no account from an event alone \u2014 a different account proves itself.
84842
+ if (account) await sayHello();
84001
84843
  }
84002
84844
 
84003
84845
  async function onChainChanged(cid) {
@@ -84007,8 +84849,14 @@ async function onChainChanged(cid) {
84007
84849
  invalidatePageRequests("Network changed \u2014 pending request invalidated.");
84008
84850
  }
84009
84851
 
84852
+ // ONE stream per page, opened at load whatever wallet this browser has: a phone paired
84853
+ // through WalletConnect needs no injected wallet, and its read-only mirror arrives on this
84854
+ // stream. Opening it proves nothing \u2014 the bridge sends this page NOTHING until a person is
84855
+ // proven (a signed hello, or a pairing a phone answered).
84856
+ let es = null;
84010
84857
  function listen() {
84011
- const es = new EventSource(BASE + "events?s=" + SESSION);
84858
+ if (es !== null) return;
84859
+ es = new EventSource(BASE + "events?s=" + SESSION);
84012
84860
  es.onmessage = (ev) => {
84013
84861
  const next = JSON.parse(ev.data);
84014
84862
  // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
@@ -84200,6 +85048,7 @@ document.getElementById("wc-connect").onclick = async () => {
84200
85048
  showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
84201
85049
  };
84202
85050
 
85051
+ listen();
84203
85052
  connect();
84204
85053
  </script>
84205
85054
  </body>
@@ -84280,6 +85129,16 @@ document.getElementById("generate").onclick = () => submit(true);
84280
85129
 
84281
85130
  // src/boundary/upstream/shared/external-bridge/bridge.ts
84282
85131
  var MAX_SESSIONS = 16;
85132
+ var MAX_PENDING_PAIRINGS = 64;
85133
+ function presenceStatement(origin2, chainId, nonce) {
85134
+ return [
85135
+ "Diamond Hands approval page",
85136
+ "Sign to prove this wallet is yours. This moves no funds and approves no operation.",
85137
+ `Origin: ${origin2}`,
85138
+ `Chain ID: ${chainId}`,
85139
+ `Session nonce: ${nonce}`
85140
+ ].join("\n");
85141
+ }
84283
85142
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
84284
85143
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
84285
85144
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -84293,6 +85152,7 @@ function wcDeclineOrFault(e) {
84293
85152
  }
84294
85153
  var SignatureBridge = class {
84295
85154
  clock;
85155
+ sweepIntervalMs;
84296
85156
  /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
84297
85157
  * differs between what SIWE signs and what a wallet reports for the SAME address. */
84298
85158
  boundAccount;
@@ -84305,7 +85165,7 @@ var SignatureBridge = class {
84305
85165
  /** Started state independent of the transport binding (mounted bridges own no server). */
84306
85166
  started = false;
84307
85167
  mount;
84308
- token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85168
+ token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84309
85169
  /** Hosted mounts: when the current page token was minted (rotation basis). */
84310
85170
  tokenMintedAt = 0;
84311
85171
  /** Ceremony-scoped link (plan 06 §1.5): the SAME URL is multi-visit and multi-owner —
@@ -84323,11 +85183,20 @@ var SignatureBridge = class {
84323
85183
  wcTransport = null;
84324
85184
  /** True while a WalletConnect session is THE wallet — ceremonies route over WC. */
84325
85185
  wcActive = false;
85186
+ /** Which page session asked for which pairing (pairing id → session id). The transport's
85187
+ * `onSession` says WHICH PAIRING a phone answered; this says whose it was. The previous
85188
+ * "most recent asker" guess let a second session claim the credit for a QR the user's
85189
+ * phone scanned (Sentinel 2 PoC-B). */
85190
+ pairingOwners = /* @__PURE__ */ new Map();
84326
85191
  keystoreUnlock;
84327
85192
  unlockToken = null;
84328
85193
  unlockSession = null;
84329
85194
  constructor(opts) {
84330
85195
  this.clock = opts?.clock ?? Date.now;
85196
+ this.sweepIntervalMs = opts?.sweepIntervalMs ?? 1e3;
85197
+ if (!Number.isInteger(this.sweepIntervalMs) || this.sweepIntervalMs < 0) {
85198
+ throw new Error(`bridge sweepIntervalMs must be a non-negative integer (got ${String(opts?.sweepIntervalMs)})`);
85199
+ }
84331
85200
  this.boundAccount = opts?.boundAccount?.toLowerCase();
84332
85201
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
84333
85202
  this.maxPending = opts?.maxPending ?? null;
@@ -84343,7 +85212,7 @@ var SignatureBridge = class {
84343
85212
  unlockUrl() {
84344
85213
  if (!this.started) throw new Error("bridge is not started");
84345
85214
  if (!this.keystoreUnlock) throw new Error("keystore unlock is not wired on this bridge");
84346
- this.unlockToken = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85215
+ this.unlockToken = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84347
85216
  return this.mount ? `${this.mount.baseUrl}/unlock?t=${this.unlockToken}` : `http://127.0.0.1:${this.port}/unlock?t=${this.unlockToken}`;
84348
85217
  }
84349
85218
  /** Idempotent — the bridge spawns on the first write that needs it (plan 04 §2).
@@ -84363,8 +85232,10 @@ var SignatureBridge = class {
84363
85232
  this.server = server;
84364
85233
  }
84365
85234
  this.started = true;
84366
- this.sweepTimer = setInterval(() => this.sweep(), 1e3);
84367
- this.sweepTimer.unref();
85235
+ if (this.sweepIntervalMs > 0) {
85236
+ this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);
85237
+ this.sweepTimer.unref();
85238
+ }
84368
85239
  if (this.urlFile) fs4.writeFileSync(this.urlFile, this.url());
84369
85240
  }
84370
85241
  /** Plan 12 C1: the outer server's dispatch entry for a MOUNTED bridge — `req.url`
@@ -84384,7 +85255,7 @@ var SignatureBridge = class {
84384
85255
  if (this.mount) {
84385
85256
  const now = this.clock();
84386
85257
  if (this.tokenMintedAt === 0 || now - this.tokenMintedAt > HOSTED_PAGE_TOKEN_TTL_MS) {
84387
- this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85258
+ this.token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84388
85259
  this.tokenMintedAt = now;
84389
85260
  }
84390
85261
  return `${this.mount.baseUrl}/?t=${this.token}`;
@@ -84424,6 +85295,16 @@ var SignatureBridge = class {
84424
85295
  pendingCount() {
84425
85296
  return this.pending.size;
84426
85297
  }
85298
+ /** A request lives for the bridge's expiry OR until its payload dies, whichever is first.
85299
+ * The BTC-withdraw execute leg's payload dies inside a sub-minute quantum window; holding
85300
+ * the ceremony open for the full five minutes kept a dead card on screen and let the phone
85301
+ * be asked to sign something the protocol would refuse. */
85302
+ deadlineFor(request, nowMs) {
85303
+ const bridgeDeadline = nowMs + this.expiryMs;
85304
+ if (request.expiresAtSec === void 0) return bridgeDeadline;
85305
+ if (!Number.isFinite(request.expiresAtSec)) throw new Error(`request ${request.id} carries a non-finite expiresAtSec`);
85306
+ return Math.min(bridgeDeadline, request.expiresAtSec * 1e3);
85307
+ }
84427
85308
  /**
84428
85309
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
84429
85310
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
@@ -84446,14 +85327,15 @@ var SignatureBridge = class {
84446
85327
  const now = this.clock();
84447
85328
  const entry = {
84448
85329
  request,
84449
- deadlineMs: now + this.expiryMs,
85330
+ deadlineMs: this.deadlineFor(request, now),
84450
85331
  enqueuedMs: now,
84451
85332
  resolve,
84452
85333
  settled: false,
84453
85334
  ...handlers?.finalize ? { finalize: handlers.finalize } : {},
84454
85335
  owner: this.wcActive ? "wc" : "page",
84455
85336
  dispatched: false,
84456
- lastAttachedMs: now
85337
+ lastAttachedMs: now,
85338
+ finalizedBy: null
84457
85339
  };
84458
85340
  this.pending.set(request.id, entry);
84459
85341
  if (entry.owner === "wc") {
@@ -84476,7 +85358,7 @@ var SignatureBridge = class {
84476
85358
  const now = this.clock();
84477
85359
  const entry = {
84478
85360
  request,
84479
- deadlineMs: now + this.expiryMs,
85361
+ deadlineMs: this.deadlineFor(request, now),
84480
85362
  enqueuedMs: now,
84481
85363
  resolve,
84482
85364
  settled: false,
@@ -84486,7 +85368,8 @@ var SignatureBridge = class {
84486
85368
  // ceremony could not reach quorum through the very pages it is broadcast to.
84487
85369
  owner: "both",
84488
85370
  dispatched: false,
84489
- lastAttachedMs: now
85371
+ lastAttachedMs: now,
85372
+ finalizedBy: null
84490
85373
  };
84491
85374
  this.pending.set(request.id, entry);
84492
85375
  this.pushEntry(entry);
@@ -84527,6 +85410,7 @@ var SignatureBridge = class {
84527
85410
  return;
84528
85411
  }
84529
85412
  try {
85413
+ if (this.expireIfOverdue(entry)) return;
84530
85414
  if (req.kind === "transaction") {
84531
85415
  this.pushEntry(entry);
84532
85416
  const tx2 = req.tx;
@@ -84538,15 +85422,23 @@ var SignatureBridge = class {
84538
85422
  } else if (req.kind === "personal-sign") {
84539
85423
  if (entry.finalize) {
84540
85424
  const fresh = await entry.finalize();
85425
+ if (entry.settled) return;
85426
+ if (entry.owner !== "wc") return;
85427
+ const live = transport.active();
85428
+ if (!this.wcActive || !live || live.account.toLowerCase() !== account.toLowerCase()) {
85429
+ this.settle(entry, {
85430
+ status: "invalidated",
85431
+ reason: "the WalletConnect wallet changed while this payload was being prepared \u2014 the phone was not asked. Reconnect your wallet and retry the operation."
85432
+ });
85433
+ return;
85434
+ }
84541
85435
  req.personalSign = fresh.personalSign;
84542
85436
  req.card = fresh.card;
84543
85437
  }
85438
+ if (this.expireIfOverdue(entry)) return;
84544
85439
  const ps = req.personalSign;
84545
- if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
84546
- this.settle(entry, {
84547
- status: "invalidated",
84548
- 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)`
84549
- });
85440
+ if (!this.pageAttached()) {
85441
+ this.settle(entry, { status: "invalidated", reason: this.noPageReason(ps.layout === RAW_HASH_LAYOUT) });
84550
85442
  return;
84551
85443
  }
84552
85444
  this.pushEntry(entry);
@@ -84571,6 +85463,16 @@ var SignatureBridge = class {
84571
85463
  }
84572
85464
  }
84573
85465
  }
85466
+ /** Refusal for a WalletConnect personal_sign with no proven approval page attached.
85467
+ *
85468
+ * The remedy names BOTH halves, because opening the link alone does not fix it: a freshly
85469
+ * opened page is a stranger until a phone answers a pairing it showed (or its wallet signs
85470
+ * the presence statement), so it receives no card. Following "just reopen the URL" looped
85471
+ * (Sentinel 2 PoC-C). */
85472
+ noPageReason(blindHash) {
85473
+ const what = blindHash ? "this step signs a 32-byte hash your wallet cannot decode" : "this step asks your wallet to sign a message your phone shows only as a hash";
85474
+ return `${what}, and no approval page linked to your wallet is open to show you what it authorizes \u2014 open ${this.url()} in a browser AND, on that page, re-scan the WalletConnect QR with your phone (or reconnect your wallet there) so the page is tied to your wallet, then retry with loan_withdraw_retry for a withdrawal or re-run the operation (it re-signs with a fresh stamp; your coins stay in the vault meanwhile)`;
85475
+ }
84574
85476
  /** A live attachment that could still decide a request: an open approval-page SSE
84575
85477
  * stream (real page or headless driver) or an active WalletConnect session. PUBLIC
84576
85478
  * (plan 17 E1): the connector's idle-eviction predicate reads it — a tenant world
@@ -84584,7 +85486,7 @@ var SignatureBridge = class {
84584
85486
  * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
84585
85487
  * WalletConnect and must stay global for the connector's eviction predicate. */
84586
85488
  pageAttached() {
84587
- for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
85489
+ for (const s of this.sessions.values()) if (s.sse && this.authorized(s)) return true;
84588
85490
  return false;
84589
85491
  }
84590
85492
  /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
@@ -84601,6 +85503,7 @@ var SignatureBridge = class {
84601
85503
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
84602
85504
  sweep() {
84603
85505
  const now = this.clock();
85506
+ this.evictDeadSessions();
84604
85507
  for (const entry of this.pending.values()) {
84605
85508
  if (entry.settled) continue;
84606
85509
  if (now >= entry.deadlineMs) {
@@ -84647,12 +85550,13 @@ var SignatureBridge = class {
84647
85550
  this.server = null;
84648
85551
  this.started = false;
84649
85552
  this.wallet = null;
84650
- this.token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85553
+ this.token = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84651
85554
  this.tokenMintedAt = 0;
84652
85555
  if (this.urlFile) fs4.rmSync(this.urlFile, { force: true });
84653
85556
  void this.wcTransport?.close().catch(() => void 0);
84654
85557
  this.wcTransport = null;
84655
85558
  this.wcActive = false;
85559
+ this.pairingOwners.clear();
84656
85560
  }
84657
85561
  // ---- HTTP plumbing ----
84658
85562
  route(req, res) {
@@ -84660,6 +85564,7 @@ var SignatureBridge = class {
84660
85564
  const url2 = new URL(req.url ?? "/", this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`);
84661
85565
  if (req.method === "GET" && url2.pathname === "/") return this.servePage(url2, res);
84662
85566
  if (req.method === "GET" && url2.pathname === "/config") return this.serveConfig(url2, res);
85567
+ if (req.method === "GET" && url2.pathname === "/challenge") return this.serveChallenge(url2, res);
84663
85568
  if (req.method === "GET" && url2.pathname === "/wc-pairing") return void this.serveWcPairing(url2, res);
84664
85569
  if (req.method === "GET" && url2.pathname === "/unlock") return this.serveUnlockPage(url2, res);
84665
85570
  if (req.method === "POST" && url2.pathname === "/unlock-submit")
@@ -84713,13 +85618,22 @@ var SignatureBridge = class {
84713
85618
  this.deny(res, 403, "this approval link has expired \u2014 ask for a fresh one (signer_setup status) and reopen");
84714
85619
  return;
84715
85620
  }
85621
+ this.makeRoomForSession();
84716
85622
  if (this.sessions.size >= MAX_SESSIONS) {
84717
85623
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
84718
85624
  return;
84719
85625
  }
84720
- const sessionId = (0, import_node_crypto8.randomBytes)(24).toString("hex");
84721
- this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
84722
- const page = htmlPageSecurityHeaders();
85626
+ const sessionId = (0, import_node_crypto9.randomBytes)(24).toString("hex");
85627
+ this.sessions.set(sessionId, {
85628
+ wallet: null,
85629
+ sse: null,
85630
+ refused: null,
85631
+ lastSeenMs: this.clock(),
85632
+ wcPaired: false,
85633
+ presenceNonce: (0, import_node_crypto9.randomBytes)(16).toString("hex"),
85634
+ provenAccount: null
85635
+ });
85636
+ const page = htmlPageSecurityHeaders(HOUSE_CSP_EXTRA);
84723
85637
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
84724
85638
  res.end(renderApprovalPage(sessionId, page.nonce));
84725
85639
  }
@@ -84729,10 +85643,29 @@ var SignatureBridge = class {
84729
85643
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
84730
85644
  res.end(JSON.stringify({ network: this.network ?? null }));
84731
85645
  }
85646
+ /** The origin this bridge is served from — what a presence statement names. */
85647
+ publicOrigin() {
85648
+ return this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`;
85649
+ }
85650
+ /** The presence statement for this session + chain (session-gated). The page signs exactly
85651
+ * this text in its wallet; the bridge rebuilds it on `hello` rather than trusting any text
85652
+ * the client sends back. */
85653
+ serveChallenge(url2, res) {
85654
+ const session = this.sessionOf(url2.searchParams.get("s"), res);
85655
+ if (!session) return;
85656
+ const chainId = Number(url2.searchParams.get("chainId"));
85657
+ if (!Number.isInteger(chainId)) {
85658
+ this.deny(res, 400, "challenge requires an integer chainId");
85659
+ return;
85660
+ }
85661
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
85662
+ res.end(JSON.stringify({ statement: presenceStatement(this.publicOrigin(), chainId, session.presenceNonce) }));
85663
+ }
84732
85664
  /** WalletConnect pairing (D2, session-gated): lazily boots the WC transport and serves a
84733
85665
  * fresh pairing URI. A wallet approving the pairing becomes THE wallet. */
84734
85666
  async serveWcPairing(url2, res) {
84735
85667
  if (!this.checkSession(url2.searchParams.get("s"), res)) return;
85668
+ const askingSession = url2.searchParams.get("s");
84736
85669
  if (!this.wcConfig) {
84737
85670
  this.deny(res, 404, "WalletConnect is not configured (set DH_WC_PROJECT_ID)");
84738
85671
  return;
@@ -84747,15 +85680,22 @@ var SignatureBridge = class {
84747
85680
  this.wcTransport.onSession((info) => {
84748
85681
  const refusal = info ? this.accountRefusal(info.account) : null;
84749
85682
  if (info && refusal) {
84750
- this.wcActive = false;
84751
- this.rebuildSharedWallet();
84752
- this.demoteWcEntries();
85683
+ if (!this.wcActive) {
85684
+ this.rebuildSharedWallet();
85685
+ this.demoteWcEntries();
85686
+ }
84753
85687
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
84754
85688
  `);
84755
- return;
85689
+ return false;
84756
85690
  }
84757
85691
  this.wcActive = info !== null;
84758
85692
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
85693
+ if (info?.pairingId) {
85694
+ const owner = this.pairingOwners.get(info.pairingId);
85695
+ this.pairingOwners.delete(info.pairingId);
85696
+ const paired = owner ? this.sessions.get(owner) : void 0;
85697
+ if (paired) paired.wcPaired = true;
85698
+ }
84759
85699
  if (info === null) {
84760
85700
  for (const entry of this.pending.values()) {
84761
85701
  if (!entry.settled && !entry.collect) {
@@ -84768,7 +85708,15 @@ var SignatureBridge = class {
84768
85708
  }
84769
85709
  });
84770
85710
  }
84771
- const { uri } = await this.wcTransport.createPairing();
85711
+ const { uri, pairingId } = await this.wcTransport.createPairing();
85712
+ if (pairingId) {
85713
+ this.pairingOwners.set(pairingId, askingSession);
85714
+ while (this.pairingOwners.size > MAX_PENDING_PAIRINGS) {
85715
+ const oldest = this.pairingOwners.keys().next();
85716
+ if (oldest.done) break;
85717
+ this.pairingOwners.delete(oldest.value);
85718
+ }
85719
+ }
84772
85720
  const { default: qrcode } = await import("qrcode-generator");
84773
85721
  const qr = qrcode(0, "M");
84774
85722
  qr.addData(uri);
@@ -84793,7 +85741,7 @@ var SignatureBridge = class {
84793
85741
  return;
84794
85742
  }
84795
85743
  this.unlockToken = null;
84796
- this.unlockSession = (0, import_node_crypto8.randomBytes)(24).toString("hex");
85744
+ this.unlockSession = (0, import_node_crypto9.randomBytes)(24).toString("hex");
84797
85745
  const page = htmlPageSecurityHeaders();
84798
85746
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
84799
85747
  res.end(renderUnlockPage(this.unlockSession, page.nonce));
@@ -84833,9 +85781,7 @@ var SignatureBridge = class {
84833
85781
  res.write(":connected\n\n");
84834
85782
  session.sse?.end();
84835
85783
  session.sse = res;
84836
- for (const entry of this.pending.values()) {
84837
- if (!entry.settled) res.write(this.wireFor(entry));
84838
- }
85784
+ this.replayPending(session);
84839
85785
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
84840
85786
  keepAlive.unref();
84841
85787
  res.on("close", () => {
@@ -84858,8 +85804,37 @@ var SignatureBridge = class {
84858
85804
  this.deny(res, 403, refusal);
84859
85805
  return;
84860
85806
  }
85807
+ const alreadyProven = session.provenAccount !== null && session.provenAccount.toLowerCase() === account.toLowerCase();
85808
+ if (!alreadyProven) {
85809
+ const signature = body["signature"];
85810
+ if (typeof signature !== "string" || signature === "") {
85811
+ this.deny(
85812
+ res,
85813
+ 403,
85814
+ `hello requires a signature proving this page controls ${account} \u2014 an address alone proves nothing. Approve the short signing prompt in your wallet (the approval page asks for it on connect); reload the page if it did not appear.`
85815
+ );
85816
+ return;
85817
+ }
85818
+ const statement = presenceStatement(this.publicOrigin(), chainId, session.presenceNonce);
85819
+ let recovered = null;
85820
+ try {
85821
+ recovered = import_ethers51.ethers.verifyMessage(statement, signature);
85822
+ } catch {
85823
+ recovered = null;
85824
+ }
85825
+ if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
85826
+ this.deny(
85827
+ res,
85828
+ 403,
85829
+ `the presence signature was not made by ${account} for this page's statement \u2014 sign the statement the approval page shows with that account (EOA wallets only; contract wallets cannot prove presence here).`
85830
+ );
85831
+ return;
85832
+ }
85833
+ session.provenAccount = account;
85834
+ }
84861
85835
  session.wallet = { account, chainId };
84862
85836
  this.wallet = { account, chainId };
85837
+ this.replayPending(session);
84863
85838
  this.ok(res);
84864
85839
  }
84865
85840
  /** C-47: the single predicate every wallet account is admitted through. There are THREE
@@ -84898,17 +85873,21 @@ var SignatureBridge = class {
84898
85873
  if (refusedSwitch) {
84899
85874
  this.quarantine(session, switchRefusal);
84900
85875
  } else {
84901
- session.wallet = offered;
85876
+ const sameProven = offered !== null && session.provenAccount !== null && offered.account.toLowerCase() === session.provenAccount.toLowerCase();
85877
+ session.wallet = sameProven ? offered : null;
84902
85878
  if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
84903
85879
  this.wallet = session.wallet;
85880
+ } else if (this.wallet === null && prev === null && session.wallet !== null) {
85881
+ this.wallet = session.wallet;
84904
85882
  }
84905
85883
  }
84906
- const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
84907
- if (unchanged) {
85884
+ const reported = refusedSwitch ? null : offered;
85885
+ const unchanged = prev !== null && reported !== null && prev.account.toLowerCase() === reported.account.toLowerCase() && prev.chainId === reported.chainId;
85886
+ if (unchanged || prev === null) {
84908
85887
  this.ok(res);
84909
85888
  return;
84910
85889
  }
84911
- 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";
85890
+ const reason = refusedSwitch ? "the wallet switched to an account this session is not signed in as" : prev && reported && prev.account.toLowerCase() !== reported.account.toLowerCase() ? "the wallet account changed while approval was pending" : prev && reported && prev.chainId !== reported.chainId ? "the wallet network changed while approval was pending" : "the wallet disconnected while approval was pending";
84912
85891
  for (const entry of this.pending.values()) {
84913
85892
  if (entry.settled || entry.collect) continue;
84914
85893
  if (this.ownedByWc(entry)) continue;
@@ -84943,12 +85922,18 @@ var SignatureBridge = class {
84943
85922
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
84944
85923
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
84945
85924
  async onFinalize(body, res) {
84946
- if (!this.sessionOf(body["sessionId"], res)) return;
85925
+ const sessionId = String(body["sessionId"] ?? "");
85926
+ const session = this.decidingSessionOf(body["sessionId"], res);
85927
+ if (!session) return;
84947
85928
  const entry = this.pending.get(String(body["requestId"] ?? ""));
84948
85929
  if (!entry || entry.settled) {
84949
85930
  this.deny(res, 404, "unknown or already-settled requestId");
84950
85931
  return;
84951
85932
  }
85933
+ if (this.expireIfOverdue(entry)) {
85934
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
85935
+ return;
85936
+ }
84952
85937
  if (entry.request.kind !== "personal-sign") {
84953
85938
  this.deny(res, 400, "finalize applies only to personal-sign requests");
84954
85939
  return;
@@ -84957,6 +85942,12 @@ var SignatureBridge = class {
84957
85942
  this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
84958
85943
  return;
84959
85944
  }
85945
+ const holder = entry.finalizedBy ? this.sessions.get(entry.finalizedBy) : void 0;
85946
+ if (entry.finalizedBy && entry.finalizedBy !== sessionId && holder?.sse) {
85947
+ this.deny(res, 409, "another approval page is signing this request \u2014 approve it there, or close that page and retry");
85948
+ return;
85949
+ }
85950
+ entry.finalizedBy = sessionId;
84960
85951
  if (entry.finalize) {
84961
85952
  let fresh;
84962
85953
  try {
@@ -84969,6 +85960,10 @@ var SignatureBridge = class {
84969
85960
  this.deny(res, 404, "request settled while finalizing");
84970
85961
  return;
84971
85962
  }
85963
+ if (this.expireIfOverdue(entry)) {
85964
+ this.deny(res, 410, "this request expired while its payload was being prepared \u2014 retry the operation");
85965
+ return;
85966
+ }
84972
85967
  entry.request.personalSign = fresh.personalSign;
84973
85968
  entry.request.card = fresh.card;
84974
85969
  }
@@ -84976,12 +85971,16 @@ var SignatureBridge = class {
84976
85971
  res.end(JSON.stringify({ request: entry.request }));
84977
85972
  }
84978
85973
  onResult(body, res) {
84979
- if (!this.sessionOf(body["sessionId"], res)) return;
85974
+ if (!this.decidingSessionOf(body["sessionId"], res)) return;
84980
85975
  const entry = this.pending.get(String(body["requestId"] ?? ""));
84981
85976
  if (!entry || entry.settled) {
84982
85977
  this.deny(res, 404, "unknown or already-settled requestId");
84983
85978
  return;
84984
85979
  }
85980
+ if (this.expireIfOverdue(entry)) {
85981
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
85982
+ return;
85983
+ }
84985
85984
  if (body["approved"] !== true) {
84986
85985
  if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
84987
85986
  this.settle(entry, {
@@ -85030,6 +86029,16 @@ var SignatureBridge = class {
85030
86029
  this.ok(res);
85031
86030
  }
85032
86031
  // ---- helpers ----
86032
+ /** Accept-time deadline check. The 1 s sweep is only the backstop: between the deadline and
86033
+ * the next tick a late click on /finalize or /result — or a WalletConnect dispatch — would
86034
+ * otherwise still ask for or accept a signature over a payload the protocol will refuse.
86035
+ * Settles the entry `expired` (the same outcome the sweep gives) and reports it. */
86036
+ expireIfOverdue(entry) {
86037
+ if (entry.settled) return true;
86038
+ if (this.clock() < entry.deadlineMs) return false;
86039
+ this.settle(entry, { status: "expired" });
86040
+ return true;
86041
+ }
85033
86042
  settle(entry, outcome) {
85034
86043
  entry.settled = true;
85035
86044
  this.pending.delete(entry.request.id);
@@ -85049,7 +86058,7 @@ var SignatureBridge = class {
85049
86058
  /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
85050
86059
  pushEntry(entry) {
85051
86060
  const data = this.wireFor(entry);
85052
- for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
86061
+ for (const s of this.sessions.values()) if (this.authorized(s)) s.sse?.write(data);
85053
86062
  }
85054
86063
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
85055
86064
  pushProgress(payload) {
@@ -85057,7 +86066,51 @@ var SignatureBridge = class {
85057
86066
  data: ${JSON.stringify(payload)}
85058
86067
 
85059
86068
  `;
85060
- for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
86069
+ for (const s of this.sessions.values()) if (this.authorized(s)) s.sse?.write(data);
86070
+ }
86071
+ /** Replay every undecided card to ONE session — used when a session becomes authorized
86072
+ * (hello) after its stream was already open, which is the ordinary page order: the page
86073
+ * attaches its EventSource, then the wallet prompt resolves. Without this the newly
86074
+ * connected page would sit blank until the next push. */
86075
+ replayPending(session) {
86076
+ if (!session.sse || !this.authorized(session)) return;
86077
+ for (const entry of this.pending.values()) {
86078
+ if (!entry.settled) session.sse.write(this.wireFor(entry));
86079
+ }
86080
+ }
86081
+ /** Retire quarantined sessions that hold no stream. Always safe: a refused session is
86082
+ * denied on every route anyway, so keeping it costs a slot and buys nothing. */
86083
+ evictDeadSessions() {
86084
+ for (const [id, s] of this.sessions) if (s.refused && !s.sse) this.sessions.delete(id);
86085
+ }
86086
+ /**
86087
+ * Free a slot for an incoming page load when the ceiling is reached.
86088
+ *
86089
+ * MAX_SESSIONS was a ceiling with NO eviction — nothing but `close()` ever removed a
86090
+ * session — and every page load mints one (a reload is a new session). A long-lived
86091
+ * hosted bridge therefore reached 16 through ordinary use and 429'd the user out of
86092
+ * approving their own ceremonies, permanently, with "close one and retry" as the advice
86093
+ * for pages that were already closed.
86094
+ *
86095
+ * Eviction is ON DEMAND and never touches a session with a live SSE stream: that stream
86096
+ * is a page open in a browser right now, and the C1 contract is that live sessions
86097
+ * survive. Among the streamless it takes the least recently seen — the closed tab.
86098
+ */
86099
+ makeRoomForSession() {
86100
+ this.evictDeadSessions();
86101
+ while (this.sessions.size >= MAX_SESSIONS) {
86102
+ let oldestId = null;
86103
+ let oldestSeen = Infinity;
86104
+ for (const [id, s] of this.sessions) {
86105
+ if (s.sse) continue;
86106
+ if (s.lastSeenMs < oldestSeen) {
86107
+ oldestSeen = s.lastSeenMs;
86108
+ oldestId = id;
86109
+ }
86110
+ }
86111
+ if (oldestId === null) return;
86112
+ this.sessions.delete(oldestId);
86113
+ }
85061
86114
  }
85062
86115
  /**
85063
86116
  * C-47: `this.wallet` is DERIVED, never guessed.
@@ -85100,12 +86153,46 @@ data: ${JSON.stringify(payload)}
85100
86153
  }
85101
86154
  this.rebuildSharedWallet();
85102
86155
  }
86156
+ /**
86157
+ * A session that may SEE cards and DECIDE them — one where a PERSON has proven to be at
86158
+ * the page: `hello` with an admissible account, or a WalletConnect pairing a wallet
86159
+ * actually answered (`wcPaired`).
86160
+ *
86161
+ * `sessionOf` only ever asked "does this session id exist and is it un-quarantined". A
86162
+ * session id is minted by LOADING the page, and on the hosted tier the mount URL travels
86163
+ * through the conversation by design — so anyone holding it could mint a session, never
86164
+ * connect a wallet, and still receive every approval card on /events (the card is the
86165
+ * operation in readable form: position, destination, amounts) and still POST /result to
86166
+ * decline, or /finalize to re-stamp, someone else's ceremony. Quarantine never caught
86167
+ * them: it fires on an OFFERED account, and they offered none.
86168
+ *
86169
+ * Opening the stream without a wallet stays legal — that is how the real page bootstraps
86170
+ * before the user connects. It simply receives nothing and decides nothing until it has
86171
+ * connected. Requesting a pairing is likewise not enough: anyone with the link can ask
86172
+ * for a QR, so only a pairing a WALLET ANSWERED counts.
86173
+ */
86174
+ authorized(session) {
86175
+ if (session.refused) return false;
86176
+ if (session.wallet) return this.accountRefusal(session.wallet.account) === null;
86177
+ return session.wcPaired;
86178
+ }
86179
+ /** `sessionOf`, plus the wallet binding above — for the routes that decide a ceremony. */
86180
+ decidingSessionOf(candidate, res) {
86181
+ const session = this.sessionOf(candidate, res);
86182
+ if (!session) return null;
86183
+ if (!this.authorized(session)) {
86184
+ this.deny(res, 403, "connect your wallet on this page before approving, declining or finalizing a request");
86185
+ return null;
86186
+ }
86187
+ return session;
86188
+ }
85103
86189
  sessionOf(candidate, res) {
85104
86190
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
85105
86191
  if (!session) {
85106
86192
  this.deny(res, 403, "missing or wrong session");
85107
86193
  return null;
85108
86194
  }
86195
+ session.lastSeenMs = this.clock();
85109
86196
  if (session.refused) {
85110
86197
  this.deny(res, 403, session.refused);
85111
86198
  return null;
@@ -85170,7 +86257,7 @@ function createBoundary(config, opts) {
85170
86257
  "createBoundary(real) is async \u2014 use createRealBoundary() so the write SDK can be built."
85171
86258
  );
85172
86259
  }
85173
- const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
86260
+ const configFingerprint = (0, import_node_crypto10.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, latency: config.latency, db: config.mockDb, signer: config.signer ?? "auto" })).digest("hex").slice(0, 12);
85174
86261
  if (opts?.ceremony) {
85175
86262
  const plugin2 = new MockUpstreamPlugin(config, { ceremony: opts.ceremony });
85176
86263
  const boundary2 = new BoundaryCore({
@@ -85333,6 +86420,7 @@ async function createRealBoundary(config, wallet, overrides) {
85333
86420
  const manager = new SignerManager({
85334
86421
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
85335
86422
  initialMode,
86423
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers52.ethers.getAddress(overrides.boundBorrower) } : {},
85336
86424
  candidate: () => bridge.walletState()?.account ?? null,
85337
86425
  pendingCeremonies: () => bridge.pendingCount(),
85338
86426
  keystore
@@ -85344,7 +86432,7 @@ async function createRealBoundary(config, wallet, overrides) {
85344
86432
  }
85345
86433
  const plugin = new RealUpstreamPlugin(config, wallet, { manager, bridge, keystore });
85346
86434
  await plugin.initWriteSdk();
85347
- const configFingerprint = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
86435
+ const configFingerprint = (0, import_node_crypto10.createHash)("sha256").update(JSON.stringify({ adapter: config.adapter, network: config.network, ops: config.serviceEndpoint })).digest("hex").slice(0, 12);
85348
86436
  const capabilities = () => ({
85349
86437
  reads: {
85350
86438
  public: true,
@@ -85428,8 +86516,8 @@ async function buildBoundary(configResult, overrides) {
85428
86516
  );
85429
86517
  }
85430
86518
  try {
85431
- const decrypted = await import_ethers51.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85432
- if (!(decrypted instanceof import_ethers51.ethers.Wallet)) {
86519
+ const decrypted = await import_ethers53.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
86520
+ if (!(decrypted instanceof import_ethers53.ethers.Wallet)) {
85433
86521
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
85434
86522
  }
85435
86523
  wallet = decrypted;
@@ -85798,8 +86886,13 @@ function authorizationModeBullets(d) {
85798
86886
  that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
85799
86887
  }
85800
86888
  if (offers(d, "keystore")) {
85801
- bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
85802
- Real adapter and mock.`);
86889
+ bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs AUTOMATICALLY, with no per-operation
86890
+ human prompt. Real adapter and mock. Say this plainly when the user picks it: the
86891
+ password is asked ONCE, at unlock; after that the key signs every write this session
86892
+ without a popup, an approval page or any second human step. The \`confirmed: true\` gate
86893
+ is the ASSISTANT's \u2014 it is not the user seeing and approving the operation \u2014 so in this
86894
+ mode you must show the operation and get a real answer before you set it. A user who
86895
+ wants to inspect each operation as it signs wants \`external\`.`);
85803
86896
  }
85804
86897
  if (offers(d, "safe") || offers(d, "safe-module")) {
85805
86898
  bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
@@ -85810,6 +86903,9 @@ function authorizationModeBullets(d) {
85810
86903
  }
85811
86904
  return bullets.join("\n");
85812
86905
  }
86906
+ function readsNeedSignIn(d) {
86907
+ return offers(d, "keystore") ? "On the real adapter a read is NOT a free pass: `position_list {borrower}`, `protocol_status` and `protocol_terms` need a signing identity \u2014 the keystore (the env pair or `unlock-keystore`) or a wallet `connect` \u2014 and refuse on a fresh session until one is connected. Only the practice (mock) world reads without one; there is no signer-less public read on the real adapter." : "On this hosted connector a read is NOT a free pass: even `position_list {borrower}`, `protocol_status` and `protocol_terms` run only AFTER the wallet sign-in that connecting performs (`signer_setup` action `connect`) \u2014 a fresh session refuses them until then. There is no separate keystore step and no signer-less public read here.";
86908
+ }
85813
86909
  function keystoreAbsenceParagraph(d) {
85814
86910
  if (offers(d, "keystore")) return "";
85815
86911
  return `
@@ -85853,9 +86949,11 @@ install matrix. ${connectorInstallNote(d)}
85853
86949
 
85854
86950
  Nothing needs a config file. Three steps:
85855
86951
 
85856
- **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
85857
- \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
85858
- signer modes exist; current terms (\`protocol_terms\`).
86952
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) \u2014 that
86953
+ resource always answers, with no sign-in \u2014 and tell the user what THIS deployment is:
86954
+ ${worldAxes(d)}; which signer modes exist. ${readsNeedSignIn(d)} So the live reads
86955
+ (\`protocol_status\`, current terms via \`protocol_terms\`) come right after step 2, not
86956
+ before it.
85859
86957
 
85860
86958
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
85861
86959
  - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
@@ -85875,8 +86973,9 @@ ${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (
85875
86973
  surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
85876
86974
  \`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
85877
86975
  - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
85878
- - **No signer is also a valid start:** every public read works without one \u2014
85879
- \`position_list {borrower}\` with the user's address needs no signer and no login.
86976
+ - **A read is not a signer-less shortcut:** the sign-in in step 2 is what turns reads ON.
86977
+ Until then \`position_list {borrower}\`, \`protocol_status\` and \`protocol_terms\` refuse
86978
+ on the real adapter \u2014 do step 2 first, then reads work.
85880
86979
  ${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
85881
86980
  talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
85882
86981
  the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
@@ -85898,7 +86997,7 @@ on the real adapter and the mock.
85898
86997
  **The walkthrough:**
85899
86998
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
85900
86999
  desktop browser; ${approvalPageLocation(d)}
85901
- 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THE APPROVAL PAGE OPEN: while a\n phone wallet is connected the page becomes the READ-ONLY reader for every ceremony \u2014\n it shows the full card, the phone shows only what a wallet can render, and you approve\n or decline in the phone. (Cancel still works from the page.)" : ". " + phoneWalletOffer(d) + "."}
87000
+ 2. On the page: connect the browser extension${d.walletConnect ? ", or \u2014 for a mobile wallet \u2014 scan the\n WalletConnect QR code or paste the pairing code. KEEP THAT APPROVAL PAGE OPEN \u2014 the one\n whose QR you scanned: while a phone wallet is connected it is the READ-ONLY reader for\n every ceremony \u2014 it shows the full card, the phone shows only what a wallet can render,\n and you approve or decline in the phone. (Cancel still works from the page.) With no\n such page open, the phone is NOT asked to sign the opaque 32-byte hashes (loan and withdrawal\n envelopes) \u2014 those refuse, because a wallet shows them as a bare hash. Plain transactions and\n typed-data are not gated: the wallet decodes those itself." : ". " + phoneWalletOffer(d) + "."}
85902
87001
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
85903
87002
  login ceremony explicitly (one typed-data signature in the wallet).
85904
87003
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -86286,7 +87385,9 @@ plus one lit-ops login signature (read access). After that, every operation that
86286
87385
  funds asks for its OWN approval in the user's wallet, every time \u2014 and reads never pop
86287
87386
  the wallet. The login session lives ONLY in the server's memory: a server restart, or
86288
87387
  an idle spell long enough that the tenant's world is evicted, means signing in again.
86289
- That is the flip side of "nothing stored at rest" \u2014 a re-login is normal, not a fault.
87388
+ That is the flip side of never storing a login session at rest \u2014 a re-login is normal,
87389
+ not a fault. (The connector's own sign-in is a separate grant; /auth.md states whether
87390
+ this deployment keeps it across restarts.)
86290
87391
 
86291
87392
  **What the hosted server IS trusted with** (the six residual trusts \u2014 state them
86292
87393
  honestly when asked "is this safe"):
@@ -86365,7 +87466,12 @@ ${wrongNetworkTroubleshootingRow(d)}
86365
87466
  owed, wrong position state, or the USER DECLINED in the wallet. The message says which.
86366
87467
  A decline is not an error to fix \u2014 it is the user's decision.
86367
87468
  - **UPSTREAM_UNAVAILABLE** \u2014 a data source or the signature bridge is unreachable/expired.
86368
- Usually transient; re-check with \`protocol_status\` and retry once.
87469
+ Usually transient; re-check with \`protocol_status\` and retry once. (A PERMANENT gap
87470
+ answers \`NOT_IMPLEMENTED\`, below \u2014 that one is not retryable.)
87471
+ - **NOT_IMPLEMENTED** \u2014 a capability this adapter does NOT implement in this build, and never
87472
+ will \u2014 PERMANENT, not a transient outage, so do NOT retry it. \`position_events\` on the
87473
+ real adapter is the case: there is no indexer projection for event history here. Say the
87474
+ history is unavailable on this deployment and move on; the practice (mock) world has it.
86369
87475
  - **NOT_FOUND** \u2014 the position id doesn't exist in this world (check \`position_list\`).
86370
87476
  - **STATE_DIVERGENCE / STALE_DATA warnings** \u2014 sources disagree or lag; the envelope says
86371
87477
  which source and when from. Prefer chain-sourced values; re-read before acting.
@@ -86550,7 +87656,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
86550
87656
 
86551
87657
  // src/tools/loan.ts
86552
87658
  var import_zod = require("zod");
86553
- var import_ethers52 = require("ethers");
87659
+ var import_ethers54 = require("ethers");
86554
87660
 
86555
87661
  // src/util/format.ts
86556
87662
  function bigintReplacer(_key, value) {
@@ -86599,7 +87705,7 @@ function requireConfirmation(confirmed, actionLabel) {
86599
87705
  type: "text",
86600
87706
  text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
86601
87707
  This is an irreversible, fund-moving action. A human must explicitly authorize it.
86602
- Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
87708
+ Show the user what this operation does \u2014 amounts, destination, and that it cannot be undone \u2014 and re-invoke with confirmed: true ONLY after they answer. Do not set confirmed on your own, and do not treat an earlier approval of a different operation as covering this one. If the signer is a keystore, no wallet prompt will follow: this is the only place a human is asked.`
86603
87709
  }
86604
87710
  ],
86605
87711
  isError: true
@@ -86738,7 +87844,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86738
87844
  const b = getB();
86739
87845
  if (!b.ok) return renderError(b.error);
86740
87846
  return renderEnvelope(
86741
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers52.parseEther)(amountUcd.toString()).toString() })
87847
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers54.parseEther)(amountUcd.toString()).toString() })
86742
87848
  );
86743
87849
  })
86744
87850
  );
@@ -86776,7 +87882,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86776
87882
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
86777
87883
  amountUcdWei = detail.data.debtUcdWei;
86778
87884
  } else {
86779
- amountUcdWei = (0, import_ethers52.parseEther)(amountUcd.toString()).toString();
87885
+ amountUcdWei = (0, import_ethers54.parseEther)(amountUcd.toString()).toString();
86780
87886
  }
86781
87887
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
86782
87888
  })
@@ -87036,7 +88142,7 @@ function registerPositionTools(server, getB) {
87036
88142
  "position_events",
87037
88143
  {
87038
88144
  title: "Get a position's event history",
87039
- description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
88145
+ description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view). NOT IMPLEMENTED on the real protocol adapter in this build \u2014 it answers NOT_IMPLEMENTED there (a PERMANENT gap, not a transient outage: do not retry). Available on the practice (mock) adapter.",
87040
88146
  inputSchema: {
87041
88147
  id: positionIdSchema2
87042
88148
  }
@@ -87379,7 +88485,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
87379
88485
 
87380
88486
  // src/tools/signer.ts
87381
88487
  var import_zod6 = require("zod");
87382
- var import_ethers53 = require("ethers");
88488
+ var import_ethers55 = require("ethers");
87383
88489
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
87384
88490
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
87385
88491
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -87421,7 +88527,7 @@ function registerSignerTool(server, getRuntime, opts) {
87421
88527
  if (mode !== void 0 && !offeredModes.includes(mode)) {
87422
88528
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
87423
88529
  }
87424
- if (safeAddress !== void 0 && !import_ethers53.ethers.isAddress(safeAddress)) {
88530
+ if (safeAddress !== void 0 && !import_ethers55.ethers.isAddress(safeAddress)) {
87425
88531
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
87426
88532
  }
87427
88533
  if (action === "status") {
@@ -87432,9 +88538,9 @@ function registerSignerTool(server, getRuntime, opts) {
87432
88538
  // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
87433
88539
  // identity is known. borrower = a persisted binding; candidate = a live
87434
88540
  // wallet connection in THIS process only.
87435
- identityProvenance: s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
88541
+ identityProvenance: manager.identityPinned() ? `borrower ${s.borrower} is the wallet that signed this connector's login \u2014 it is your borrowing identity for this session and cannot be swapped, and only this wallet can approve writes` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.borrower !== null ? `borrower ${s.borrower} is a PERSISTED binding (survives restarts until 'disconnect' or 'reset-borrower')` + (s.candidate !== null ? `; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only)` : "") : s.candidate !== null ? `no borrower is bound; candidate ${s.candidate} is a LIVE wallet connection (approval page / WalletConnect, this process only) \u2014 the first verified signature binds it` : "no borrower is bound and no wallet is connected",
87436
88542
  approvalPageUrl: bridge.url(),
87437
- hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
88543
+ hint: s.mode === "none" ? manager.invitation() + (s.keystoreConfigured ? " Note: keystore material IS already configured \u2014 choosing 'keystore' (or 'safe') unlocks it automatically; the unlock page is only for NEW material." : "") : s.mode === "external" && !s.borrower && !s.candidate ? "External mode: open the approval page URL above and connect your wallet \u2014 it becomes your borrowing identity." : s.mode === "external" && manager.identityPinned() && !s.candidate ? `Signed in as ${s.borrower}. Chain reads work now (position_status by id, protocol_status, btc_price). Listing positions (position_list borrower=${s.borrower}) goes through the authenticated indexer proxy and needs a lit-ops login: open the approval page URL above, connect THIS wallet (any other is refused), then run signer_setup 'connect' \u2014 one login signature that moves nothing. The same connected wallet approves writes.` : !s.keystoreUnlocked && s.keystoreConfigured ? `Active mode: ${s.mode}. Keystore material is configured \u2014 'use keystore' unlocks it automatically; the unlock page is only for NEW material.` : `Active mode: ${s.mode}. Writes still require confirmed:true, always.`
87438
88544
  });
87439
88545
  }
87440
88546
  if (action === "use") {
@@ -87511,6 +88617,11 @@ function registerSignerTool(server, getRuntime, opts) {
87511
88617
  });
87512
88618
  }
87513
88619
  if (action === "reset-borrower") {
88620
+ if (manager.identityPinned()) {
88621
+ return validationFailed(
88622
+ `the borrowing identity is ${manager.boundBorrower()} \u2014 the wallet that signed this connector's login \u2014 and cannot be swapped here. To act as a different wallet, sign in to the connector again with that wallet.`
88623
+ );
88624
+ }
87514
88625
  manager.resetBorrower();
87515
88626
  return ok({
87516
88627
  reset: true,
@@ -87582,7 +88693,7 @@ function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
87582
88693
  role: "user",
87583
88694
  content: {
87584
88695
  type: "text",
87585
- text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, keep me on the read-only path (position_list with my address needs no signer) and say the true reason; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
88696
+ text: "I'm new to Diamond Hands. FIRST read boundary://info and its capabilities block \u2014 it is the truth about this session: the network, practice vs real money, whether writes are enabled (and the true reason when not), and which signer modes exist here. Never promise anything it does not list. Then read the guide topics 'getting-started' and 'first-setup' (guide tool), check protocol_status, and walk me through setup step by step IN MY LANGUAGE: tell me plainly whether this is practice or real money. BRANCH on capabilities: if no signer mode is available or writes are disabled, say the true reason \u2014 and note that on the real adapter even a read (position_list, protocol_status, protocol_terms) needs the wallet sign-in that connecting performs first; there is no signer-less read path, so guide me to sign in before expecting any read to return; " + onboardAuthorizationLine(deployment) + "Ask before every operation; never assume confirmation."
87586
88697
  }
87587
88698
  }
87588
88699
  ]
@@ -87770,7 +88881,7 @@ function registerProtocolResources(server, getB) {
87770
88881
  "protocol://psm",
87771
88882
  {
87772
88883
  title: "PSM status (UCD \u2194 USDC exchange)",
87773
- description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = real USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
88884
+ description: "Live SimplePSMV2 state as {data, warnings, source}. `data` carries network + chainId + psmAddress (the money surface names its chain) and `stablecoins`: EVERY coin this PSM supports, each with its own stablecoinKind (mock = practice token with a public self-serve mint; circle = canonical mainnet USDC, i.e. real Circle USDC; onchain = any OTHER real coin such as mainnet USDT \u2014 real and on-chain, but NOT Circle USDC), pause + redeemEnabled switches, live reserves, and per-direction fees (WITH their token), min/max (WITH their units \u2014 to-ucd caps in the stablecoin's smallest units, from-ucd caps in UCD wei) and per-block volume caps ('uncapped' when the on-chain cap is 0). This is where a caller learns the coin names that `psm_quote` and `psm_swap` require.",
87774
88885
  mimeType: "application/json"
87775
88886
  },
87776
88887
  async (uri) => {
@@ -87906,8 +89017,16 @@ function requireSafeCount(value, fallback, name, min) {
87906
89017
  return value;
87907
89018
  }
87908
89019
  var RATE_WINDOW_MS = 60 * 1e3;
89020
+ function assertWcLegComposable(opts) {
89021
+ assertWcMinSafeVersion(
89022
+ opts.serverVersion ?? SERVER_VERSION,
89023
+ opts.siweWc !== void 0 || resolvedWcProjectId(opts.env) !== void 0
89024
+ );
89025
+ resolveWcLimits(opts.siweWcLimits);
89026
+ }
87909
89027
  function composeConnector(opts, rawPublicOrigin) {
87910
89028
  const publicOrigin = normalizePublicOrigin(rawPublicOrigin);
89029
+ assertWcLegComposable(opts);
87911
89030
  const allowedNetworks = opts.allowedNetworks ?? ["sepolia"];
87912
89031
  if (allowedNetworks.length === 0) throw new Error("connector service: allowedNetworks must name at least one network");
87913
89032
  const launchNetwork = allowedNetworks[0];
@@ -87949,7 +89068,7 @@ function composeConnector(opts, rawPublicOrigin) {
87949
89068
  }
87950
89069
  async function buildWorld(tenantKey) {
87951
89070
  const stores = /* @__PURE__ */ new Map();
87952
- const mountId = (0, import_node_crypto10.randomUUID)().replaceAll("-", "");
89071
+ const mountId = (0, import_node_crypto11.randomUUID)().replaceAll("-", "");
87953
89072
  const overrides = {
87954
89073
  externalOnly: true,
87955
89074
  allowedNetworks,
@@ -88228,7 +89347,7 @@ function composeConnector(opts, rawPublicOrigin) {
88228
89347
  }
88229
89348
  const mcp = createServer2(world.deps, CONNECTOR_INSTRUCTIONS);
88230
89349
  const transport = new import_streamableHttp.StreamableHTTPServerTransport({
88231
- sessionIdGenerator: () => (0, import_node_crypto10.randomUUID)(),
89350
+ sessionIdGenerator: () => (0, import_node_crypto11.randomUUID)(),
88232
89351
  onsessioninitialized: (sessionId) => {
88233
89352
  evictExcessSessions(tenantKey);
88234
89353
  sessions.set(sessionId, { transport, tenant: tenantKey, lastSeen: clock() });
@@ -88254,6 +89373,10 @@ function composeConnector(opts, rawPublicOrigin) {
88254
89373
  }
88255
89374
  const app = (0, import_express.default)();
88256
89375
  app.set("trust proxy", trustProxyHops);
89376
+ app.use((_req, res, next) => {
89377
+ res.setHeader(STRICT_TRANSPORT_SECURITY.name, STRICT_TRANSPORT_SECURITY.value);
89378
+ next();
89379
+ });
88257
89380
  app.use((_req, res, next) => {
88258
89381
  if (!allowGlobal()) {
88259
89382
  deny(res, 429, `rate limit: this connector exceeded ${globalPerMin} requests/minute across all clients \u2014 a shared-capacity protection; wait for the minute window to pass and retry`);
@@ -88261,6 +89384,31 @@ function composeConnector(opts, rawPublicOrigin) {
88261
89384
  }
88262
89385
  next();
88263
89386
  });
89387
+ const expectedHost = opts.publicOrigin ? new URL(publicOrigin).host.toLowerCase() : null;
89388
+ app.use((req, res, next) => {
89389
+ if (expectedHost === null) {
89390
+ next();
89391
+ return;
89392
+ }
89393
+ const p = (req.originalUrl ?? req.url).split("?")[0].toLowerCase();
89394
+ const sensitive = ["/mcp", "/token", "/register", "/revoke", "/authorize", "/account"].some(
89395
+ (r) => p === r || p.startsWith(`${r}/`)
89396
+ );
89397
+ if (!sensitive) {
89398
+ next();
89399
+ return;
89400
+ }
89401
+ const host = (req.headers.host ?? "").toLowerCase();
89402
+ if (host !== expectedHost) {
89403
+ deny(
89404
+ res,
89405
+ 421,
89406
+ `misdirected request: this connector serves ${expectedHost} \u2014 the request arrived on Host '${req.headers.host ?? "(none)"}'. Use the canonical origin advertised in the discovery documents.`
89407
+ );
89408
+ return;
89409
+ }
89410
+ next();
89411
+ });
88264
89412
  app.use((req, res, next) => {
88265
89413
  const path5 = (req.originalUrl ?? req.url).split("?")[0];
88266
89414
  if (path5 === "/mcp" || path5.startsWith("/approval/")) {
@@ -88279,9 +89427,12 @@ function composeConnector(opts, rawPublicOrigin) {
88279
89427
  origin: () => publicOrigin,
88280
89428
  chainId: launchNetwork === "mainnet" ? 1 : 11155111,
88281
89429
  ...wcLeg ? { wc: wcLeg } : {},
89430
+ ...opts.siweWcLimits ? { wcLimits: opts.siweWcLimits } : {},
89431
+ ...opts.oauthStore ? { store: opts.oauthStore } : {},
88282
89432
  ...opts.clock ? { clock: opts.clock } : {}
88283
89433
  });
88284
89434
  siweRef = siwe;
89435
+ mountAccountApi(app, siwe, opts.account);
88285
89436
  app.post("/authorize/siwe-message", import_express.default.json(), (req, res) => {
88286
89437
  const b = req.body;
88287
89438
  const r = siwe.siweMessage(String(b.flowId ?? ""), String(b.address ?? ""));
@@ -88302,7 +89453,12 @@ function composeConnector(opts, rawPublicOrigin) {
88302
89453
  });
88303
89454
  app.post("/authorize/wc-pairing", import_express.default.json(), (req, res) => {
88304
89455
  const b = req.body;
88305
- void siwe.wcPairing(String(b.flowId ?? "")).then((r) => {
89456
+ const ip = req.ip;
89457
+ if (ip === void 0) {
89458
+ res.status(400).json({ reason: "cannot determine the requesting network address - mobile wallet sign-in refused" });
89459
+ return;
89460
+ }
89461
+ void siwe.wcPairing(String(b.flowId ?? ""), ip).then((r) => {
88306
89462
  if (!r.ok) res.status(r.status).json({ reason: r.reason });
88307
89463
  else res.json({ uri: r.uri, qrSvg: r.qrSvg });
88308
89464
  }).catch((e) => {
@@ -88316,7 +89472,8 @@ function composeConnector(opts, rawPublicOrigin) {
88316
89472
  const authMd = renderAuthMd({
88317
89473
  publicOrigin,
88318
89474
  networks: allowedNetworks,
88319
- walletConnectEnabled: wcLeg !== void 0
89475
+ walletConnectEnabled: wcLeg !== void 0,
89476
+ grants: { durable: opts.oauthStore !== void 0, accountApi: opts.account !== void 0 }
88320
89477
  });
88321
89478
  app.get("/auth.md", (_req, res) => {
88322
89479
  res.setHeader("X-Content-Type-Options", "nosniff");
@@ -88346,10 +89503,10 @@ function composeConnector(opts, rawPublicOrigin) {
88346
89503
  })
88347
89504
  );
88348
89505
  authImpl = {
88349
- tenant(req) {
89506
+ async tenant(req) {
88350
89507
  const header = req.headers.authorization;
88351
89508
  if (typeof header !== "string" || !header.startsWith("Bearer ")) return null;
88352
- const info = siwe.lookupAccessToken(header.slice("Bearer ".length));
89509
+ const info = await siwe.lookupAccessToken(header.slice("Bearer ".length));
88353
89510
  const address = info?.extra?.["address"];
88354
89511
  return typeof address === "string" ? { address } : null;
88355
89512
  }
@@ -88390,6 +89547,64 @@ function composeConnector(opts, rawPublicOrigin) {
88390
89547
  }
88391
89548
  };
88392
89549
  }
89550
+ function mountAccountApi(app, siwe, account) {
89551
+ const allowed = new Set(account?.appOrigins ?? []);
89552
+ app.use("/account", (req, res, next) => {
89553
+ const origin2 = req.headers.origin;
89554
+ if (typeof origin2 === "string" && allowed.has(origin2)) {
89555
+ res.setHeader("Access-Control-Allow-Origin", origin2);
89556
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
89557
+ res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
89558
+ res.setHeader("Access-Control-Max-Age", "600");
89559
+ }
89560
+ res.setHeader("Vary", "Origin");
89561
+ res.setHeader("Cache-Control", "no-store");
89562
+ if (req.method === "OPTIONS") {
89563
+ res.status(204).end();
89564
+ return;
89565
+ }
89566
+ next();
89567
+ });
89568
+ const fail = (res, status, error, reason) => {
89569
+ res.status(status).json({ error, reason });
89570
+ };
89571
+ const identify = async (req, res) => {
89572
+ if (!account) {
89573
+ fail(res, 501, "not_configured", "the account API is not configured on this deployment (no app identity verifier)");
89574
+ return null;
89575
+ }
89576
+ const header = req.headers.authorization;
89577
+ if (typeof header !== "string" || !header.startsWith("Bearer ") || header.length === "Bearer ".length) {
89578
+ fail(res, 401, "unauthorized", "missing app session \u2014 send the app's Firebase ID token as 'Authorization: Bearer <token>'");
89579
+ return null;
89580
+ }
89581
+ const who = await account.verifier.verify(header.slice("Bearer ".length));
89582
+ if (!who.ok) {
89583
+ fail(res, 401, "unauthorized", who.reason);
89584
+ return null;
89585
+ }
89586
+ return who.address;
89587
+ };
89588
+ app.get("/account/grants", (req, res) => {
89589
+ void (async () => {
89590
+ const address = await identify(req, res);
89591
+ if (address === null) return;
89592
+ res.json({ address, grants: await siwe.listGrants(address) });
89593
+ })().catch((e) => fail(res, 503, "store_error", `the connection store failed: ${e instanceof Error ? e.message : String(e)}`));
89594
+ });
89595
+ app.post("/account/grants/:id/revoke", (req, res) => {
89596
+ void (async () => {
89597
+ const address = await identify(req, res);
89598
+ if (address === null) return;
89599
+ const id = String(req.params["id"]);
89600
+ if (!await siwe.revokeGrantForAddress(address, id)) {
89601
+ fail(res, 404, "not_found", `no live connection '${id}' belongs to ${address}`);
89602
+ return;
89603
+ }
89604
+ res.json({ revoked: true, id });
89605
+ })().catch((e) => fail(res, 503, "store_error", `the connection store failed: ${e instanceof Error ? e.message : String(e)}`));
89606
+ });
89607
+ }
88393
89608
  var CONNECTOR_PATH_PREFIXES = [
88394
89609
  "/mcp",
88395
89610
  "/approval/",