@gvnrdao/dh-lit-actions 0.0.327 → 0.0.329

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.
Files changed (72) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/agent-module-executor.meta.json +1 -1
  9. package/dist/backing-attestation.action.js +1 -0
  10. package/dist/backing-attestation.hash +1 -0
  11. package/dist/backing-attestation.meta.json +9 -0
  12. package/dist/btc-address-balance.action.js +1 -1
  13. package/dist/btc-address-balance.hash +1 -1
  14. package/dist/btc-address-balance.meta.json +5 -5
  15. package/dist/btc-provider-probe.meta.json +1 -1
  16. package/dist/btc-transaction-signer.action.js +1 -1
  17. package/dist/btc-transaction-signer.hash +1 -1
  18. package/dist/btc-transaction-signer.meta.json +5 -5
  19. package/dist/btc-utxo-invalidator.action.js +1 -1
  20. package/dist/btc-utxo-invalidator.hash +1 -1
  21. package/dist/btc-utxo-invalidator.meta.json +5 -5
  22. package/dist/btc-withdrawal.action.js +1 -1
  23. package/dist/btc-withdrawal.hash +1 -1
  24. package/dist/btc-withdrawal.meta.json +5 -5
  25. package/dist/carry-collateral-attestation.action.js +1 -1
  26. package/dist/carry-collateral-attestation.hash +1 -1
  27. package/dist/carry-collateral-attestation.meta.json +5 -5
  28. package/dist/carry-funding-attestation.meta.json +1 -1
  29. package/dist/encrypt-parameter.meta.json +1 -1
  30. package/dist/extend-position-validator.action.js +1 -1
  31. package/dist/extend-position-validator.hash +1 -1
  32. package/dist/extend-position-validator.meta.json +5 -5
  33. package/dist/liquidation-validator.action.js +1 -1
  34. package/dist/liquidation-validator.hash +1 -1
  35. package/dist/liquidation-validator.meta.json +5 -5
  36. package/dist/loan-vault-btc-balance.action.js +1 -1
  37. package/dist/loan-vault-btc-balance.hash +1 -1
  38. package/dist/loan-vault-btc-balance.meta.json +5 -5
  39. package/dist/pkp-validator.meta.json +1 -1
  40. package/dist/price-oracle.meta.json +1 -1
  41. package/dist/process-payment-validator.action.js +1 -1
  42. package/dist/process-payment-validator.hash +1 -1
  43. package/dist/process-payment-validator.meta.json +5 -5
  44. package/dist/stale-spend-recovery-validator.action.js +1 -1
  45. package/dist/stale-spend-recovery-validator.hash +1 -1
  46. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  47. package/dist/ucd-mint-validator.action.js +1 -1
  48. package/dist/ucd-mint-validator.hash +1 -1
  49. package/dist/ucd-mint-validator.meta.json +5 -5
  50. package/package.json +5 -1
  51. package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
  52. package/pkg-dist/pkg-src/index.js +170 -94
  53. package/pkg-dist/pkg-src/index.js.map +3 -3
  54. package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts +2 -0
  55. package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts.map +1 -1
  56. package/pkg-dist/src/constants/chunks/backing.d.ts +40 -0
  57. package/pkg-dist/src/constants/chunks/backing.d.ts.map +1 -0
  58. package/pkg-dist/src/constants/chunks/liquidation.d.ts +14 -11
  59. package/pkg-dist/src/constants/chunks/liquidation.d.ts.map +1 -1
  60. package/pkg-dist/src/constants/index.d.ts +1 -1
  61. package/pkg-dist/src/constants/index.d.ts.map +1 -1
  62. package/pkg-dist/src/modules/authorization.module.d.ts +8 -20
  63. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  64. package/pkg-dist/src/modules/backing-attestation.module.d.ts +78 -0
  65. package/pkg-dist/src/modules/backing-attestation.module.d.ts.map +1 -0
  66. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
  67. package/pkg-dist/src/modules/business-rules-math.module.d.ts +30 -15
  68. package/pkg-dist/src/modules/business-rules-math.module.d.ts.map +1 -1
  69. package/pkg-dist/src/modules/protocol-parameters.module.d.ts +18 -1
  70. package/pkg-dist/src/modules/protocol-parameters.module.d.ts.map +1 -1
  71. package/pkg-dist/src/modules/vault-balance-consensus.module.d.ts.map +1 -1
  72. package/pkg-dist/src/modules/vault-snapshot.d.ts.map +1 -1
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1608,
5
5
  "compressionRatio": 0.45895020188425306,
6
6
  "hash": "c6042989c2e0ac53631e008a960aef78f977471b9a7a8fc05a1537b10f34c8a9",
7
- "buildTime": 1792746369127,
7
+ "buildTime": 1793892468868,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 856,
5
5
  "compressionRatio": 0.4827794561933535,
6
6
  "hash": "bc0bcb38452275c93fa74c5240ae496d7a3eef9d38e7fb0dd99c5202c554d5e3",
7
- "buildTime": 1792746369174,
7
+ "buildTime": 1793892468880,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 4307,
5
5
  "compressionRatio": 0.5257130271996476,
6
6
  "hash": "22aa318284a25e721d1c949c8b4e5dbbb21853d1a3f649a72fd85ae32467bb17",
7
- "buildTime": 1792746369260,
7
+ "buildTime": 1793892468918,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1889,
5
5
  "compressionRatio": 0.4549913444893249,
