@gvnrdao/dh-lit-actions 0.0.308 → 0.0.310

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 (54) 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/btc-address-balance.action.js +1 -1
  9. package/dist/btc-address-balance.hash +1 -1
  10. package/dist/btc-address-balance.meta.json +5 -5
  11. package/dist/btc-transaction-signer.action.js +1 -1
  12. package/dist/btc-transaction-signer.hash +1 -1
  13. package/dist/btc-transaction-signer.meta.json +5 -5
  14. package/dist/btc-utxo-invalidator.action.js +1 -1
  15. package/dist/btc-utxo-invalidator.hash +1 -1
  16. package/dist/btc-utxo-invalidator.meta.json +5 -5
  17. package/dist/btc-withdrawal.action.js +1 -1
  18. package/dist/btc-withdrawal.hash +1 -1
  19. package/dist/btc-withdrawal.meta.json +5 -5
  20. package/dist/encrypt-parameter.meta.json +1 -1
  21. package/dist/extend-position-validator.action.js +1 -1
  22. package/dist/extend-position-validator.hash +1 -1
  23. package/dist/extend-position-validator.meta.json +5 -5
  24. package/dist/liquidation-validator.action.js +1 -1
  25. package/dist/liquidation-validator.hash +1 -1
  26. package/dist/liquidation-validator.meta.json +5 -5
  27. package/dist/loan-vault-btc-balance.action.js +1 -1
  28. package/dist/loan-vault-btc-balance.hash +1 -1
  29. package/dist/loan-vault-btc-balance.meta.json +5 -5
  30. package/dist/pkp-validator.meta.json +1 -1
  31. package/dist/price-oracle.meta.json +1 -1
  32. package/dist/process-payment-validator.action.js +1 -1
  33. package/dist/process-payment-validator.hash +1 -1
  34. package/dist/process-payment-validator.meta.json +5 -5
  35. package/dist/stale-spend-recovery-validator.action.js +1 -1
  36. package/dist/stale-spend-recovery-validator.hash +1 -1
  37. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  38. package/dist/ucd-mint-validator.action.js +1 -1
  39. package/dist/ucd-mint-validator.hash +1 -1
  40. package/dist/ucd-mint-validator.meta.json +5 -5
  41. package/package.json +1 -1
  42. package/pkg-dist/pkg-src/index.js +150 -77
  43. package/pkg-dist/pkg-src/index.js.map +4 -4
  44. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +7 -0
  45. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
  46. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +5 -0
  47. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
  48. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts +23 -2
  49. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts.map +1 -1
  50. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts +8 -1
  51. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
  52. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts +70 -0
  53. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts.map +1 -0
  54. package/pkg-dist/src/modules/bitcoin-provider-registry.d.ts.map +1 -1
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1608,
5
5
  "compressionRatio": 0.45895020188425306,
6
6
  "hash": "c6042989c2e0ac53631e008a960aef78f977471b9a7a8fc05a1537b10f34c8a9",
