@gvnrdao/dh-lit-actions 0.0.327 → 0.0.328

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 (62) 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/btc-address-balance.action.js +1 -1
  10. package/dist/btc-address-balance.hash +1 -1
  11. package/dist/btc-address-balance.meta.json +5 -5
  12. package/dist/btc-provider-probe.meta.json +1 -1
  13. package/dist/btc-transaction-signer.action.js +1 -1
  14. package/dist/btc-transaction-signer.hash +1 -1
  15. package/dist/btc-transaction-signer.meta.json +5 -5
  16. package/dist/btc-utxo-invalidator.action.js +1 -1
  17. package/dist/btc-utxo-invalidator.hash +1 -1
  18. package/dist/btc-utxo-invalidator.meta.json +5 -5
  19. package/dist/btc-withdrawal.action.js +1 -1
  20. package/dist/btc-withdrawal.hash +1 -1
  21. package/dist/btc-withdrawal.meta.json +5 -5
  22. package/dist/carry-collateral-attestation.action.js +1 -1
  23. package/dist/carry-collateral-attestation.hash +1 -1
  24. package/dist/carry-collateral-attestation.meta.json +5 -5
  25. package/dist/carry-funding-attestation.meta.json +1 -1
  26. package/dist/encrypt-parameter.meta.json +1 -1
  27. package/dist/extend-position-validator.action.js +1 -1
  28. package/dist/extend-position-validator.hash +1 -1
  29. package/dist/extend-position-validator.meta.json +5 -5
  30. package/dist/liquidation-validator.action.js +1 -1
  31. package/dist/liquidation-validator.hash +1 -1
  32. package/dist/liquidation-validator.meta.json +5 -5
  33. package/dist/loan-vault-btc-balance.action.js +1 -1
  34. package/dist/loan-vault-btc-balance.hash +1 -1
  35. package/dist/loan-vault-btc-balance.meta.json +5 -5
  36. package/dist/pkp-validator.meta.json +1 -1
  37. package/dist/price-oracle.meta.json +1 -1
  38. package/dist/process-payment-validator.action.js +1 -1
  39. package/dist/process-payment-validator.hash +1 -1
  40. package/dist/process-payment-validator.meta.json +5 -5
  41. package/dist/stale-spend-recovery-validator.action.js +1 -1
  42. package/dist/stale-spend-recovery-validator.hash +1 -1
  43. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  44. package/dist/ucd-mint-validator.action.js +1 -1
  45. package/dist/ucd-mint-validator.hash +1 -1
  46. package/dist/ucd-mint-validator.meta.json +5 -5
  47. package/package.json +5 -1
  48. package/pkg-dist/pkg-src/index.js +155 -92
  49. package/pkg-dist/pkg-src/index.js.map +2 -2
  50. package/pkg-dist/src/constants/chunks/liquidation.d.ts +14 -11
  51. package/pkg-dist/src/constants/chunks/liquidation.d.ts.map +1 -1
  52. package/pkg-dist/src/constants/index.d.ts +1 -1
  53. package/pkg-dist/src/constants/index.d.ts.map +1 -1
  54. package/pkg-dist/src/modules/authorization.module.d.ts +8 -20
  55. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  56. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
  57. package/pkg-dist/src/modules/business-rules-math.module.d.ts +30 -15
  58. package/pkg-dist/src/modules/business-rules-math.module.d.ts.map +1 -1
  59. package/pkg-dist/src/modules/protocol-parameters.module.d.ts +18 -1
  60. package/pkg-dist/src/modules/protocol-parameters.module.d.ts.map +1 -1
  61. package/pkg-dist/src/modules/vault-balance-consensus.module.d.ts.map +1 -1
  62. 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": 1793695554394,
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": 1793695554402,
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": 1793695554427,
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": 1793695554435,
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": 1793695554444,
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": 1793695554450,
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": 1793695554459,
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": 1793695554508,
8
8
  "version": "0.1.0"
9
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": 1793695554602,
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": 1793695554619,
8
8
  "version": "0.1.0"
9
9
  }