6
6
  "hash": "790a1c5326a623065ab3c295d2c50cc8838d643730e53cb993a303ab9d7e0d83",
7
- "buildTime": 1792746369282,
7
+ "buildTime": 1793892468931,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 2220,
5
5
  "compressionRatio": 0.4740582800284293,
6
6
  "hash": "828aea87c7a7652377e00cb7a97c18324f09b87d3fa6703487fa3034e204a82c",
7
- "buildTime": 1792746369323,
7
+ "buildTime": 1793892468941,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1046,
5
5
  "compressionRatio": 0.47960199004975124,
6
6
  "hash": "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72",
7
- "buildTime": 1792746369372,
7
+ "buildTime": 1793892468948,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 2329,
5
5
  "compressionRatio": 0.44875739644970414,
6
6
  "hash": "6d26460ed9170782834926bcc30669fb48a9a0346f555eb838c99f8d9e6e8796",
7
- "buildTime": 1792746369393,
7
+ "buildTime": 1793892468957,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 17562,
5
5
  "compressionRatio": 0.4234784321449675,
6
6
  "hash": "a10d463ffd48f2392401efe3dde566faa1869e5e089db830632873a5b9528ee0",
7
- "buildTime": 1792746369490,
7
+ "buildTime": 1793892469008,
8
8
  "version": "0.1.0"
9
9
  }
