@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.
package/dist/index.js CHANGED
@@ -13422,6 +13422,12 @@ var require_follow_redirects = __commonJS({
13422
13422
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
13423
13423
  if (!options.headers) {
13424
13424
  options.headers = {};
13425
+ } else if (Array.isArray(options.headers)) {
13426
+ var headerList = options.headers;
13427
+ options.headers = {};
13428
+ for (var i = 0; i < headerList.length; i += 2) {
13429
+ options.headers[headerList[i]] = headerList[i + 1];
13430
+ }
13425
13431
  }
13426
13432
  if (!isArray2(options.sensitiveHeaders)) {
13427
13433
  options.sensitiveHeaders = [];
@@ -13696,7 +13702,7 @@ var require_follow_redirects = __commonJS({
13696
13702
  return URL3 && value instanceof URL3;
13697
13703
  }
13698
13704
  function escapeRegex(regex) {
13699
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
13705
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
13700
13706
  }
13701
13707
  module2.exports = wrap({ http: http4, https: https2 });
13702
13708
  module2.exports.wrap = wrap;
@@ -14450,113 +14456,113 @@ var require_pkg_src = __commonJS({
14450
14456
  deployedAt: 1784569687492,
14451
14457
  size: 4140,
14452
14458
  hash: "4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b",
14453
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
14459
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
14454
14460
  pkp: {
14455
14461
  publicKey: "0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f",
14456
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14462
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14457
14463
  }
14458
14464
  },
14459
14465
  btcTransactionSigner: {
14460
- cid: "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf",
14466
+ cid: "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U",
14461
14467
  authorizedCidHex: cidToHex(
14462
- "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf"
14468
+ "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U"
14463
14469
  ),
14464
14470
  name: "Btc Transaction Signer",
14465
14471
  description: "Production Btc Transaction Signer",
14466
14472
  version: "1.1.1",
14467
14473
  deployed: true,
14468
- deployedAt: 1787923905597,
14469
- size: 70646,
14470
- hash: "37c3bb72a660c8275d92e1b73f9482742d86b64789480b9246304c0ca1bab47a"
14474
+ deployedAt: 1790246185256,
14475
+ size: 73313,
14476
+ hash: "d8b6bc646ba33fee7d46c8e9b281de776081ea6f182f56fd15d4c52aaf3dd030"
14471
14477
  },
14472
14478
  ucdMintValidator: {
14473
- cid: "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc",
14479
+ cid: "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe",
14474
14480
  authorizedCidHex: cidToHex(
14475
- "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc"
14481
+ "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe"
14476
14482
  ),
14477
14483
  name: "Ucd Mint Validator",
14478
14484
  description: "Production Ucd Mint Validator",
14479
- version: "1.2.1",
14485
+ version: "1.3.0",
14480
14486
  deployed: true,
14481
- deployedAt: 1787923919527,
14482
- size: 86197,
14483
- hash: "c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf",
14484
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14487
+ deployedAt: 1790246219868,
14488
+ size: 90022,
14489
+ hash: "65e8cb778c2b767ae6eb37cb5db7b4c5a3f2468d508463c847c83c1b6825fadd",
14490
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14485
14491
  pkp: {
14486
14492
  publicKey: "0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb",
14487
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14493
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14488
14494
  }
14489
14495
  },
14490
14496
  processPaymentValidator: {
14491
- cid: "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF",
14497
+ cid: "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8",
14492
14498
  authorizedCidHex: cidToHex(
14493
- "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF"
14499
+ "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8"
14494
14500
  ),
14495
14501
  name: "Process Payment Validator",
14496
14502
  description: "Production Process Payment Validator",
14497
14503
  version: "1.2.1",
14498
14504
  deployed: true,
14499
- deployedAt: 1787923987153,
14500
- size: 82217,
14501
- hash: "13defa19614215ab3b1fe88955d69e530d13a09475396af932fe0e213637da2f",
14502
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14505
+ deployedAt: 1790246225795,
14506
+ size: 85107,
14507
+ hash: "25ecf952c4c44c40b0920b92d57906e7010ed9a38e2ba41ccdee6d3377c2b596",
14508
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14503
14509
  pkp: {
14504
14510
  publicKey: "0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad",
14505
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14511
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14506
14512
  }
14507
14513
  },
14508
14514
  extendPositionValidator: {
14509
- cid: "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m",
14515
+ cid: "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX",
14510
14516
  authorizedCidHex: cidToHex(
14511
- "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m"
14517
+ "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX"
14512
14518
  ),
14513
14519
  name: "Extend Position Validator",
14514
14520
  description: "Production Extend Position Validator",
14515
14521
  version: "1.2.1",
14516
14522
  deployed: true,
14517
- deployedAt: 1787923999294,
14518
- size: 79975,
14519
- hash: "31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a",
14520
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14523
+ deployedAt: 1790246231975,
14524
+ size: 82853,
14525
+ hash: "25d4887b7f646649db2bb7f2bfb77d039db83228a6c454377ca26c779b0903cc",
14526
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14521
14527
  pkp: {
14522
14528
  publicKey: "0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836",
14523
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14529
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14524
14530
  }
14525
14531
  },
14526
14532
  btcWithdrawal: {
14527
- cid: "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY",
14533
+ cid: "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP",
14528
14534
  authorizedCidHex: cidToHex(
14529
- "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY"
14535
+ "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP"
14530
14536
  ),
14531
14537
  name: "Btc Withdrawal",
14532
14538
  description: "Production Btc Withdrawal",
14533
14539
  version: "1.2.7",
14534
14540
  deployed: true,
14535
- deployedAt: 1787924017769,
14536
- size: 100069,
14537
- hash: "4f8e27414e4da235e63d6ae1325c63f3d2fb956464515a21aa007a99935f0f13",
14538
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14541
+ deployedAt: 1790246239599,
14542
+ size: 101228,
14543
+ hash: "2ed25eca6cc80a43061b7ad119737af48158fdb61d59f10cd06cea51b607f112",
14544
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14539
14545
  pkp: {
14540
14546
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
14541
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14547
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14542
14548
  }
14543
14549
  },
14544
14550
  liquidationValidator: {
14545
- cid: "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx",
14551
+ cid: "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb",
14546
14552
  authorizedCidHex: cidToHex(
14547
- "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx"
14553
+ "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb"
14548
14554
  ),
14549
14555
  name: "Liquidation Validator",
14550
14556
  description: "Production Liquidation Validator",
14551
14557
  version: "1.2.1",
14552
14558
  deployed: true,
14553
- deployedAt: 1785173262533,
14554
- size: 66846,
14555
- hash: "b35ee7706d733d625faa4dbe37f73c8e20f0c1befa897cd7875e827de52003de",
14556
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14559
+ deployedAt: 1790246247904,
14560
+ size: 70308,
14561
+ hash: "582ccf0ec7f715195e20fdc885996743cb42125b64173424e360ee63db62bbd8",
14562
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14557
14563
  pkp: {
14558
14564
  publicKey: "0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8",
14559
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14565
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14560
14566
  }
14561
14567
  },
14562
14568
  priceOracle: {
@@ -14571,28 +14577,28 @@ var require_pkg_src = __commonJS({
14571
14577
  deployedAt: 1781116663270,
14572
14578
  size: 8695,
14573
14579
  hash: "ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74",
14574
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
14580
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
14575
14581
  pkp: {
14576
14582
  publicKey: "0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b",
14577
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14583
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14578
14584
  }
14579
14585
  },
14580
14586
  loanVaultBtcBalance: {
14581
- cid: "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4",
14587
+ cid: "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W",
14582
14588
  authorizedCidHex: cidToHex(
14583
- "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4"
14589
+ "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W"
14584
14590
  ),
14585
14591
  name: "Loan Vault Btc Balance",
14586
14592
  description: "Production Loan Vault Btc Balance",
14587
14593
  version: "1.2.1",
14588
14594
  deployed: true,
14589
- deployedAt: 1785173271802,
14590
- size: 56800,
14591
- hash: "a059133214e6ba0a73d655a15600c4b33e361fb340c98f8eecaf8ab7b95aaf83",
14592
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14595
+ deployedAt: 1790179961079,
14596
+ size: 60046,
14597
+ hash: "922e86c0a667fe0c0945771f84aa6b9fe08be9c96dd2f73a9c5cb257d24e22b0",
14598
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14593
14599
  pkp: {
14594
14600
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
14595
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14601
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14596
14602
  }
14597
14603
  },
14598
14604
  // btc-address-balance (Option B) — address-only signed total balance via
@@ -14602,21 +14608,21 @@ var require_pkg_src = __commonJS({
14602
14608
  // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))
14603
14609
  // on each target chain (the action decrypts registry slots). No OAR entry.
14604
14610
  btcAddressBalance: {
14605
- cid: "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj",
14611
+ cid: "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN",
14606
14612
  authorizedCidHex: cidToHex(
14607
- "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj"
14613
+ "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN"
14608
14614
  ),
14609
14615
  name: "Btc Address Balance",
14610
14616
  description: "Address-only signed total BTC balance via registry consensus (no positionId, no price)",
14611
14617
  version: "0.2.1",
14612
14618
  deployed: true,
14613
- deployedAt: 1785173280221,
14614
- size: 27309,
14615
- hash: "f0d08938713d9d89a56a3a386cacbc2b57afd5ad367ea82d827d40e1bfc70989",
14616
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14619
+ deployedAt: 1790179971315,
14620
+ size: 30295,
14621
+ hash: "2c67d9cfa4d50e835fbb28ae50e80217ceb2be3bb862c89290aadf43fdc739c9",
14622
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14617
14623
  pkp: {
14618
14624
  publicKey: "0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd",
14619
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14625
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14620
14626
  }
14621
14627
  },
14622
14628
  alwaysSigner: {
@@ -14646,48 +14652,74 @@ var require_pkg_src = __commonJS({
14646
14652
  hash: "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72"
14647
14653
  },
14648
14654
  agentModuleExecutor: {
14649
- cid: "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf",
14655
+ cid: "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX",
14650
14656
  authorizedCidHex: cidToHex(
14651
- "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf"
14657
+ "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX"
14652
14658
  ),
14653
14659
  name: "Agent Module Executor",
14654
14660
  description: "Production Agent Module Executor",
14655
14661
  version: "1.1.1",
14656
14662
  deployed: true,
14657
- deployedAt: 1787924032013,
14658
- size: 13878,
14659
- hash: "a7f0204700912e26e5a354bee13a1242a2baa218643b3bb22d28481f67f9baf4"
14663
+ deployedAt: 1790179978959,
14664
+ size: 14688,
14665
+ hash: "8edb9b12c784c8d7d153cce97235584c24665a788767ae68713dce91109ab35e"
14660
14666
  },
14661
14667
  staleSpendRecoveryValidator: {
14662
- cid: "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8",
14668
+ cid: "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz",
14663
14669
  authorizedCidHex: cidToHex(
14664
- "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8"
14670
+ "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz"
14665
14671
  ),
14666
14672
  name: "Stale Spend Recovery Validator",
14667
14673
  description: "Production Stale Spend Recovery Validator",
14668
14674
  version: "1.1.2",
14669
14675
  deployed: true,
14670
- deployedAt: 1787924048772,
14671
- size: 41424,
14672
- hash: "3c5f028d2bef4344768462993616d45e30d9d44ef126e04d6eb579821d57d99c",
14673
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
14676
+ deployedAt: 1790246256280,
14677
+ size: 48143,
14678
+ hash: "ec9236bcbe0af24d3e1844791fc8fe37371bbecd8ce95d02e13f7c6e1fc7d94c",
14679
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
14674
14680
  pkp: {
14675
14681
  publicKey: "0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21",
14676
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
14682
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
14677
14683
  }
14678
14684
  },
14679
14685
  btcUtxoInvalidator: {
14680
- cid: "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf",
14686
+ cid: "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX",
14681
14687
  authorizedCidHex: cidToHex(
14682
- "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf"
14688
+ "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX"
14683
14689
  ),
14684
14690
  name: "Btc Utxo Invalidator",
14685
14691
  description: "Production Btc Utxo Invalidator",
14686
14692
  version: "1.0.0",
14687
14693
  deployed: true,
14688
- deployedAt: 1787924133241,
14689
- size: 66026,
14690
- hash: "603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9"
14694
+ deployedAt: 1790246264563,
14695
+ size: 69219,
14696
+ hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
14697
+ },
14698
+ carryCollateralAttestation: {
14699
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
14700
+ authorizedCidHex: cidToHex(
14701
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
14702
+ ),
14703
+ name: "Carry Collateral Attestation",
14704
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
14705
+ version: "1.0.0",
14706
+ deployed: true,
14707
+ deployedAt: 1790927734070,
14708
+ size: 21156,
14709
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
14710
+ },
14711
+ carryFundingAttestation: {
14712
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
14713
+ authorizedCidHex: cidToHex(
14714
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
14715
+ ),
14716
+ name: "Carry Funding Attestation",
14717
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
14718
+ version: "1.0.0",
14719
+ deployed: true,
14720
+ deployedAt: 1790925699980,
14721
+ size: 7193,
14722
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
14691
14723
  }
14692
14724
  };
14693
14725
  function getDeploymentsForNetwork(network) {
@@ -15431,7 +15463,7 @@ ${errorReport}`);
15431
15463
  }
15432
15464
  init_debug_logger();
15433
15465
  init_session_signature_cache();
15434
- var import_ethers53 = require("ethers");
15466
+ var import_ethers55 = require("ethers");
15435
15467
  var EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11e3;
15436
15468
  var GRACE_PERIOD_DAYS = 30;
15437
15469
  var SATOSHIS_PER_BITCOIN = 100000000n;
@@ -15453,7 +15485,10 @@ ${errorReport}`);
15453
15485
  BTCSpendAuthorizer: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
15454
15486
  BitcoinProviderRegistry: "0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",
15455
15487
  LITActionValidator: "0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",
15456
- PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"
15488
+ PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",
15489
+ TermManagerModule: "0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",
15490
+ UCDController: "0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",
15491
+ LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9"
15457
15492
  },
15458
15493
  11155111: {
15459
15494
  PositionManager: "0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",
@@ -15461,7 +15496,10 @@ ${errorReport}`);
15461
15496
  BTCSpendAuthorizer: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
15462
15497
  BitcoinProviderRegistry: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
15463
15498
  LITActionValidator: "0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",
15464
- PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9"
15499
+ PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
15500
+ TermManagerModule: "0x94Adc6F9558368B1482197584f1fc7133Ecf835b",
15501
+ UCDController: "0x360Bde4e489ee94E26601B206932De09EE60FF04",
15502
+ LiquidationManagerModule: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"
15465
15503
  }
15466
15504
  };
15467
15505
  function getPinnedContractAddresses(chainId) {
@@ -15647,10 +15685,10 @@ ${errorReport}`);
15647
15685
  };
15648
15686
  }
15649
15687
  const ratioBigInt = collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n / ucdDebt;
15650
- const collateralRatioBps = Number(ratioBigInt);
15688
+ const collateralRatioBps2 = Number(ratioBigInt);
15651
15689
  return {
15652
15690
  collateralValueUsd,
15653
- collateralRatioBps
15691
+ collateralRatioBps: collateralRatioBps2
15654
15692
  };
15655
15693
  }
15656
15694
  function hasSufficientCollateralForDebt(collateralValueUsd, currentDebt, additionalDebt, requiredRatioBps) {
@@ -16495,6 +16533,17 @@ ${auth.clientId}`;
16495
16533
  );
16496
16534
  }
16497
16535
  }
16536
+ var TIP_READ_FAILURE_PREFIX = "Bitcoin tip-height read failed";
16537
+ var BitcoinTipUnreadableError = class extends Error {
16538
+ constructor(message) {
16539
+ super(message);
16540
+ this.isBitcoinTipUnreadable = true;
16541
+ this.name = "BitcoinTipUnreadableError";
16542
+ }
16543
+ };
16544
+ function isBitcoinTipUnreadableError(error) {
16545
+ return typeof error === "object" && error !== null && error.isBitcoinTipUnreadable === true;
16546
+ }
16498
16547
  var BitcoinDataProvider = class {
16499
16548
  constructor(config) {
16500
16549
  this.config = config;
@@ -16946,27 +16995,12 @@ ${auth.clientId}`;
16946
16995
  if (!data.status.confirmed || !data.status.block_height) {
16947
16996
  return { txid: data.txid ?? txid, confirmations: 0 };
16948
16997
  }
16949
- try {
16950
- const tipResp = await fetch(
16951
- `${this.config.providerUrl}/blocks/tip/height`,
16952
- { signal: controller.signal, headers: await this.withAuth() }
16953
- );
16954
- if (!tipResp.ok) {
16955
- return { txid: data.txid ?? txid, confirmations: 1 };
16956
- }
16957
- const tipBody = (await tipResp.text()).trim();
16958
- const tipHeight = Number.parseInt(tipBody, 10);
16959
- if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
16960
- return { txid: data.txid ?? txid, confirmations: 1 };
16961
- }
16962
- const depth = tipHeight - data.status.block_height + 1;
16963
- return {
16964
- txid: data.txid ?? txid,
16965
- confirmations: depth > 0 ? depth : 0
16966
- };
16967
- } catch {
16968
- return { txid: data.txid ?? txid, confirmations: 1 };
16969
- }
16998
+ const tipHeight = await this.fetchTipHeight(controller.signal);
16999
+ const depth = tipHeight - data.status.block_height + 1;
17000
+ return {
17001
+ txid: data.txid ?? txid,
17002
+ confirmations: depth > 0 ? depth : 0
17003
+ };
16970
17004
  }
16971
17005
  return null;
16972
17006
  } catch (error) {
@@ -16974,12 +17008,55 @@ ${auth.clientId}`;
16974
17008
  if (isAbortError(error)) {
16975
17009
  throw new Error(`Request timeout after ${this.timeout}ms`);
16976
17010
  }
17011
+ if (isBitcoinTipUnreadableError(error)) {
17012
+ throw error;
17013
+ }
16977
17014
  if (getUnknownErrorMessage(error).includes("404")) {
16978
17015
  return null;
16979
17016
  }
16980
17017
  throw error;
16981
17018
  }
16982
17019
  }
17020
+ /**
17021
+ * Current chain tip height from THIS provider — or throw.
17022
+ *
17023
+ * Every exit is a throw naming the provider and the precise failure, because
17024
+ * the only alternative is inventing a confirmation depth (see the call site).
17025
+ * The single `try` exists solely to attach that name to a transport-level
17026
+ * rejection (DNS, TLS, connection reset, abort); it re-throws the cause
17027
+ * verbatim inside the message and never substitutes a value — authorized for
17028
+ * this case by the Batch 2 plan, §C2.
17029
+ *
17030
+ * @param signal - The caller's AbortSignal, so this read shares the same
17031
+ * timeout budget as the transaction fetch it serves.
17032
+ */
17033
+ async fetchTipHeight(signal) {
17034
+ const endpoint = `${this.config.providerUrl}/blocks/tip/height`;
17035
+ let tipResp;
17036
+ try {
17037
+ tipResp = await fetch(endpoint, {
17038
+ signal,
17039
+ headers: await this.withAuth()
17040
+ });
17041
+ } catch (error) {
17042
+ throw new BitcoinTipUnreadableError(
17043
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`
17044
+ );
17045
+ }
17046
+ if (!tipResp.ok) {
17047
+ throw new BitcoinTipUnreadableError(
17048
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`
17049
+ );
17050
+ }
17051
+ const tipBody = (await tipResp.text()).trim();
17052
+ const tipHeight = Number.parseInt(tipBody, 10);
17053
+ if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
17054
+ throw new BitcoinTipUnreadableError(
17055
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height "${tipBody.slice(0, 64)}"`
17056
+ );
17057
+ }
17058
+ return tipHeight;
17059
+ }
16983
17060
  /**
16984
17061
  * Get outputs (vouts) of a Bitcoin transaction
16985
17062
  *
@@ -17614,10 +17691,13 @@ ${auth.clientId}`;
17614
17691
  * only on unanimity. The confirmed-balance consensus the validators run
17615
17692
  * covers `chain_stats` only, so without this the primary provider alone
17616
17693
  * could fabricate an unconfirmed UTXO plus a self-consistent parent proof
17617
- * and inflate the signed balance. Any provider failure or verdict
17618
- * disagreement THROWS (fail-closed) — exclusion on a suppressed proof
17619
- * would deflate the balance and open a wrongful-liquidation window, so
17620
- * neither direction may proceed without agreement.
17694
+ * and inflate the signed balance. Any verdict disagreement THROWS
17695
+ * (fail-closed) — exclusion on a suppressed proof would deflate the balance
17696
+ * and open a wrongful-liquidation window, so neither direction may proceed
17697
+ * without agreement. A provider that cannot state the chain tip — and only
17698
+ * that failure — is dropped from the quorum rather than aborting the read (it
17699
+ * never counts as agreeing), and falling below `minConsensusProviders`
17700
+ * survivors throws — see `verifyParentIsSelfSpendConsensus`.
17621
17701
  *
17622
17702
  * The same per-provider `/tx` fetch also returns the parent's outputs, and
17623
17703
  * every provider must corroborate each claimed UTXO (index, vault address,
@@ -17712,10 +17792,26 @@ ${auth.clientId}`;
17712
17792
  }
17713
17793
  /**
17714
17794
  * Run the self-spend proof against every configured provider and require
17715
- * unanimity. Fail-closed: a provider request failure or a verdict
17716
- * disagreement throws and aborts the balance calculation — see
17795
+ * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:
17796
+ * a verdict mismatch throws and aborts the balance calculation — see
17717
17797
  * classifySelfChange for why exclusion is not a safe fallback here.
17718
17798
  *
17799
+ * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a
17800
+ * provider that could not state the chain tip (`BitcoinTipUnreadableError`).
17801
+ * It is ABSENT from the quorum — never counted as agreeing, never allowed to
17802
+ * decide the verdict — and the policy floor, not "at least one", decides when
17803
+ * that absence is fatal: below `minConsensusProviders` surviving readings
17804
+ * there is no cross-check left to trust, and the read fails loudly naming
17805
+ * every provider that dropped out.
17806
+ *
17807
+ * Why only that class. `getTransaction` now throws on an unreadable tip
17808
+ * instead of fabricating `confirmations: 1`; without this carve-out one flaky
17809
+ * `/blocks/tip/height` endpoint would take every balance and spend path down
17810
+ * with it. Every OTHER failure remains fatal, as before: a provider that
17811
+ * answers "I have never seen that transaction" is making a claim about the
17812
+ * chain rather than suffering an outage, and that shape is precisely the
17813
+ * fabricated-UTXO signature the fail-closed rule exists to catch.
17814
+ *
17719
17815
  * When the parent IS a unanimous self-spend, every provider's view of the
17720
17816
  * parent's OUTPUTS must additionally corroborate the primary's claimed
17721
17817
  * UTXOs (index exists, pays the vault, exact value). Without this, a
@@ -17740,32 +17836,52 @@ ${auth.clientId}`;
17740
17836
  )
17741
17837
  )
17742
17838
  );
17743
- const failures = settled.map((r, i) => ({ r, name: providerName(i) })).filter(
17744
- (x) => x.r.status === "rejected"
17745
- ).map(
17746
- ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`
17747
- );
17839
+ const answered = [];
17840
+ const absences = [];
17841
+ const failures = [];
17842
+ settled.forEach((result, i) => {
17843
+ if (result.status === "fulfilled") {
17844
+ answered.push({ index: i, evaluation: result.value });
17845
+ return;
17846
+ }
17847
+ const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;
17848
+ if (isBitcoinTipUnreadableError(result.reason)) {
17849
+ absences.push(described);
17850
+ return;
17851
+ }
17852
+ failures.push(described);
17853
+ });
17748
17854
  if (failures.length > 0) {
17749
17855
  throw new Error(
17750
17856
  `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join("; ")}`
17751
17857
  );
17752
17858
  }
17753
- const evaluations = settled.map(
17754
- (r) => r.value
17755
- );
17756
- const votes = evaluations.map((e) => e.selfSpend);
17757
- const disagreements = votes.map((vote, i) => ({ vote, name: providerName(i) })).filter((x) => x.vote !== votes[0]).map(
17758
- (x) => `${providerName(0)}=${votes[0]} vs ${x.name}=${x.vote}`
17859
+ const floor = Math.max(1, this.minConsensusProviders);
17860
+ if (answered.length < floor) {
17861
+ throw new Error(
17862
+ `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("; ")}`
17863
+ );
17864
+ }
17865
+ if (absences.length > 0) {
17866
+ litDebugLog(
17867
+ `[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("; ")}`
17868
+ );
17869
+ }
17870
+ const first = answered[0];
17871
+ const disagreements = answered.slice(1).filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend).map(
17872
+ (a) => `${providerName(first.index)}=${first.evaluation.selfSpend} vs ${providerName(a.index)}=${a.evaluation.selfSpend}`
17759
17873
  );
17760
17874
  if (disagreements.length > 0) {
17761
17875
  throw new Error(
17762
17876
  `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`
17763
17877
  );
17764
17878
  }
17765
- if (!votes[0]) {
17879
+ if (!first.evaluation.selfSpend) {
17766
17880
  return false;
17767
17881
  }
17768
- const outputMismatches = evaluations.map((e, i) => e.outputMismatch ? `${providerName(i)} \u2192 ${e.outputMismatch}` : null).filter((m) => m !== null);
17882
+ const outputMismatches = answered.map(
17883
+ (a) => a.evaluation.outputMismatch ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}` : null
17884
+ ).filter((m) => m !== null);
17769
17885
  if (outputMismatches.length > 0) {
17770
17886
  throw new Error(
17771
17887
  `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`
@@ -18008,16 +18124,6 @@ ${auth.clientId}`;
18008
18124
  minConfirmations
18009
18125
  );
18010
18126
  const authorizedSpends = await this.getAuthorizedSpendsFromContract(positionId);
18011
- for (const spend of authorizedSpends) {
18012
- const utxoStillExists = utxoSet.utxos.some(
18013
- (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout
18014
- );
18015
- if (utxoStillExists) {
18016
- throw new Error(
18017
- `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.`
18018
- );
18019
- }
18020
- }
18021
18127
  const authorizedBalance = authorizedSpends.reduce(
18022
18128
  (sum, spend) => sum + spend.satoshis,
18023
18129
  0n
@@ -18313,7 +18419,13 @@ ${auth.clientId}`;
18313
18419
  allowDevSinglePriceProvider: false,
18314
18420
  minBitcoinBalanceConfirmations: 1,
18315
18421
  minBitcoinSpendConfirmations: 1,
18316
- minConsensusProviders: 1
18422
+ // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider
18423
+ // "by design", so the consensus floor was documented as a mainnet-only
18424
+ // guarantee. The registry now holds two, and leaving the floor at 1 meant
18425
+ // Sepolia could never exercise the multi-provider agreement the stale-spend
18426
+ // and balance paths rely on — the one environment where that logic is
18427
+ // supposed to be proved before mainnet.
18428
+ minConsensusProviders: 2
18317
18429
  },
18318
18430
  [
18319
18431
  "ethereum"
@@ -18347,12 +18459,12 @@ ${auth.clientId}`;
18347
18459
  }
18348
18460
  async function executeVaultSnapshot(params) {
18349
18461
  global.ethers = {
18350
- ...import_ethers53.ethers,
18462
+ ...import_ethers55.ethers,
18351
18463
  providers: {
18352
- StaticJsonRpcProvider: import_ethers53.ethers.JsonRpcProvider
18464
+ StaticJsonRpcProvider: import_ethers55.ethers.JsonRpcProvider
18353
18465
  },
18354
- Contract: import_ethers53.ethers.Contract,
18355
- utils: import_ethers53.ethers
18466
+ Contract: import_ethers55.ethers.Contract,
18467
+ utils: import_ethers55.ethers
18356
18468
  // v6 moved utils to top level
18357
18469
  };
18358
18470
  global.Lit = {
@@ -23922,9 +24034,35 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
23922
24034
  return mod && mod.__esModule ? mod : { "default": mod };
23923
24035
  };
23924
24036
  Object.defineProperty(exports2, "__esModule", { value: true });
24037
+ exports2.computeCidV0 = computeCidV0;
23925
24038
  exports2.fetchLitActionCodeFromIpfs = fetchLitActionCodeFromIpfs;
23926
24039
  var axios_1 = __importDefault(require_axios());
24040
+ var ethers_1 = require("ethers");
23927
24041
  var ipfsCodeCache = /* @__PURE__ */ new Map();
24042
+ var CIDV0 = /^Qm[1-9A-HJ-NP-Za-km-z]{44}$/;
24043
+ var SINGLE_BLOCK_MAX_BYTES = 262144;
24044
+ function varint(n) {
24045
+ const out = [];
24046
+ while (n >= 128) {
24047
+ out.push(n & 127 | 128);
24048
+ n >>>= 7;
24049
+ }
24050
+ out.push(n);
24051
+ return out;
24052
+ }
24053
+ function computeCidV0(content) {
24054
+ const n = varint(content.length);
24055
+ const unixfs = new Uint8Array([8, 2, 18, ...n, ...content, 24, ...n]);
24056
+ const node = new Uint8Array([10, ...varint(unixfs.length), ...unixfs]);
24057
+ return (0, ethers_1.encodeBase58)(new Uint8Array([18, 32, ...(0, ethers_1.getBytes)((0, ethers_1.sha256)(node))]));
24058
+ }
24059
+ function responseBytes(data) {
24060
+ if (data instanceof Uint8Array)
24061
+ return data;
24062
+ if (data instanceof ArrayBuffer)
24063
+ return new Uint8Array(data);
24064
+ return null;
24065
+ }
23928
24066
  var GATEWAY_TIMEOUT_MS = 2e4;
23929
24067
  var buildGatewayList = (cid, pinataJwt) => {
23930
24068
  const gateways = [];
@@ -23945,6 +24083,9 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
23945
24083
  }
23946
24084
  return cached;
23947
24085
  }
24086
+ if (!CIDV0.test(cid)) {
24087
+ throw new Error(`Refusing to fetch LIT Action for ${cid}: only CIDv0 (Qm\u2026) content can be verified`);
24088
+ }
23948
24089
  const pinataJwt = options.pinataJwt ?? process.env.PINATA_JWT;
23949
24090
  const extraGateways = options.extraGateways?.map((t) => ({ url: t.replace("{cid}", cid) })) ?? [];
23950
24091
  const gateways = [...extraGateways, ...buildGatewayList(cid, pinataJwt)];
@@ -23956,19 +24097,32 @@ var require_fetch_lit_action_from_ipfs = __commonJS({
23956
24097
  }
23957
24098
  const response = await axios_1.default.get(gateway.url, {
23958
24099
  timeout: GATEWAY_TIMEOUT_MS,
24100
+ responseType: "arraybuffer",
23959
24101
  headers: {
23960
24102
  Accept: "text/plain, application/javascript, text/javascript",
23961
24103
  ...gateway.headers
23962
24104
  }
23963
24105
  });
23964
- if (response.data && typeof response.data === "string") {
23965
- if (options.debug) {
23966
- console.log(`\u2705 [fetchLitActionCodeFromIpfs] Fetched from ${gateway.url}`);
23967
- }
23968
- ipfsCodeCache.set(cid, response.data);
23969
- return response.data;
24106
+ const bytes = responseBytes(response.data);
24107
+ if (!bytes || bytes.length === 0) {
24108
+ failures.push(`${gateway.url}: HTTP ${response.status} returned ${bytes ? "an empty body" : typeof response.data}, expected bytes`);
24109
+ continue;
24110
+ }
24111
+ if (bytes.length > SINGLE_BLOCK_MAX_BYTES) {
24112
+ failures.push(`${gateway.url}: ${bytes.length} bytes exceeds the single-block CIDv0 limit (${SINGLE_BLOCK_MAX_BYTES}); content cannot be verified`);
24113
+ continue;
23970
24114
  }
23971
- failures.push(`${gateway.url}: HTTP ${response.status} returned ${typeof response.data}, expected string`);
24115
+ const actualCid = computeCidV0(bytes);
24116
+ if (actualCid !== cid) {
24117
+ failures.push(`${gateway.url}: content hashes to ${actualCid}, not the requested CID`);
24118
+ continue;
24119
+ }
24120
+ const code = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
24121
+ if (options.debug) {
24122
+ console.log(`\u2705 [fetchLitActionCodeFromIpfs] Fetched and verified from ${gateway.url}`);
24123
+ }
24124
+ ipfsCodeCache.set(cid, code);
24125
+ return code;
23972
24126
  } catch (error) {
23973
24127
  const message = error instanceof Error ? error.message : String(error);
23974
24128
  failures.push(`${gateway.url}: ${message}`);
@@ -25456,6 +25610,53 @@ var require_pkp_signer_module = __commonJS({
25456
25610
  }
25457
25611
  });
25458
25612
 
25613
+ // node_modules/@gvnrdao/dh-lit-ops/dist/modules/mainnet-validator-wallets.js
25614
+ var require_mainnet_validator_wallets = __commonJS({
25615
+ "node_modules/@gvnrdao/dh-lit-ops/dist/modules/mainnet-validator-wallets.js"(exports2) {
25616
+ "use strict";
25617
+ Object.defineProperty(exports2, "__esModule", { value: true });
25618
+ exports2.MAINNET_OP_VALIDATOR_WALLETS = exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET = exports2.NON_MAINNET_CHAIN_IDS = void 0;
25619
+ exports2.resolveMainnetValidatorWallet = resolveMainnetValidatorWallet;
25620
+ exports2.NON_MAINNET_CHAIN_IDS = /* @__PURE__ */ new Set([
25621
+ 11155111,
25622
+ // Sepolia
25623
+ 1337,
25624
+ // Hardhat (DH local deployment chainId)
25625
+ 31337
25626
+ // Hardhat (default)
25627
+ ]);
25628
+ exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET = "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c";
25629
+ exports2.MAINNET_OP_VALIDATOR_WALLETS = {
25630
+ ucdMintValidator: "0x19C8FeE0f8f4b6F9Aa8e521D4CC62F4697CF85af",
25631
+ processPaymentValidator: "0x01480725c1fA026fd4A6bfA3100c691aeC955135",
25632
+ extendPositionValidator: "0xcE08AF213D8d95ad3dD317276F9e93Ab2eD75030",
25633
+ btcWithdrawal: "0x69dCd1204CDB31437CaF7114f74422390b472d3A",
25634
+ loanVaultBtcBalance: "0xc3d549EEb62721750Ff6518f6730Ab0e8D0Fea97",
25635
+ liquidationValidator: "0x66B30C19173005A51f21e2e4180FD7BC8c1d485b",
25636
+ // Non-OAR: verified on-chain by BTCSpendAuthorizer.staleSpendValidatorAddress (set via
25637
+ // AdminModule to this PKP's derived signer). Self-deriving Safe-owned PKP; seed == signer.
25638
+ staleSpendRecoveryValidator: "0x58F9144cF9781c15C061ba86901905a5a19F7661",
25639
+ // Non-OAR: no on-chain consumer verifies these signatures. The Sepolia seed has no key
25640
+ // derivation registered on the mainnet Lit account, so they reuse the Safe-owned
25641
+ // pkp-validator PKP (live derivation, group 2). See
25642
+ // docs/INCIDENT_2026-09-21_MAINNET_PKP_DERIVATION_DECRYPT.md.
25643
+ btcAddressBalance: "0x19524aE4e514a0f08A542596c2DA0B2262c61f48",
25644
+ priceOracle: "0x19524aE4e514a0f08A542596c2DA0B2262c61f48"
25645
+ };
25646
+ function resolveMainnetValidatorWallet(args) {
25647
+ const { registryKey, chainId, wallet } = args;
25648
+ const isNonMainnetChain = Number.isFinite(chainId) && exports2.NON_MAINNET_CHAIN_IDS.has(chainId);
25649
+ if (isNonMainnetChain || !wallet || wallet.toLowerCase() !== exports2.SEPOLIA_DEFAULT_VALIDATOR_WALLET) {
25650
+ return wallet;
25651
+ }
25652
+ if (!registryKey || !Object.prototype.hasOwnProperty.call(exports2.MAINNET_OP_VALIDATOR_WALLETS, registryKey)) {
25653
+ return wallet;
25654
+ }
25655
+ return exports2.MAINNET_OP_VALIDATOR_WALLETS[registryKey];
25656
+ }
25657
+ }
25658
+ });
25659
+
25459
25660
  // node_modules/@gvnrdao/dh-lit-ops/dist/utils/async-request.util.js
25460
25661
  var require_async_request_util = __commonJS({
25461
25662
  "node_modules/@gvnrdao/dh-lit-ops/dist/utils/async-request.util.js"(exports2) {
@@ -25483,7 +25684,9 @@ var require_async_request_util = __commonJS({
25483
25684
  });
25484
25685
  if (!submitResponse.ok) {
25485
25686
  const errorText = await submitResponse.text();
25486
- throw new Error(`Failed to submit request (${submitResponse.status}): ${errorText}`);
25687
+ const retryAfter = submitResponse.status === 429 ? submitResponse.headers.get("retry-after") : null;
25688
+ const retryHint = retryAfter && /^\d+$/.test(retryAfter.trim()) ? ` Retry after ${retryAfter.trim()}s.` : "";
25689
+ throw new Error(`Failed to submit request (${submitResponse.status}): ${errorText}${retryHint}`);
25487
25690
  }
25488
25691
  const submitEnvelope = await submitResponse.json();
25489
25692
  if (!submitEnvelope.success || !submitEnvelope.data?.ticketId) {
@@ -25761,6 +25964,7 @@ var require_lit_ops_module = __commonJS({
25761
25964
  var pkp_manager_module_1 = require_pkp_manager_module();
25762
25965
  var pkp_minter_module_1 = require_pkp_minter_module();
25763
25966
  var pkp_signer_module_1 = require_pkp_signer_module();
25967
+ var mainnet_validator_wallets_1 = require_mainnet_validator_wallets();
25764
25968
  var async_request_util_1 = require_async_request_util();
25765
25969
  var crypto_1 = require("crypto");
25766
25970
  var lit_core_lit_action_client_1 = require_lit_core_lit_action_client();
@@ -25773,26 +25977,6 @@ var require_lit_ops_module = __commonJS({
25773
25977
  { name: "borrower", type: "address" }
25774
25978
  ]
25775
25979
  };
25776
- var NON_MAINNET_CHAIN_IDS = /* @__PURE__ */ new Set([
25777
- 11155111,
25778
- // Sepolia
25779
- 1337,
25780
- // Hardhat (DH local deployment chainId)
25781
- 31337
25782
- // Hardhat (default)
25783
- ]);
25784
- var SEPOLIA_DEFAULT_VALIDATOR_WALLET = "0x82db9f515957aa380b596c6ea2bd30cef181f236";
25785
- var MAINNET_OP_VALIDATOR_WALLETS = {
25786
- ucdMintValidator: "0x19C8FeE0f8f4b6F9Aa8e521D4CC62F4697CF85af",
25787
- processPaymentValidator: "0x01480725c1fA026fd4A6bfA3100c691aeC955135",
25788
- extendPositionValidator: "0xcE08AF213D8d95ad3dD317276F9e93Ab2eD75030",
25789
- btcWithdrawal: "0x69dCd1204CDB31437CaF7114f74422390b472d3A",
25790
- loanVaultBtcBalance: "0xc3d549EEb62721750Ff6518f6730Ab0e8D0Fea97",
25791
- liquidationValidator: "0x66B30C19173005A51f21e2e4180FD7BC8c1d485b",
25792
- // Non-OAR: verified on-chain by BTCSpendAuthorizer.staleSpendValidatorAddress (set via
25793
- // AdminModule to this PKP's derived signer). Self-deriving Safe-owned PKP; seed == signer.
25794
- staleSpendRecoveryValidator: "0x58F9144cF9781c15C061ba86901905a5a19F7661"
25795
- };
25796
25980
  function resolvePkpValidationRegistryAddress(config) {
25797
25981
  const fromConfig = config.pkpValidationRegistryAddress;
25798
25982
  return fromConfig || process.env.PKP_VALIDATION_REGISTRY_ADDRESS || process.env.PKP_VALIDATION_REGISTRY;
@@ -27033,17 +27217,18 @@ var require_lit_ops_module = __commonJS({
27033
27217
  let effectiveValidatorWallet = litActionInfo.validatorWalletAddress;
27034
27218
  const jp = jsParams;
27035
27219
  const resolvedChainId = Number(jp.chainId ?? jp.auth?.chainId ?? jp.authMessage?.chainId ?? this.config.chainId);
27036
- const isNonMainnetChain = Number.isFinite(resolvedChainId) && NON_MAINNET_CHAIN_IDS.has(resolvedChainId);
27037
- if (!isNonMainnetChain && effectiveValidatorWallet && effectiveValidatorWallet.toLowerCase() === SEPOLIA_DEFAULT_VALIDATOR_WALLET) {
27038
- const reg = (0, dh_lit_actions_1.getDeploymentsForNetwork)(this.config.network);
27039
- const registryKey = Object.keys(reg).find((k) => reg[k]?.cid === litActionInfo.cid);
27040
- const mainnetWallet = registryKey ? MAINNET_OP_VALIDATOR_WALLETS[registryKey] : void 0;
27041
- if (mainnetWallet) {
27042
- if (this.config.debug) {
27043
- console.log(`[${label}] mainnet validator remap (${registryKey}, chainId=${Number.isFinite(resolvedChainId) ? resolvedChainId : "unknown\u2192mainnet"}): ${effectiveValidatorWallet} -> ${mainnetWallet}`);
27044
- }
27045
- effectiveValidatorWallet = mainnetWallet;
27220
+ const reg = (0, dh_lit_actions_1.getDeploymentsForNetwork)(this.config.network);
27221
+ const registryKey = Object.keys(reg).find((k) => reg[k]?.cid === litActionInfo.cid);
27222
+ const mainnetWallet = (0, mainnet_validator_wallets_1.resolveMainnetValidatorWallet)({
27223
+ registryKey,
27224
+ chainId: resolvedChainId,
27225
+ wallet: effectiveValidatorWallet
27226
+ });
27227
+ if (mainnetWallet !== effectiveValidatorWallet) {
27228
+ if (this.config.debug) {
27229
+ console.log(`[${label}] mainnet validator remap (${registryKey}, chainId=${Number.isFinite(resolvedChainId) ? resolvedChainId : "unknown\u2192mainnet"}): ${effectiveValidatorWallet} -> ${mainnetWallet}`);
27046
27230
  }
27231
+ effectiveValidatorWallet = mainnetWallet;
27047
27232
  }
27048
27233
  if (process.env.LIT_LANE_VALIDATOR_WALLET_OVERRIDE) {
27049
27234
  if (process.env.LIT_LANE_GUARD !== "1") {
@@ -27159,7 +27344,7 @@ var require_lit_ops_module = __commonJS({
27159
27344
  break;
27160
27345
  case 11155111:
27161
27346
  chain = "sepolia";
27162
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27347
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27163
27348
  break;
27164
27349
  case 1337:
27165
27350
  // Hardhat local testnet (actual deployment chainId)
@@ -27348,7 +27533,7 @@ var require_lit_ops_module = __commonJS({
27348
27533
  break;
27349
27534
  case 11155111:
27350
27535
  chain = "sepolia";
27351
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27536
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27352
27537
  break;
27353
27538
  case 1337:
27354
27539
  // Hardhat local testnet (actual deployment chainId)
@@ -27539,7 +27724,7 @@ var require_lit_ops_module = __commonJS({
27539
27724
  break;
27540
27725
  case 11155111:
27541
27726
  chain = "sepolia";
27542
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27727
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27543
27728
  break;
27544
27729
  case 1337:
27545
27730
  case 31337:
@@ -27687,7 +27872,7 @@ var require_lit_ops_module = __commonJS({
27687
27872
  break;
27688
27873
  case 11155111:
27689
27874
  chain = "sepolia";
27690
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
27875
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27691
27876
  break;
27692
27877
  case 1337:
27693
27878
  // Hardhat local testnet (actual deployment chainId)
@@ -27907,7 +28092,7 @@ var require_lit_ops_module = __commonJS({
27907
28092
  bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://mempool.space/api";
27908
28093
  break;
27909
28094
  case 11155111:
27910
- bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/api/esplora";
28095
+ bitcoinProviderUrl = process.env.BITCOIN_PROVIDER_URL || "https://regtest.diamondhands.credit/api/esplora";
27911
28096
  break;
27912
28097
  case 1337:
27913
28098
  // Hardhat local testnet (actual deployment chainId)
@@ -28210,7 +28395,11 @@ var require_lit_ops_module = __commonJS({
28210
28395
  error: "sign=true requires price oracle PKP in registry (ethAddress/publicKey) or options.pkpId (Lit jsParams pkpId)"
28211
28396
  };
28212
28397
  }
28213
- priceOracleParams.pkpId = resolvedPkpId;
28398
+ priceOracleParams.pkpId = (0, mainnet_validator_wallets_1.resolveMainnetValidatorWallet)({
28399
+ registryKey: "priceOracle",
28400
+ chainId: Number(this.config.chainId),
28401
+ wallet: resolvedPkpId
28402
+ });
28214
28403
  }
28215
28404
  if (this.config.debug) {
28216
28405
  console.log("\u{1F4B0} Calling Price Oracle LIT Action:");
@@ -40435,7 +40624,7 @@ var require_dist3 = __commonJS({
40435
40624
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
40436
40625
  };
40437
40626
  Object.defineProperty(exports2, "__esModule", { value: true });
40438
- 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;
40627
+ 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;
40439
40628
  __exportStar(require_interfaces(), exports2);
40440
40629
  var dh_lit_actions_1 = require_pkg_src();
40441
40630
  Object.defineProperty(exports2, "getDeploymentsForNetwork", { enumerable: true, get: function() {
@@ -40448,6 +40637,10 @@ var require_dist3 = __commonJS({
40448
40637
  Object.defineProperty(exports2, "LitOps", { enumerable: true, get: function() {
40449
40638
  return lit_ops_module_1.LitOps;
40450
40639
  } });
40640
+ var mainnet_validator_wallets_1 = require_mainnet_validator_wallets();
40641
+ Object.defineProperty(exports2, "resolveMainnetValidatorWallet", { enumerable: true, get: function() {
40642
+ return mainnet_validator_wallets_1.resolveMainnetValidatorWallet;
40643
+ } });
40451
40644
  var auth_manager_module_1 = require_auth_manager_module();
40452
40645
  Object.defineProperty(exports2, "LitAuthManager", { enumerable: true, get: function() {
40453
40646
  return auth_manager_module_1.LitAuthManager;
@@ -40590,7 +40783,8 @@ var init_wc_transport = __esm({
40590
40783
  this.client = client;
40591
40784
  this.cfg = cfg;
40592
40785
  this.scratch = scratch;
40593
- client.on("session_delete", () => {
40786
+ client.on("session_delete", ({ topic }) => {
40787
+ if (this.session === null || this.session.topic !== topic) return;
40594
40788
  this.session = null;
40595
40789
  this.sessionListener?.(null);
40596
40790
  });
@@ -40602,7 +40796,7 @@ var init_wc_transport = __esm({
40602
40796
  const client = await import_sign_client.default.init({
40603
40797
  core,
40604
40798
  projectId: cfg.projectId,
40605
- metadata: WC_DAPP_METADATA
40799
+ metadata: cfg.metadata ?? WC_DAPP_METADATA
40606
40800
  });
40607
40801
  return new _WcTransport(client, cfg, scratch);
40608
40802
  }
@@ -40620,14 +40814,21 @@ var init_wc_transport = __esm({
40620
40814
  optionalNamespaces: wcSessionNamespaces(this.cfg.chainId)
40621
40815
  });
40622
40816
  if (!uri) throw new Error("WalletConnect returned no pairing URI");
40817
+ const pairingId = /^wc:([0-9a-f]+)@/i.exec(uri)?.[1];
40818
+ if (!pairingId) throw new Error(`WalletConnect pairing URI has no recognisable topic: ${uri.slice(0, 12)}\u2026`);
40623
40819
  void approval().then((session) => {
40624
40820
  const first = session.namespaces["eip155"]?.accounts[0];
40625
40821
  if (!first) throw new Error("WalletConnect session carries no eip155 account");
40626
40822
  const [, chainIdStr, account] = first.split(":");
40823
+ const previous = this.session;
40627
40824
  this.session = { topic: session.topic, account, chainId: Number(chainIdStr) };
40628
- this.sessionListener?.(this.active());
40825
+ const verdict = this.sessionListener?.({ ...this.active(), pairingId });
40826
+ if (verdict === false) {
40827
+ this.session = previous;
40828
+ void this.client.disconnect({ topic: session.topic, reason: { code: 6e3, message: "session refused by the bridge" } }).catch(() => void 0);
40829
+ }
40629
40830
  }).catch((e) => console.error(`[dh-mcp] WalletConnect pairing failed: ${e.message}`));
40630
- return { uri };
40831
+ return { uri, pairingId };
40631
40832
  }
40632
40833
  /** Route one wallet request over the active session. Throws on user rejection. */
40633
40834
  async request(method, params) {
@@ -40883,13 +41084,14 @@ function resolveRealConfig(env) {
40883
41084
 
40884
41085
  // src/boot.ts
40885
41086
  var fs6 = __toESM(require("fs"));
40886
- var import_ethers50 = require("ethers");
41087
+ var import_ethers52 = require("ethers");
40887
41088
 
40888
41089
  // src/boundary/index.ts
40889
41090
  var import_node_crypto8 = require("crypto");
40890
41091
  var fs5 = __toESM(require("fs"));
40891
41092
  var os2 = __toESM(require("os"));
40892
41093
  var path4 = __toESM(require("path"));
41094
+ var import_ethers51 = require("ethers");
40893
41095
 
40894
41096
  // src/boundary/envelope.ts
40895
41097
  function okEnvelope(data, source, warnings = []) {
@@ -40973,8 +41175,13 @@ function iso(sec) {
40973
41175
  return new Date(sec * 1e3).toISOString();
40974
41176
  }
40975
41177
  var PSM_FLOOR_TOLERANCE_BPS = 100;
41178
+ var CANONICAL_MAINNET_USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
41179
+ function stablecoinKindFor(network, stablecoinAddress) {
41180
+ if (network !== "mainnet") return "mock";
41181
+ return stablecoinAddress.toLowerCase() === CANONICAL_MAINNET_USDC.toLowerCase() ? "circle" : "onchain";
41182
+ }
40976
41183
  function failureToError(f) {
40977
- const code = f.kind === "signer-missing" ? "SIGNER_UNAVAILABLE" : f.kind === "unavailable" ? "UPSTREAM_UNAVAILABLE" : f.kind === "not-found" ? "NOT_FOUND" : "UPSTREAM_REJECTED";
41184
+ 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";
40978
41185
  const message = f.kind === "malformed" ? `${f.message} (upstream response failed integrity checks)` : f.message;
40979
41186
  return boundaryError(code, message, {
40980
41187
  source: f.source,
@@ -41450,7 +41657,7 @@ var BoundaryCore = class {
41450
41657
  tokenAddress: a.tokenAddress,
41451
41658
  spenderAddress: a.spenderAddress,
41452
41659
  spenderContract: a.spenderContract,
41453
- 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",
41660
+ 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",
41454
41661
  before: a.before,
41455
41662
  amountUnit: q.amountInUnit,
41456
41663
  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."
@@ -41509,9 +41716,10 @@ var BoundaryCore = class {
41509
41716
  chainId: this.deps.chainId,
41510
41717
  psmAddress: s.psmAddress,
41511
41718
  stablecoinAddress: s.stablecoinAddress,
41512
- // Only mainnet runs real Circle USDC; the mock world and sepolia both run a
41513
- // practice stablecoin with a public self-serve mint.
41514
- stablecoinKind: this.deps.network === "mainnet" ? "circle" : "mock",
41719
+ // Labelled by the ACTUAL coin, not the network (C-49): `circle` only for canonical
41720
+ // mainnet USDC, `mock` for the practice token, `onchain` for any other real coin
41721
+ // (e.g. mainnet USDT) — a USDT swap must never render as "real USDC".
41722
+ stablecoinKind: stablecoinKindFor(this.deps.network, s.stablecoinAddress),
41515
41723
  stablecoinSymbol: s.stablecoinSymbol,
41516
41724
  stablecoinDecimals: s.stablecoinDecimals,
41517
41725
  exchangeRate: s.exchangeRate,
@@ -43377,8 +43585,13 @@ var SignerManager = class {
43377
43585
  mode: deps.initialMode,
43378
43586
  borrower: deps.configuredBorrower ?? null
43379
43587
  };
43588
+ if (deps.authenticatedBorrower) this.state = { ...this.state, borrower: deps.authenticatedBorrower };
43380
43589
  }
43381
43590
  state;
43591
+ /** True when the borrower is the signed-in identity and cannot be swapped. */
43592
+ identityPinned() {
43593
+ return this.deps.authenticatedBorrower !== void 0;
43594
+ }
43382
43595
  mode() {
43383
43596
  return this.state.mode;
43384
43597
  }
@@ -43418,7 +43631,7 @@ var SignerManager = class {
43418
43631
  this.deps.persistence.save(this.state);
43419
43632
  }
43420
43633
  resetBorrower() {
43421
- this.state = { ...this.state, borrower: null };
43634
+ this.state = { ...this.state, borrower: this.deps.authenticatedBorrower ?? null };
43422
43635
  this.deps.persistence.save(this.state);
43423
43636
  }
43424
43637
  async use(mode, opts) {
@@ -44493,6 +44706,35 @@ var import_ethers9 = require("ethers");
44493
44706
  // src/boundary/upstream/shared/external-bridge/card.ts
44494
44707
  var import_ethers7 = require("ethers");
44495
44708
  init_tx_validator();
44709
+
44710
+ // src/boundary/upstream/shared/external-bridge/card-escape.ts
44711
+ var MAX_VALUE_CHARS = 200;
44712
+ function mustEscape(code) {
44713
+ if (code <= 31 || code === 127) return true;
44714
+ if (code >= 128 && code <= 159) return true;
44715
+ if (code === 8232 || code === 8233) return true;
44716
+ if (code >= 8234 && code <= 8238) return true;
44717
+ if (code >= 8294 && code <= 8297) return true;
44718
+ return false;
44719
+ }
44720
+ function safeValue(raw) {
44721
+ let out = "";
44722
+ for (const ch of String(raw)) {
44723
+ const code = ch.codePointAt(0);
44724
+ out += mustEscape(code) ? `\\u${code.toString(16).padStart(4, "0")}` : ch;
44725
+ if (out.length > MAX_VALUE_CHARS) return `${out.slice(0, MAX_VALUE_CHARS)}\u2026[truncated]`;
44726
+ }
44727
+ return out;
44728
+ }
44729
+
44730
+ // src/boundary/upstream/shared/external-bridge/card.ts
44731
+ function formatBtc(sats) {
44732
+ const negative = sats < 0n;
44733
+ const abs = negative ? -sats : sats;
44734
+ const whole = abs / 10n ** 8n;
44735
+ const frac = (abs % 10n ** 8n).toString().padStart(8, "0").replace(/0+$/, "");
44736
+ return `${negative ? "-" : ""}${whole}${frac ? "." + frac : ""}`;
44737
+ }
44496
44738
  function formatUcd(wei) {
44497
44739
  const negative = wei < 0n;
44498
44740
  const abs = negative ? -wei : wei;
@@ -44538,15 +44780,15 @@ function cardForTx(tx2) {
44538
44780
  "Operation: create a new borrowing position (your wallet is the borrower)",
44539
44781
  `Term: ${Number(args[4])} months`,
44540
44782
  `Position key (PKP id): ${String(args[0])}`,
44541
- `BTC vault (mainnet form): ${String(args[2])}`,
44542
- `BTC vault (regtest form): ${String(args[3])}`,
44783
+ `BTC vault (mainnet form): ${safeValue(args[2])}`,
44784
+ `BTC vault (regtest form): ${safeValue(args[3])}`,
44543
44785
  `Validator generation: ${Number(args[5])}`,
44544
44786
  ...head
44545
44787
  ];
44546
44788
  case "addAddress":
44547
44789
  return [
44548
44790
  "Operation: allowlist a Bitcoin withdrawal destination for YOUR account",
44549
- `BTC address to allowlist: ${String(args[0])}`,
44791
+ `BTC address to allowlist: ${safeValue(args[0])}`,
44550
44792
  "Withdrawals to this address become possible only after the registry's on-chain delay",
44551
44793
  ...head
44552
44794
  ];
@@ -44574,15 +44816,40 @@ function cardForTx(tx2) {
44574
44816
  `Minimum stablecoin out \u2014 the slippage floor (smallest units): ${String(args[2])}`,
44575
44817
  ...head
44576
44818
  ];
44819
+ case "withdrawBTC": {
44820
+ const p = args[0];
44821
+ return [
44822
+ "Operation: withdraw BTC from your vault \u2014 THIS MOVES BITCOIN OUT",
44823
+ `Position: ${safeValue(p.positionId)}`,
44824
+ // The destination is the whole security question of this card. It is a caller-
44825
+ // supplied string, hence safeValue: see the escaping note above.
44826
+ `BTC sent to: ${safeValue(p.withdrawalAddress)}`,
44827
+ `Leaves the vault (fee included): ${formatBtc(BigInt(p.totalDeduction))} BTC (${BigInt(p.totalDeduction)} sats)`,
44828
+ `Collateral remaining after this: ${formatBtc(BigInt(p.newCollateral))} BTC (${BigInt(p.newCollateral)} sats)`,
44829
+ `Spending vault UTXO: ${safeValue(p.utxoTxid)}:${Number(p.utxoVout)}`,
44830
+ ...head
44831
+ ];
44832
+ }
44833
+ case "setPositionDelegate":
44834
+ return [
44835
+ "Operation: set the DELEGATE for this position \u2014 this address may act on the position on your behalf",
44836
+ `Position: ${safeValue(args[0])}`,
44837
+ `Delegate address: ${safeValue(args[1])}`,
44838
+ "Setting the zero address removes the current delegate",
44839
+ ...head
44840
+ ];
44577
44841
  default:
44578
- return [`Operation: ${name}`, ...args.map((a, i) => `arg[${i}]: ${String(a)}`), ...head];
44842
+ throw new Error(
44843
+ `no approval card is defined for the signable function "${name}" \u2014 add a case to cardForTx before this operation can be approved`
44844
+ );
44579
44845
  }
44580
44846
  }
44581
44847
  function cardForTypedData(action, payload) {
44582
44848
  const m = payload.message;
44583
44849
  return [
44584
44850
  `Operation: ${action} \u2014 this signature AUTHORIZES the operation described below; the protocol executes it after your approval`,
44585
- ...Object.entries(m).map(([k, v]) => `${k}: ${String(v)}`),
44851
+ // `detail` here is a server-composed string — same escaping rule as the tx card.
44852
+ ...Object.entries(m).map(([k, v]) => `${safeValue(k)}: ${safeValue(v)}`),
44586
44853
  `Signing domain: ${String(payload.domain["name"])} v${String(payload.domain["version"])} \xB7 chain ${String(payload.domain["chainId"])}`
44587
44854
  ];
44588
44855
  }
@@ -44933,12 +45200,10 @@ init_tx_validator();
44933
45200
 
44934
45201
  // src/boundary/upstream/shared/quantum.ts
44935
45202
  var QUANTUM_WINDOW_SECONDS = 60;
44936
- var AUTH_VALIDITY_WINDOWS = 3;
44937
- function authValiditySec() {
44938
- return QUANTUM_WINDOW_SECONDS * AUTH_VALIDITY_WINDOWS;
44939
- }
44940
45203
  function isAuthFresh(issuedAtSec, nowSec) {
44941
- return issuedAtSec <= nowSec && nowSec - issuedAtSec < authValiditySec();
45204
+ const sq = Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS;
45205
+ const cq = Math.floor(nowSec / QUANTUM_WINDOW_SECONDS) * QUANTUM_WINDOW_SECONDS;
45206
+ return sq === cq - QUANTUM_WINDOW_SECONDS || sq === cq || sq === cq + QUANTUM_WINDOW_SECONDS;
44942
45207
  }
44943
45208
  function isStrictCurrentQuantum(issuedAtSec, nowSec) {
44944
45209
  return issuedAtSec <= nowSec && Math.floor(issuedAtSec / QUANTUM_WINDOW_SECONDS) === Math.floor(nowSec / QUANTUM_WINDOW_SECONDS);
@@ -44979,7 +45244,7 @@ var SafeCeremony = class {
44979
45244
  if (!auth.ok) return auth.refusal;
44980
45245
  if (!isAuthFresh(issuedAtSec, surface.nowSec())) {
44981
45246
  return this.refuse(
44982
- `${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`
45247
+ `${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`
44983
45248
  );
44984
45249
  }
44985
45250
  const raw = await executor.signTransaction({
@@ -51698,7 +51963,6 @@ var init_deployment_addresses = __esm2({
51698
51963
  PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
51699
51964
  FeeRecipientRegistry: "0x95795F8403DDb629E8527B2934C4e71f5fC0C374",
51700
51965
  BitcoinWithdrawalAddressRegistry: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
51701
- CarryAgentRegistry: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
51702
51966
  AgentDelegationRegistry: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
51703
51967
  DHAgentDelegate: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF",
51704
51968
  AgentModuleFactory: "0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5"
@@ -51747,11 +52011,11 @@ var init_deployment_addresses = __esm2({
51747
52011
  reason: "Shared upgrade script: AdminModule implementation update"
51748
52012
  },
51749
52013
  PositionManagerViews: {
51750
- previousImplementation: "0x1EB2B1d058006ACd9033E01e846D73eDE686b620",
51751
- newImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
51752
- upgradedAt: "2026-07-03T20:11:25.817Z",
51753
- upgradedBy: "0xF20986F02420EF443AE9BE5092FB8A4975cF3aA6",
51754
- reason: "Shared upgrade script: PositionManagerViews implementation update"
52014
+ previousImplementation: "0xA455B542cFb36AF8451fc420dB89e590E5c87cef",
52015
+ newImplementation: "0x8cEB3F1c07fDB3301f55b96a5B9aDb33C8d36Da3",
52016
+ upgradedAt: "2026-10-02T17:04:25.853Z",
52017
+ upgradedBy: "0x0f8f23674cc90Ef7107930a4437341fD8B460362",
52018
+ reason: "1.1.2: getBackingVaults (PoR backing set) + implementation lock (constructor)"
51755
52019
  },
51756
52020
  TestPositionManager: {
51757
52021
  previousImplementation: "0x0B46Ee1a9C6b42559758B7FF78294Cd867BB08f8",
@@ -51968,8 +52232,6 @@ var init_deployment_addresses = __esm2({
51968
52232
  OPERATION_AUTHORIZATION_REGISTRY_IMPL: "0xe0D981B60351f0f8fFDA2b50C8180Fb37CeF3883",
51969
52233
  BITCOIN_WITHDRAWAL_ADDRESS_REGISTRY: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
51970
52234
  BITCOIN_WITHDRAWAL_ADDRESS_REGISTRY_IMPL: "0x76E0a2c9d89562fD7c50b5f554d7fa25957e39Db",
51971
- CARRY_AGENT_REGISTRY: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
51972
- CARRY_AGENT_REGISTRY_IMPL: "0x1b11a3D5e46F3672E643c997f0d569DFf0b64a01",
51973
52235
  AGENT_DELEGATION_REGISTRY: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
51974
52236
  AGENT_DELEGATION_REGISTRY_IMPL: "0xE931E4b9ceF2A48Ac7D57192da4B523756cFC310",
51975
52237
  DH_AGENT_DELEGATE: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF"
@@ -52001,7 +52263,6 @@ var init_deployment_addresses = __esm2({
52001
52263
  PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
52002
52264
  FeeRecipientRegistry: "0x95795F8403DDb629E8527B2934C4e71f5fC0C374",
52003
52265
  BitcoinWithdrawalAddressRegistry: "0x6376D392097F0A81e51BD83960A97EA20eaf1dbe",
52004
- CarryAgentRegistry: "0x5595CB538D44E6Cf179D20364fD631D0477e69f7",
52005
52266
  AgentDelegationRegistry: "0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",
52006
52267
  DHAgentDelegate: "0xa5A14489ae883960df6E1463A41a47aBE9Ecc5AF",
52007
52268
  AgentModuleFactory: "0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5"
@@ -52976,113 +53237,113 @@ var require_pkg_src2 = __commonJS2({
52976
53237
  deployedAt: 1784569687492,
52977
53238
  size: 4140,
52978
53239
  hash: "4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b",
52979
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
53240
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
52980
53241
  pkp: {
52981
53242
  publicKey: "0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f",
52982
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53243
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
52983
53244
  }
52984
53245
  },
52985
53246
  btcTransactionSigner: {
52986
- cid: "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf",
53247
+ cid: "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U",
52987
53248
  authorizedCidHex: cidToHex(
52988
- "QmVi1BYdxvCX3QUhXwPtP6FjWMzqSPtXzrS54YsXjTgjYf"
53249
+ "QmULkz7hwwqsyLwY23U14dnartdVuSNMrykt69PaNiAq7U"
52989
53250
  ),
52990
53251
  name: "Btc Transaction Signer",
52991
53252
  description: "Production Btc Transaction Signer",
52992
53253
  version: "1.1.1",
52993
53254
  deployed: true,
52994
- deployedAt: 1787923905597,
52995
- size: 70646,
52996
- hash: "37c3bb72a660c8275d92e1b73f9482742d86b64789480b9246304c0ca1bab47a"
53255
+ deployedAt: 1790246185256,
53256
+ size: 73313,
53257
+ hash: "d8b6bc646ba33fee7d46c8e9b281de776081ea6f182f56fd15d4c52aaf3dd030"
52997
53258
  },
52998
53259
  ucdMintValidator: {
52999
- cid: "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc",
53260
+ cid: "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe",
53000
53261
  authorizedCidHex: cidToHex(
53001
- "QmUWR5fLiyimLT9TPXpYx3HgwNwkvR6MxjZ7hdeYCFodbc"
53262
+ "QmcxVSn9saEPGBS6mqPhNefgW83V2qeZjjXbhwYLP373xe"
53002
53263
  ),
53003
53264
  name: "Ucd Mint Validator",
53004
53265
  description: "Production Ucd Mint Validator",
53005
- version: "1.2.1",
53266
+ version: "1.3.0",
53006
53267
  deployed: true,
53007
- deployedAt: 1787923919527,
53008
- size: 86197,
53009
- hash: "c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf",
53010
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53268
+ deployedAt: 1790246219868,
53269
+ size: 90022,
53270
+ hash: "65e8cb778c2b767ae6eb37cb5db7b4c5a3f2468d508463c847c83c1b6825fadd",
53271
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53011
53272
  pkp: {
53012
53273
  publicKey: "0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb",
53013
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53274
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53014
53275
  }
53015
53276
  },
53016
53277
  processPaymentValidator: {
53017
- cid: "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF",
53278
+ cid: "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8",
53018
53279
  authorizedCidHex: cidToHex(
53019
- "QmXmXuMRAjMLdgKGyTf9KQdGwYrDp8DxkiF44TvSXDf7wF"
53280
+ "QmWFbxJkfxhCtES4wrePWQkYtjhtrP1tohvn9d1r9N5Hd8"
53020
53281
  ),
53021
53282
  name: "Process Payment Validator",
53022
53283
  description: "Production Process Payment Validator",
53023
53284
  version: "1.2.1",
53024
53285
  deployed: true,
53025
- deployedAt: 1787923987153,
53026
- size: 82217,
53027
- hash: "13defa19614215ab3b1fe88955d69e530d13a09475396af932fe0e213637da2f",
53028
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53286
+ deployedAt: 1790246225795,
53287
+ size: 85107,
53288
+ hash: "25ecf952c4c44c40b0920b92d57906e7010ed9a38e2ba41ccdee6d3377c2b596",
53289
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53029
53290
  pkp: {
53030
53291
  publicKey: "0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad",
53031
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53292
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53032
53293
  }
53033
53294
  },
53034
53295
  extendPositionValidator: {
53035
- cid: "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m",
53296
+ cid: "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX",
53036
53297
  authorizedCidHex: cidToHex(
53037
- "QmU8h99EEVEsQkxroXiYqLsKZw9gNjE6N5CcTpE9aUc12m"
53298
+ "QmZ3g7g5DkgU1gEYpFjprQf3sctUHtGjNQVYezw2bnPGEX"
53038
53299
  ),
53039
53300
  name: "Extend Position Validator",
53040
53301
  description: "Production Extend Position Validator",
53041
53302
  version: "1.2.1",
53042
53303
  deployed: true,
53043
- deployedAt: 1787923999294,
53044
- size: 79975,
53045
- hash: "31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a",
53046
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53304
+ deployedAt: 1790246231975,
53305
+ size: 82853,
53306
+ hash: "25d4887b7f646649db2bb7f2bfb77d039db83228a6c454377ca26c779b0903cc",
53307
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53047
53308
  pkp: {
53048
53309
  publicKey: "0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836",
53049
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53310
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53050
53311
  }
53051
53312
  },
53052
53313
  btcWithdrawal: {
53053
- cid: "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY",
53314
+ cid: "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP",
53054
53315
  authorizedCidHex: cidToHex(
53055
- "QmZQWET9pzrVD4gwQuSzYZmqa24JrUNtnnGFDd513sxMCY"
53316
+ "QmbRaaMQr1jCctDGe8mPADsUz1rkb4frT1YqSKroiXjzyP"
53056
53317
  ),
53057
53318
  name: "Btc Withdrawal",
53058
53319
  description: "Production Btc Withdrawal",
53059
53320
  version: "1.2.7",
53060
53321
  deployed: true,
53061
- deployedAt: 1787924017769,
53062
- size: 100069,
53063
- hash: "4f8e27414e4da235e63d6ae1325c63f3d2fb956464515a21aa007a99935f0f13",
53064
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53322
+ deployedAt: 1790246239599,
53323
+ size: 101228,
53324
+ hash: "2ed25eca6cc80a43061b7ad119737af48158fdb61d59f10cd06cea51b607f112",
53325
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53065
53326
  pkp: {
53066
53327
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
53067
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53328
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53068
53329
  }
53069
53330
  },
53070
53331
  liquidationValidator: {
53071
- cid: "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx",
53332
+ cid: "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb",
53072
53333
  authorizedCidHex: cidToHex(
53073
- "Qme6aGADhiszkQbZL977E6nmBacd2PEB7K9Hs8puVrscNx"
53334
+ "QmTs2w8gfAwWZLbzJZg2CZmiLhVXS5kbMgaj42Zuxfodpb"
53074
53335
  ),
53075
53336
  name: "Liquidation Validator",
53076
53337
  description: "Production Liquidation Validator",
53077
53338
  version: "1.2.1",
53078
53339
  deployed: true,
53079
- deployedAt: 1785173262533,
53080
- size: 66846,
53081
- hash: "b35ee7706d733d625faa4dbe37f73c8e20f0c1befa897cd7875e827de52003de",
53082
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53340
+ deployedAt: 1790246247904,
53341
+ size: 70308,
53342
+ hash: "582ccf0ec7f715195e20fdc885996743cb42125b64173424e360ee63db62bbd8",
53343
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53083
53344
  pkp: {
53084
53345
  publicKey: "0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8",
53085
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53346
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53086
53347
  }
53087
53348
  },
53088
53349
  priceOracle: {
@@ -53097,28 +53358,28 @@ var require_pkg_src2 = __commonJS2({
53097
53358
  deployedAt: 1781116663270,
53098
53359
  size: 8695,
53099
53360
  hash: "ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74",
53100
- validatorWalletAddress: "0x82db9f515957aa380b596c6ea2bd30cef181f236",
53361
+ validatorWalletAddress: "0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c",
53101
53362
  pkp: {
53102
53363
  publicKey: "0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b",
53103
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53364
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53104
53365
  }
53105
53366
  },
53106
53367
  loanVaultBtcBalance: {
53107
- cid: "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4",
53368
+ cid: "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W",
53108
53369
  authorizedCidHex: cidToHex(
53109
- "QmaeQoHYvcMYobNbu9hQavGDudi8AXoW9tg3YHrvy1g2A4"
53370
+ "QmZ27xCzuoaAhWxRsMPsUQkp45a8WPBb21uhxwchw3LG5W"
53110
53371
  ),
53111
53372
  name: "Loan Vault Btc Balance",
53112
53373
  description: "Production Loan Vault Btc Balance",
53113
53374
  version: "1.2.1",
53114
53375
  deployed: true,
53115
- deployedAt: 1785173271802,
53116
- size: 56800,
53117
- hash: "a059133214e6ba0a73d655a15600c4b33e361fb340c98f8eecaf8ab7b95aaf83",
53118
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53376
+ deployedAt: 1790179961079,
53377
+ size: 60046,
53378
+ hash: "922e86c0a667fe0c0945771f84aa6b9fe08be9c96dd2f73a9c5cb257d24e22b0",
53379
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53119
53380
  pkp: {
53120
53381
  publicKey: "0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d",
53121
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53382
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53122
53383
  }
53123
53384
  },
53124
53385
  // btc-address-balance (Option B) — address-only signed total balance via
@@ -53128,21 +53389,21 @@ var require_pkg_src2 = __commonJS2({
53128
53389
  // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))
53129
53390
  // on each target chain (the action decrypts registry slots). No OAR entry.
53130
53391
  btcAddressBalance: {
53131
- cid: "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj",
53392
+ cid: "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN",
53132
53393
  authorizedCidHex: cidToHex(
53133
- "QmUXUtU9r1HhQVYgkXPN5s19SKXanhn4pMsCtFEP3GK4Kj"
53394
+ "QmVVjB6zCBiXFKffhQPYUAZhj7TXduuvcrPqKtHa3DMXhN"
53134
53395
  ),
53135
53396
  name: "Btc Address Balance",
53136
53397
  description: "Address-only signed total BTC balance via registry consensus (no positionId, no price)",
53137
53398
  version: "0.2.1",
53138
53399
  deployed: true,
53139
- deployedAt: 1785173280221,
53140
- size: 27309,
53141
- hash: "f0d08938713d9d89a56a3a386cacbc2b57afd5ad367ea82d827d40e1bfc70989",
53142
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53400
+ deployedAt: 1790179971315,
53401
+ size: 30295,
53402
+ hash: "2c67d9cfa4d50e835fbb28ae50e80217ceb2be3bb862c89290aadf43fdc739c9",
53403
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53143
53404
  pkp: {
53144
53405
  publicKey: "0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd",
53145
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53406
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53146
53407
  }
53147
53408
  },
53148
53409
  alwaysSigner: {
@@ -53172,48 +53433,74 @@ var require_pkg_src2 = __commonJS2({
53172
53433
  hash: "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72"
53173
53434
  },
53174
53435
  agentModuleExecutor: {
53175
- cid: "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf",
53436
+ cid: "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX",
53176
53437
  authorizedCidHex: cidToHex(
53177
- "QmcD65vuremot5fsHVgp9JBAmei6gAaEtm5mdtLP7Yt9Kf"
53438
+ "QmSwPPvQhT7UhcuVA2m3UxGhVj5WqMpDvYNKU1228QLFsX"
53178
53439
  ),
53179
53440
  name: "Agent Module Executor",
53180
53441
  description: "Production Agent Module Executor",
53181
53442
  version: "1.1.1",
53182
53443
  deployed: true,
53183
- deployedAt: 1787924032013,
53184
- size: 13878,
53185
- hash: "a7f0204700912e26e5a354bee13a1242a2baa218643b3bb22d28481f67f9baf4"
53444
+ deployedAt: 1790179978959,
53445
+ size: 14688,
53446
+ hash: "8edb9b12c784c8d7d153cce97235584c24665a788767ae68713dce91109ab35e"
53186
53447
  },
53187
53448
  staleSpendRecoveryValidator: {
53188
- cid: "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8",
53449
+ cid: "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz",
53189
53450
  authorizedCidHex: cidToHex(
53190
- "QmNuwo4PT4AikAmhMdZgPWCb2mJDwWa9TnUqrqvofjbrT8"
53451
+ "Qmarj59zdSSgivkimryrdvnyZqH5YpTimKj1LivXNBHmNz"
53191
53452
  ),
53192
53453
  name: "Stale Spend Recovery Validator",
53193
53454
  description: "Production Stale Spend Recovery Validator",
53194
53455
  version: "1.1.2",
53195
53456
  deployed: true,
53196
- deployedAt: 1787924048772,
53197
- size: 41424,
53198
- hash: "3c5f028d2bef4344768462993616d45e30d9d44ef126e04d6eb579821d57d99c",
53199
- validatorWalletAddress: "0x82DB9F515957aA380B596C6eA2Bd30CEF181f236",
53457
+ deployedAt: 1790246256280,
53458
+ size: 48143,
53459
+ hash: "ec9236bcbe0af24d3e1844791fc8fe37371bbecd8ce95d02e13f7c6e1fc7d94c",
53460
+ validatorWalletAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C",
53200
53461
  pkp: {
53201
53462
  publicKey: "0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21",
53202
- ethAddress: "0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607"
53463
+ ethAddress: "0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C"
53203
53464
  }
53204
53465
  },
53205
53466
  btcUtxoInvalidator: {
53206
- cid: "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf",
53467
+ cid: "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX",
53207
53468
  authorizedCidHex: cidToHex(
53208
- "QmaNGeWut7EiGwW4zUc2sFSt7RY5NWFgxYboyG333TwrJf"
53469
+ "QmbS44bGcmKYF64Cu35qzsk9sxiU4Umde8Z3q24ZnEbQvX"
53209
53470
  ),
53210
53471
  name: "Btc Utxo Invalidator",
53211
53472
  description: "Production Btc Utxo Invalidator",
53212
53473
  version: "1.0.0",
53213
53474
  deployed: true,
53214
- deployedAt: 1787924133241,
53215
- size: 66026,
53216
- hash: "603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9"
53475
+ deployedAt: 1790246264563,
53476
+ size: 69219,
53477
+ hash: "bda048d8cd6b5a39c2774bcf1320e82d1eea935c2a521006fb8b887e13b6dd8d"
53478
+ },
53479
+ carryCollateralAttestation: {
53480
+ cid: "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8",
53481
+ authorizedCidHex: cidToHex(
53482
+ "QmYWULmXD9S5AmTdQqWqoZ28ctsZQNcXkAgre9G2Xo9dh8"
53483
+ ),
53484
+ name: "Carry Collateral Attestation",
53485
+ description: "LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)",
53486
+ version: "1.0.0",
53487
+ deployed: true,
53488
+ deployedAt: 1790927734070,
53489
+ size: 21156,
53490
+ hash: "05b177e0bb36b0483db4a42d33c1bbbf47eb9ef34ae278459397d51a7f8957ff"
53491
+ },
53492
+ carryFundingAttestation: {
53493
+ cid: "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W",
53494
+ authorizedCidHex: cidToHex(
53495
+ "QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W"
53496
+ ),
53497
+ name: "Carry Funding Attestation",
53498
+ description: "LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)",
53499
+ version: "1.0.0",
53500
+ deployed: true,
53501
+ deployedAt: 1790925699980,
53502
+ size: 7193,
53503
+ hash: "4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9"
53217
53504
  }
53218
53505
  };
53219
53506
  function getDeploymentsForNetwork(network) {
@@ -53981,7 +54268,10 @@ ${errorReport}`);
53981
54268
  BTCSpendAuthorizer: "0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",
53982
54269
  BitcoinProviderRegistry: "0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",
53983
54270
  LITActionValidator: "0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",
53984
- PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"
54271
+ PositionDelegateRegistry: "0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",
54272
+ TermManagerModule: "0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",
54273
+ UCDController: "0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",
54274
+ LiquidationManagerModule: "0x74B28695352E7bf736D6c9F76ccb7B4439477De9"
53985
54275
  },
53986
54276
  11155111: {
53987
54277
  PositionManager: "0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",
@@ -53989,7 +54279,10 @@ ${errorReport}`);
53989
54279
  BTCSpendAuthorizer: "0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",
53990
54280
  BitcoinProviderRegistry: "0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",
53991
54281
  LITActionValidator: "0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",
53992
- PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9"
54282
+ PositionDelegateRegistry: "0x482369De283622E7b05731875ec137d4E3D208F9",
54283
+ TermManagerModule: "0x94Adc6F9558368B1482197584f1fc7133Ecf835b",
54284
+ UCDController: "0x360Bde4e489ee94E26601B206932De09EE60FF04",
54285
+ LiquidationManagerModule: "0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"
53993
54286
  }
53994
54287
  };
53995
54288
  function getPinnedContractAddresses(chainId) {
@@ -54175,10 +54468,10 @@ ${errorReport}`);
54175
54468
  };
54176
54469
  }
54177
54470
  const ratioBigInt = collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n / ucdDebt;
54178
- const collateralRatioBps = Number(ratioBigInt);
54471
+ const collateralRatioBps2 = Number(ratioBigInt);
54179
54472
  return {
54180
54473
  collateralValueUsd,
54181
- collateralRatioBps
54474
+ collateralRatioBps: collateralRatioBps2
54182
54475
  };
54183
54476
  }
54184
54477
  function hasSufficientCollateralForDebt(collateralValueUsd, currentDebt, additionalDebt, requiredRatioBps) {
@@ -55032,6 +55325,17 @@ ${auth.clientId}`;
55032
55325
  );
55033
55326
  }
55034
55327
  }
55328
+ var TIP_READ_FAILURE_PREFIX = "Bitcoin tip-height read failed";
55329
+ var BitcoinTipUnreadableError = class extends Error {
55330
+ constructor(message) {
55331
+ super(message);
55332
+ this.isBitcoinTipUnreadable = true;
55333
+ this.name = "BitcoinTipUnreadableError";
55334
+ }
55335
+ };
55336
+ function isBitcoinTipUnreadableError(error) {
55337
+ return typeof error === "object" && error !== null && error.isBitcoinTipUnreadable === true;
55338
+ }
55035
55339
  var BitcoinDataProvider = class {
55036
55340
  constructor(config) {
55037
55341
  this.config = config;
@@ -55483,27 +55787,12 @@ ${auth.clientId}`;
55483
55787
  if (!data.status.confirmed || !data.status.block_height) {
55484
55788
  return { txid: data.txid ?? txid, confirmations: 0 };
55485
55789
  }
55486
- try {
55487
- const tipResp = await fetch(
55488
- `${this.config.providerUrl}/blocks/tip/height`,
55489
- { signal: controller.signal, headers: await this.withAuth() }
55490
- );
55491
- if (!tipResp.ok) {
55492
- return { txid: data.txid ?? txid, confirmations: 1 };
55493
- }
55494
- const tipBody = (await tipResp.text()).trim();
55495
- const tipHeight = Number.parseInt(tipBody, 10);
55496
- if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
55497
- return { txid: data.txid ?? txid, confirmations: 1 };
55498
- }
55499
- const depth = tipHeight - data.status.block_height + 1;
55500
- return {
55501
- txid: data.txid ?? txid,
55502
- confirmations: depth > 0 ? depth : 0
55503
- };
55504
- } catch {
55505
- return { txid: data.txid ?? txid, confirmations: 1 };
55506
- }
55790
+ const tipHeight = await this.fetchTipHeight(controller.signal);
55791
+ const depth = tipHeight - data.status.block_height + 1;
55792
+ return {
55793
+ txid: data.txid ?? txid,
55794
+ confirmations: depth > 0 ? depth : 0
55795
+ };
55507
55796
  }
55508
55797
  return null;
55509
55798
  } catch (error) {
@@ -55511,12 +55800,55 @@ ${auth.clientId}`;
55511
55800
  if (isAbortError(error)) {
55512
55801
  throw new Error(`Request timeout after ${this.timeout}ms`);
55513
55802
  }
55803
+ if (isBitcoinTipUnreadableError(error)) {
55804
+ throw error;
55805
+ }
55514
55806
  if (getUnknownErrorMessage(error).includes("404")) {
55515
55807
  return null;
55516
55808
  }
55517
55809
  throw error;
55518
55810
  }
55519
55811
  }
55812
+ /**
55813
+ * Current chain tip height from THIS provider — or throw.
55814
+ *
55815
+ * Every exit is a throw naming the provider and the precise failure, because
55816
+ * the only alternative is inventing a confirmation depth (see the call site).
55817
+ * The single `try` exists solely to attach that name to a transport-level
55818
+ * rejection (DNS, TLS, connection reset, abort); it re-throws the cause
55819
+ * verbatim inside the message and never substitutes a value — authorized for
55820
+ * this case by the Batch 2 plan, §C2.
55821
+ *
55822
+ * @param signal - The caller's AbortSignal, so this read shares the same
55823
+ * timeout budget as the transaction fetch it serves.
55824
+ */
55825
+ async fetchTipHeight(signal) {
55826
+ const endpoint = `${this.config.providerUrl}/blocks/tip/height`;
55827
+ let tipResp;
55828
+ try {
55829
+ tipResp = await fetch(endpoint, {
55830
+ signal,
55831
+ headers: await this.withAuth()
55832
+ });
55833
+ } catch (error) {
55834
+ throw new BitcoinTipUnreadableError(
55835
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`
55836
+ );
55837
+ }
55838
+ if (!tipResp.ok) {
55839
+ throw new BitcoinTipUnreadableError(
55840
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`
55841
+ );
55842
+ }
55843
+ const tipBody = (await tipResp.text()).trim();
55844
+ const tipHeight = Number.parseInt(tipBody, 10);
55845
+ if (!Number.isFinite(tipHeight) || tipHeight <= 0) {
55846
+ throw new BitcoinTipUnreadableError(
55847
+ `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height "${tipBody.slice(0, 64)}"`
55848
+ );
55849
+ }
55850
+ return tipHeight;
55851
+ }
55520
55852
  /**
55521
55853
  * Get outputs (vouts) of a Bitcoin transaction
55522
55854
  *
@@ -56154,10 +56486,13 @@ ${auth.clientId}`;
56154
56486
  * only on unanimity. The confirmed-balance consensus the validators run
56155
56487
  * covers `chain_stats` only, so without this the primary provider alone
56156
56488
  * could fabricate an unconfirmed UTXO plus a self-consistent parent proof
56157
- * and inflate the signed balance. Any provider failure or verdict
56158
- * disagreement THROWS (fail-closed) — exclusion on a suppressed proof
56159
- * would deflate the balance and open a wrongful-liquidation window, so
56160
- * neither direction may proceed without agreement.
56489
+ * and inflate the signed balance. Any verdict disagreement THROWS
56490
+ * (fail-closed) — exclusion on a suppressed proof would deflate the balance
56491
+ * and open a wrongful-liquidation window, so neither direction may proceed
56492
+ * without agreement. A provider that cannot state the chain tip — and only
56493
+ * that failure — is dropped from the quorum rather than aborting the read (it
56494
+ * never counts as agreeing), and falling below `minConsensusProviders`
56495
+ * survivors throws — see `verifyParentIsSelfSpendConsensus`.
56161
56496
  *
56162
56497
  * The same per-provider `/tx` fetch also returns the parent's outputs, and
56163
56498
  * every provider must corroborate each claimed UTXO (index, vault address,
@@ -56252,10 +56587,26 @@ ${auth.clientId}`;
56252
56587
  }
56253
56588
  /**
56254
56589
  * Run the self-spend proof against every configured provider and require
56255
- * unanimity. Fail-closed: a provider request failure or a verdict
56256
- * disagreement throws and aborts the balance calculation — see
56590
+ * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:
56591
+ * a verdict mismatch throws and aborts the balance calculation — see
56257
56592
  * classifySelfChange for why exclusion is not a safe fallback here.
56258
56593
  *
56594
+ * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a
56595
+ * provider that could not state the chain tip (`BitcoinTipUnreadableError`).
56596
+ * It is ABSENT from the quorum — never counted as agreeing, never allowed to
56597
+ * decide the verdict — and the policy floor, not "at least one", decides when
56598
+ * that absence is fatal: below `minConsensusProviders` surviving readings
56599
+ * there is no cross-check left to trust, and the read fails loudly naming
56600
+ * every provider that dropped out.
56601
+ *
56602
+ * Why only that class. `getTransaction` now throws on an unreadable tip
56603
+ * instead of fabricating `confirmations: 1`; without this carve-out one flaky
56604
+ * `/blocks/tip/height` endpoint would take every balance and spend path down
56605
+ * with it. Every OTHER failure remains fatal, as before: a provider that
56606
+ * answers "I have never seen that transaction" is making a claim about the
56607
+ * chain rather than suffering an outage, and that shape is precisely the
56608
+ * fabricated-UTXO signature the fail-closed rule exists to catch.
56609
+ *
56259
56610
  * When the parent IS a unanimous self-spend, every provider's view of the
56260
56611
  * parent's OUTPUTS must additionally corroborate the primary's claimed
56261
56612
  * UTXOs (index exists, pays the vault, exact value). Without this, a
@@ -56280,32 +56631,52 @@ ${auth.clientId}`;
56280
56631
  )
56281
56632
  )
56282
56633
  );
56283
- const failures = settled.map((r, i) => ({ r, name: providerName(i) })).filter(
56284
- (x) => x.r.status === "rejected"
56285
- ).map(
56286
- ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`
56287
- );
56634
+ const answered = [];
56635
+ const absences = [];
56636
+ const failures = [];
56637
+ settled.forEach((result, i) => {
56638
+ if (result.status === "fulfilled") {
56639
+ answered.push({ index: i, evaluation: result.value });
56640
+ return;
56641
+ }
56642
+ const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;
56643
+ if (isBitcoinTipUnreadableError(result.reason)) {
56644
+ absences.push(described);
56645
+ return;
56646
+ }
56647
+ failures.push(described);
56648
+ });
56288
56649
  if (failures.length > 0) {
56289
56650
  throw new Error(
56290
56651
  `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join("; ")}`
56291
56652
  );
56292
56653
  }
56293
- const evaluations = settled.map(
56294
- (r) => r.value
56295
- );
56296
- const votes = evaluations.map((e) => e.selfSpend);
56297
- const disagreements = votes.map((vote, i) => ({ vote, name: providerName(i) })).filter((x) => x.vote !== votes[0]).map(
56298
- (x) => `${providerName(0)}=${votes[0]} vs ${x.name}=${x.vote}`
56654
+ const floor = Math.max(1, this.minConsensusProviders);
56655
+ if (answered.length < floor) {
56656
+ throw new Error(
56657
+ `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("; ")}`
56658
+ );
56659
+ }
56660
+ if (absences.length > 0) {
56661
+ litDebugLog(
56662
+ `[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("; ")}`
56663
+ );
56664
+ }
56665
+ const first = answered[0];
56666
+ const disagreements = answered.slice(1).filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend).map(
56667
+ (a) => `${providerName(first.index)}=${first.evaluation.selfSpend} vs ${providerName(a.index)}=${a.evaluation.selfSpend}`
56299
56668
  );
56300
56669
  if (disagreements.length > 0) {
56301
56670
  throw new Error(
56302
56671
  `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`
56303
56672
  );
56304
56673
  }
56305
- if (!votes[0]) {
56674
+ if (!first.evaluation.selfSpend) {
56306
56675
  return false;
56307
56676
  }
56308
- const outputMismatches = evaluations.map((e, i) => e.outputMismatch ? `${providerName(i)} \u2192 ${e.outputMismatch}` : null).filter((m) => m !== null);
56677
+ const outputMismatches = answered.map(
56678
+ (a) => a.evaluation.outputMismatch ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}` : null
56679
+ ).filter((m) => m !== null);
56309
56680
  if (outputMismatches.length > 0) {
56310
56681
  throw new Error(
56311
56682
  `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`
@@ -56548,16 +56919,6 @@ ${auth.clientId}`;
56548
56919
  minConfirmations
56549
56920
  );
56550
56921
  const authorizedSpends = await this.getAuthorizedSpendsFromContract(positionId);
56551
- for (const spend of authorizedSpends) {
56552
- const utxoStillExists = utxoSet.utxos.some(
56553
- (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout
56554
- );
56555
- if (utxoStillExists) {
56556
- throw new Error(
56557
- `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.`
56558
- );
56559
- }
56560
- }
56561
56922
  const authorizedBalance = authorizedSpends.reduce(
56562
56923
  (sum, spend) => sum + spend.satoshis,
56563
56924
  0n
@@ -56853,7 +57214,13 @@ ${auth.clientId}`;
56853
57214
  allowDevSinglePriceProvider: false,
56854
57215
  minBitcoinBalanceConfirmations: 1,
56855
57216
  minBitcoinSpendConfirmations: 1,
56856
- minConsensusProviders: 1
57217
+ // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider
57218
+ // "by design", so the consensus floor was documented as a mainnet-only
57219
+ // guarantee. The registry now holds two, and leaving the floor at 1 meant
57220
+ // Sepolia could never exercise the multi-provider agreement the stale-spend
57221
+ // and balance paths rely on — the one environment where that logic is
57222
+ // supposed to be proved before mainnet.
57223
+ minConsensusProviders: 2
56857
57224
  },
56858
57225
  [
56859
57226
  "ethereum"
@@ -57162,7 +57529,6 @@ function getSepoliaConfig() {
57162
57529
  feeRecipientRegistry: SEPOLIA_CONTRACTS.FeeRecipientRegistry || "",
57163
57530
  positionDelegateRegistry: SEPOLIA_CONTRACTS.PositionDelegateRegistry || "",
57164
57531
  bitcoinWithdrawalAddressRegistry: SEPOLIA_CONTRACTS.BitcoinWithdrawalAddressRegistry || "",
57165
- carryAgentRegistry: SEPOLIA_CONTRACTS.CarryAgentRegistry || "",
57166
57532
  agentDelegationRegistry: SEPOLIA_CONTRACTS.AgentDelegationRegistry || "",
57167
57533
  dhAgentDelegate: SEPOLIA_CONTRACTS.DHAgentDelegate || "",
57168
57534
  agentModuleFactory: SEPOLIA_CONTRACTS.AgentModuleFactory || ""
@@ -57216,7 +57582,6 @@ function getMainnetConfig() {
57216
57582
  feeRecipientRegistry: MAINNET_CONTRACTS.FeeRecipientRegistry || "",
57217
57583
  positionDelegateRegistry: MAINNET_CONTRACTS.PositionDelegateRegistry || "",
57218
57584
  bitcoinWithdrawalAddressRegistry: MAINNET_CONTRACTS.BitcoinWithdrawalAddressRegistry || "",
57219
- carryAgentRegistry: MAINNET_CONTRACTS.CarryAgentRegistry || "",
57220
57585
  agentDelegationRegistry: MAINNET_CONTRACTS.AgentDelegationRegistry || "",
57221
57586
  dhAgentDelegate: MAINNET_CONTRACTS.DHAgentDelegate || "",
57222
57587
  // Empty on mainnet until the factory is deployed there — the ceremony is Sepolia-only.
@@ -58289,6 +58654,51 @@ async function resolveAuthorizationInput(provider, signer, ctx) {
58289
58654
  }
58290
58655
  return { timestamp: result.timestamp, signature: result.signature };
58291
58656
  }
58657
+ var BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
58658
+ function segwitProgramShape(address) {
58659
+ const lower2 = address.trim().toLowerCase();
58660
+ if (!/^(bc1|tb1|bcrt1)/.test(lower2))
58661
+ return null;
58662
+ const sep = lower2.lastIndexOf("1");
58663
+ const data = lower2.slice(sep + 1);
58664
+ if (data.length < 8)
58665
+ return null;
58666
+ const version2 = BECH32_CHARSET.indexOf(data[0]);
58667
+ if (version2 < 0)
58668
+ return null;
58669
+ const programChars = data.length - 1 - 6;
58670
+ return { version: version2, programBytes: Math.floor(programChars * 5 / 8) };
58671
+ }
58672
+ function dustLimitForAddress(address) {
58673
+ const shape = segwitProgramShape(address);
58674
+ if (shape === null)
58675
+ return 546;
58676
+ if (shape.version === 0 && shape.programBytes === 20)
58677
+ return 294;
58678
+ if (shape.version === 0 && shape.programBytes === 32)
58679
+ return 330;
58680
+ if (shape.version === 1 && shape.programBytes === 32)
58681
+ return 330;
58682
+ return 546;
58683
+ }
58684
+ function destinationDustShortfall(targetAmount, networkFee, destination) {
58685
+ const limit = dustLimitForAddress(destination);
58686
+ return targetAmount - networkFee < limit ? limit : null;
58687
+ }
58688
+ function calculateMintFee(params) {
58689
+ const { mintAmount, mintTimestamp, originationFeeBps, previousExpiryAt, selectedTerm, totalTerm } = params;
58690
+ let mintFee = mintAmount * BigInt(originationFeeBps) / 10000n;
58691
+ if (previousExpiryAt > 0 && mintTimestamp < previousExpiryAt) {
58692
+ const tailSeconds = BigInt(previousExpiryAt) - BigInt(mintTimestamp);
58693
+ const originalTermMonths = totalTerm - selectedTerm;
58694
+ const originalTermSeconds = BigInt(
58695
+ originalTermMonths === 12 ? 365 * 86400 : originalTermMonths * 30 * 86400
58696
+ );
58697
+ const tailFee = tailSeconds * BigInt(originationFeeBps) * mintAmount / (10000n * originalTermSeconds);
58698
+ mintFee = mintFee + tailFee;
58699
+ }
58700
+ return mintFee;
58701
+ }
58292
58702
  function baseMintFeeWei(mintAmountWei, originationFeeBps) {
58293
58703
  if (mintAmountWei < 0n)
58294
58704
  throw new Error("baseMintFeeWei: mintAmountWei cannot be negative");
@@ -58307,20 +58717,34 @@ function debtAfterMintExceedsLoanCap(params) {
58307
58717
  }
58308
58718
  return currentDebtWei + mintAmountWei + mintFeeWei > maxLoanWei;
58309
58719
  }
58310
- function maxPrincipalWithinLoanCap(params) {
58311
- const { maxLoanWei, currentDebtWei, originationFeeBps } = params;
58312
- if (maxLoanWei < 0n || currentDebtWei < 0n) {
58313
- throw new Error("maxPrincipalWithinLoanCap: amounts cannot be negative");
58720
+ function collateralRatioBps(sats, price8, debtWei) {
58721
+ if (sats < 0n || price8 < 0n) {
58722
+ throw new Error("collateralRatioBps: sats and price cannot be negative");
58314
58723
  }
58315
- if (!Number.isInteger(originationFeeBps) || originationFeeBps < 0 || originationFeeBps > 1e4) {
58316
- throw new Error(
58317
- `maxPrincipalWithinLoanCap: originationFeeBps must be an integer in [0, 10000] (got ${String(originationFeeBps)})`
58318
- );
58724
+ if (debtWei <= 0n) {
58725
+ throw new Error("collateralRatioBps: debt must be positive");
58319
58726
  }
58320
- const room = maxLoanWei - currentDebtWei;
58321
- if (room <= 0n)
58322
- return 0n;
58323
- return room * 10000n / (10000n + BigInt(originationFeeBps));
58727
+ return sats * price8 * 100n * 10000n / debtWei;
58728
+ }
58729
+ function collateralRatioPercentString(sats, price8, debtWei) {
58730
+ const bps = collateralRatioBps(sats, price8, debtWei);
58731
+ return `${bps / 100n}.${(bps % 100n).toString().padStart(2, "0")}`;
58732
+ }
58733
+ function maxPrincipalForFee(room, fee) {
58734
+ if (room < 0n)
58735
+ throw new Error("maxPrincipalForFee: room cannot be negative");
58736
+ if (fee(0n) !== 0n)
58737
+ throw new Error("maxPrincipalForFee: fee(0) must be 0");
58738
+ let lo = 0n;
58739
+ let hi = room;
58740
+ while (lo < hi) {
58741
+ const mid = (lo + hi + 1n) / 2n;
58742
+ if (mid + fee(mid) <= room)
58743
+ lo = mid;
58744
+ else
58745
+ hi = mid - 1n;
58746
+ }
58747
+ return lo;
58324
58748
  }
58325
58749
  function buildLoginDomain(chainId) {
58326
58750
  return {
@@ -70483,9 +70907,17 @@ async function mintAgentPkp(params) {
70483
70907
  }
70484
70908
  var AGENT_STATUS = { None: 0, Active: 1, Revoked: 2 };
70485
70909
  function planAgentBinding(params) {
70486
- const { isActive, record, nowSeconds } = params;
70910
+ const { isActive, paused, record, nowSeconds } = params;
70911
+ if (typeof paused !== "boolean") {
70912
+ throw new Error("planAgentBinding: `paused` must be read from the registry (boolean required)");
70913
+ }
70487
70914
  if (isActive)
70488
70915
  return { kind: "reuse", agent: record.agent };
70916
+ if (paused) {
70917
+ throw new Error(
70918
+ "AgentDelegationRegistry is paused \u2014 agent delegation cannot be changed until it is unpaused."
70919
+ );
70920
+ }
70489
70921
  const status = Number(record.status);
70490
70922
  if (status === AGENT_STATUS.None || status === AGENT_STATUS.Revoked) {
70491
70923
  return { kind: "register" };
@@ -70495,7 +70927,7 @@ function planAgentBinding(params) {
70495
70927
  }
70496
70928
  if (Number(record.validUntil) > nowSeconds) {
70497
70929
  throw new Error(
70498
- "AgentDelegationRegistry reports an unexpired agent as inactive \u2014 the registry is paused. Agent delegation cannot be changed until it is unpaused."
70930
+ "AgentDelegationRegistry returned an inconsistent read (an unexpired, unpaused Active agent reported inactive); retry."
70499
70931
  );
70500
70932
  }
70501
70933
  return { kind: "rotate" };
@@ -71664,7 +72096,7 @@ function normalizeBigNumberish(value) {
71664
72096
  }
71665
72097
  return value;
71666
72098
  }
71667
- if (typeof value === "object" && value !== null && "toString" in value && typeof value.toString === "function") {
72099
+ if (typeof value === "object" && value !== null && "toString" in value && typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
71668
72100
  const result = value.toString();
71669
72101
  if (typeof result === "object" && result !== null && "_hex" in result) {
71670
72102
  const resultObj = result;
@@ -73086,12 +73518,21 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
73086
73518
  maxLoanWei: maxLoanValueWei
73087
73519
  })) {
73088
73520
  const debtAfterWei = currentDebtWei + requestAmountWei + baseFeeWei;
73521
+ const suggestionStamp = calculateNextQuantumTimestamp();
73522
+ const room = maxLoanValueWei > currentDebtWei ? maxLoanValueWei - currentDebtWei : 0n;
73089
73523
  const maxPrincipalUcd = Number(
73090
- maxPrincipalWithinLoanCap({
73091
- maxLoanWei: maxLoanValueWei,
73092
- currentDebtWei,
73093
- originationFeeBps: positionTerm.originationFeeBps
73094
- }) / BigInt(10 ** 18)
73524
+ maxPrincipalForFee(
73525
+ room,
73526
+ (principal) => calculateMintFee({
73527
+ mintAmount: principal,
73528
+ mintTimestamp: suggestionStamp,
73529
+ originationFeeBps: positionTerm.originationFeeBps,
73530
+ expiryAt: Number(position2.expiryAt),
73531
+ previousExpiryAt: Number(position2.previousExpiryAt),
73532
+ selectedTerm: Number(position2.selectedTerm),
73533
+ totalTerm: Number(position2.totalTerm)
73534
+ })
73535
+ ) / BigInt(10 ** 18)
73095
73536
  );
73096
73537
  return {
73097
73538
  success: false,
@@ -74169,11 +74610,7 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
74169
74610
  const debt = positionDetails.debt || positionDetails.ucdDebt || "0";
74170
74611
  const btcPrice2 = litActionResult.btcPrice || "0";
74171
74612
  const btcVaultBalance = litActionResult.btcAmountSats || positionDetails.btcVaultBalance || "0";
74172
- const usdPricePerBTC = Number(btcPrice2) / 1e8;
74173
- const btcAmount = Number(btcVaultBalance) / 1e8;
74174
- const btcValueUSD = btcAmount * usdPricePerBTC;
74175
- const debtUSD = Number(debt) / 1e18;
74176
- const ratio = debtUSD > 0 ? (btcValueUSD / debtUSD * 100).toFixed(2) : "0.00";
74613
+ const ratio = BigInt(debt) > 0n ? collateralRatioPercentString(BigInt(btcVaultBalance), BigInt(btcPrice2), BigInt(debt)) : "0.00";
74177
74614
  const message = formatLiquidationSkippedMessage(
74178
74615
  request.positionId,
74179
74616
  ratio,
@@ -74662,14 +75099,15 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
74662
75099
  }
74663
75100
  const debt = positionDetails.debt || positionDetails.ucdDebt || "0";
74664
75101
  const btcPrice2 = litActionResult.btcPrice || "0";
74665
- const ratio = debt !== "0" ? (Number(positionDetails.btcVaultBalance || "0") * Number(btcPrice2) / Number(debt) * 100 / 1e8).toFixed(2) : "0.00";
75102
+ const btcVaultBalance = litActionResult.btcAmountSats || positionDetails.btcVaultBalance || "0";
75103
+ const ratio = BigInt(debt) > 0n ? collateralRatioPercentString(BigInt(btcVaultBalance), BigInt(btcPrice2), BigInt(debt)) : "0.00";
74666
75104
  const message = formatLiquidationSuccessMessage(
74667
75105
  request.positionId,
74668
75106
  ratio,
74669
75107
  `${liquidationThreshold / 100}`,
74670
75108
  // Convert to percentage
74671
75109
  positionDetails.btcVault || "unknown",
74672
- positionDetails.btcVaultBalance || "0",
75110
+ btcVaultBalance,
74673
75111
  debt,
74674
75112
  btcPrice2
74675
75113
  );
@@ -77153,6 +77591,17 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
77153
77591
  error: `networkFee=${request.networkFee} is \u2265 50% of targetAmount=${request.targetAmount}. Refusing to broadcast \u2014 real Bitcoin fees are typically <1% of value.`
77154
77592
  };
77155
77593
  }
77594
+ const destinationDustLimit = destinationDustShortfall(
77595
+ request.targetAmount,
77596
+ request.networkFee,
77597
+ request.destination
77598
+ );
77599
+ if (destinationDustLimit !== null) {
77600
+ return {
77601
+ success: false,
77602
+ 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.`
77603
+ };
77604
+ }
77156
77605
  const [txid, voutStr] = request.utxoIdentifier.split(":");
77157
77606
  const vout = parseInt(voutStr || "0", 10);
77158
77607
  if (!txid || isNaN(vout)) {
@@ -78628,8 +79077,9 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
78628
79077
  const user = await signer.getAddress();
78629
79078
  const registry = AgentDelegationRegistry__factory.connect(addr, signer);
78630
79079
  let agentAddress;
78631
- const [isActive, record, latestBlock] = await Promise.all([
79080
+ const [isActive, paused, record, latestBlock] = await Promise.all([
78632
79081
  registry.isAgentActive(user),
79082
+ registry.paused(),
78633
79083
  registry.agentOf(user),
78634
79084
  this.getProviderOrThrow().getBlock("latest")
78635
79085
  ]);
@@ -78641,7 +79091,7 @@ Message: ${causeMessage}${quantumContext}${loanCapDiagnostics}${mintDebtDiagnost
78641
79091
  /* HIGH */
78642
79092
  });
78643
79093
  }
78644
- const plan = planAgentBinding({ isActive, record, nowSeconds: latestBlock.timestamp });
79094
+ const plan = planAgentBinding({ isActive, paused, record, nowSeconds: latestBlock.timestamp });
78645
79095
  if (plan.kind === "reuse") {
78646
79096
  agentAddress = plan.agent;
78647
79097
  } else {
@@ -82106,11 +82556,16 @@ var RealUpstreamPlugin = class {
82106
82556
  this.src("subgraph")
82107
82557
  );
82108
82558
  },
82109
- getPositionEvents: async () => upFail({
82110
- kind: "unavailable",
82111
- source: "subgraph",
82112
- message: "event history is not mapped in this delivery of the real adapter (indexer projection pending)"
82113
- })
82559
+ getPositionEvents: async () => (
82560
+ // PERMANENT capability gap, not a transient outage: the real adapter has no indexer
82561
+ // projection for event history, and this build never will. `unsupported` →
82562
+ // NOT_IMPLEMENTED so the guide does not tell the model to retry it (C-44).
82563
+ upFail({
82564
+ kind: "unsupported",
82565
+ source: "subgraph",
82566
+ 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"
82567
+ })
82568
+ )
82114
82569
  };
82115
82570
  this.chain = {
82116
82571
  getPositionDetails: (id) => this.chainRead(() => this.readPositionDetails(id)),
@@ -82456,7 +82911,7 @@ var RealUpstreamPlugin = class {
82456
82911
  }
82457
82912
  if (mode === "external") {
82458
82913
  const borrower = await rt.manager.resolveBorrowerForWrite();
82459
- if (!borrower) {
82914
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: false })) {
82460
82915
  return {
82461
82916
  ok: false,
82462
82917
  failure: {
@@ -82506,6 +82961,20 @@ var RealUpstreamPlugin = class {
82506
82961
  }
82507
82962
  };
82508
82963
  }
82964
+ /** Hosted tier: the SIWE borrower is bound from boot, so "bound" no longer implies a
82965
+ * wallet can sign. Refuse as "no wallet is connected" instead of starting a ceremony
82966
+ * nobody can answer.
82967
+ *
82968
+ * `allowCachedLogin` is for `connectExternal` ONLY: a still-valid lit-ops login lets it
82969
+ * succeed without a wallet (it signs nothing). A WRITE always needs a fresh wallet
82970
+ * signature (ExternalEoaDHSigner), so a cached JWT must not admit it — that would queue
82971
+ * an approval with no wallet attached to sign it. */
82972
+ pinnedWalletUnreachable(borrower, opts) {
82973
+ if (!this.runtime?.manager.identityPinned()) return false;
82974
+ if (this.runtime.bridge.walletState() !== null) return false;
82975
+ if (!opts.allowCachedLogin) return true;
82976
+ return !this.sessionCache.get(`external:${borrower.toLowerCase()}`)?.hasValidToken();
82977
+ }
82509
82978
  /** The EXPLICIT login action (plan 10 OV-10 / A0.7): the ONLY path that may summon the
82510
82979
  * wallet for a lit-ops login outside a write ceremony. Binds the borrower on success —
82511
82980
  * the first verified ceremony fixes the identity. */
@@ -82516,7 +82985,7 @@ var RealUpstreamPlugin = class {
82516
82985
  return { ok: false, reason: `the active mode is '${manager.mode()}' \u2014 run signer_setup action 'use' mode 'external' first` };
82517
82986
  }
82518
82987
  const borrower = manager.borrowerForWrite();
82519
- if (!borrower) {
82988
+ if (!borrower || this.pinnedWalletUnreachable(borrower, { allowCachedLogin: true })) {
82520
82989
  return { ok: false, reason: "no wallet is connected \u2014 open the approval page (signer_setup action 'status') and connect your wallet first" };
82521
82990
  }
82522
82991
  const key = `external:${borrower.toLowerCase()}`;
@@ -83053,6 +83522,81 @@ var RealUpstreamPlugin = class {
83053
83522
  var fs4 = __toESM(require("fs"));
83054
83523
  var http3 = __toESM(require("http"));
83055
83524
  var import_node_crypto7 = require("crypto");
83525
+ var import_ethers50 = require("ethers");
83526
+
83527
+ // src/util/brand-assets.ts
83528
+ 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>`;
83529
+ var FAVICON_DATA_URI = `data:image/svg+xml,${encodeURIComponent(FAVICON_SVG).replace(/'/g, "%27")}`;
83530
+ var GVN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UTcoBGXWIgiF1hxoj+9u9+84Djym0sXlTryN/tRDz525WQvCIIgcEGzGzIHtN/3e5qo7Xbmw+LH/U0PwNis4z8snQD4c/+0TX8+U5cUcmrArZYjJz+4lrPUpteOioLWH59S33282MT9Sb5bfATs5pD7zz+dySYvCIIgVEExrVP1HbsW7K/0MaPTqH+oMBv4zWrpBnVcxWDDloY6giAIQq1xCJvDgp3hnBilrLrY4Kj1IgiCIAiCkBR+f78oi7fKHtBH1S9ruOiL3lzmshxBEARBSI3R7o2jZc39MsCRvujLXpYjCIIgCCnhT/xbF1+MjDQvBMClvuhLO6hDEARBEFLicsMufW4uZhoUAoDaUo4Op/BRgEpGEwqCIAiCEI7Rhl0002S0v8RFJ0CjVqipx9ALsHFidkUECIIgCEJN+ad5+ni0e+Po6Z+4EAAUBbAjc6oR8UHZowkFQRAEQVick/ynTYtuZ/i1debJ5e6SX8zxujTukHU0oSAIgiAIYaFW3S4DCv0PG9cdrant9uXnfTEMKMdsdDhKMZrwJN+V/gCCIAiCEDlk4h/d/Gk/zz6ZsVMnvxAAlArQaO6NigBU+Ip7KpEgCIIgCNfn2Ow+yLT+bPOnaaaTBkvhpB9EA3KM029HJ+U5cF1j7P12Q2ajC4IgCEIM0Kl/0MOnM3xs2uY/eM5kSATkLns54gkYcpAb80SEgCAIgiBUw7iNn/AH93eNT2Zr2kjpKwXAEJoDDYhfpAAoIgAOD8CZd8baI2j0ZKytIAiCIASGptNCr9HSqrHh0G4oVFSld2lkPZ6hs09W9aPns/zMmQQAQdGAnlU7ONJRSBAEQRCEKHidfTIPp536R5lZAAwZCgGFeHfUHyAIgiAIQpngmXXml5Vz93yejf/iv4YFOHVPO9bCBiJ5BLDlf9g3PjHQBEEQBEEQAoI+ve5+8wfvI+dT70rB0RoW03wFQRAEQRBm5/8BP0+mvgFrTN4AAAAASUVORK5CYII=";
83531
+
83532
+ // src/util/house-style.ts
83533
+ var APP_BACKGROUND_ORIGIN = "https://images.diamondhands.credit";
83534
+ var APP_BACKGROUND_URL = `${APP_BACKGROUND_ORIGIN}/bg-diamond-hands.png`;
83535
+ var FONT_ORIGIN = "https://images.gvnr.xyz";
83536
+ var MANROPE_BASE = `${FONT_ORIGIN}/fonts/manrope`;
83537
+ var HOUSE_CSP_EXTRA = {
83538
+ "img-src": [APP_BACKGROUND_ORIGIN, "data:"],
83539
+ "font-src": [FONT_ORIGIN]
83540
+ };
83541
+ var HOUSE_HEAD_LINKS = `<link rel="icon" type="image/svg+xml" href="${FAVICON_DATA_URI}">
83542
+ <link rel="apple-touch-icon" href="${FAVICON_DATA_URI}">`;
83543
+ var MANROPE_WEIGHTS = [
83544
+ [300, "Light"],
83545
+ [400, "Regular"],
83546
+ [500, "Medium"],
83547
+ [600, "SemiBold"],
83548
+ [700, "Bold"]
83549
+ ];
83550
+ var HOUSE_BASE_CSS = `
83551
+ ${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")}
83552
+ * { box-sizing: border-box; }
83553
+ html { min-height: 100%; background: #000006; }
83554
+ body { margin: 0; min-height: 100vh; color: #fff; font: 14px/1.5 "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
83555
+ background: #000006 url("${APP_BACKGROUND_URL}") center / cover no-repeat fixed; }
83556
+ .house-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem; }
83557
+ @media (min-width: 768px) { .house-header { padding: 1rem 2.5rem; } }
83558
+ .house-header > img { height: 1.92rem; width: auto; display: block; flex: none; }
83559
+ /* Narrow viewports: the chip may shrink (its label ellipsises), and below 400px the label
83560
+ is dropped so logo + chip icon always fit a 320px phone with no horizontal page scroll. */
83561
+ .house-header .chip { min-width: 0; }
83562
+ .chip-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
83563
+ /* ".house-header .chip", not ".chip": the base .chip rule below declares padding too, and at
83564
+ equal specificity the LATER rule wins regardless of the media query; this selector outranks it. */
83565
+ @media (max-width: 400px) { .chip-label { display: none; } .house-header .chip { padding: 0.4rem 0.6rem; } }
83566
+ .chip { display: inline-flex; align-items: center; gap: 0.45rem; padding: 0.4rem 0.85rem; border-radius: 999px;
83567
+ 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);
83568
+ font-size: 0.8rem; font-weight: 600; color: #dbff91; white-space: nowrap; }
83569
+ .chip img { height: 1rem; }
83570
+ main { max-width: 34rem; margin: 2.5rem auto 3rem; padding: 0 1rem; }
83571
+ .panel { background: #121212; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 1rem;
83572
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); }
83573
+ @media (min-width: 768px) { .panel { padding: 1.25rem; } }
83574
+ h1 { font-size: 1.25rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 1rem; }
83575
+ @media (min-width: 768px) { h1 { font-size: 1.5rem; margin-bottom: 1.25rem; } }
83576
+ h2 { font-size: 1rem; font-weight: 600; line-height: 1.375; color: #fafafa; margin: 0 0 0.75rem; }
83577
+ p { margin: 0 0 1rem; color: #e5e5e5; font-size: 0.875rem; font-weight: 300; line-height: 1.5; }
83578
+ button { font: inherit; font-size: 0.875rem; cursor: pointer; border: 0; display: inline-flex; align-items: center; justify-content: center;
83579
+ min-height: 2.75rem; padding: 0.65rem 1.25rem; transition: opacity 0.2s, background-color 0.2s; }
83580
+ button:focus-visible { outline: 2px solid #84cc16; outline-offset: 2px; }
83581
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
83582
+ /* Primary = lime-700 (#4d7c0f): white 14px text on it is 4.99:1 (WCAG AA needs 4.5:1; the
83583
+ brighter #65a30d was 3.09:1). Hover = lime-800 (#3f6212), 7.08:1. A test recomputes both. */
83584
+ .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); }
83585
+ .btn-primary:hover:not(:disabled) { background: #3f6212; }
83586
+ .btn-secondary { background: #34440e; color: #dbff91; font-weight: 500; border-radius: 20px; }
83587
+ .btn-secondary:hover:not(:disabled) { background: #3d5210; }
83588
+ .btn-danger { background: transparent; color: #fca5a5; font-weight: 600; border-radius: 12px; border: 1px solid rgba(248, 113, 113, 0.45); }
83589
+ .btn-danger:hover:not(:disabled) { background: rgba(220, 38, 38, 0.15); }
83590
+ /* A QR needs dark-on-light to scan: it keeps a white plate on the dark page. */
83591
+ .qr-plate { max-width: 16rem; margin-top: 1rem; background: #fff; border-radius: 12px; padding: 0.5rem; }
83592
+ .qr-plate svg { width: 100%; height: auto; display: block; }
83593
+ `;
83594
+ function houseHeader(label) {
83595
+ return `<header class="house-header">
83596
+ <img src="${GVNR_PILL_LOGO_DATA_URI}" alt="GVNR">
83597
+ <span class="chip"><img src="${FAVICON_DATA_URI}" alt=""><span class="chip-label">${label}</span></span>
83598
+ </header>`;
83599
+ }
83056
83600
 
83057
83601
  // src/boundary/upstream/shared/external-bridge/approval-page.ts
83058
83602
  function renderApprovalPage(sessionId, nonce) {
@@ -83062,46 +83606,47 @@ function renderApprovalPage(sessionId, nonce) {
83062
83606
  <meta charset="utf-8">
83063
83607
  <meta name="viewport" content="width=device-width, initial-scale=1">
83064
83608
  <title>Diamond Hands \u2014 signature approval</title>
83609
+ ${HOUSE_HEAD_LINKS}
83065
83610
  <style>
83066
- :root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --text:#e6edf3; --dim:#8b949e;
83067
- --accent:#58a6ff; --approve:#238636; --reject:#da3633; }
83068
- * { box-sizing:border-box; }
83069
- body { margin:0; font:15px/1.5 system-ui,sans-serif; background:var(--bg); color:var(--text);
83070
- display:flex; min-height:100vh; align-items:center; justify-content:center; }
83071
- main { width:min(560px,94vw); }
83072
- h1 { font-size:18px; font-weight:600; letter-spacing:.02em; }
83073
- h1 span { color:var(--accent); }
83074
- .panel { background:var(--panel); border:1px solid var(--line); border-radius:10px; padding:20px; margin-top:12px; }
83075
- .status { color:var(--dim); font-size:13px; }
83076
- .card { white-space:pre-wrap; font-family:ui-monospace,monospace; font-size:14px;
83077
- background:var(--bg); border:1px solid var(--line); border-radius:8px; padding:14px; margin:14px 0; }
83078
- .action { text-transform:uppercase; letter-spacing:.08em; font-size:12px; color:var(--accent); }
83079
- button { border:0; border-radius:8px; padding:10px 22px; font-size:15px; color:#fff; cursor:pointer; }
83080
- #approve { background:var(--approve); margin-right:10px; }
83081
- #reject { background:var(--reject); }
83082
- #wallet { font-family:ui-monospace,monospace; font-size:12px; color:var(--dim); margin-top:10px; }
83611
+ ${HOUSE_BASE_CSS}
83612
+ /* \u2500\u2500 approval page only \u2500\u2500 */
83613
+ main { max-width: 36rem; }
83614
+ .status { color:#a1a1a1; font-size:0.875rem; }
83615
+ .action { text-transform:uppercase; letter-spacing:.08em; font-size:0.75rem; font-weight:600; color:#dbff91; margin-top:0.25rem; }
83616
+ /* The decoded card IS the operation (decode-equivalence): kept monospace and pre-wrapped
83617
+ exactly as the server rendered it, on an inset well darker than the panel. */
83618
+ .card { white-space:pre-wrap; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.875rem; color:#fafafa;
83619
+ background:#0a0a0a; border:1px solid rgba(255,255,255,0.1); border-radius:10px; padding:14px; margin:0.75rem 0 1rem; }
83620
+ .actions { display:flex; flex-wrap:wrap; gap:0.75rem; }
83621
+ #deadline { margin-bottom:1rem; }
83622
+ #wallet { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:0.75rem; color:#a1a1a1; margin-top:1rem; }
83623
+ #wallet:empty { display:none; }
83624
+ #wc { margin-top:1.25rem; border-top:1px solid rgba(255,255,255,0.06); padding-top:1rem; }
83625
+ #wc-uri { user-select:all; word-break:break-all; font-size:0.75rem; }
83626
+ #wc-hint { margin-top:0.75rem; }
83083
83627
  .hidden { display:none; }
83084
83628
  </style>
83085
83629
  </head>
83086
83630
  <body>
83631
+ ${houseHeader("Diamond Hands \xB7 signature approval")}
83087
83632
  <main>
83088
- <h1><span>\u25C6</span> Diamond Hands \u2014 signature approval</h1>
83633
+ <h1>Signature approval</h1>
83089
83634
  <div class="panel">
83090
83635
  <div id="status" class="status">Connecting to your wallet\u2026</div>
83091
83636
  <div id="request" class="hidden">
83092
83637
  <div id="action" class="action"></div>
83093
83638
  <div id="card" class="card"></div>
83094
83639
  <div id="deadline" class="status hidden"></div>
83095
- <button id="approve">Approve in wallet</button>
83096
- <button id="reject">Reject</button>
83640
+ <div class="actions">
83641
+ <button id="approve" class="btn-primary">Approve in wallet</button>
83642
+ <button id="reject" class="btn-danger">Reject</button>
83643
+ </div>
83097
83644
  </div>
83098
83645
  <div id="wallet"></div>
83099
- <div id="wc" style="margin-top:14px; border-top:1px solid var(--line); padding-top:12px;">
83100
- <button id="wc-connect" style="background:var(--panel); border:1px solid var(--line); color:var(--text);">
83101
- Use a mobile wallet instead (WalletConnect)
83102
- </button>
83103
- <div id="wc-qr" class="hidden" style="background:#fff; border-radius:8px; padding:8px; margin-top:10px; max-width:280px;"></div>
83104
- <div id="wc-uri" class="card hidden" style="user-select:all; word-break:break-all; font-size:12px;"></div>
83646
+ <div id="wc">
83647
+ <button id="wc-connect" class="btn-secondary">Use a mobile wallet instead (WalletConnect)</button>
83648
+ <div id="wc-qr" class="qr-plate hidden"></div>
83649
+ <div id="wc-uri" class="card hidden"></div>
83105
83650
  <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>
83106
83651
  </div>
83107
83652
  </div>
@@ -83176,21 +83721,63 @@ async function healChain() {
83176
83721
  }).catch(() => undefined);
83177
83722
  }
83178
83723
  await readWallet();
83179
- await post(BASE + "hello", { account: account, chainId: chainId });
83724
+ await sayHello();
83180
83725
  showWallet();
83181
83726
  }
83182
83727
 
83728
+ function utf8Hex(text) {
83729
+ return "0x" + Array.from(new TextEncoder().encode(text)).map((b) => b.toString(16).padStart(2, "0")).join("");
83730
+ }
83731
+
83732
+ // Presence proof: the bridge only believes a wallet is at this page once the wallet has
83733
+ // SIGNED a short statement naming this page's origin, the chain and a per-page nonce. Saying
83734
+ // an address proves nothing (it is public); signing proves the key is here. One prompt per
83735
+ // page session: once this account has proven itself the bridge accepts later hellos for it
83736
+ // (a chain switch) without asking the wallet again.
83737
+ let provenFor = null;
83738
+ async function sayHello() {
83739
+ let signature;
83740
+ if (provenFor === null || provenFor.toLowerCase() !== String(account).toLowerCase()) {
83741
+ const ch = await fetch(BASE + "challenge?s=" + SESSION + "&chainId=" + chainId).then((r) => r.json());
83742
+ showIdleStatus("Sign the short statement in your wallet to prove it is yours \u2014 it moves no funds.");
83743
+ signature = await window.ethereum.request({ method: "personal_sign", params: [utf8Hex(ch.statement), account] });
83744
+ }
83745
+ const r = await post(BASE + "hello", { account: account, chainId: chainId, signature: signature });
83746
+ if (!r.ok) {
83747
+ const b = await r.json().catch(() => ({}));
83748
+ showStatus("This wallet was not accepted: " + (b.error || "HTTP " + r.status));
83749
+ return false;
83750
+ }
83751
+ provenFor = account;
83752
+ return true;
83753
+ }
83754
+
83755
+ // The stream opens at load, so a card can be on screen BEFORE connect() finishes. The status
83756
+ // line then belongs to that card (its review / mobile-wallet guidance), and connection
83757
+ // progress must not overwrite it. Connection progress lines (idle / "sign the statement", whose
83758
+ // wallet popup is self-explanatory) go through here; failures (a refused hello, a lost
83759
+ // stream, a wrong network) still show unconditionally.
83760
+ function showIdleStatus(text) {
83761
+ if (current !== null) return;
83762
+ showStatus(text);
83763
+ }
83764
+
83183
83765
  async function connect() {
83184
- if (!window.ethereum) { showStatus("No wallet detected \u2014 install MetaMask (or open this page in a wallet browser)."); return; }
83766
+ if (!window.ethereum) {
83767
+ // The event stream is already open (see the bottom of this script) \u2014 a phone paired
83768
+ // below still mirrors its cards here.
83769
+ showIdleStatus("No browser wallet detected \u2014 use the mobile wallet option below, or install MetaMask (or open this page in a wallet browser).");
83770
+ return;
83771
+ }
83185
83772
  await window.ethereum.request({ method: "eth_requestAccounts" });
83186
83773
  await readWallet();
83187
- await post(BASE + "hello", { account: account, chainId: chainId });
83774
+ const accepted = await sayHello();
83188
83775
  showWallet();
83189
83776
  window.ethereum.on("accountsChanged", onAccountsChanged);
83190
83777
  window.ethereum.on("chainChanged", onChainChanged);
83778
+ if (!accepted) return;
83191
83779
  await healChain();
83192
- showStatus("Connected. Waiting for a signature request\u2026");
83193
- listen();
83780
+ showIdleStatus("Connected. Waiting for a signature request\u2026");
83194
83781
  }
83195
83782
 
83196
83783
  // Handlers trust the EVENT payloads \u2014 re-reading eth_accounts/eth_chainId here races the
@@ -83200,6 +83787,8 @@ async function onAccountsChanged(accounts) {
83200
83787
  await post(BASE + "wallet-event", { account: account, chainId: chainId });
83201
83788
  showWallet();
83202
83789
  invalidatePageRequests("Wallet changed \u2014 pending request invalidated.");
83790
+ // The bridge adopts no account from an event alone \u2014 a different account proves itself.
83791
+ if (account) await sayHello();
83203
83792
  }
83204
83793
 
83205
83794
  async function onChainChanged(cid) {
@@ -83209,8 +83798,14 @@ async function onChainChanged(cid) {
83209
83798
  invalidatePageRequests("Network changed \u2014 pending request invalidated.");
83210
83799
  }
83211
83800
 
83801
+ // ONE stream per page, opened at load whatever wallet this browser has: a phone paired
83802
+ // through WalletConnect needs no injected wallet, and its read-only mirror arrives on this
83803
+ // stream. Opening it proves nothing \u2014 the bridge sends this page NOTHING until a person is
83804
+ // proven (a signed hello, or a pairing a phone answered).
83805
+ let es = null;
83212
83806
  function listen() {
83213
- const es = new EventSource(BASE + "events?s=" + SESSION);
83807
+ if (es !== null) return;
83808
+ es = new EventSource(BASE + "events?s=" + SESSION);
83214
83809
  es.onmessage = (ev) => {
83215
83810
  const next = JSON.parse(ev.data);
83216
83811
  // A later frame for an id REPLACES the earlier one: driveWc re-stamps a personal-sign
@@ -83402,6 +83997,7 @@ document.getElementById("wc-connect").onclick = async () => {
83402
83997
  showStatus("Scan the QR (or paste the code) in your mobile wallet \u2014 it becomes the signing wallet.");
83403
83998
  };
83404
83999
 
84000
+ listen();
83405
84001
  connect();
83406
84002
  </script>
83407
84003
  </body>
@@ -83510,6 +84106,16 @@ function htmlPageSecurityHeaders(extra) {
83510
84106
 
83511
84107
  // src/boundary/upstream/shared/external-bridge/bridge.ts
83512
84108
  var MAX_SESSIONS = 16;
84109
+ var MAX_PENDING_PAIRINGS = 64;
84110
+ function presenceStatement(origin2, chainId, nonce) {
84111
+ return [
84112
+ "Diamond Hands approval page",
84113
+ "Sign to prove this wallet is yours. This moves no funds and approves no operation.",
84114
+ `Origin: ${origin2}`,
84115
+ `Chain ID: ${chainId}`,
84116
+ `Session nonce: ${nonce}`
84117
+ ].join("\n");
84118
+ }
83513
84119
  var DEFAULT_EXPIRY_MS = 5 * 60 * 1e3;
83514
84120
  var DEFAULT_ATTACH_GRACE_MS = 60 * 1e3;
83515
84121
  var DEFAULT_HOSTED_ATTACH_GRACE_MS = 180 * 1e3;
@@ -83523,6 +84129,7 @@ function wcDeclineOrFault(e) {
83523
84129
  }
83524
84130
  var SignatureBridge = class {
83525
84131
  clock;
84132
+ sweepIntervalMs;
83526
84133
  /** Lowercased at construction so every comparison is case-flat — EIP-55 checksum casing
83527
84134
  * differs between what SIWE signs and what a wallet reports for the SAME address. */
83528
84135
  boundAccount;
@@ -83553,11 +84160,20 @@ var SignatureBridge = class {
83553
84160
  wcTransport = null;
83554
84161
  /** True while a WalletConnect session is THE wallet — ceremonies route over WC. */
83555
84162
  wcActive = false;
84163
+ /** Which page session asked for which pairing (pairing id → session id). The transport's
84164
+ * `onSession` says WHICH PAIRING a phone answered; this says whose it was. The previous
84165
+ * "most recent asker" guess let a second session claim the credit for a QR the user's
84166
+ * phone scanned (Sentinel 2 PoC-B). */
84167
+ pairingOwners = /* @__PURE__ */ new Map();
83556
84168
  keystoreUnlock;
83557
84169
  unlockToken = null;
83558
84170
  unlockSession = null;
83559
84171
  constructor(opts) {
83560
84172
  this.clock = opts?.clock ?? Date.now;
84173
+ this.sweepIntervalMs = opts?.sweepIntervalMs ?? 1e3;
84174
+ if (!Number.isInteger(this.sweepIntervalMs) || this.sweepIntervalMs < 0) {
84175
+ throw new Error(`bridge sweepIntervalMs must be a non-negative integer (got ${String(opts?.sweepIntervalMs)})`);
84176
+ }
83561
84177
  this.boundAccount = opts?.boundAccount?.toLowerCase();
83562
84178
  this.expiryMs = opts?.expiryMs ?? DEFAULT_EXPIRY_MS;
83563
84179
  this.maxPending = opts?.maxPending ?? null;
@@ -83593,8 +84209,10 @@ var SignatureBridge = class {
83593
84209
  this.server = server;
83594
84210
  }
83595
84211
  this.started = true;
83596
- this.sweepTimer = setInterval(() => this.sweep(), 1e3);
83597
- this.sweepTimer.unref();
84212
+ if (this.sweepIntervalMs > 0) {
84213
+ this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);
84214
+ this.sweepTimer.unref();
84215
+ }
83598
84216
  if (this.urlFile) fs4.writeFileSync(this.urlFile, this.url());
83599
84217
  }
83600
84218
  /** Plan 12 C1: the outer server's dispatch entry for a MOUNTED bridge — `req.url`
@@ -83654,6 +84272,16 @@ var SignatureBridge = class {
83654
84272
  pendingCount() {
83655
84273
  return this.pending.size;
83656
84274
  }
84275
+ /** A request lives for the bridge's expiry OR until its payload dies, whichever is first.
84276
+ * The BTC-withdraw execute leg's payload dies inside a sub-minute quantum window; holding
84277
+ * the ceremony open for the full five minutes kept a dead card on screen and let the phone
84278
+ * be asked to sign something the protocol would refuse. */
84279
+ deadlineFor(request, nowMs) {
84280
+ const bridgeDeadline = nowMs + this.expiryMs;
84281
+ if (request.expiresAtSec === void 0) return bridgeDeadline;
84282
+ if (!Number.isFinite(request.expiresAtSec)) throw new Error(`request ${request.id} carries a non-finite expiresAtSec`);
84283
+ return Math.min(bridgeDeadline, request.expiresAtSec * 1e3);
84284
+ }
83657
84285
  /**
83658
84286
  * Enqueue a request and resolve on the human's decision (or expiry/invalidation).
83659
84287
  * Chain-id mismatch with an already-connected wallet refuses BEFORE the wallet is asked.
@@ -83676,14 +84304,15 @@ var SignatureBridge = class {
83676
84304
  const now = this.clock();
83677
84305
  const entry = {
83678
84306
  request,
83679
- deadlineMs: now + this.expiryMs,
84307
+ deadlineMs: this.deadlineFor(request, now),
83680
84308
  enqueuedMs: now,
83681
84309
  resolve,
83682
84310
  settled: false,
83683
84311
  ...handlers?.finalize ? { finalize: handlers.finalize } : {},
83684
84312
  owner: this.wcActive ? "wc" : "page",
83685
84313
  dispatched: false,
83686
- lastAttachedMs: now
84314
+ lastAttachedMs: now,
84315
+ finalizedBy: null
83687
84316
  };
83688
84317
  this.pending.set(request.id, entry);
83689
84318
  if (entry.owner === "wc") {
@@ -83706,7 +84335,7 @@ var SignatureBridge = class {
83706
84335
  const now = this.clock();
83707
84336
  const entry = {
83708
84337
  request,
83709
- deadlineMs: now + this.expiryMs,
84338
+ deadlineMs: this.deadlineFor(request, now),
83710
84339
  enqueuedMs: now,
83711
84340
  resolve,
83712
84341
  settled: false,
@@ -83716,7 +84345,8 @@ var SignatureBridge = class {
83716
84345
  // ceremony could not reach quorum through the very pages it is broadcast to.
83717
84346
  owner: "both",
83718
84347
  dispatched: false,
83719
- lastAttachedMs: now
84348
+ lastAttachedMs: now,
84349
+ finalizedBy: null
83720
84350
  };
83721
84351
  this.pending.set(request.id, entry);
83722
84352
  this.pushEntry(entry);
@@ -83757,6 +84387,7 @@ var SignatureBridge = class {
83757
84387
  return;
83758
84388
  }
83759
84389
  try {
84390
+ if (this.expireIfOverdue(entry)) return;
83760
84391
  if (req.kind === "transaction") {
83761
84392
  this.pushEntry(entry);
83762
84393
  const tx2 = req.tx;
@@ -83768,15 +84399,23 @@ var SignatureBridge = class {
83768
84399
  } else if (req.kind === "personal-sign") {
83769
84400
  if (entry.finalize) {
83770
84401
  const fresh = await entry.finalize();
84402
+ if (entry.settled) return;
84403
+ if (entry.owner !== "wc") return;
84404
+ const live = transport.active();
84405
+ if (!this.wcActive || !live || live.account.toLowerCase() !== account.toLowerCase()) {
84406
+ this.settle(entry, {
84407
+ status: "invalidated",
84408
+ reason: "the WalletConnect wallet changed while this payload was being prepared \u2014 the phone was not asked. Reconnect your wallet and retry the operation."
84409
+ });
84410
+ return;
84411
+ }
83771
84412
  req.personalSign = fresh.personalSign;
83772
84413
  req.card = fresh.card;
83773
84414
  }
84415
+ if (this.expireIfOverdue(entry)) return;
83774
84416
  const ps = req.personalSign;
83775
- if (ps.layout === RAW_HASH_LAYOUT && !this.pageAttached()) {
83776
- this.settle(entry, {
83777
- status: "invalidated",
83778
- 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)`
83779
- });
84417
+ if (!this.pageAttached()) {
84418
+ this.settle(entry, { status: "invalidated", reason: this.noPageReason(ps.layout === RAW_HASH_LAYOUT) });
83780
84419
  return;
83781
84420
  }
83782
84421
  this.pushEntry(entry);
@@ -83801,6 +84440,16 @@ var SignatureBridge = class {
83801
84440
  }
83802
84441
  }
83803
84442
  }
84443
+ /** Refusal for a WalletConnect personal_sign with no proven approval page attached.
84444
+ *
84445
+ * The remedy names BOTH halves, because opening the link alone does not fix it: a freshly
84446
+ * opened page is a stranger until a phone answers a pairing it showed (or its wallet signs
84447
+ * the presence statement), so it receives no card. Following "just reopen the URL" looped
84448
+ * (Sentinel 2 PoC-C). */
84449
+ noPageReason(blindHash) {
84450
+ 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";
84451
+ 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)`;
84452
+ }
83804
84453
  /** A live attachment that could still decide a request: an open approval-page SSE
83805
84454
  * stream (real page or headless driver) or an active WalletConnect session. PUBLIC
83806
84455
  * (plan 17 E1): the connector's idle-eviction predicate reads it — a tenant world
@@ -83814,7 +84463,7 @@ var SignatureBridge = class {
83814
84463
  * receives nothing cannot show anything. Distinct from `attachedNow()`, which counts
83815
84464
  * WalletConnect and must stay global for the connector's eviction predicate. */
83816
84465
  pageAttached() {
83817
- for (const s of this.sessions.values()) if (!s.refused && s.sse) return true;
84466
+ for (const s of this.sessions.values()) if (s.sse && this.authorized(s)) return true;
83818
84467
  return false;
83819
84468
  }
83820
84469
  /** Attachment for ONE entry — the wallet that entry is actually waiting on. The global
@@ -83831,6 +84480,7 @@ var SignatureBridge = class {
83831
84480
  * the deadline is checked first so expiry semantics stay pinned (T-EXT-03). */
83832
84481
  sweep() {
83833
84482
  const now = this.clock();
84483
+ this.evictDeadSessions();
83834
84484
  for (const entry of this.pending.values()) {
83835
84485
  if (entry.settled) continue;
83836
84486
  if (now >= entry.deadlineMs) {
@@ -83883,6 +84533,7 @@ var SignatureBridge = class {
83883
84533
  void this.wcTransport?.close().catch(() => void 0);
83884
84534
  this.wcTransport = null;
83885
84535
  this.wcActive = false;
84536
+ this.pairingOwners.clear();
83886
84537
  }
83887
84538
  // ---- HTTP plumbing ----
83888
84539
  route(req, res) {
@@ -83890,6 +84541,7 @@ var SignatureBridge = class {
83890
84541
  const url2 = new URL(req.url ?? "/", this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`);
83891
84542
  if (req.method === "GET" && url2.pathname === "/") return this.servePage(url2, res);
83892
84543
  if (req.method === "GET" && url2.pathname === "/config") return this.serveConfig(url2, res);
84544
+ if (req.method === "GET" && url2.pathname === "/challenge") return this.serveChallenge(url2, res);
83893
84545
  if (req.method === "GET" && url2.pathname === "/wc-pairing") return void this.serveWcPairing(url2, res);
83894
84546
  if (req.method === "GET" && url2.pathname === "/unlock") return this.serveUnlockPage(url2, res);
83895
84547
  if (req.method === "POST" && url2.pathname === "/unlock-submit")
@@ -83943,13 +84595,22 @@ var SignatureBridge = class {
83943
84595
  this.deny(res, 403, "this approval link has expired \u2014 ask for a fresh one (signer_setup status) and reopen");
83944
84596
  return;
83945
84597
  }
84598
+ this.makeRoomForSession();
83946
84599
  if (this.sessions.size >= MAX_SESSIONS) {
83947
84600
  this.deny(res, 429, `too many open approval pages (${MAX_SESSIONS}) \u2014 close one and retry`);
83948
84601
  return;
83949
84602
  }
83950
84603
  const sessionId = (0, import_node_crypto7.randomBytes)(24).toString("hex");
83951
- this.sessions.set(sessionId, { wallet: null, sse: null, refused: null });
83952
- const page = htmlPageSecurityHeaders();
84604
+ this.sessions.set(sessionId, {
84605
+ wallet: null,
84606
+ sse: null,
84607
+ refused: null,
84608
+ lastSeenMs: this.clock(),
84609
+ wcPaired: false,
84610
+ presenceNonce: (0, import_node_crypto7.randomBytes)(16).toString("hex"),
84611
+ provenAccount: null
84612
+ });
84613
+ const page = htmlPageSecurityHeaders(HOUSE_CSP_EXTRA);
83953
84614
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", ...page.headers });
83954
84615
  res.end(renderApprovalPage(sessionId, page.nonce));
83955
84616
  }
@@ -83959,10 +84620,29 @@ var SignatureBridge = class {
83959
84620
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
83960
84621
  res.end(JSON.stringify({ network: this.network ?? null }));
83961
84622
  }
84623
+ /** The origin this bridge is served from — what a presence statement names. */
84624
+ publicOrigin() {
84625
+ return this.mount ? this.mount.origin : `http://127.0.0.1:${this.port}`;
84626
+ }
84627
+ /** The presence statement for this session + chain (session-gated). The page signs exactly
84628
+ * this text in its wallet; the bridge rebuilds it on `hello` rather than trusting any text
84629
+ * the client sends back. */
84630
+ serveChallenge(url2, res) {
84631
+ const session = this.sessionOf(url2.searchParams.get("s"), res);
84632
+ if (!session) return;
84633
+ const chainId = Number(url2.searchParams.get("chainId"));
84634
+ if (!Number.isInteger(chainId)) {
84635
+ this.deny(res, 400, "challenge requires an integer chainId");
84636
+ return;
84637
+ }
84638
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
84639
+ res.end(JSON.stringify({ statement: presenceStatement(this.publicOrigin(), chainId, session.presenceNonce) }));
84640
+ }
83962
84641
  /** WalletConnect pairing (D2, session-gated): lazily boots the WC transport and serves a
83963
84642
  * fresh pairing URI. A wallet approving the pairing becomes THE wallet. */
83964
84643
  async serveWcPairing(url2, res) {
83965
84644
  if (!this.checkSession(url2.searchParams.get("s"), res)) return;
84645
+ const askingSession = url2.searchParams.get("s");
83966
84646
  if (!this.wcConfig) {
83967
84647
  this.deny(res, 404, "WalletConnect is not configured (set DH_WC_PROJECT_ID)");
83968
84648
  return;
@@ -83977,15 +84657,22 @@ var SignatureBridge = class {
83977
84657
  this.wcTransport.onSession((info) => {
83978
84658
  const refusal = info ? this.accountRefusal(info.account) : null;
83979
84659
  if (info && refusal) {
83980
- this.wcActive = false;
83981
- this.rebuildSharedWallet();
83982
- this.demoteWcEntries();
84660
+ if (!this.wcActive) {
84661
+ this.rebuildSharedWallet();
84662
+ this.demoteWcEntries();
84663
+ }
83983
84664
  process.stderr.write(`[bridge] WalletConnect session refused \u2014 ${refusal}
83984
84665
  `);
83985
- return;
84666
+ return false;
83986
84667
  }
83987
84668
  this.wcActive = info !== null;
83988
84669
  this.wallet = info ? { account: info.account, chainId: info.chainId } : null;
84670
+ if (info?.pairingId) {
84671
+ const owner = this.pairingOwners.get(info.pairingId);
84672
+ this.pairingOwners.delete(info.pairingId);
84673
+ const paired = owner ? this.sessions.get(owner) : void 0;
84674
+ if (paired) paired.wcPaired = true;
84675
+ }
83989
84676
  if (info === null) {
83990
84677
  for (const entry of this.pending.values()) {
83991
84678
  if (!entry.settled && !entry.collect) {
@@ -83998,7 +84685,15 @@ var SignatureBridge = class {
83998
84685
  }
83999
84686
  });
84000
84687
  }
84001
- const { uri } = await this.wcTransport.createPairing();
84688
+ const { uri, pairingId } = await this.wcTransport.createPairing();
84689
+ if (pairingId) {
84690
+ this.pairingOwners.set(pairingId, askingSession);
84691
+ while (this.pairingOwners.size > MAX_PENDING_PAIRINGS) {
84692
+ const oldest = this.pairingOwners.keys().next();
84693
+ if (oldest.done) break;
84694
+ this.pairingOwners.delete(oldest.value);
84695
+ }
84696
+ }
84002
84697
  const { default: qrcode } = await import("qrcode-generator");
84003
84698
  const qr = qrcode(0, "M");
84004
84699
  qr.addData(uri);
@@ -84063,9 +84758,7 @@ var SignatureBridge = class {
84063
84758
  res.write(":connected\n\n");
84064
84759
  session.sse?.end();
84065
84760
  session.sse = res;
84066
- for (const entry of this.pending.values()) {
84067
- if (!entry.settled) res.write(this.wireFor(entry));
84068
- }
84761
+ this.replayPending(session);
84069
84762
  const keepAlive = setInterval(() => res.write(":ka\n\n"), 2e4);
84070
84763
  keepAlive.unref();
84071
84764
  res.on("close", () => {
@@ -84088,8 +84781,37 @@ var SignatureBridge = class {
84088
84781
  this.deny(res, 403, refusal);
84089
84782
  return;
84090
84783
  }
84784
+ const alreadyProven = session.provenAccount !== null && session.provenAccount.toLowerCase() === account.toLowerCase();
84785
+ if (!alreadyProven) {
84786
+ const signature = body["signature"];
84787
+ if (typeof signature !== "string" || signature === "") {
84788
+ this.deny(
84789
+ res,
84790
+ 403,
84791
+ `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.`
84792
+ );
84793
+ return;
84794
+ }
84795
+ const statement = presenceStatement(this.publicOrigin(), chainId, session.presenceNonce);
84796
+ let recovered = null;
84797
+ try {
84798
+ recovered = import_ethers50.ethers.verifyMessage(statement, signature);
84799
+ } catch {
84800
+ recovered = null;
84801
+ }
84802
+ if (recovered === null || recovered.toLowerCase() !== account.toLowerCase()) {
84803
+ this.deny(
84804
+ res,
84805
+ 403,
84806
+ `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).`
84807
+ );
84808
+ return;
84809
+ }
84810
+ session.provenAccount = account;
84811
+ }
84091
84812
  session.wallet = { account, chainId };
84092
84813
  this.wallet = { account, chainId };
84814
+ this.replayPending(session);
84093
84815
  this.ok(res);
84094
84816
  }
84095
84817
  /** C-47: the single predicate every wallet account is admitted through. There are THREE
@@ -84128,17 +84850,21 @@ var SignatureBridge = class {
84128
84850
  if (refusedSwitch) {
84129
84851
  this.quarantine(session, switchRefusal);
84130
84852
  } else {
84131
- session.wallet = offered;
84853
+ const sameProven = offered !== null && session.provenAccount !== null && offered.account.toLowerCase() === session.provenAccount.toLowerCase();
84854
+ session.wallet = sameProven ? offered : null;
84132
84855
  if (this.wallet !== null && prev !== null && this.wallet.account.toLowerCase() === prev.account.toLowerCase()) {
84133
84856
  this.wallet = session.wallet;
84857
+ } else if (this.wallet === null && prev === null && session.wallet !== null) {
84858
+ this.wallet = session.wallet;
84134
84859
  }
84135
84860
  }
84136
- const unchanged = prev !== null && session.wallet !== null && prev.account.toLowerCase() === session.wallet.account.toLowerCase() && prev.chainId === session.wallet.chainId;
84137
- if (unchanged) {
84861
+ const reported = refusedSwitch ? null : offered;
84862
+ const unchanged = prev !== null && reported !== null && prev.account.toLowerCase() === reported.account.toLowerCase() && prev.chainId === reported.chainId;
84863
+ if (unchanged || prev === null) {
84138
84864
  this.ok(res);
84139
84865
  return;
84140
84866
  }
84141
- 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";
84867
+ 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";
84142
84868
  for (const entry of this.pending.values()) {
84143
84869
  if (entry.settled || entry.collect) continue;
84144
84870
  if (this.ownedByWc(entry)) continue;
@@ -84173,12 +84899,18 @@ var SignatureBridge = class {
84173
84899
  /** Click-time re-stamp (A0.9): returns the FRESH personal-sign payload for a pending
84174
84900
  * request. Idempotent for requests without a finalize handler (payload as enqueued). */
84175
84901
  async onFinalize(body, res) {
84176
- if (!this.sessionOf(body["sessionId"], res)) return;
84902
+ const sessionId = String(body["sessionId"] ?? "");
84903
+ const session = this.decidingSessionOf(body["sessionId"], res);
84904
+ if (!session) return;
84177
84905
  const entry = this.pending.get(String(body["requestId"] ?? ""));
84178
84906
  if (!entry || entry.settled) {
84179
84907
  this.deny(res, 404, "unknown or already-settled requestId");
84180
84908
  return;
84181
84909
  }
84910
+ if (this.expireIfOverdue(entry)) {
84911
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
84912
+ return;
84913
+ }
84182
84914
  if (entry.request.kind !== "personal-sign") {
84183
84915
  this.deny(res, 400, "finalize applies only to personal-sign requests");
84184
84916
  return;
@@ -84187,6 +84919,12 @@ var SignatureBridge = class {
84187
84919
  this.deny(res, 409, "a mobile wallet is holding this approval \u2014 it is read-only here; approve or decline it in the wallet");
84188
84920
  return;
84189
84921
  }
84922
+ const holder = entry.finalizedBy ? this.sessions.get(entry.finalizedBy) : void 0;
84923
+ if (entry.finalizedBy && entry.finalizedBy !== sessionId && holder?.sse) {
84924
+ this.deny(res, 409, "another approval page is signing this request \u2014 approve it there, or close that page and retry");
84925
+ return;
84926
+ }
84927
+ entry.finalizedBy = sessionId;
84190
84928
  if (entry.finalize) {
84191
84929
  let fresh;
84192
84930
  try {
@@ -84199,6 +84937,10 @@ var SignatureBridge = class {
84199
84937
  this.deny(res, 404, "request settled while finalizing");
84200
84938
  return;
84201
84939
  }
84940
+ if (this.expireIfOverdue(entry)) {
84941
+ this.deny(res, 410, "this request expired while its payload was being prepared \u2014 retry the operation");
84942
+ return;
84943
+ }
84202
84944
  entry.request.personalSign = fresh.personalSign;
84203
84945
  entry.request.card = fresh.card;
84204
84946
  }
@@ -84206,12 +84948,16 @@ var SignatureBridge = class {
84206
84948
  res.end(JSON.stringify({ request: entry.request }));
84207
84949
  }
84208
84950
  onResult(body, res) {
84209
- if (!this.sessionOf(body["sessionId"], res)) return;
84951
+ if (!this.decidingSessionOf(body["sessionId"], res)) return;
84210
84952
  const entry = this.pending.get(String(body["requestId"] ?? ""));
84211
84953
  if (!entry || entry.settled) {
84212
84954
  this.deny(res, 404, "unknown or already-settled requestId");
84213
84955
  return;
84214
84956
  }
84957
+ if (this.expireIfOverdue(entry)) {
84958
+ this.deny(res, 410, "this request has expired \u2014 retry the operation");
84959
+ return;
84960
+ }
84215
84961
  if (body["approved"] !== true) {
84216
84962
  if (this.ownedByWc(entry) && entry.request.kind === "transaction") {
84217
84963
  this.settle(entry, {
@@ -84260,6 +85006,16 @@ var SignatureBridge = class {
84260
85006
  this.ok(res);
84261
85007
  }
84262
85008
  // ---- helpers ----
85009
+ /** Accept-time deadline check. The 1 s sweep is only the backstop: between the deadline and
85010
+ * the next tick a late click on /finalize or /result — or a WalletConnect dispatch — would
85011
+ * otherwise still ask for or accept a signature over a payload the protocol will refuse.
85012
+ * Settles the entry `expired` (the same outcome the sweep gives) and reports it. */
85013
+ expireIfOverdue(entry) {
85014
+ if (entry.settled) return true;
85015
+ if (this.clock() < entry.deadlineMs) return false;
85016
+ this.settle(entry, { status: "expired" });
85017
+ return true;
85018
+ }
84263
85019
  settle(entry, outcome) {
84264
85020
  entry.settled = true;
84265
85021
  this.pending.delete(entry.request.id);
@@ -84279,7 +85035,7 @@ var SignatureBridge = class {
84279
85035
  /** Broadcast a pending entry to EVERY open page (multi-owner links — plan 06 §1.5). */
84280
85036
  pushEntry(entry) {
84281
85037
  const data = this.wireFor(entry);
84282
- for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
85038
+ for (const s of this.sessions.values()) if (this.authorized(s)) s.sse?.write(data);
84283
85039
  }
84284
85040
  /** Progress goes out as a NAMED event so `es.onmessage` request handling never sees it. */
84285
85041
  pushProgress(payload) {
@@ -84287,7 +85043,51 @@ var SignatureBridge = class {
84287
85043
  data: ${JSON.stringify(payload)}
84288
85044
 
84289
85045
  `;
84290
- for (const s of this.sessions.values()) if (!s.refused) s.sse?.write(data);
85046
+ for (const s of this.sessions.values()) if (this.authorized(s)) s.sse?.write(data);
85047
+ }
85048
+ /** Replay every undecided card to ONE session — used when a session becomes authorized
85049
+ * (hello) after its stream was already open, which is the ordinary page order: the page
85050
+ * attaches its EventSource, then the wallet prompt resolves. Without this the newly
85051
+ * connected page would sit blank until the next push. */
85052
+ replayPending(session) {
85053
+ if (!session.sse || !this.authorized(session)) return;
85054
+ for (const entry of this.pending.values()) {
85055
+ if (!entry.settled) session.sse.write(this.wireFor(entry));
85056
+ }
85057
+ }
85058
+ /** Retire quarantined sessions that hold no stream. Always safe: a refused session is
85059
+ * denied on every route anyway, so keeping it costs a slot and buys nothing. */
85060
+ evictDeadSessions() {
85061
+ for (const [id, s] of this.sessions) if (s.refused && !s.sse) this.sessions.delete(id);
85062
+ }
85063
+ /**
85064
+ * Free a slot for an incoming page load when the ceiling is reached.
85065
+ *
85066
+ * MAX_SESSIONS was a ceiling with NO eviction — nothing but `close()` ever removed a
85067
+ * session — and every page load mints one (a reload is a new session). A long-lived
85068
+ * hosted bridge therefore reached 16 through ordinary use and 429'd the user out of
85069
+ * approving their own ceremonies, permanently, with "close one and retry" as the advice
85070
+ * for pages that were already closed.
85071
+ *
85072
+ * Eviction is ON DEMAND and never touches a session with a live SSE stream: that stream
85073
+ * is a page open in a browser right now, and the C1 contract is that live sessions
85074
+ * survive. Among the streamless it takes the least recently seen — the closed tab.
85075
+ */
85076
+ makeRoomForSession() {
85077
+ this.evictDeadSessions();
85078
+ while (this.sessions.size >= MAX_SESSIONS) {
85079
+ let oldestId = null;
85080
+ let oldestSeen = Infinity;
85081
+ for (const [id, s] of this.sessions) {
85082
+ if (s.sse) continue;
85083
+ if (s.lastSeenMs < oldestSeen) {
85084
+ oldestSeen = s.lastSeenMs;
85085
+ oldestId = id;
85086
+ }
85087
+ }
85088
+ if (oldestId === null) return;
85089
+ this.sessions.delete(oldestId);
85090
+ }
84291
85091
  }
84292
85092
  /**
84293
85093
  * C-47: `this.wallet` is DERIVED, never guessed.
@@ -84330,12 +85130,46 @@ data: ${JSON.stringify(payload)}
84330
85130
  }
84331
85131
  this.rebuildSharedWallet();
84332
85132
  }
85133
+ /**
85134
+ * A session that may SEE cards and DECIDE them — one where a PERSON has proven to be at
85135
+ * the page: `hello` with an admissible account, or a WalletConnect pairing a wallet
85136
+ * actually answered (`wcPaired`).
85137
+ *
85138
+ * `sessionOf` only ever asked "does this session id exist and is it un-quarantined". A
85139
+ * session id is minted by LOADING the page, and on the hosted tier the mount URL travels
85140
+ * through the conversation by design — so anyone holding it could mint a session, never
85141
+ * connect a wallet, and still receive every approval card on /events (the card is the
85142
+ * operation in readable form: position, destination, amounts) and still POST /result to
85143
+ * decline, or /finalize to re-stamp, someone else's ceremony. Quarantine never caught
85144
+ * them: it fires on an OFFERED account, and they offered none.
85145
+ *
85146
+ * Opening the stream without a wallet stays legal — that is how the real page bootstraps
85147
+ * before the user connects. It simply receives nothing and decides nothing until it has
85148
+ * connected. Requesting a pairing is likewise not enough: anyone with the link can ask
85149
+ * for a QR, so only a pairing a WALLET ANSWERED counts.
85150
+ */
85151
+ authorized(session) {
85152
+ if (session.refused) return false;
85153
+ if (session.wallet) return this.accountRefusal(session.wallet.account) === null;
85154
+ return session.wcPaired;
85155
+ }
85156
+ /** `sessionOf`, plus the wallet binding above — for the routes that decide a ceremony. */
85157
+ decidingSessionOf(candidate, res) {
85158
+ const session = this.sessionOf(candidate, res);
85159
+ if (!session) return null;
85160
+ if (!this.authorized(session)) {
85161
+ this.deny(res, 403, "connect your wallet on this page before approving, declining or finalizing a request");
85162
+ return null;
85163
+ }
85164
+ return session;
85165
+ }
84333
85166
  sessionOf(candidate, res) {
84334
85167
  const session = typeof candidate === "string" ? this.sessions.get(candidate) ?? null : null;
84335
85168
  if (!session) {
84336
85169
  this.deny(res, 403, "missing or wrong session");
84337
85170
  return null;
84338
85171
  }
85172
+ session.lastSeenMs = this.clock();
84339
85173
  if (session.refused) {
84340
85174
  this.deny(res, 403, session.refused);
84341
85175
  return null;
@@ -84563,6 +85397,7 @@ async function createRealBoundary(config, wallet, overrides) {
84563
85397
  const manager = new SignerManager({
84564
85398
  persistence: overrides?.signerPersistence?.(config.network) ?? fileSignerPersistence(stateFile),
84565
85399
  initialMode,
85400
+ ...overrides?.boundBorrower ? { authenticatedBorrower: import_ethers51.ethers.getAddress(overrides.boundBorrower) } : {},
84566
85401
  candidate: () => bridge.walletState()?.account ?? null,
84567
85402
  pendingCeremonies: () => bridge.pendingCount(),
84568
85403
  keystore
@@ -84658,8 +85493,8 @@ async function buildBoundary(configResult, overrides) {
84658
85493
  );
84659
85494
  }
84660
85495
  try {
84661
- const decrypted = await import_ethers50.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
84662
- if (!(decrypted instanceof import_ethers50.ethers.Wallet)) {
85496
+ const decrypted = await import_ethers52.ethers.Wallet.fromEncryptedJson(keystoreJson, config.keystorePassword);
85497
+ if (!(decrypted instanceof import_ethers52.ethers.Wallet)) {
84663
85498
  return bootError("DH_KEYSTORE_PATH did not decrypt to an EOA wallet keystore.", ["DH_KEYSTORE_PATH"]);
84664
85499
  }
84665
85500
  wallet = decrypted;
@@ -85028,8 +85863,13 @@ function authorizationModeBullets(d) {
85028
85863
  that one \u2014 say it before the popup. Walkthrough: \`guide connect-wallet\`.`);
85029
85864
  }
85030
85865
  if (offers(d, "keystore")) {
85031
- bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs automatically after each confirmation.
85032
- Real adapter and mock.`);
85866
+ bullets.push(` - \`keystore\` \u2014 a local encrypted keystore signs AUTOMATICALLY, with no per-operation
85867
+ human prompt. Real adapter and mock. Say this plainly when the user picks it: the
85868
+ password is asked ONCE, at unlock; after that the key signs every write this session
85869
+ without a popup, an approval page or any second human step. The \`confirmed: true\` gate
85870
+ is the ASSISTANT's \u2014 it is not the user seeing and approving the operation \u2014 so in this
85871
+ mode you must show the operation and get a real answer before you set it. A user who
85872
+ wants to inspect each operation as it signs wants \`external\`.`);
85033
85873
  }
85034
85874
  if (offers(d, "safe") || offers(d, "safe-module")) {
85035
85875
  bullets.push(` - \`safe\` / \`safe-module\` \u2014 PRACTICE-ONLY today: on the real adapter these modes
@@ -85040,6 +85880,9 @@ function authorizationModeBullets(d) {
85040
85880
  }
85041
85881
  return bullets.join("\n");
85042
85882
  }
85883
+ function readsNeedSignIn(d) {
85884
+ 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.";
85885
+ }
85043
85886
  function keystoreAbsenceParagraph(d) {
85044
85887
  if (offers(d, "keystore")) return "";
85045
85888
  return `
@@ -85083,9 +85926,11 @@ install matrix. ${connectorInstallNote(d)}
85083
85926
 
85084
85927
  Nothing needs a config file. Three steps:
85085
85928
 
85086
- **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) and
85087
- \`protocol_status\`, then tell the user what THIS deployment is: ${worldAxes(d)}; which
85088
- signer modes exist; current terms (\`protocol_terms\`).
85929
+ **1. Know your world.** Read \`boundary://info\` (its \`capabilities\` block) \u2014 that
85930
+ resource always answers, with no sign-in \u2014 and tell the user what THIS deployment is:
85931
+ ${worldAxes(d)}; which signer modes exist. ${readsNeedSignIn(d)} So the live reads
85932
+ (\`protocol_status\`, current terms via \`protocol_terms\`) come right after step 2, not
85933
+ before it.
85089
85934
 
85090
85935
  **2. Choose HOW to authorize operations** (the user's choice, made by talking):
85091
85936
  - **"Use my own wallet"** \u2192 call \`signer_setup\` action \`use\`, mode \`external\` \u2014 works
@@ -85105,8 +85950,9 @@ ${offers(d, "safe") || offers(d, "safe-module") ? `- **Safe / delegation modes (
85105
85950
  surface is the wallet ceremony and nothing else; \`signer_setup\` lists no other mode.
85106
85951
  \`guide safe\` and \`guide delegation\` state what exists elsewhere.`}
85107
85952
  - Not sure? \`signer_setup\` action \`status\` explains what is active and what is missing.
85108
- - **No signer is also a valid start:** every public read works without one \u2014
85109
- \`position_list {borrower}\` with the user's address needs no signer and no login.
85953
+ - **A read is not a signer-less shortcut:** the sign-in in step 2 is what turns reads ON.
85954
+ Until then \`position_list {borrower}\`, \`protocol_status\` and \`protocol_terms\` refuse
85955
+ on the real adapter \u2014 do step 2 first, then reads work.
85110
85956
  ${d.networks.length > 1 ? `- **Wrong network?** On the real adapter the user can switch sepolia \u2194 mainnet by
85111
85957
  talking (\`network_switch\`, human-confirmed) \u2014 see \`guide switch-network\`. State
85112
85958
  the money reality after any switch.` : `- **Wrong network?** This deployment is rolled out to ${d.networks[0]} alone \u2014
@@ -85128,7 +85974,7 @@ on the real adapter and the mock.
85128
85974
  **The walkthrough:**
85129
85975
  1. \`signer_setup\` action \`use\`, mode \`external\`. The approval page auto-opens in the
85130
85976
  desktop browser; ${approvalPageLocation(d)}
85131
- 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) + "."}
85977
+ 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) + "."}
85132
85978
  3. For authenticated reads before any write: \`signer_setup\` action \`connect\` runs the
85133
85979
  login ceremony explicitly (one typed-data signature in the wallet).
85134
85980
  4. The FIRST verified signature binds that wallet address as the borrower \u2014 it persists
@@ -85516,7 +86362,9 @@ plus one lit-ops login signature (read access). After that, every operation that
85516
86362
  funds asks for its OWN approval in the user's wallet, every time \u2014 and reads never pop
85517
86363
  the wallet. The login session lives ONLY in the server's memory: a server restart, or
85518
86364
  an idle spell long enough that the tenant's world is evicted, means signing in again.
85519
- That is the flip side of "nothing stored at rest" \u2014 a re-login is normal, not a fault.
86365
+ That is the flip side of never storing a login session at rest \u2014 a re-login is normal,
86366
+ not a fault. (The connector's own sign-in is a separate grant; /auth.md states whether
86367
+ this deployment keeps it across restarts.)
85520
86368
 
85521
86369
  **What the hosted server IS trusted with** (the six residual trusts \u2014 state them
85522
86370
  honestly when asked "is this safe"):
@@ -85595,7 +86443,12 @@ ${wrongNetworkTroubleshootingRow(d)}
85595
86443
  owed, wrong position state, or the USER DECLINED in the wallet. The message says which.
85596
86444
  A decline is not an error to fix \u2014 it is the user's decision.
85597
86445
  - **UPSTREAM_UNAVAILABLE** \u2014 a data source or the signature bridge is unreachable/expired.
85598
- Usually transient; re-check with \`protocol_status\` and retry once.
86446
+ Usually transient; re-check with \`protocol_status\` and retry once. (A PERMANENT gap
86447
+ answers \`NOT_IMPLEMENTED\`, below \u2014 that one is not retryable.)
86448
+ - **NOT_IMPLEMENTED** \u2014 a capability this adapter does NOT implement in this build, and never
86449
+ will \u2014 PERMANENT, not a transient outage, so do NOT retry it. \`position_events\` on the
86450
+ real adapter is the case: there is no indexer projection for event history here. Say the
86451
+ history is unavailable on this deployment and move on; the practice (mock) world has it.
85599
86452
  - **NOT_FOUND** \u2014 the position id doesn't exist in this world (check \`position_list\`).
85600
86453
  - **STATE_DIVERGENCE / STALE_DATA warnings** \u2014 sources disagree or lag; the envelope says
85601
86454
  which source and when from. Prefer chain-sourced values; re-read before acting.
@@ -85780,7 +86633,7 @@ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
85780
86633
 
85781
86634
  // src/tools/loan.ts
85782
86635
  var import_zod = require("zod");
85783
- var import_ethers51 = require("ethers");
86636
+ var import_ethers53 = require("ethers");
85784
86637
 
85785
86638
  // src/util/format.ts
85786
86639
  function bigintReplacer(_key, value) {
@@ -85829,7 +86682,7 @@ function requireConfirmation(confirmed, actionLabel) {
85829
86682
  type: "text",
85830
86683
  text: `CONFIRMATION REQUIRED \u2014 refusing to run "${actionLabel}".
85831
86684
  This is an irreversible, fund-moving action. A human must explicitly authorize it.
85832
- Re-invoke with confirmed: true ONLY after a human has approved this exact operation. Do not set confirmed on your own.`
86685
+ 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.`
85833
86686
  }
85834
86687
  ],
85835
86688
  isError: true
@@ -85968,7 +86821,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
85968
86821
  const b = getB();
85969
86822
  if (!b.ok) return renderError(b.error);
85970
86823
  return renderEnvelope(
85971
- await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers51.parseEther)(amountUcd.toString()).toString() })
86824
+ await b.boundary.mintUcd({ positionId, amountUcdWei: (0, import_ethers53.parseEther)(amountUcd.toString()).toString() })
85972
86825
  );
85973
86826
  })
85974
86827
  );
@@ -86006,7 +86859,7 @@ function registerLoanTools(server, getB, adapter2 = "real") {
86006
86859
  if (BigInt(detail.data.debtUcdWei) === 0n) return validationFailed("the position has no outstanding debt");
86007
86860
  amountUcdWei = detail.data.debtUcdWei;
86008
86861
  } else {
86009
- amountUcdWei = (0, import_ethers51.parseEther)(amountUcd.toString()).toString();
86862
+ amountUcdWei = (0, import_ethers53.parseEther)(amountUcd.toString()).toString();
86010
86863
  }
86011
86864
  return renderEnvelope(await b.boundary.repayUcd({ positionId, amountUcdWei }));
86012
86865
  })
@@ -86266,7 +87119,7 @@ function registerPositionTools(server, getB) {
86266
87119
  "position_events",
86267
87120
  {
86268
87121
  title: "Get a position's event history",
86269
- description: "Return mint, payment, withdrawal, renewal, and liquidation events for a position (indexer view).",
87122
+ 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.",
86270
87123
  inputSchema: {
86271
87124
  id: positionIdSchema2
86272
87125
  }
@@ -86609,7 +87462,7 @@ function registerMockControlTool(server, control, chainId = 1337) {
86609
87462
 
86610
87463
  // src/tools/signer.ts
86611
87464
  var import_zod6 = require("zod");
86612
- var import_ethers52 = require("ethers");
87465
+ var import_ethers54 = require("ethers");
86613
87466
  var MODES = ["external", "keystore", "safe", "safe-module", "mock-simulated"];
86614
87467
  var ACTIONS2 = ["status", "use", "reset-borrower", "unlock-keystore", "connect", "disconnect"];
86615
87468
  var EXTERNAL_ONLY_MODES = ["external"];
@@ -86651,7 +87504,7 @@ function registerSignerTool(server, getRuntime, opts) {
86651
87504
  if (mode !== void 0 && !offeredModes.includes(mode)) {
86652
87505
  return validationFailed(looksSecretShaped(mode) ? SECRET_REFUSAL : `mode '${mode}' is not one of: ${offeredModes.join(" | ")}`);
86653
87506
  }
86654
- if (safeAddress !== void 0 && !import_ethers52.ethers.isAddress(safeAddress)) {
87507
+ if (safeAddress !== void 0 && !import_ethers54.ethers.isAddress(safeAddress)) {
86655
87508
  return validationFailed(looksSecretShaped(safeAddress) ? SECRET_REFUSAL : `'${safeAddress}' is not a valid Safe address`);
86656
87509
  }
86657
87510
  if (action === "status") {
@@ -86662,9 +87515,9 @@ function registerSignerTool(server, getRuntime, opts) {
86662
87515
  // Plan 16 A3 — provenance honesty: the assistant must never guess HOW an
86663
87516
  // identity is known. borrower = a persisted binding; candidate = a live
86664
87517
  // wallet connection in THIS process only.
86665
- 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",
87518
+ 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",
86666
87519
  approvalPageUrl: bridge.url(),
86667
- 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.`
87520
+ 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.`
86668
87521
  });
86669
87522
  }
86670
87523
  if (action === "use") {
@@ -86741,6 +87594,11 @@ function registerSignerTool(server, getRuntime, opts) {
86741
87594
  });
86742
87595
  }
86743
87596
  if (action === "reset-borrower") {
87597
+ if (manager.identityPinned()) {
87598
+ return validationFailed(
87599
+ `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.`
87600
+ );
87601
+ }
86744
87602
  manager.resetBorrower();
86745
87603
  return ok({
86746
87604
  reset: true,
@@ -86812,7 +87670,7 @@ function registerGuidePrompts(server, deployment = LOCAL_GUIDE_DEPLOYMENT) {
86812
87670
  role: "user",
86813
87671
  content: {
86814
87672
  type: "text",
86815
- 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."
87673
+ 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."
86816
87674
  }
86817
87675
  }
86818
87676
  ]
@@ -87000,7 +87858,7 @@ function registerProtocolResources(server, getB) {
87000
87858
  "protocol://psm",
87001
87859
  {
87002
87860
  title: "PSM status (UCD \u2194 USDC exchange)",
87003
- 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.",
87861
+ 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.",
87004
87862
  mimeType: "application/json"
87005
87863
  },
87006
87864
  async (uri) => {
@@ -87062,7 +87920,7 @@ function registerBoundaryInfoResource(server, getB) {
87062
87920
  }
87063
87921
 
87064
87922
  // src/version.ts
87065
- var SERVER_VERSION = "0.5.19";
87923
+ var SERVER_VERSION = "0.5.21";
87066
87924
 
87067
87925
  // src/server.ts
87068
87926
  var SERVER_INSTRUCTIONS = "Diamond Hands MCP \u2014 Bitcoin-collateralized borrowing. Before promising ANY flow, read the boundary://info resource and honor its `capabilities` block: it states which network this server is on, whether money is real (practiceWorld), whether writes are enabled (and the true reason when they are not), and which signer modes this build actually offers \u2014 never describe a flow outside it. State the network and whether funds are real when the user first acts. Authorization is chosen by conversation via the signer_setup tool (when listed); writes always require confirmed:true after showing the human-readable card. For walkthroughs consult the guide tool / guide:// resources instead of inventing steps; when a tool refuses, relay its stated reason and remedy \u2014 do not improvise alternatives. When a network_switch tool is listed, the network can change mid-session \u2014 after ANY switch, re-read boundary://info and state the new network and money reality to the user before doing anything else. When the user asks to disconnect / log out / sign out / forget or remove their wallet, call signer_setup action 'disconnect' (the full flush) \u2014 never treat 'reset-borrower' as a disconnect; it only swaps identity. READING DATA: a payload's fields and notes are authoritative \u2014 state what they say, never speculate past them, and when the data does not carry something, say 'the data does not carry X'. Field meanings live in guide topic 'reading-data'; `reading` notes inside a result are interpretation instructions for that exact payload \u2014 follow them over any prior assumption.";