7
- "buildTime": 1781133966995,
7
+ "buildTime": 1781559386579,
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": 1781133967005,
7
+ "buildTime": 1781559386593,
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": 1781133967033,
7
+ "buildTime": 1781559386643,
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": 1781133967041,
7
+ "buildTime": 1781559386654,
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": 1781133967050,
7
+ "buildTime": 1781559386668,
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": 1781133967056,
7
+ "buildTime": 1781559386688,
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": 1781133967066,
7
+ "buildTime": 1781559386720,
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="DiamondHands.Protocol",h="1",u="address-balance",p=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(p||{}),g={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},m=["infura.io","drpc.org"],f={ethereum:1,sepolia:11155111,hardhat:1337};function w(t){return f[t]}function y(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function v(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}var b=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}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:{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"),$(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: ${v(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: ${v(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${v(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=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),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");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}/utxos`;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:{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 utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (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: ${v(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"),$(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(v(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${v(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(),e=await fetch(r,{signal:i.signal,headers:{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)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const n=await e.json();if(!n.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=n.chain_stats.funded_txo_sum,c=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);const l=BigInt(a-c);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=v(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=v(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});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};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:n.txid??t,confirmations:1};const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)return{txid:n.txid??t,confirmations:1};const s=o-n.status.block_height+1;return{txid:n.txid??t,confirmations:s>0?s:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(v(t).includes("404"))return null;throw t}}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});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(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},T={hardhat:{chain:"hardhat",chainId:f.hardhat,bitcoinNetwork:g.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:g.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:g.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function E(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(p).join(", ")}`)}(t),r=T[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var A=[{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 B(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 I(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,A,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(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. 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 B(e.ciphertext,e.pkpId);o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return o}var P,k={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},C="qpzry9x8gf2tvdw0s3jn54khce6mua7l";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=y();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.timestamp||Math.floor(Date.now()/1e3),a=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 c=E(r),l=c.chain,p=c.bitcoinNetwork,g=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=k[e],o=new RegExp(`^q[${C}]{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,p);let f;a&&"string"==typeof a?(!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(!m.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${m.join(", ")}`)}(c,a),f=a):f=await Lit.Actions.getRpcUrl({chain:r});const v=e.contractAddresses?.BitcoinProviderRegistry;if(c.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!v)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${l})`),s(` \u2705 Bitcoin Network: ${p}`),s(` \u2705 Vault Address: ${g}`);try{const t=new ethers.providers.JsonRpcProvider(f);let r;r=c.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:c.minBitcoinConfirmations,network:c.bitcoinNetwork}]:await I(c,t,v),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=r[0],o=new b({providerUrl:i.url}),a=await o.getBalance(g);if(r.length>1){for(let t=1;t<r.length;t++){const e=r[t],o=new b({providerUrl:e.url}),n=await o.getBalance(g);if(n!==a)throw new Error(`Bitcoin provider balance mismatch: ${i.name}=${a.toString()} vs ${e.name}=${n.toString()}`)}s(` \u2705 Consensus reached across ${r.length} providers (${a.toString()} sats)`)}const p=r.length;s("[Step 2] Signing address balance attestation...");const m=c.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:v,{domain:y,types:T,value:E}=($={verifyingContract:m,chainId:w(l),vaultAddress:g,totalBalanceSats:a,providerCount:p,timestamp:n},{domain:{name:d,version:h,chainId:$.chainId,verifyingContract:ethers.utils.getAddress($.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(u)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes($.vaultAddress)),totalBalanceSats:$.totalBalanceSats.toString(),providerCount:$.providerCount,timestamp:$.timestamp}}),A=globalThis.validatorWalletAddress;if(!A||!A.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const x=await Lit.Actions.getPrivateKey({pkpId:A}),B="string"==typeof x?x.startsWith("0x")?x:`0x${x}`:String(x),P=new ethers.Wallet(B),k=await P._signTypedData(y,T,E);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:g,totalBalanceSats:a.toString(),providerCount:p,signature:k,timestamp:n,validatorPkp:P.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:g||null,timestamp:Date.now()}}var $}return P=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}),P)})();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="DiamondHands.Protocol",h="1",u="address-balance",p=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(p||{}),m={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},g=["infura.io","drpc.org"],w={ethereum:1,sepolia:11155111,hardhat:1337};function f(t){return w[t]}function y(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function v(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}function b(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function T(t){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const e=t.trim();if(!e.startsWith("{"))return{url:e,auth:{provider:"esplora"}};let r;try{r=JSON.parse(e)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof r.url||0===r.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=r.url.trim();switch(r.provider){case void 0:case"esplora":return{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof r.apiKey||0===r.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return b(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:r.apiKey}};case"blockstream-enterprise":{if("string"!=typeof r.clientId||0===r.clientId.length||"string"!=typeof r.clientSecret||0===r.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");b(i,"blockstream-enterprise provider url");const t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&b(r.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:r.clientId,clientSecret:r.clientSecret,...t?{tokenUrl:r.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(r.provider)}"`)}}var E=new Map;async function A(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=E.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((()=>E.delete(i))),E.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}var k=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await A(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"),$(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: ${v(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: ${v(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${v(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=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),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");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: ${v(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"),$(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(v(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${v(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(),e=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)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const n=await e.json();if(!n.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=n.chain_stats.funded_txo_sum,c=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);const l=BigInt(a-c);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=v(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=v(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};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:n.txid??t,confirmations:1};const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)return{txid:n.txid??t,confirmations:1};const s=o-n.status.block_height+1;return{txid:n.txid??t,confirmations:s>0?s:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(v(t).includes("404"))return null;throw t}}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(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};var x={hardhat:{chain:"hardhat",chainId:w.hardhat,bitcoinNetwork:m.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:w.sepolia,bitcoinNetwork:m.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:w.ethereum,bitcoinNetwork:m.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function P(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(p).join(", ")}`)}(t),r=x[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var I=[{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"}],B=[{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 S(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 C(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,I,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(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. 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,B,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 S(e.ciphertext,e.pkpId),{url:i,auth:n}=T(r);o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return o}var U,_={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},N="qpzry9x8gf2tvdw0s3jn54khce6mua7l";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=y();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.timestamp||Math.floor(Date.now()/1e3),a=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 c=P(r),l=c.chain,p=c.bitcoinNetwork,m=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=_[e],o=new RegExp(`^q[${N}]{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,p);let w;a&&"string"==typeof a?(!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(!g.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${g.join(", ")}`)}(c,a),w=a):w=await Lit.Actions.getRpcUrl({chain:r});const v=e.contractAddresses?.BitcoinProviderRegistry;if(c.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!v)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${l})`),s(` \u2705 Bitcoin Network: ${p}`),s(` \u2705 Vault Address: ${m}`);try{const t=new ethers.providers.JsonRpcProvider(w);let r;r=c.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:c.minBitcoinConfirmations,network:c.bitcoinNetwork}]:await C(c,t,v),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=await async function(t,e,r,i){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");const o=i??(t=>new k({providerUrl:t.url,auth:t.auth,...r?{timeout:r}:{}})),n=await Promise.allSettled(e.map((e=>o(e).getBalance(t)))),s=n.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(s.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${s.length}/${e.length} provider(s): ${s.join("; ")}`);const a=n.map((t=>t.value)),c=a[0],l=a.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==c)).map((t=>`${e[0].name}=${c.toString()} vs ${t.name}=${t.bal.toString()}`));if(l.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${l.join("; ")}`);return e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${c.toString()} sats)`),c}(m,r),o=r.length;s("[Step 2] Signing address balance attestation...");const a=c.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:v,{domain:p,types:g,value:y}=($={verifyingContract:a,chainId:f(l),vaultAddress:m,totalBalanceSats:i,providerCount:o,timestamp:n},{domain:{name:d,version:h,chainId:$.chainId,verifyingContract:ethers.utils.getAddress($.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(u)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes($.vaultAddress)),totalBalanceSats:$.totalBalanceSats.toString(),providerCount:$.providerCount,timestamp:$.timestamp}}),b=globalThis.validatorWalletAddress;if(!b||!b.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const T=await Lit.Actions.getPrivateKey({pkpId:b}),E="string"==typeof T?T.startsWith("0x")?T:`0x${T}`:String(T),A=new ethers.Wallet(E),x=await A._signTypedData(p,g,y);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:m,totalBalanceSats:i.toString(),providerCount:o,signature:x,timestamp:n,validatorPkp:A.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:m||null,timestamp:Date.now()}}var $}return U=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}),U)})();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
- b17977304be6b117bcb29feafc3bb654113d72d5147ceeba92e91b4d7f5c0327
1
+ 000e2f8bdbccdc95b0db0fb3f12412e2e76eea16a8456d37914d324437ae291c
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-address-balance",
3
- "originalSize": 45547,
4
- "minifiedSize": 21957,
5
- "compressionRatio": 0.5179265374228819,
6
- "hash": "b17977304be6b117bcb29feafc3bb654113d72d5147ceeba92e91b4d7f5c0327",
7
- "buildTime": 1781133967132,
3
+ "originalSize": 51794,
4
+ "minifiedSize": 25519,
5
+ "compressionRatio": 0.5072981426420049,
6
+ "hash": "000e2f8bdbccdc95b0db0fb3f12412e2e76eea16a8456d37914d324437ae291c",
7
+ "buildTime": 1781559386845,
8
8
  "version": "0.1.0"