@@ -0,0 +1 @@
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{main:()=>main});var o=60,a=16,s={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var c="DiamondHands.Protocol",d="1",l=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(l||{}),u={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},h=["infura.io","drpc.org","drpc.live"],g={ethereum:1,sepolia:11155111,hardhat:1337};var p={Backing:[{name:"btcSats",type:"uint256"},{name:"btcPriceE8",type:"uint256"},{name:"ucdDebt",type:"uint256"},{name:"ratioBps",type:"uint256"},{name:"asOf",type:"uint256"},{name:"ethBlock",type:"uint256"},{name:"btcBlockHash",type:"bytes32"},{name:"vaultsRoot",type:"bytes32"},{name:"vaultCount",type:"uint256"}]},f=50,w=100,b=3,m=5,y=21n*10n**14n,v=10n**16n,k={11155111:{oracle:"0x003b97EF135e414198bCc4D2c50AC6B1BFb602C0",signer:"0x38a1ddb3a4463E621bd97242f91e04f41DD94611"}};function A(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/o)*o;var e}async function E(){const t=Math.floor(Date.now()/1e3),e=t%o;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%o;return e<8||e>=o-8}(t))return;const r=a/2;let n;n=e>=o-r?o-e+r:r-e,console.log(`[Quantum] Waiting ${n}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*n))),console.log(`[Quantum] Safe quantum ready: ${A()}`)}var B={hardhat:{chain:"hardhat",chainId:g.hardhat,bitcoinNetwork:u.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:g.sepolia,bitcoinNetwork:u.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:g.ethereum,bitcoinNetwork:u.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function C(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(l).join(", ")}`)}(t),r=B[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var $=["drpc.org","drpc.live"],I="Drpc-Key",P=/^[A-Za-z0-9_-]{16,128}$/;function D(t){return $.some((e=>t===e||t.endsWith(`.${e}`)))}function S(t,e){if("string"!=typeof t||!P.test(t))throw new Error(`Invalid ${e}: expected 16-128 characters of [A-Za-z0-9_-]`)}function T(t){if("https:"!==t.protocol)throw new Error(`A dRPC key is only sent over https, but the RPC URL scheme is "${t.protocol}"`)}function x(t,e){if(void 0===e)return;S(e,'"drpcKey"');const r=new URL(t);if(!D(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${$.join(" or ")})`);if(T(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return e}var R=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function F(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const n=(i=t.chainId,s[i]??null);var i;if(!n)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of R){const i=n[e];if(!i)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const o=r[e];if("string"==typeof o&&o.length>0&&o.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${e}" (${o}) contradicts the pinned ${t.chain} address (${i}); refusing to sign`);r[e]=i}return r}async function M(t,e){const r=e.rpcUrl,n=e.rpcSource??"params-or-lit-node";let i;if("string"==typeof r&&r.length>0)!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!h.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${h.join(", ")}`)}(t,r),i=r;else{if("params-only"===n)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(i=await async function(t,e){if(void 0!==e)throw new Error('"drpcKey" was supplied without an "rpcUrl" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\'s own endpoint');return Lit.Actions.getRpcUrl({chain:t})}(e.chain,e.drpcKey),"string"!=typeof i||0===i.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${e.chain}"`)}return{rpcUrl:i,drpcKey:x(i,e.drpcKey),addresses:F(t,e.contractAddresses)}}var L={BalanceConfirmation:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"collateralValue",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},U="updateBalance(bytes32,uint256,uint256,uint256,bytes)",O=180;function _(t){const e=t.confirmation;if(!e||"string"!=typeof e.signature||!/^0x[0-9a-fA-F]{130}$/.test(e.signature))throw new Error("[carry] balanceConfirmation.signature is missing or malformed");if(!/^\d+$/.test(String(e.vaultBalance))||!/^\d+$/.test(String(e.btcPrice))||!/^\d+$/.test(String(e.quantumTimestamp)))throw new Error("[carry] balanceConfirmation fields must be unsigned integers");const r=Number(e.quantumTimestamp);if(r>t.nowSeconds+60||t.nowSeconds-r>O)throw new Error(`[carry] balanceConfirmation at ${r} is outside the window at ${t.nowSeconds}`);const n={actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes("balance-confirmation")),positionId:t.positionId,collateralValue:String(e.vaultBalance),btcPrice:String(e.btcPrice),quantumTimestamp:String(e.quantumTimestamp),borrower:ethers.utils.getAddress(t.borrower)},i=ethers.utils._TypedDataEncoder.hash(t.domain,L,n),o=ethers.utils.recoverAddress(i,e.signature);if(o!==ethers.utils.getAddress(t.validator))throw new Error(`[carry] balanceConfirmation signed by ${o}, not the updateBalance validator ${t.validator}`);return BigInt(e.vaultBalance)}var N=/^0x[0-9a-fA-F]{64}$/,H=/^\d+$/;var j,q=["function views() view returns (address)","function core() view returns (address)","function authorizationRegistry() view returns (address)"],z=["function getBackingVaults(uint256 offset, uint256 limit) view returns (tuple(bytes32 positionId, string vaultAddress, uint256 ucdDebt, uint8 status)[] vaults, uint256 nextOffset, uint256 total)"],K=["function getPositionDetails(bytes32 positionId) view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status, uint40 previousExpiryAt, uint16 totalTerm, uint40 lastRenewedAt) position)"],V=["function getValidator(bytes4) view returns (tuple(address pkpAddress, uint256 version, bool active))"],W=["function getAuthorizedSpends(bytes32 positionId) view returns (tuple(string txid, uint32 vout, uint256 satoshis, string targetAddress, uint256 targetAmount, uint256 authorizedAt)[])"],Z=["function btcUsdPriceFeed() view returns (address)","function maxBtcFeedAgeBorrow() view returns (uint32)"],Q=["function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)"];async function main(t){if(!t||"object"!=typeof t)throw new Error("[backing] missing args");for(const e of["chain","backingOracle","validatorWalletAddress","rpcUrl"])if("string"!=typeof t[e]||0===t[e].length)throw new Error(`[backing] missing "${e}"`);const e=function(t){if(!t||"object"!=typeof t)throw new Error('[backing] missing "snapshot"');const e=t;if(!Number.isInteger(e.ethBlock)||e.ethBlock<=0)throw new Error("[backing] snapshot.ethBlock must be a positive integer");if(!Number.isInteger(e.btcBlockHeight)||e.btcBlockHeight<=0)throw new Error("[backing] snapshot.btcBlockHeight must be a positive integer");if("string"!=typeof e.btcBlockHash||!N.test(e.btcBlockHash)||/^0x0{64}$/.test(e.btcBlockHash))throw new Error("[backing] snapshot.btcBlockHash must be a non-zero 32-byte hex hash");if(!Array.isArray(e.leaves))throw new Error("[backing] snapshot.leaves must be an array");const r=e.leaves.map(((t,e)=>{if(!t||"object"!=typeof t)throw new Error(`[backing] snapshot.leaves[${e}] is not an object`);const r=t;if("string"!=typeof r.positionId||!N.test(r.positionId))throw new Error(`[backing] snapshot.leaves[${e}].positionId is not bytes32`);if("string"!=typeof r.vaultAddress||0===r.vaultAddress.length)throw new Error(`[backing] snapshot.leaves[${e}].vaultAddress is empty`);if("string"!=typeof r.sats||!H.test(r.sats))throw new Error(`[backing] snapshot.leaves[${e}].sats must be an unsigned integer string`);return{positionId:r.positionId.toLowerCase(),vaultAddress:r.vaultAddress,sats:BigInt(r.sats)}}));return{ethBlock:e.ethBlock,btcBlockHash:e.btcBlockHash.toLowerCase(),btcBlockHeight:e.btcBlockHeight,leaves:r}}(t.snapshot),r=function(t){if(!Array.isArray(t))throw new Error('[backing] missing "samples" (an array)');return t.map(((t,e)=>{if(!t||"object"!=typeof t)throw new Error(`[backing] samples[${e}] is not an object`);const r=t;if("string"!=typeof r.positionId||!N.test(r.positionId))throw new Error(`[backing] samples[${e}].positionId is not bytes32`);if(!r.confirmation||"object"!=typeof r.confirmation)throw new Error(`[backing] samples[${e}].confirmation is missing`);return{positionId:r.positionId.toLowerCase(),confirmation:r.confirmation}}))}(t.samples),n=C(t.chain),i=function(t,e,r,n,i,o){const a=ethers.utils.getAddress(e),s=ethers.utils.getAddress(r);if(t.pinContractAddresses){if(!n)throw new Error(`[backing] no pinned backing pairing for ${t.chain} (${t.chainId}) \u2014 the oracle is not deployed/pinned there; refusing to sign`);if(a!==ethers.utils.getAddress(n.oracle))throw new Error(`[backing] requested oracle ${a} is not the pinned oracle ${n.oracle} for ${t.chain}; refusing to sign`);if(s!==ethers.utils.getAddress(n.signer))throw new Error(`[backing] signer ${s} is not the pinned backing signer ${n.signer}; refusing to sign`)}return{name:i,version:o,chainId:t.chainId,verifyingContract:a}}(n,t.backingOracle,t.validatorWalletAddress,(o=n.chainId,k[o]??null),c,d);var o;const{rpcUrl:a,drpcKey:s,addresses:l}=await M(n,{chain:t.chain,rpcUrl:t.rpcUrl,drpcKey:t.drpcKey,contractAddresses:t.contractAddresses,rpcSource:"params-only"});for(const t of["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer"])if(!l[t])throw new Error(`[backing] contractAddresses.${t} is required`);const u=new ethers.providers.JsonRpcProvider(function(t,e,r){const n={url:t},i=x(t,e);if(void 0!==i)n.headers={[I]:i};else{const e=new URL(t),r=e.searchParams.getAll("dkey");if(r.length>1)throw new Error(`rpcUrl carries ${r.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===r.length&&!D(e.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${e.hostname}" \u2014 a dRPC key is only sent to ${$.join(" or ")}`);if(1===r.length){const t=r[0];S(t,"dRPC key in rpcUrl (?dkey=)"),T(e),e.searchParams.delete("dkey"),n.url=e.toString(),n.headers={[I]:t}}}return void 0!==r&&(n.timeout=r),n}(a,s)),h=await u.getBlockNumber(),g=e.ethBlock;if(g>h)throw new Error(`[backing] snapshot.ethBlock ${g} is ahead of this node's latest ${h}`);if(h-g>w)throw new Error(`[backing] snapshot.ethBlock ${g} is ${h-g} blocks behind latest ${h} (max ${w})`);const B=await u.getBlock(g);if(!B||!Number.isInteger(B.timestamp)||B.timestamp<=0)throw new Error(`[backing] no block ${g}`);const P=BigInt(B.timestamp),R=new ethers.Contract(l.PositionManager,q,u),F=new ethers.Contract(await R.views({blockTag:g}),z,u),L=await async function(t,e){const r=[];let n=0;for(let i=0;i<1e4;i++){const i=await t.getBackingVaults(n,f,{blockTag:e});for(const t of i.vaults)r.push({positionId:String(t.positionId).toLowerCase(),vaultAddress:String(t.vaultAddress),ucdDebt:BigInt(t.ucdDebt.toString()),status:Number(t.status)});const o=Number(i.nextOffset.toString());if(o>=Number(i.total.toString()))return r;if(o<=n)throw new Error(`[backing] getBackingVaults did not advance at offset ${n}`);n=o}throw new Error("[backing] getBackingVaults did not finish within 10,000 pages")}(F,g);!function(t,e){if(t.length!==e.length)throw new Error(`[backing] snapshot has ${e.length} leaves but the chain's backing set has ${t.length} entries at this block`);for(let r=0;r<t.length;r++){const n=t[r],i=e[r];if(n.positionId.toLowerCase()!==i.positionId)throw new Error(`[backing] leaf ${r}: positionId ${i.positionId} is not the chain's ${n.positionId}`);if(n.vaultAddress!==i.vaultAddress)throw new Error(`[backing] leaf ${r} (${n.positionId}): vault ${i.vaultAddress} is not the chain's ${n.vaultAddress}`)}}(L,e.leaves);let O=0n,j=0n;const J=[];for(let t=0;t<L.length;t++)O+=e.leaves[t].sats,j+=L[t].ucdDebt,J.push((G=L[t].positionId,X=L[t].vaultAddress,Y=e.leaves[t].sats,ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","string","uint256"],[G,X,Y.toString()]))));var G,X,Y;const tt=function(t){if(0===t.length)return ethers.constants.HashZero;let e=t.map((t=>t.toLowerCase()));for(;e.length>1;){const t=[];for(let r=0;r<e.length;r+=2)if(r+1===e.length)t.push(e[r]);else{const[n,i]=e[r]<e[r+1]?[e[r],e[r+1]]:[e[r+1],e[r]];t.push(ethers.utils.keccak256(ethers.utils.concat([n,i])))}e=t}return e[0]}(J),et=function(t,e){const r=t.length;if(0===r)return[];const n=new Set,i=t.map(((t,e)=>({i:e,d:t.ucdDebt}))).sort(((t,e)=>t.d===e.d?t.i-e.i:t.d>e.d?-1:1));for(let t=0;t<Math.min(b,r);t++)n.add(i[t].i);for(let t=0;t<m;t++){const i=ethers.utils.keccak256(ethers.utils.solidityPack(["bytes32","uint8"],[e,t]));n.add(Number(BigInt(i)%BigInt(r)))}return[...n].sort(((t,e)=>t-e))}(L,e.btcBlockHash),rt=new Map(r.map((t=>[t.positionId,t])));if(r.length!==et.length)throw new Error(`[backing] ${r.length} samples supplied; the sample set at this block has ${et.length}`);if(et.length>0){const t=new ethers.Contract(await R.authorizationRegistry({blockTag:g}),V,u),r=await t.getValidator(ethers.utils.id(U).slice(0,10),{blockTag:g});if(!r.active)throw new Error("[backing] the updateBalance validator is not active");const i=new ethers.Contract(await R.core({blockTag:g}),K,u),o=new ethers.Contract(l.BTCSpendAuthorizer,W,u);await E();const a=A(),s={name:c,version:d,chainId:n.chainId,verifyingContract:ethers.utils.getAddress(l.LoanOperationsManagerModule)};for(const t of et){const n=L[t],c=rt.get(n.positionId);if(!c)throw new Error(`[backing] no sample for sampled position ${n.positionId} (index ${t})`);const d=await i.getPositionDetails(n.positionId,{blockTag:g}),l=_({confirmation:c.confirmation,positionId:n.positionId,borrower:ethers.utils.getAddress(d.borrower),validator:r.pkpAddress,domain:s,nowSeconds:a}),u=e.leaves[t].sats,h=await o.getAuthorizedSpends(n.positionId,{blockTag:g});if(0===h.length){if(l!==u)throw new Error(`[backing] sample ${n.positionId}: the loans' signed balance is ${l} sats but the leaf says ${u}; refusing to sign`)}else if(l<u)throw new Error(`[backing] sample ${n.positionId}: ${h.length} authorised spend(s) in flight; the loans' signed balance ${l} sats is below the leaf ${u} (a lagging leaf may only understate); refusing to sign`)}}const nt=new ethers.Contract(l.LoanOperationsManagerModule,Z,u),it=new ethers.Contract(await nt.btcUsdPriceFeed({blockTag:g}),Q,u),ot=await it.latestRoundData({blockTag:g}),at=BigInt(ot.answer.toString()),st=BigInt(ot.updatedAt.toString()),ct=BigInt((await nt.maxBtcFeedAgeBorrow({blockTag:g})).toString());if(st>P)throw new Error(`[backing] price feed updatedAt ${st} is after block ${g} (${P})`);if(P-st>ct)throw new Error(`[backing] price feed is ${P-st}s old at block ${g}; the protocol allows ${ct}s`);!function(t,e){if(t>y)throw new Error(`[backing] btcSats ${t} exceeds 21,000,000 BTC`);if(e<=0n)throw new Error("[backing] btcPriceE8 must be positive");if(e>v)throw new Error(`[backing] btcPriceE8 ${e} exceeds the $100,000,000 ceiling`)}(O,at);const dt=function(t,e,r){if(0n===r)throw new Error("[backing] ucdDebt is zero; the oracle refuses a report over no debt");return t*e*1000000n/r}(O,at,j),lt={btcSats:O.toString(),btcPriceE8:at.toString(),ucdDebt:j.toString(),ratioBps:dt.toString(),asOf:P.toString(),ethBlock:String(g),btcBlockHash:e.btcBlockHash,vaultsRoot:tt,vaultCount:String(L.length)},{signature:ut,signer:ht}=await async function(t,e,r,n){const i=await Lit.Actions.getPrivateKey({pkpId:t}),o="string"==typeof i?i.startsWith("0x")?i:`0x${i}`:String(i),a=new ethers.Wallet(o);if(a.address!==ethers.utils.getAddress(t))throw new Error(`[carry] key for ${t} derives ${a.address}; refusing to sign`);return{signature:await a._signTypedData(e,r,n),signer:a.address}}(t.validatorWalletAddress,i,p,lt);return{backing:lt,signature:ut,signer:ht,domain:i,sampled:et.map((t=>L[t].positionId))}}return j=i,((i,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))n.call(i,c)||c===a||t(i,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return i})(t({},"__esModule",{value:!0}),j)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -0,0 +1 @@
1
+ 8489b1a3180799b7c7492dd6d589e946f7a726e9afbcbc79339c0772d363eff5
@@ -0,0 +1,9 @@
1
+ {
2
+ "actionName": "backing-attestation",
3
+ "originalSize": 33918,
4
+ "minifiedSize": 19189,
5
+ "compressionRatio": 0.4342531988914441,
6
+ "hash": "8489b1a3180799b7c7492dd6d589e946f7a726e9afbcbc79339c0772d363eff5",
7
+ "buildTime": 1793892469091,
8
+ "version": "0.1.0"
9
+ }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function n(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function s(...t){n()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},c=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},l=class{static create(t="LIT Action",e){return n(e)?new c(t):new a}},d=25e14,u=60,h=16,p={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var g="DiamondHands.Protocol",m="1",f="address-balance",w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["infura.io","drpc.org","drpc.live"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){return $[t]}function E(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function A(t){return t instanceof Error&&"AbortError"===t.name}function C(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function B(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&C(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&C(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return C(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");C(o,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&C(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var P=new Map;async function k(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,o=P.get(i);if(o)return o;const n=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,n=setTimeout((()=>o.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:o.signal})}finally{clearTimeout(n)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>P.delete(i))),P.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function x(t,e){if(!Number.isSafeInteger(t)||t<0||t>d)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var I="Bitcoin tip-height read failed",S=class extends Error{constructor(t){super(t),this.isBitcoinTipUnreadable=!0,this.name="BitcoinTipUnreadableError"}};var U=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await k(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),s(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const o=await i.text();if(o.trim().startsWith("<!DOCTYPE")||o.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const n=parseInt(o.trim(),10);if(isNaN(n)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return x(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,n=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===n||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");x(s,`parseBlockstreamUTXOs ${o}:${n}`),i.push({txid:o,vout:n,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(o),s(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const c=await a.text();if(c.trim().startsWith("<!DOCTYPE")||c.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${T(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,n);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-n;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),s(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const a=await n.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const c=a.chain_stats.funded_txo_sum,l=a.chain_stats.spent_txo_sum;if(void 0===c||void 0===l)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${c}, spent_txo_sum: ${l}`);x(c,`getBalance ${e} funded_txo_sum`),x(l,`getBalance ${e} spent_txo_sum`);const d=c-l;x(d,`getBalance ${e} confirmed balance`);const u=BigInt(d);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${c} sats, Spent: ${l} sats`),u}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),s(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const n=await o.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};const r=await this.fetchTipHeight(e.signal)-n.status.block_height+1;return{txid:n.txid??t,confirmations:r>0?r:0}}return null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(function(t){return"object"==typeof t&&null!==t&&!0===t.isBitcoinTipUnreadable}(t))throw t;if(T(t).includes("404"))return null;throw t}}async fetchTipHeight(t){const e=`${this.config.providerUrl}/blocks/tip/height`;let r;try{r=await fetch(e,{signal:t,headers:await this.withAuth()})}catch(t){throw new S(`${I}: GET ${e} threw \u2014 ${T(t)}`)}if(!r.ok)throw new S(`${I}: GET ${e} \u2192 ${r.status} ${r.statusText}`);const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)throw new S(`${I}: GET ${e} returned an unusable tip height "${i.slice(0,64)}"`);return o}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return x(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};var D={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:y.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:y.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:y.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function R(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(w).join(", ")}`)}(t),r=D[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _=["drpc.org","drpc.live"],O="Drpc-Key",N=/^[A-Za-z0-9_-]{16,128}$/;function M(t){return _.some((e=>t===e||t.endsWith(`.${e}`)))}function F(t,e){if("string"!=typeof t||!N.test(t))throw new Error(`Invalid ${e}: expected 16-128 characters of [A-Za-z0-9_-]`)}function L(t){if("https:"!==t.protocol)throw new Error(`A dRPC key is only sent over https, but the RPC URL scheme is "${t.protocol}"`)}function q(t,e){if(void 0===e)return;F(e,'"drpcKey"');const r=new URL(t);if(!M(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${_.join(" or ")})`);if(L(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return e}var H=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function j(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const i=(o=t.chainId,p[o]??null);var o;if(!i)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of H){const o=i[e];if(!o)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}async function W(t,e){const r=e.rpcUrl,i=e.rpcSource??"params-or-lit-node";let o;if("string"==typeof r&&r.length>0)!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!v.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(t,r),o=r;else{if("params-only"===i)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(o=await async function(t,e){if(void 0!==e)throw new Error('"drpcKey" was supplied without an "rpcUrl" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\'s own endpoint');return Lit.Actions.getRpcUrl({chain:t})}(e.chain,e.drpcKey),"string"!=typeof o||0===o.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${e.chain}"`)}return{rpcUrl:o,drpcKey:q(o,e.drpcKey),addresses:j(t,e.contractAddresses)}}var K=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],X=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function G(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function z(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,K,e),[o,n]=await i.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return s}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(i,X,r);let a;try{a=await s.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${n.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const o=[];for(const e of i){const r=await G(e.ciphertext,e.pkpId),{url:i,auth:n}=B(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}var J,V={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},Z="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function Q(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/u)*u;var e}async function Y(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=u-8}(t))return;const r=h/2;let i;i=e>=u-r?u-e+r:r-e,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${Q()}`)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=E();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "vaultAddress"');if(!o)throw new Error('Missing required parameter: "publicKey"');const a=R(r),c=a.chain,l=a.bitcoinNetwork,d=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=V[e],o=new RegExp(`^q[${Z}]{38}$`);if(!r.startsWith(i)){const o=r.startsWith("bcrt1")?"bcrt1":r.startsWith("tb1")?"tb1":r.startsWith("bc1")?"bc1":null;if(o&&o!==i)throw new Error(`vaultAddress network mismatch: address prefix "${o}" does not match chain network "${e}" (expected "${i}")`);throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`)}const n=r.slice(i.length);if(!o.test(n))throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`);return r}(i,l),{rpcUrl:u,drpcKey:h,addresses:p}=await W(a,{chain:r,rpcUrl:n,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses}),w=p.BitcoinProviderRegistry;if(a.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!w)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${c})`),s(` \u2705 Bitcoin Network: ${l}`),s(` \u2705 Vault Address: ${d}`);try{const t=new ethers.providers.JsonRpcProvider(function(t,e,r){const i={url:t},o=q(t,e);if(void 0!==o)i.headers={[O]:o};else{const e=new URL(t),r=e.searchParams.getAll("dkey");if(r.length>1)throw new Error(`rpcUrl carries ${r.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===r.length&&!M(e.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${e.hostname}" \u2014 a dRPC key is only sent to ${_.join(" or ")}`);if(1===r.length){const t=r[0];F(t,"dRPC key in rpcUrl (?dkey=)"),L(e),e.searchParams.delete("dkey"),i.url=e.toString(),i.headers={[O]:t}}}return void 0!==r&&(i.timeout=r),i}(u,h));let r;r=a.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:a.minBitcoinBalanceConfirmations,network:a.bitcoinNetwork}]:await z(a,t,w),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=await async function(t,e,r,i,o){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=o??(t=>new U({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),s=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=s.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const c=s.map((t=>t.value)),l=c[0],d=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(d.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${d.join("; ")}`);return e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`),l}(d,r,a.minConsensusProviders),o=r.length;s("[Step 2] Signing address balance attestation..."),await Y();const n=Q(),l=a.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:w,{domain:p,types:v,value:$}=(y={verifyingContract:l,chainId:b(c),vaultAddress:d,totalBalanceSats:i,providerCount:o,timestamp:n},{domain:{name:g,version:m,chainId:y.chainId,verifyingContract:ethers.utils.getAddress(y.verifyingContract)},types:{AddressBalanceAttestation:[{name:"actionTag",type:"bytes32"},{name:"vaultAddressHash",type:"bytes32"},{name:"totalBalanceSats",type:"uint256"},{name:"providerCount",type:"uint256"},{name:"timestamp",type:"uint256"}]},value:{actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(y.vaultAddress)),totalBalanceSats:y.totalBalanceSats.toString(),providerCount:y.providerCount,timestamp:y.timestamp}}),E=globalThis.validatorWalletAddress;if(!E||!E.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const T=await Lit.Actions.getPrivateKey({pkpId:E}),A="string"==typeof T?T.startsWith("0x")?T:`0x${T}`:String(T),C=new ethers.Wallet(A),B=await C._signTypedData(p,v,$);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:d,totalBalanceSats:i.toString(),providerCount:o,signature:B,timestamp:n,validatorPkp:C.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:d||null,timestamp:Date.now()}}var y}return J=o,((o,n,s,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))i.call(o,c)||c===s||t(o,c,{get:()=>n[c],enumerable:!(a=e(n,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),J)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function n(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function s(...t){n()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},c=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},l=class{static create(t="LIT Action",e){return n(e)?new c(t):new a}},d=25e14,u=60,h=16,p={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var g="DiamondHands.Protocol",m="1",f="address-balance",w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["infura.io","drpc.org","drpc.live"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){return $[t]}function E(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function A(t){return t instanceof Error&&"AbortError"===t.name}function C(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function B(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&C(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&C(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return C(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");C(o,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&C(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var P=new Map;async function k(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,o=P.get(i);if(o)return o;const n=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,n=setTimeout((()=>o.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:o.signal})}finally{clearTimeout(n)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>P.delete(i))),P.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function x(t,e){if(!Number.isSafeInteger(t)||t<0||t>d)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var I="Bitcoin tip-height read failed",S=class extends Error{constructor(t){super(t),this.isBitcoinTipUnreadable=!0,this.name="BitcoinTipUnreadableError"}};var U=class{constructor(t){if("string"!=typeof t.providerUrl||0===t.providerUrl.trim().length)throw new Error("BitcoinDataProvider: providerUrl must be a non-empty string; refusing to construct a provider that cannot be queried");this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await k(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),s(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const o=await i.text();if(o.trim().startsWith("<!DOCTYPE")||o.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const n=parseInt(o.trim(),10);if(isNaN(n)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return x(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,n=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===n||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");x(s,`parseBlockstreamUTXOs ${o}:${n}`),i.push({txid:o,vout:n,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(o),s(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const c=await a.text();if(c.trim().startsWith("<!DOCTYPE")||c.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${T(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,n);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-n;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),s(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const a=await n.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const c=a.chain_stats.funded_txo_sum,l=a.chain_stats.spent_txo_sum;if(void 0===c||void 0===l)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${c}, spent_txo_sum: ${l}`);x(c,`getBalance ${e} funded_txo_sum`),x(l,`getBalance ${e} spent_txo_sum`);const d=c-l;x(d,`getBalance ${e} confirmed balance`);const u=BigInt(d);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${c} sats, Spent: ${l} sats`),u}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),s(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const n=await o.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};const r=await this.fetchTipHeight(e.signal)-n.status.block_height+1;return{txid:n.txid??t,confirmations:r>0?r:0}}return null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(function(t){return"object"==typeof t&&null!==t&&!0===t.isBitcoinTipUnreadable}(t))throw t;if(T(t).includes("404"))return null;throw t}}async fetchTipHeight(t){const e=`${this.config.providerUrl}/blocks/tip/height`;let r;try{r=await fetch(e,{signal:t,headers:await this.withAuth()})}catch(t){throw new S(`${I}: GET ${e} threw \u2014 ${T(t)}`)}if(!r.ok)throw new S(`${I}: GET ${e} \u2192 ${r.status} ${r.statusText}`);const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)throw new S(`${I}: GET ${e} returned an unusable tip height "${i.slice(0,64)}"`);return o}async getTransactionOutputs(t){const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return x(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};var D={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:y.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:y.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:y.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function R(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(w).join(", ")}`)}(t),r=D[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _=["drpc.org","drpc.live"],O="Drpc-Key",N=/^[A-Za-z0-9_-]{16,128}$/;function M(t){return _.some((e=>t===e||t.endsWith(`.${e}`)))}function F(t,e){if("string"!=typeof t||!N.test(t))throw new Error(`Invalid ${e}: expected 16-128 characters of [A-Za-z0-9_-]`)}function L(t){if("https:"!==t.protocol)throw new Error(`A dRPC key is only sent over https, but the RPC URL scheme is "${t.protocol}"`)}function q(t,e){if(void 0===e)return;F(e,'"drpcKey"');const r=new URL(t);if(!M(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${_.join(" or ")})`);if(L(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return e}var H=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function j(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const i=(o=t.chainId,p[o]??null);var o;if(!i)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of H){const o=i[e];if(!o)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}async function W(t,e){const r=e.rpcUrl,i=e.rpcSource??"params-or-lit-node";let o;if("string"==typeof r&&r.length>0)!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!v.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(t,r),o=r;else{if("params-only"===i)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(o=await async function(t,e){if(void 0!==e)throw new Error('"drpcKey" was supplied without an "rpcUrl" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\'s own endpoint');return Lit.Actions.getRpcUrl({chain:t})}(e.chain,e.drpcKey),"string"!=typeof o||0===o.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${e.chain}"`)}return{rpcUrl:o,drpcKey:q(o,e.drpcKey),addresses:j(t,e.contractAddresses)}}var K=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],X=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function G(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function z(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,K,e),[o,n]=await i.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return s}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(i,X,r);let a;try{a=await s.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${n.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const o=[];for(const e of i){const r=await G(e.ciphertext,e.pkpId),{url:i,auth:n}=B(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}var J,V={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},Z="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function Q(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/u)*u;var e}async function Y(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=u-8}(t))return;const r=h/2;let i;i=e>=u-r?u-e+r:r-e,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${Q()}`)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=E();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "vaultAddress"');if(!o)throw new Error('Missing required parameter: "publicKey"');const a=R(r),c=a.chain,l=a.bitcoinNetwork,d=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=V[e],o=new RegExp(`^q[${Z}]{38}$`);if(!r.startsWith(i)){const o=r.startsWith("bcrt1")?"bcrt1":r.startsWith("tb1")?"tb1":r.startsWith("bc1")?"bc1":null;if(o&&o!==i)throw new Error(`vaultAddress network mismatch: address prefix "${o}" does not match chain network "${e}" (expected "${i}")`);throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`)}const n=r.slice(i.length);if(!o.test(n))throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`);return r}(i,l),{rpcUrl:u,drpcKey:h,addresses:p}=await W(a,{chain:r,rpcUrl:n,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses}),w=p.BitcoinProviderRegistry;if(a.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!w)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${c})`),s(` \u2705 Bitcoin Network: ${l}`),s(` \u2705 Vault Address: ${d}`);try{const t=new ethers.providers.JsonRpcProvider(function(t,e,r){const i={url:t},o=q(t,e);if(void 0!==o)i.headers={[O]:o};else{const e=new URL(t),r=e.searchParams.getAll("dkey");if(r.length>1)throw new Error(`rpcUrl carries ${r.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===r.length&&!M(e.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${e.hostname}" \u2014 a dRPC key is only sent to ${_.join(" or ")}`);if(1===r.length){const t=r[0];F(t,"dRPC key in rpcUrl (?dkey=)"),L(e),e.searchParams.delete("dkey"),i.url=e.toString(),i.headers={[O]:t}}}return void 0!==r&&(i.timeout=r),i}(u,h));let r;r=a.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:a.minBitcoinBalanceConfirmations,network:a.bitcoinNetwork}]:await z(a,t,w),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=await async function(t,e,r,i,o){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=o??(t=>new U({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),s=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=s.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const c=s.map((t=>t.value)),l=c[0],d=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(d.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${d.join("; ")}`);return e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`),l}(d,r,a.minConsensusProviders),o=r.length;s("[Step 2] Signing address balance attestation..."),await Y();const n=Q(),l=a.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:w,{domain:p,types:v,value:$}=(y={verifyingContract:l,chainId:b(c),vaultAddress:d,totalBalanceSats:i,providerCount:o,timestamp:n},{domain:{name:g,version:m,chainId:y.chainId,verifyingContract:ethers.utils.getAddress(y.verifyingContract)},types:{AddressBalanceAttestation:[{name:"actionTag",type:"bytes32"},{name:"vaultAddressHash",type:"bytes32"},{name:"totalBalanceSats",type:"uint256"},{name:"providerCount",type:"uint256"},{name:"timestamp",type:"uint256"}]},value:{actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(y.vaultAddress)),totalBalanceSats:y.totalBalanceSats.toString(),providerCount:y.providerCount,timestamp:y.timestamp}}),E=globalThis.validatorWalletAddress;if(!E||!E.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const T=await Lit.Actions.getPrivateKey({pkpId:E}),A="string"==typeof T?T.startsWith("0x")?T:`0x${T}`:String(T),C=new ethers.Wallet(A),B=await C._signTypedData(p,v,$);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:d,totalBalanceSats:i.toString(),providerCount:o,signature:B,timestamp:n,validatorPkp:C.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:d||null,timestamp:Date.now()}}var y}return J=o,((o,n,s,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))i.call(o,c)||c===s||t(o,c,{get:()=>n[c],enumerable:!(a=e(n,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),J)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -1 +1 @@
1
- 2297c7b625340f048b5926325a14c958016594b77f4c4270ef413b164a8ac975
1
+ bdd1356d959916d427094b77877c6337477ae84d6a7a54e600b93e66c01b5ae5
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-address-balance",
3
- "originalSize": 65366,
4
- "minifiedSize": 31909,
5
- "compressionRatio": 0.5118410182663771,
6
- "hash": "2297c7b625340f048b5926325a14c958016594b77f4c4270ef413b164a8ac975",
7
- "buildTime": 1792746369661,
3
+ "originalSize": 65566,
4
+ "minifiedSize": 32072,
5
+ "compressionRatio": 0.5108440350181497,
6
+ "hash": "bdd1356d959916d427094b77877c6337477ae84d6a7a54e600b93e66c01b5ae5",
7
+ "buildTime": 1793892469199,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 5769,
5
5
  "compressionRatio": 0.43173758865248224,
6
6
  "hash": "5e420c2f758018417309d4114333fc4c8200212db518f32281e9ec766cd7ebac",
7
- "buildTime": 1792746369719,
7
+ "buildTime": 1793892469241,
8
8
  "version": "0.1.0"
9
9
  }