9
9
  }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,r={};async function i(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const o=e.slice(2,66),n=e.slice(66,130),r=(BigInt("0x"+n)%2n===0n?"02":"03")+o,i=ethers.utils.sha256("0x"+r);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const u=function(t,e,o){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=[];for(let t=0;t<o.length;t+=2)r.push(parseInt(o.substr(t,2),16));const i=a(r,8,5,!0),s=[e,...i],u=function(t,e){const o=function(t){const e=[];for(let o=0;o<t.length;o++)e.push(t.charCodeAt(o)>>5);e.push(0);for(let o=0;o<t.length;o++)e.push(31&t.charCodeAt(o));return e}(t).concat(e).concat([0,0,0,0,0,0]),n=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let o=1;for(let n=0;n<t.length;n++){const r=o>>25;o=(33554431&o)<<5^t[n];for(let t=0;t<5;t++)r>>t&1&&(o^=e[t])}return o}(o),r=[];for(let t=0;t<6;t++)r.push(n>>5*(5-t)&31);return r}(t,s),c=[...s,...u];let l=t+"1";for(let t=0;t<c.length;t++)l+=n[c[t]];return l}(s,0,ethers.utils.ripemd160(i).slice(2));return u}function s(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",o=t.lastIndexOf("1");if(o<1)throw new Error("No separator character for bech32");const n=t.substring(o+1).toLowerCase(),r=[];for(let t=0;t<n.length;t++){const o=e.indexOf(n[t]);if(-1===o)throw new Error(`Invalid bech32 character: ${n[t]}`);r.push(o)}const i=r.slice(0,-6),s=a(i.slice(1),5,8,!1);return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let o=0n;for(let n=0;n<t.length;n++){const r=e.indexOf(t[n]);if(r<0)throw new Error(`Invalid Base58 character: ${t[n]}`);o=58n*o+BigInt(r)}let n=o.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function a(t,e,o,n){let r=0,i=0;const s=[],a=(1<<o)-1;for(let n=0;n<t.length;n++){const u=t[n];if(u<0||u>>e)throw new Error("Invalid data for bit conversion");for(r=r<<e|u,i+=e;i>=o;)i-=o,s.push(r>>i&a)}if(n)i>0&&s.push(r<<o-i&a);else if(i>=e||r<<o-i&a)throw new Error("Invalid padding in bit conversion");return s}function u(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function c(t,e){const o=t.toString(16).padStart(2*e,"0").match(/../g);if(!o)throw new Error(`Invalid hex conversion: ${t}`);return o.reverse().join("")}function l(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+c(t,2):t<=4294967295?"fe"+c(t,4):"ff"+c(t,8)}((e,o)=>{for(var n in o)t(e,n,{get:o[n],enumerable:!0})})(r,{main:()=>main});var d=100,h=1e5,g=60,p={ethereum:1,sepolia:11155111,hardhat:1337};function m(t){return Math.floor(t/g)*g}async function f(){const t=Math.floor(Date.now()/1e3),e=t%g;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%g;return e<8||e>=52}(t))return;let o;o=e>=52?g-e+8:8-e,console.log(`[Quantum] Waiting ${o}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*o))),console.log(`[Quantum] Safe quantum ready: ${m(Math.floor(Date.now()/1e3))}`)}var w=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const o=ethers.utils.arrayify(t),n=ethers.utils.hashMessage(o);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,o,n){try{const r=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await r.isValidSignature(e,o)}catch{return!1}}static async checkPositionDelegate(t,e,o,n){try{const r=new ethers.Contract(o,["function positionDelegate(bytes32) view returns (address)"],n),i=await r.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,o,n){const r=Math.floor(Date.now()/1e3);await f();const i=n?.strictCurrentQuantum?r:void 0;try{!function(t,e,o){const n=e??Math.floor(Date.now()/1e3),r=m(n),i=m(t);if(o?.strictCurrentQuantum){if(i!==r)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${r}`);return}const s=r-g,a=r+g;if(i!==s&&i!==r&&i!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${s} (past), ${r} (current), ${a} (next)]`);if(i===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(i===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===n?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await o(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,o,n,r,i){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,o.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyMintAuthorization(t,e,o,n,r){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,o,n,r)}static async verifyPaymentAuthorization(t,e,o,n,r){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,o,n,r)}static async verifyWithdrawAuthorization(e,o,n,r,i){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,o.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyRecoveryAuthorization(e,o,n,r,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],o)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,o,n,r,i){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyExtendAuthorization(t,e,o,n,r){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,o,n,r)}static async verifyBtcExecutionAuthorization(e,o,n,r,i){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,o.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const o=BigInt(e);if(o!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${o.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const o=Number(e);if(!Number.isFinite(o)||o!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function y(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 b(...t){y()&&console.log(...t)}var T=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...o){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},P=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(),o=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${o}`,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 o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${o}ms | Remaining: ${n}ms`)}stepEnd(t,e=5e3){const o=this.stepStartTimes.get(t);if(!o)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const n=Date.now()-o;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;i<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${i}ms (approaching timeout)`)}log(t,e,...o){o.length>0?console.log(`[Step ${t}] ${e}`,...o):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,o]of this.stepDurations.entries()){const n=(o/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${o}ms (${n}%)`)}}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}},$=class{static create(t="LIT Action",e){return y(e)?new P(t):new T}};function v(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function x(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}var I=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=$.create("BitcoinDataProvider")}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 o=Date.now(),n=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),b(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const r=await n.text();if(r.trim().startsWith("<!DOCTYPE")||r.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 i=parseInt(r.trim(),10);if(isNaN(i)){const t=r.length>200?r.substring(0,200)+"... (truncated)":r;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),i}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: ${x(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const o of t)try{return this.logger.log("0",`Trying fallback: ${o.name} (${o.url})`),await this.fetchUTXOsFromProvider(o.url,e)}catch(t){this.logger.warn("0",`Fallback ${o.name} failed: ${x(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${x(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=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const o=t,n=[];for(const t of o){let o=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(o=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(o=t.confirmations);const r=t.txid,i=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===r||void 0===i||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");n.push({txid:r,vout:i,satoshis:BigInt(s),confirmations:o})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const o=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${o}`);const n=new AbortController,r=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[i,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(o,{signal:n.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(r),b(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${i}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.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 u;try{u=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${x(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(u,null,2)}`);const c=this.parseBlockstreamUTXOs(u,i);return this.logger.stepEnd("1"),c}catch(t){if(clearTimeout(r),this.logger.stepEnd("1"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let o=[],n=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),o=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(x(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${x(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const r=o.reduce(((t,e)=>t+e.satoshis),0n),i=o.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=r-i;return{utxos:o,totalBalance:r,totalUTXOs:o.length,confirmedBalance:i,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),o=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${o}`);const n=new AbortController,r=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),e=await fetch(o,{signal:n.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(r),b(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const i=await e.json();if(!i.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=i.chain_stats.funded_txo_sum,a=i.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const u=BigInt(s-a);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),u}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);const o=x(t);throw this.logger.log("3",`Balance fetch failed: ${o}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${o}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",o=await this.config.rpcHelper.getTransaction(e,t);return{txid:o.txid,confirmations:o.confirmations||0}}catch(t){const e=x(t),o=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===o)return null;throw t}const e=new AbortController,o=setTimeout((()=>e.abort()),this.timeout);try{const n=Date.now(),r=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(o),b(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!r.ok){if(404===r.status)return null;throw new Error(`Bitcoin provider error: ${r.status} ${r.statusText}`)}const i=await r.json();if(i.status){if(!i.status.confirmed||!i.status.block_height)return{txid:i.txid??t,confirmations:0};try{const o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!o.ok)return{txid:i.txid??t,confirmations:1};const n=(await o.text()).trim(),r=Number.parseInt(n,10);if(!Number.isFinite(r)||r<=0)return{txid:i.txid??t,confirmations:1};const s=r-i.status.block_height+1;return{txid:i.txid??t,confirmations:s>0?s:0}}catch{return{txid:i.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(x(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,o=setTimeout((()=>e.abort()),this.timeout);try{const n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(o),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const r=await n.json();return r.vout&&Array.isArray(r.vout)?r.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},E="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",k={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function S(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var C,M=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),O=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),B=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),U=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function D(t,e,o){return t.call({to:e,data:o})}async function N(t,e){const o=new ethers.utils.Interface([E]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([E]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?S({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):S(e)}(await t.call({to:e,data:o}))}catch(t){n=t}try{return await async function(t,e){const o=await D(t,e,M.encodeFunctionData("views",[])),[n]=M.decodeFunctionResult("views",o),[r,i,s,a,u,c,l,d]=await Promise.all([D(t,e,M.encodeFunctionData("paused",[])),D(t,e,M.encodeFunctionData("liquidationPaused",[])),D(t,e,M.encodeFunctionData("simplePsm",[])),D(t,n,O.encodeFunctionData("core",[])),D(t,n,O.encodeFunctionData("loanOps",[])),D(t,n,O.encodeFunctionData("collateralManager",[])),D(t,n,O.encodeFunctionData("liquidationManager",[])),D(t,n,O.encodeFunctionData("circuitBreaker",[]))]),h=M.decodeFunctionResult("paused",r)[0],g=M.decodeFunctionResult("liquidationPaused",i)[0],p=M.decodeFunctionResult("simplePsm",s)[0],m=O.decodeFunctionResult("core",a)[0],f=O.decodeFunctionResult("loanOps",u)[0],w=O.decodeFunctionResult("collateralManager",c)[0],y=O.decodeFunctionResult("liquidationManager",l)[0],b=O.decodeFunctionResult("circuitBreaker",d)[0],T=await D(t,f,B.encodeFunctionData("getUcdController",[])),P=await D(t,f,B.encodeFunctionData("ucdToken",[])),$=B.decodeFunctionResult("getUcdController",T)[0],v=B.decodeFunctionResult("ucdToken",P)[0],x=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const o=await D(t,e,U.encodeFunctionData("paused",[]));return U.decodeFunctionResult("paused",o)[0]}catch{return!1}},[A,I,E,k,C,N,L,q]=await Promise.all([x(m),x(f),x(w),x(y),x(b),x($),x(v),x(p)]);return S({positionManagerPaused:h,positionManagerLiquidationsPaused:g,positionManagerCorePaused:A,loanOperationsPaused:I,collateralManagerPaused:E,liquidationManagerPaused:k,circuitBreakerPaused:C,ucdControllerPaused:N,ucdTokenPaused:L,simplePsmPaused:q})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),o=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${o})`)}}async function main(t){for(const[e,o]of Object.entries(t))globalThis[e]=o;const e=v();console.log("[Step 0] Validating configuration...");const o=e.chain,n=e.bitcoinNetwork;if(!o)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!n)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(n))throw new Error(`Invalid bitcoinNetwork: "${n}". Must be "mainnet", "testnet", or "regtest"`);const r=e.auth;if(!r||"object"!=typeof r)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!r.positionId)throw new Error("auth.positionId is required");if(!r.utxo||"object"!=typeof r.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===r.networkFee||r.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!r.targetAddress||"string"!=typeof r.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===r.targetAmount||null===r.targetAmount)throw new Error("auth.targetAmount is required");if(!r.utxo.txid||void 0===r.utxo.vout||!r.utxo.value||!r.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const a=r.positionId,g=r.utxo,m=r.utxos&&r.utxos.length>0?r.utxos:[g],f=r.networkFee;if(!m.some((t=>String(t.txid).toLowerCase()===String(g.txid).toLowerCase()&&Number(t.vout)===Number(g.vout))))throw new Error(`Authorized UTXO ${g.txid}:${g.vout} is not present in the utxos[] input set; refusing to sign.`);console.log(" \u2705 Parameters validated"),console.log(` Position: ${a}`),console.log(` UTXOs to spend: ${m.length}`),console.log(` Network fee: ${f} sats`),console.log(` Bitcoin network: ${n}`);const y=e.publicKey;if(!y)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof y||0===y.length)throw new Error("Invalid publicKey: must be non-empty string");const b=y;if(!e.contractAddresses||!e.contractAddresses.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!e.contractAddresses.PositionManager)throw new Error("contractAddresses.PositionManager is required");const T=e.contractAddresses.LoanOperationsManagerModule,P=e.contractAddresses.PositionManager,$=e.contractAddresses.BTCSpendAuthorizer??T;console.log(" \u2705 Contract addresses loaded from parameters");let x="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${a}`),console.log(` UTXO: ${g.txid}:${g.vout} (${g.value} sats)`),x="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;if(!t||"string"!=typeof t)return Lit.Actions.setResponse({response:JSON.stringify({success:!1,error:"rpcUrl jsParam is required but was not provided"})}),void 0;console.log(` \u2705 Using RPC URL: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(t)}`);const y=t,T=new ethers.providers.JsonRpcProvider(y);!function(t,e){const o=k[t],n=[];for(const t of o)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await N(T,P)),x="2",console.log("[Step 2] Validating Bitcoin provider URL...");const v=e.bitcoinProviderUrl;if(!v||"string"!=typeof v)throw new Error("bitcoinProviderUrl is required for btc-transaction-signer (needed for UTXO existence pre-check)");console.log(` \u2705 Bitcoin provider URL present (${v.replace(/\/\/[^@]*@/,"//***@")})`),x="3",console.log("[Step 3] Querying authorization from contract...");const A=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],E=new ethers.Contract($,A,T),S=await E.getAuthorizedSpends(a);let C=null;for(const t of S){const e=t.txid.toLowerCase(),o=g.txid.toLowerCase(),n=Number(t.vout),r=Number(g.vout);if(e===o&&n===r){C=t;break}}if(!C)throw new Error(`No authorization found for UTXO ${g.txid}:${g.vout}`);const M=BigInt(C.targetAmount.toString()),O=C.targetAddress,B=BigInt(C.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${O}`),console.log(` Authorized at: ${B.toString()}`),x="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const U=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],D=new ethers.Contract(P,U,T),L=await D.core();console.log(` Core facet address: ${L}`);const q=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"uint8",name:"status",type:"uint8"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],F=new ethers.Contract(L,q,T),_=await F.getPositionDetails(a);let z;if(5===_.status){if(!e.contractAddresses?.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(e.contractAddresses.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],T),o=await t.pkpOwners(_.pkpId);if(!o||o===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");z=o,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${z}`)}else z=_.borrower;console.log(` Position owner: ${z}`);const R=`${g.txid}:${g.vout}`,X=await w.verifyBtcExecutionAuthorization({positionId:r.positionId,timestamp:r.timestamp,chainId:r.chainId,utxoIdentifier:R,networkFee:r.networkFee,targetAddress:r.targetAddress,targetAmount:r.targetAmount,action:"execute-btc-withdrawal",signature:r.signature},z,function(t){return p[t]}(o),T,globalThis.contractAddresses?.PositionDelegateRegistry);if(!X)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const j=String(O);if(r.targetAddress.toLowerCase()!==j.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${r.targetAddress}" but on-chain authorizer records "${j}"`);const K=BigInt(r.targetAmount.toString());if(K!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${K.toString()} but on-chain authorizer records ${M.toString()}`);if(x="4",console.log("[Step 4] Validating network fee..."),f>h)throw new Error(`Network fee ${f} sats exceeds maximum ${h} sats`);if(f<d)throw new Error(`Network fee ${f} sats below minimum ${d} sats`);if(BigInt(f)>=M)throw new Error(`Network fee ${f} sats cannot exceed target amount ${M.toString()} sats`);const H=Number(M)-f;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${H} sats`),x="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const V=await i(b,n);console.log(` \u2705 PKP BTC address: ${V}`),x="5.5",console.log("[Step 5.5] Checking UTXO existence on Bitcoin network..."),console.log(` Authorized UTXO: ${g.txid}:${g.vout}`);const W=new I({providerUrl:v}),Q=await W.getUTXOs(V);if(!Q.some((t=>String(t.txid).toLowerCase()===String(g.txid).toLowerCase()&&Number(t.vout)===Number(g.vout))))throw new Error(`Authorized UTXO ${g.txid}:${g.vout} no longer exists on Bitcoin (already spent) \u2014 refusing to sign a doomed transaction`);console.log(` \u2705 Authorized UTXO ${g.txid}:${g.vout} confirmed unspent on Bitcoin network`),x="6",console.log("[Step 6] Validating UTXO ownership...");const G=s(V);for(const t of m){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==G)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${G}, got ${e}`)}console.log(` \u2705 All ${m.length} UTXO(s) belong to vault (PKP address)`),x="7",console.log("[Step 7] Validating UTXO value...");const J=Number(M),Z=m.reduce(((t,e)=>t+e.value),0);if(Z<J)throw new Error(`Insufficient UTXO value: total ${Z} sats across ${m.length} input(s), need ${J} sats`);const Y=Z-J;console.log(` \u2705 Total UTXO value sufficient (${m.length} input(s))`),console.log(` Total value: ${Z} sats`),console.log(` Total required: ${J} sats`),console.log(` Change: ${Y} sats`),x="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:tt,sigHashes:et}=function(t){const{utxos:e,destination:o,amount:n,changeAddress:r,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",d="ffffffff",h="00000000",g=l(e.length),p=e.map((t=>u(t.txid)+c(t.vout,4)+"00"+d)).join(""),m=[],f=s(o);if(m.push(c(n,8)+l(f.length/2)+f),i>0){const t=s(r);m.push(c(i,8)+l(t.length/2)+t)}const w=l(m.length),y=m.join(""),b=a+g+p+w+y+h,T=e.map((t=>u(t.txid)+c(t.vout,4))).join(""),P=ethers.utils.sha256(ethers.utils.sha256("0x"+T)),$=e.map((()=>d)).join(""),v=ethers.utils.sha256(ethers.utils.sha256("0x"+$)),x=ethers.utils.sha256(ethers.utils.sha256("0x"+y));return{txHex:b,sigHashes:e.map((t=>{const e=u(t.txid)+c(t.vout,4),o="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+P.slice(2)+v.slice(2)+e+o+c(t.value,8)+d+x.slice(2)+h+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}({utxos:m,destination:O,amount:H,changeAddress:V,changeAmount:Y,network:n,pkpPublicKey:b});console.log(` \u2705 Transaction built (${m.length} input(s))`),console.log(` Signature hashes: ${et.length}`),x="9",console.log(`[Step 9] Signing ${et.length} input(s)...`);const ot=globalThis.pkpId;if(!ot)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const nt=await Lit.Actions.getPrivateKey({pkpId:ot}),rt="string"==typeof nt?nt.startsWith("0x")?nt:`0x${nt}`:String(nt),it=new ethers.utils.SigningKey(rt),st=[];for(let t=0;t<et.length;t++){const e=it.signDigest(et[t]);st.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${et[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:tt,sigHashes:et,sigHash:et[0],signatures:st,signature:st[0],pkpPublicKey:b,pkpBtcAddress:V,destination:O,userReceivesAmount:H,networkFee:f,changeAmount:Y,utxos:m.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:g.txid,vout:g.vout,value:g.value},authorization:{targetAmount:M.toString(),authorizedAt:B.toString()},timestamp:Date.now(),action:"btc-transaction-signer"}}catch(t){return console.error("[BTC Transaction Signer] \u274c Failed:",t.message),console.error(`[BTC Transaction Signer] Failed at step: ${x}`),{success:!1,error:t.message||t.toString(),positionId:r?.positionId,timestamp:Date.now()}}}return C=r,((r,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let u of o(i))n.call(r,u)||u===s||t(r,u,{get:()=>i[u],enumerable:!(a=e(i,u))||a.enumerable});return r})(t({},"__esModule",{value:!0}),C)})();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,o=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,r={};async function i(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const o=e.slice(2,66),n=e.slice(66,130),r=(BigInt("0x"+n)%2n===0n?"02":"03")+o,i=ethers.utils.sha256("0x"+r);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const c=function(t,e,o){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=[];for(let t=0;t<o.length;t+=2)r.push(parseInt(o.substr(t,2),16));const i=a(r,8,5,!0),s=[e,...i],c=function(t,e){const o=function(t){const e=[];for(let o=0;o<t.length;o++)e.push(t.charCodeAt(o)>>5);e.push(0);for(let o=0;o<t.length;o++)e.push(31&t.charCodeAt(o));return e}(t).concat(e).concat([0,0,0,0,0,0]),n=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let o=1;for(let n=0;n<t.length;n++){const r=o>>25;o=(33554431&o)<<5^t[n];for(let t=0;t<5;t++)r>>t&1&&(o^=e[t])}return o}(o),r=[];for(let t=0;t<6;t++)r.push(n>>5*(5-t)&31);return r}(t,s),u=[...s,...c];let l=t+"1";for(let t=0;t<u.length;t++)l+=n[u[t]];return l}(s,0,ethers.utils.ripemd160(i).slice(2));return c}function s(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",o=t.lastIndexOf("1");if(o<1)throw new Error("No separator character for bech32");const n=t.substring(o+1).toLowerCase(),r=[];for(let t=0;t<n.length;t++){const o=e.indexOf(n[t]);if(-1===o)throw new Error(`Invalid bech32 character: ${n[t]}`);r.push(o)}const i=r.slice(0,-6),s=a(i.slice(1),5,8,!1);return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let o=0n;for(let n=0;n<t.length;n++){const r=e.indexOf(t[n]);if(r<0)throw new Error(`Invalid Base58 character: ${t[n]}`);o=58n*o+BigInt(r)}let n=o.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function a(t,e,o,n){let r=0,i=0;const s=[],a=(1<<o)-1;for(let n=0;n<t.length;n++){const c=t[n];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(r=r<<e|c,i+=e;i>=o;)i-=o,s.push(r>>i&a)}if(n)i>0&&s.push(r<<o-i&a);else if(i>=e||r<<o-i&a)throw new Error("Invalid padding in bit conversion");return s}function c(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function u(t,e){const o=t.toString(16).padStart(2*e,"0").match(/../g);if(!o)throw new Error(`Invalid hex conversion: ${t}`);return o.reverse().join("")}function l(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+u(t,2):t<=4294967295?"fe"+u(t,4):"ff"+u(t,8)}((e,o)=>{for(var n in o)t(e,n,{get:o[n],enumerable:!0})})(r,{main:()=>main});var d=100,h=1e5,g=60,p={ethereum:1,sepolia:11155111,hardhat:1337};function m(t){return Math.floor(t/g)*g}async function f(){const t=Math.floor(Date.now()/1e3),e=t%g;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%g;return e<8||e>=52}(t))return;let o;o=e>=52?g-e+8:8-e,console.log(`[Quantum] Waiting ${o}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*o))),console.log(`[Quantum] Safe quantum ready: ${m(Math.floor(Date.now()/1e3))}`)}var w=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const o=ethers.utils.arrayify(t),n=ethers.utils.hashMessage(o);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,o,n){try{const r=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await r.isValidSignature(e,o)}catch{return!1}}static async checkPositionDelegate(t,e,o,n){try{const r=new ethers.Contract(o,["function positionDelegate(bytes32) view returns (address)"],n),i=await r.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,o,n){const r=Math.floor(Date.now()/1e3);await f();const i=n?.strictCurrentQuantum?r:void 0;try{!function(t,e,o){const n=e??Math.floor(Date.now()/1e3),r=m(n),i=m(t);if(o?.strictCurrentQuantum){if(i!==r)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${r}`);return}const s=r-g,a=r+g;if(i!==s&&i!==r&&i!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${s} (past), ${r} (current), ${a} (next)]`);if(i===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(i===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===n?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await o(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,o,n,r,i){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,o.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyMintAuthorization(t,e,o,n,r){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,o,n,r)}static async verifyPaymentAuthorization(t,e,o,n,r){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,o,n,r)}static async verifyWithdrawAuthorization(e,o,n,r,i){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,o.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyRecoveryAuthorization(e,o,n,r,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],o)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,o,n,r,i){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}))}static async verifyExtendAuthorization(t,e,o,n,r){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,o,n,r)}static async verifyBtcExecutionAuthorization(e,o,n,r,i){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),o="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,o.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===o.toLowerCase())return!0;if(r){if(await t.checkEIP1271(o,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,r)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const o=BigInt(e);if(o!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${o.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const o=Number(e);if(!Number.isFinite(o)||o!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function y(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 b(...t){y()&&console.log(...t)}var T=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...o){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},P=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(),o=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${o}`,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 o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${o}ms | Remaining: ${n}ms`)}stepEnd(t,e=5e3){const o=this.stepStartTimes.get(t);if(!o)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const n=Date.now()-o;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;i<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${i}ms (approaching timeout)`)}log(t,e,...o){o.length>0?console.log(`[Step ${t}] ${e}`,...o):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,o]of this.stepDurations.entries()){const n=(o/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${o}ms (${n}%)`)}}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}},$=class{static create(t="LIT Action",e){return y(e)?new P(t):new T}};function v(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function A(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function x(t){return t instanceof Error&&"AbortError"===t.name}var k=new Map;async function I(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const o=await async function(t,e){const o=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",n=`${o}\n${t.clientId}`,r=k.get(n);if(r)return r;const i=(async()=>{const n=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,r=new AbortController,i=setTimeout((()=>r.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,signal:r.signal})}finally{clearTimeout(i)}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 i.catch((()=>k.delete(n))),k.set(n,i),i}(t,e);return{Authorization:`Bearer ${o}`}}}}var E=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=$.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await I(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 o=Date.now(),n=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),b(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const r=await n.text();if(r.trim().startsWith("<!DOCTYPE")||r.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 i=parseInt(r.trim(),10);if(isNaN(i)){const t=r.length>200?r.substring(0,200)+"... (truncated)":r;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),i}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),x(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: ${A(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const o of t)try{return this.logger.log("0",`Trying fallback: ${o.name} (${o.url})`),await this.fetchUTXOsFromProvider(o.url,e)}catch(t){this.logger.warn("0",`Fallback ${o.name} failed: ${A(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${A(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=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const o=t,n=[];for(const t of o){let o=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(o=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(o=t.confirmations);const r=t.txid,i=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===r||void 0===i||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");n.push({txid:r,vout:i,satoshis:BigInt(s),confirmations:o})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const o=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${o}`);const n=new AbortController,r=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[i,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(o,{signal:n.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(r),b(`[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: ${i}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.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 c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${A(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,i);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(r),this.logger.stepEnd("1"),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let o=[],n=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),o=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(A(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${A(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const r=o.reduce(((t,e)=>t+e.satoshis),0n),i=o.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=r-i;return{utxos:o,totalBalance:r,totalUTXOs:o.length,confirmedBalance:i,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),o=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${o}`);const n=new AbortController,r=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),e=await fetch(o,{signal:n.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(r),b(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const i=await e.json();if(!i.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=i.chain_stats.funded_txo_sum,a=i.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const c=BigInt(s-a);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),c}catch(t){if(clearTimeout(r),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);const o=A(t);throw this.logger.log("3",`Balance fetch failed: ${o}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${o}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",o=await this.config.rpcHelper.getTransaction(e,t);return{txid:o.txid,confirmations:o.confirmations||0}}catch(t){const e=A(t),o=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===o)return null;throw t}const e=new AbortController,o=setTimeout((()=>e.abort()),this.timeout);try{const n=Date.now(),r=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(o),b(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!r.ok){if(404===r.status)return null;throw new Error(`Bitcoin provider error: ${r.status} ${r.statusText}`)}const i=await r.json();if(i.status){if(!i.status.confirmed||!i.status.block_height)return{txid:i.txid??t,confirmations:0};try{const o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!o.ok)return{txid:i.txid??t,confirmations:1};const n=(await o.text()).trim(),r=Number.parseInt(n,10);if(!Number.isFinite(r)||r<=0)return{txid:i.txid??t,confirmations:1};const s=r-i.status.block_height+1;return{txid:i.txid??t,confirmations:s>0?s:0}}catch{return{txid:i.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(o),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(A(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,o=setTimeout((()=>e.abort()),this.timeout);try{const n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(o),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const r=await n.json();return r.vout&&Array.isArray(r.vout)?r.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(o),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},S="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",C={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function M(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var O,B=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),U=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),D=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),N=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function L(t,e,o){return t.call({to:e,data:o})}async function q(t,e){const o=new ethers.utils.Interface([S]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([S]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?M({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):M(e)}(await t.call({to:e,data:o}))}catch(t){n=t}try{return await async function(t,e){const o=await L(t,e,B.encodeFunctionData("views",[])),[n]=B.decodeFunctionResult("views",o),[r,i,s,a,c,u,l,d]=await Promise.all([L(t,e,B.encodeFunctionData("paused",[])),L(t,e,B.encodeFunctionData("liquidationPaused",[])),L(t,e,B.encodeFunctionData("simplePsm",[])),L(t,n,U.encodeFunctionData("core",[])),L(t,n,U.encodeFunctionData("loanOps",[])),L(t,n,U.encodeFunctionData("collateralManager",[])),L(t,n,U.encodeFunctionData("liquidationManager",[])),L(t,n,U.encodeFunctionData("circuitBreaker",[]))]),h=B.decodeFunctionResult("paused",r)[0],g=B.decodeFunctionResult("liquidationPaused",i)[0],p=B.decodeFunctionResult("simplePsm",s)[0],m=U.decodeFunctionResult("core",a)[0],f=U.decodeFunctionResult("loanOps",c)[0],w=U.decodeFunctionResult("collateralManager",u)[0],y=U.decodeFunctionResult("liquidationManager",l)[0],b=U.decodeFunctionResult("circuitBreaker",d)[0],T=await L(t,f,D.encodeFunctionData("getUcdController",[])),P=await L(t,f,D.encodeFunctionData("ucdToken",[])),$=D.decodeFunctionResult("getUcdController",T)[0],v=D.decodeFunctionResult("ucdToken",P)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const o=await L(t,e,N.encodeFunctionData("paused",[]));return N.decodeFunctionResult("paused",o)[0]}catch{return!1}},[x,k,I,E,S,C,O,q]=await Promise.all([A(m),A(f),A(w),A(y),A(b),A($),A(v),A(p)]);return M({positionManagerPaused:h,positionManagerLiquidationsPaused:g,positionManagerCorePaused:x,loanOperationsPaused:k,collateralManagerPaused:I,liquidationManagerPaused:E,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:O,simplePsmPaused:q})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),o=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${o})`)}}async function main(t){for(const[e,o]of Object.entries(t))globalThis[e]=o;const e=v();console.log("[Step 0] Validating configuration...");const o=e.chain,n=e.bitcoinNetwork;if(!o)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!n)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(n))throw new Error(`Invalid bitcoinNetwork: "${n}". Must be "mainnet", "testnet", or "regtest"`);const r=e.auth;if(!r||"object"!=typeof r)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!r.positionId)throw new Error("auth.positionId is required");if(!r.utxo||"object"!=typeof r.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===r.networkFee||r.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!r.targetAddress||"string"!=typeof r.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===r.targetAmount||null===r.targetAmount)throw new Error("auth.targetAmount is required");if(!r.utxo.txid||void 0===r.utxo.vout||!r.utxo.value||!r.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const a=r.positionId,g=r.utxo,m=r.utxos&&r.utxos.length>0?r.utxos:[g],f=r.networkFee;if(!m.some((t=>String(t.txid).toLowerCase()===String(g.txid).toLowerCase()&&Number(t.vout)===Number(g.vout))))throw new Error(`Authorized UTXO ${g.txid}:${g.vout} is not present in the utxos[] input set; refusing to sign.`);console.log(" \u2705 Parameters validated"),console.log(` Position: ${a}`),console.log(` UTXOs to spend: ${m.length}`),console.log(` Network fee: ${f} sats`),console.log(` Bitcoin network: ${n}`);const y=e.publicKey;if(!y)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof y||0===y.length)throw new Error("Invalid publicKey: must be non-empty string");const b=y;if(!e.contractAddresses||!e.contractAddresses.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!e.contractAddresses.PositionManager)throw new Error("contractAddresses.PositionManager is required");const T=e.contractAddresses.LoanOperationsManagerModule,P=e.contractAddresses.PositionManager,$=e.contractAddresses.BTCSpendAuthorizer??T;console.log(" \u2705 Contract addresses loaded from parameters");let A="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${a}`),console.log(` UTXO: ${g.txid}:${g.vout} (${g.value} sats)`),A="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;if(!t||"string"!=typeof t)return Lit.Actions.setResponse({response:JSON.stringify({success:!1,error:"rpcUrl jsParam is required but was not provided"})}),void 0;console.log(` \u2705 Using RPC URL: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(t)}`);const y=t,T=new ethers.providers.JsonRpcProvider(y);!function(t,e){const o=C[t],n=[];for(const t of o)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await q(T,P)),A="2",console.log("[Step 2] Validating Bitcoin provider URL...");const v=e.bitcoinProviderUrl;if(!v||"string"!=typeof v)throw new Error("bitcoinProviderUrl is required for btc-transaction-signer (needed for UTXO existence pre-check)");console.log(` \u2705 Bitcoin provider URL present (${v.replace(/\/\/[^@]*@/,"//***@")})`),A="3",console.log("[Step 3] Querying authorization from contract...");const x=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],k=new ethers.Contract($,x,T),I=await k.getAuthorizedSpends(a);let S=null;for(const t of I){const e=t.txid.toLowerCase(),o=g.txid.toLowerCase(),n=Number(t.vout),r=Number(g.vout);if(e===o&&n===r){S=t;break}}if(!S)throw new Error(`No authorization found for UTXO ${g.txid}:${g.vout}`);const M=BigInt(S.targetAmount.toString()),O=S.targetAddress,B=BigInt(S.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${O}`),console.log(` Authorized at: ${B.toString()}`),A="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const U=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],D=new ethers.Contract(P,U,T),N=await D.core();console.log(` Core facet address: ${N}`);const L=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"uint8",name:"status",type:"uint8"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],_=new ethers.Contract(N,L,T),F=await _.getPositionDetails(a);let z;if(5===F.status){if(!e.contractAddresses?.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(e.contractAddresses.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],T),o=await t.pkpOwners(F.pkpId);if(!o||o===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");z=o,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${z}`)}else z=F.borrower;console.log(` Position owner: ${z}`);const R=`${g.txid}:${g.vout}`,X=await w.verifyBtcExecutionAuthorization({positionId:r.positionId,timestamp:r.timestamp,chainId:r.chainId,utxoIdentifier:R,networkFee:r.networkFee,targetAddress:r.targetAddress,targetAmount:r.targetAmount,action:"execute-btc-withdrawal",signature:r.signature},z,function(t){return p[t]}(o),T,globalThis.contractAddresses?.PositionDelegateRegistry);if(!X)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const j=String(O);if(r.targetAddress.toLowerCase()!==j.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${r.targetAddress}" but on-chain authorizer records "${j}"`);const K=BigInt(r.targetAmount.toString());if(K!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${K.toString()} but on-chain authorizer records ${M.toString()}`);if(A="4",console.log("[Step 4] Validating network fee..."),f>h)throw new Error(`Network fee ${f} sats exceeds maximum ${h} sats`);if(f<d)throw new Error(`Network fee ${f} sats below minimum ${d} sats`);if(BigInt(f)>=M)throw new Error(`Network fee ${f} sats cannot exceed target amount ${M.toString()} sats`);const H=Number(M)-f;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${H} sats`),A="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const V=await i(b,n);console.log(` \u2705 PKP BTC address: ${V}`),A="5.5",console.log("[Step 5.5] Checking UTXO existence on Bitcoin network..."),console.log(` Authorized UTXO: ${g.txid}:${g.vout}`);const W=new E({providerUrl:v}),Q=await W.getUTXOs(V);if(!Q.some((t=>String(t.txid).toLowerCase()===String(g.txid).toLowerCase()&&Number(t.vout)===Number(g.vout))))throw new Error(`Authorized UTXO ${g.txid}:${g.vout} no longer exists on Bitcoin (already spent) \u2014 refusing to sign a doomed transaction`);console.log(` \u2705 Authorized UTXO ${g.txid}:${g.vout} confirmed unspent on Bitcoin network`),A="6",console.log("[Step 6] Validating UTXO ownership...");const G=s(V);for(const t of m){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==G)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${G}, got ${e}`)}console.log(` \u2705 All ${m.length} UTXO(s) belong to vault (PKP address)`),A="7",console.log("[Step 7] Validating UTXO value...");const J=Number(M),Z=m.reduce(((t,e)=>t+e.value),0);if(Z<J)throw new Error(`Insufficient UTXO value: total ${Z} sats across ${m.length} input(s), need ${J} sats`);const Y=Z-J;console.log(` \u2705 Total UTXO value sufficient (${m.length} input(s))`),console.log(` Total value: ${Z} sats`),console.log(` Total required: ${J} sats`),console.log(` Change: ${Y} sats`),A="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:tt,sigHashes:et}=function(t){const{utxos:e,destination:o,amount:n,changeAddress:r,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",d="ffffffff",h="00000000",g=l(e.length),p=e.map((t=>c(t.txid)+u(t.vout,4)+"00"+d)).join(""),m=[],f=s(o);if(m.push(u(n,8)+l(f.length/2)+f),i>0){const t=s(r);m.push(u(i,8)+l(t.length/2)+t)}const w=l(m.length),y=m.join(""),b=a+g+p+w+y+h,T=e.map((t=>c(t.txid)+u(t.vout,4))).join(""),P=ethers.utils.sha256(ethers.utils.sha256("0x"+T)),$=e.map((()=>d)).join(""),v=ethers.utils.sha256(ethers.utils.sha256("0x"+$)),A=ethers.utils.sha256(ethers.utils.sha256("0x"+y));return{txHex:b,sigHashes:e.map((t=>{const e=c(t.txid)+u(t.vout,4),o="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+P.slice(2)+v.slice(2)+e+o+u(t.value,8)+d+A.slice(2)+h+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}({utxos:m,destination:O,amount:H,changeAddress:V,changeAmount:Y,network:n,pkpPublicKey:b});console.log(` \u2705 Transaction built (${m.length} input(s))`),console.log(` Signature hashes: ${et.length}`),A="9",console.log(`[Step 9] Signing ${et.length} input(s)...`);const ot=globalThis.pkpId;if(!ot)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const nt=await Lit.Actions.getPrivateKey({pkpId:ot}),rt="string"==typeof nt?nt.startsWith("0x")?nt:`0x${nt}`:String(nt),it=new ethers.utils.SigningKey(rt),st=[];for(let t=0;t<et.length;t++){const e=it.signDigest(et[t]);st.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${et[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:tt,sigHashes:et,sigHash:et[0],signatures:st,signature:st[0],pkpPublicKey:b,pkpBtcAddress:V,destination:O,userReceivesAmount:H,networkFee:f,changeAmount:Y,utxos:m.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:g.txid,vout:g.vout,value:g.value},authorization:{targetAmount:M.toString(),authorizedAt:B.toString()},timestamp:Date.now(),action:"btc-transaction-signer"}}catch(t){return console.error("[BTC Transaction Signer] \u274c Failed:",t.message),console.error(`[BTC Transaction Signer] Failed at step: ${A}`),{success:!1,error:t.message||t.toString(),positionId:r?.positionId,timestamp:Date.now()}}}return O=r,((r,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of o(i))n.call(r,c)||c===s||t(r,c,{get:()=>i[c],enumerable:!(a=e(i,c))||a.enumerable});return r})(t({},"__esModule",{value:!0}),O)})();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
- 93725b2020e1914e93f1e21bdcc75d9cb28bc0b6bc4ea9b470f112e1f068998f
1
+ f4aed3d88f6fbff6623ed2047436cecd4f561a74883171ea6f4ebe0a1129973c
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-transaction-signer",
3
- "originalSize": 94590,
4
- "minifiedSize": 41048,
5
- "compressionRatio": 0.5660429220847869,
6
- "hash": "93725b2020e1914e93f1e21bdcc75d9cb28bc0b6bc4ea9b470f112e1f068998f",
7
- "buildTime": 1781133967243,
3
+ "originalSize": 97389,
4
+ "minifiedSize": 42376,
5
+ "compressionRatio": 0.5648789904403988,
6
+ "hash": "f4aed3d88f6fbff6623ed2047436cecd4f561a74883171ea6f4ebe0a1129973c",
7
+ "buildTime": 1781559387062,
8
8
  "version": "0.1.0"
9
9
  }