@gvnrdao/dh-lit-actions 0.0.305 → 0.0.307
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/address-probe-signer.meta.json +1 -1
- package/dist/address-probe.meta.json +1 -1
- package/dist/always-signer.meta.json +1 -1
- package/dist/authorization-dummy-b.meta.json +1 -1
- package/dist/authorization-dummy.meta.json +1 -1
- package/dist/btc-address-balance.action.js +1 -1
- package/dist/btc-address-balance.hash +1 -1
- package/dist/btc-address-balance.meta.json +5 -5
- package/dist/btc-transaction-signer.meta.json +1 -1
- package/dist/btc-utxo-invalidator.meta.json +1 -1
- package/dist/btc-withdrawal.action.js +1 -1
- package/dist/btc-withdrawal.hash +1 -1
- package/dist/btc-withdrawal.meta.json +5 -5
- package/dist/encrypt-parameter.meta.json +1 -1
- package/dist/ethers-version-probe.meta.json +1 -1
- package/dist/extend-position-validator.meta.json +1 -1
- package/dist/liquidation-validator.meta.json +1 -1
- package/dist/loan-vault-btc-balance.meta.json +1 -1
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-sign-only.meta.json +1 -1
- package/dist/process-payment-validator.meta.json +1 -1
- package/dist/stale-spend-recovery-validator.meta.json +1 -1
- package/dist/ucd-mint-validator.action.js +1 -1
- package/dist/ucd-mint-validator.hash +1 -1
- package/dist/ucd-mint-validator.meta.json +5 -5
- package/package.json +3 -2
- package/pkg-dist/pkg-src/index.js +15 -15
- package/pkg-dist/pkg-src/index.js.map +1 -1
- package/pkg-dist/src/modules/address-balance-attestation.module.d.ts +11 -3
- package/pkg-dist/src/modules/address-balance-attestation.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/validator-registry-check.module.d.ts +14 -9
- package/pkg-dist/src/modules/validator-registry-check.module.d.ts.map +1 -1
|
@@ -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,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:g.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:g.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!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"}],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 x(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,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 x(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 C,k={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"};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;let g;!function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase();if(!/^(bc1|tb1|bcrt1)[0-9a-z]{11,87}$/.test(r))throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`);const i=k[e],o=r.startsWith("bcrt1")?"bcrt1":r.startsWith("tb1")?"tb1":"bc1";if(o!==i)throw new Error(`vaultAddress network mismatch: address prefix "${o}" does not match chain network "${e}" (expected "${i}")`)}(i,p),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),g=a):g=await Lit.Actions.getRpcUrl({chain:r});const f=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(!f)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: ${i}`);try{const t=new ethers.providers.JsonRpcProvider(g);let r;r=c.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:c.minBitcoinConfirmations,network:c.bitcoinNetwork}]:await I(c,t,f),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const o=r[0],a=new b({providerUrl:o.url}),p=await a.getBalance(i);if(r.length>1){for(let t=1;t<r.length;t++){const e=r[t],n=new b({providerUrl:e.url}),s=await n.getBalance(i);if(s!==p)throw new Error(`Bitcoin provider balance mismatch: ${o.name}=${p.toString()} vs ${e.name}=${s.toString()}`)}s(` \u2705 Consensus reached across ${r.length} providers (${p.toString()} sats)`)}const m=r.length;s("[Step 2] Signing address balance attestation...");const y=c.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:f,{domain:$,types:T,value:E}=(v={verifyingContract:y,chainId:w(l),vaultAddress:i,totalBalanceSats:p,providerCount:m,timestamp:n},{domain:{name:d,version:h,chainId:v.chainId,verifyingContract:ethers.utils.getAddress(v.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(v.vaultAddress)),totalBalanceSats:v.totalBalanceSats.toString(),providerCount:v.providerCount,timestamp:v.timestamp}}),A=globalThis.validatorWalletAddress;if(!A||!A.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const B=await Lit.Actions.getPrivateKey({pkpId:A}),x="string"==typeof B?B.startsWith("0x")?B:`0x${B}`:String(B),C=new ethers.Wallet(x),k=await C._signTypedData($,T,E);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:i,totalBalanceSats:p.toString(),providerCount:m,signature:k,timestamp:n,validatorPkp:C.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:i||null,timestamp:Date.now()}}var v}return C=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}),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,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,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:g.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:g.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!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 k,C={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},P="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=C[e],o=new RegExp(`^q[${P}]{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),k=new ethers.Wallet(B),C=await k._signTypedData(y,T,E);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:g,totalBalanceSats:a.toString(),providerCount:p,signature:C,timestamp:n,validatorPkp:k.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 k=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}),k)})();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
|
-
|
|
1
|
+
8369701c40e742ec54d34fec373f21cfd75f5dfd3ece4bc5358c7566032e7605
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "btc-address-balance",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 45422,
|
|
4
|
+
"minifiedSize": 21864,
|
|
5
|
+
"compressionRatio": 0.5186473515036767,
|
|
6
|
+
"hash": "8369701c40e742ec54d34fec373f21cfd75f5dfd3ece4bc5358c7566032e7605",
|
|
7
|
+
"buildTime": 1780652526138,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var n=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,l=100000000000000n,u=546n,d=3,h=500,p=60,g=8e3;function m(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var w="DiamondHands.Protocol",f="1",y=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(y||{}),b={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],v={ethereum:1,sepolia:11155111,hardhat:1337};function P(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(y).join(", ")}`)}function A(t){return v[t]}function E(t){return Math.floor(t/p)*p}async function S(){const t=Math.floor(Date.now()/1e3),e=t%p;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%p;return e<8||e>=52}(t))return;let r;r=e>=52?p-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${E(Math.floor(Date.now()/1e3))}`)}var $=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 r=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,o){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,o){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],o),n=await i.positionDelegate(t);return!(!n||n===ethers.constants.AddressZero)&&n.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,o){const i=Math.floor(Date.now()/1e3);await S();const n=o?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const o=e??Math.floor(Date.now()/1e3),i=E(o),n=E(t);if(r?.strictCurrentQuantum){if(n!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${n}, current quantum: ${i}`);return}const a=i-p,s=i+p;if(n!==a&&n!==i&&n!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${a} (past), ${i} (current), ${s} (next)]`);if(n===a){if(o<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(n===s&&o>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i,n){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,o,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i)}static async verifyPaymentAuthorization(t,e,r,o,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i)}static async verifyWithdrawAuthorization(e,r,o,i,n){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,o,i,n){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}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,r,o,i,n){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,o,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o,i)}static async verifyBtcExecutionAuthorization(e,r,o,i,n){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==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 I(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 C(...t){I()&&console.log(...t)}var B=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}},U=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,o=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${o}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 o=Date.now()-r;this.stepDurations.set(t,o),console.log(`[Step ${t}] Duration: ${o}ms`),o>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${o}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-i;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 o=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${o}%)`)}}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}},x=class{static create(t="LIT Action",e){return I(e)?new U(t):new B}};function D(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function k(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function O(t){return t instanceof Error&&"AbortError"===t.name}var M=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=x.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(),o=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),C(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Failed to fetch block height: ${o.status} ${o.statusText}`);const i=await o.text();if(i.trim().startsWith("<!DOCTYPE")||i.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(i.trim(),10);if(isNaN(n)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),O(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: ${k(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: ${k(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${k(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,o=[];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 i=t.txid,n=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===n||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");o.push({txid:i,vout:n,satoshis:BigInt(a),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.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(i),C(`[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 s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.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(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${k(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const l=this.parseBlockstreamUTXOs(c,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;const i=d,n=h;for(let e=1;e<=i;e++)try{this.logger.log("2",`UTXO query attempt ${e}/${i}...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(k(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${k(t)}`),e<i&&(this.logger.log("2",`Waiting ${n}ms before retry...`),await new Promise((t=>setTimeout(t,n))))}if(o)throw new Error(`Failed to query UTXOs after ${i} attempts: ${o.message}`);const a=r.reduce(((t,e)=>t+e.satoshis),0n),s=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),c=a-s;return{utxos:r,totalBalance:a,totalUTXOs:r.length,confirmedBalance:s,unconfirmedBalance:c}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:o.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(i),C(`[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,s=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(i),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=k(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=k(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 o=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),C(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.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 o=(await r.text()).trim(),i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<=0)return{txid:n.txid??t,confirmations:1};const a=i-n.status.block_height+1;return{txid:n.txid??t,confirmations:a>0?a:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(k(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 o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},R=class t{constructor(e,r,o){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`Price oracle requires exactly ${t.REQUIRED_PROVIDER_COUNT} providers. Currently configured: ${this.sources.length} provider(s). Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(e.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`priceProviders must contain exactly ${t.REQUIRED_PROVIDER_COUNT} entries. Received: ${e.length}. Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`CryptoCompare HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(t){return async(e,r)=>{const o=new AbortController,i=setTimeout((()=>o.abort()),5e3);try{const i=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:o.signal});if(!i.ok)throw new Error(`${t} HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const a=await r(n.toString(),i),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const e=Date.now();if(this.sources.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`Price oracle requires exactly ${t.REQUIRED_PROVIDER_COUNT} providers. Currently configured: ${this.sources.length}`);const r=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),o=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([o,r])].sort(((t,e)=>t-e)),n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}const a=Math.round(100*n),s=1000000n*BigInt(a),c=Date.now()-e;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${c}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${s}`),s}};R.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],R.REQUIRED_PROVIDER_COUNT=3;var N=R;async function L(t,e,r,o){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:o});return"string"==typeof t?t:String(t??"")}catch(r){const o=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${o}`)}}var q=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),o=await this.getAuthorizedSpendsFromContract(t),i=o.reduce(((t,e)=>t+e.satoshis),0n),n=r>i?r-i:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:o,authorizedBalance:i,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,o),availableUTXOs:[],availableBalance:n,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const o=this.config.minConfirmations||6,i=await this.bitcoinProvider.getUTXOSet(e,o),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=n.reduce(((t,e)=>t+e.satoshis),0n),s=i.utxos.filter((t=>!this.isUTXOAuthorized(t,n))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:a,authorizedSpendsHash:l,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,o){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===o))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{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"}],o);return(await i.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const o=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,o]))}};function _(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}function F(t,e,r,o){if(!t)return r;const i=o??n,a=Math.min(e,30);return n+a*a*(i-n)/900}function z(t,e,r){const o=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:o,collateralRatioBps:Number(o*s*10000n/r)}}function X(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}function V(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function H(t){return t/100}var j=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.loanOpsManagerAddress,r,e),i=await o.liquidationThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.termManagerAddress,o,r),n=await i.getTermFees(t);return{originationFeeBps:Number(n.originationFee?.toString?.()??n[0]?.toString?.()??n[0]),extensionFeeBps:Number(n.extensionFee?.toString?.()??n[1]?.toString?.()??n[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,i=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await i.getAuthorizedSpendsHash(o)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.liquidationManagerAddress,r,e),i=await o.maxEscalatedThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function W(t){return new j(t)}var G=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=_(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=z(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=_(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=z(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],o),n=await i.core(),a=new ethers.Contract(n,[{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:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],o),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const l=Number(s.expiryAt),u=Number(s.selectedTerm),d=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=Number(s.lastRenewedAt),m=(f=u,0===(w=l)?0:w-30*f*86400);var w,f;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,P(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d,lastRenewedAt:p}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const o=await this.getVaultSnapshot(t);return function(t,e,r,o){const i=e+r;return 0n===i||Number(t*s*10000n/i)>=o}(o.collateralValueUsd,o.ucdDebt,e,r)}};var K="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))",Q={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 J(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 Z=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=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)"]),tt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),et=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function rt(t,e,r){return t.call({to:e,data:r})}async function ot(t,e){const r=new ethers.utils.Interface([K]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([K]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({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]}):J(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await rt(t,e,Z.encodeFunctionData("views",[])),[o]=Z.decodeFunctionResult("views",r),[i,n,a,s,c,l,u,d]=await Promise.all([rt(t,e,Z.encodeFunctionData("paused",[])),rt(t,e,Z.encodeFunctionData("liquidationPaused",[])),rt(t,e,Z.encodeFunctionData("simplePsm",[])),rt(t,o,Y.encodeFunctionData("core",[])),rt(t,o,Y.encodeFunctionData("loanOps",[])),rt(t,o,Y.encodeFunctionData("collateralManager",[])),rt(t,o,Y.encodeFunctionData("liquidationManager",[])),rt(t,o,Y.encodeFunctionData("circuitBreaker",[]))]),h=Z.decodeFunctionResult("paused",i)[0],p=Z.decodeFunctionResult("liquidationPaused",n)[0],g=Z.decodeFunctionResult("simplePsm",a)[0],m=Y.decodeFunctionResult("core",s)[0],w=Y.decodeFunctionResult("loanOps",c)[0],f=Y.decodeFunctionResult("collateralManager",l)[0],y=Y.decodeFunctionResult("liquidationManager",u)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await rt(t,w,tt.encodeFunctionData("getUcdController",[])),v=await rt(t,w,tt.encodeFunctionData("ucdToken",[])),P=tt.decodeFunctionResult("getUcdController",T)[0],A=tt.decodeFunctionResult("ucdToken",v)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await rt(t,e,et.encodeFunctionData("paused",[]));return et.decodeFunctionResult("paused",r)[0]}catch{return!1}},[S,$,I,C,B,U,x,D]=await Promise.all([E(m),E(w),E(f),E(y),E(b),E(P),E(A),E(g)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:S,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:U,ucdTokenPaused:x,simplePsmPaused:D})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}function it(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}var nt={hardhat:{chain:"hardhat",chainId:v.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:v.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:v.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var at,st=[{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"}],ct=[{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 lt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),o="string"==typeof e?e:String(e??"");if(!o)throw new Error("Decrypt returned empty plaintext");return o}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ut(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=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 o=new ethers.Contract(r,st,e),[i,n]=await o.getProviders(t),a=[];for(let t=0;t<i.length;t++)a.push({providerId:i[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return a}(t.chainId,e,r);if(0===o.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:o}=t;if(!o||"string"!=typeof o)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),a=new ethers.Contract(o,ct,r);let s;try{s=await a.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)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 i=[];for(const e of o){const r=await lt(e.ciphertext,e.pkpId);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}function dt(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const o=t.substring(r+1).toLowerCase(),i=[];for(let t=0;t<o.length;t++){const r=e.indexOf(o[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${o[t]}`);i.push(r)}const n=i.slice(0,-6),a=(n[0],function(t,e,r,o){let i=0,n=0;const a=[],s=(1<<r)-1;for(let o=0;o<t.length;o++){const c=t[o];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,n+=e;n>=r;)n-=r,a.push(i>>n&s)}if(o)n>0&&a.push(i<<r-n&s);else if(n>=e||i<<r-n&s)throw new Error("Invalid padding in bit conversion");return a}(n.slice(1),5,8,!1));return{witnessProgram:a.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let o=0;o<t.length;o++){const i=e.indexOf(t[o]);if(i<0)throw new Error(`Invalid Base58 character: ${t[o]}`);r=58n*r+BigInt(i)}let o=r.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=x.create("BTC Withdrawal Validator");console.log("[Step 0] Validating configuration..."),e.stepStart("0","Validate configuration parameters");const r=globalThis.chain;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');const o=function(t){const e=P(t),r=nt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),i=o.chain,n=o.bitcoinNetwork;let a=[];if(console.log(` \u2705 Chain: ${r} (${i})`),console.log(` \u2705 Bitcoin Network: ${n}`),!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error('Required "contractAddresses" object with: PositionManager, LoanOperationsManagerModule, TermManagerModule');const s=globalThis.contractAddresses.PositionManager,p=globalThis.contractAddresses.LoanOperationsManagerModule,g=globalThis.contractAddresses.TermManagerModule,y=globalThis.contractAddresses.UCDController,b=globalThis.contractAddresses.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",E=globalThis.contractAddresses.BTCSpendAuthorizer??"";if(!(s&&p&&g&&y&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");if(console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${s}`),console.log(` LoanOpsManager: ${p}`),!o.allowArbitraryBitcoinProvider&&!globalThis.contractAddresses.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const S=globalThis.auth;if(!S||"object"!=typeof S)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!S.positionId)throw new Error("auth.positionId is required");if("number"!=typeof S.timestamp)throw new Error("auth.timestamp must be a number");if(!S.signature)throw new Error("auth.signature is required");const I=BigInt(S.amount);if(I<=0n)throw new Error(`Withdrawal amount must be positive, got: ${I.toString()} sats`);const C=u;if(I<C)throw new Error(`Withdrawal amount ${I.toString()} sats is below minimum ${C.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const B=S.destinationAddress;if(!B||"string"!=typeof B)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const U=D().publicKey;if(!U)throw new Error("publicKey must not be blank");if("string"!=typeof U||0===U.length)throw new Error("publicKey must not be blank");const k=U;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(B),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(B);return!(!t&&!e)&&("testnet"===n||"regtest"===n?B.startsWith("m")||B.startsWith("n")||B.startsWith("2")||B.startsWith("tb1")||B.startsWith("bcrt1"):"mainnet"===n&&(B.startsWith("1")||B.startsWith("3")||B.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${B}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);console.log(` \u2705 Destination address validated: ${B} (${n})`);let O="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${S.positionId}`),console.log(` Withdrawal Amount: ${I.toString()} sats`),console.log(` Destination Address: ${B}`);const t=await async function(t){if(!t)return t;const e=[];for(const o of t){if(!o?.name||"string"!=typeof o.name)throw new Error("Each price provider must include a valid name");let t,i;if(o.pkpId&&"string"==typeof o.pkpId){const e=(r=o.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;o.apiKey&&(t=await L(o.name,"apiKey",e,o.apiKey)),o.apiSecret&&(i=await L(o.name,"apiSecret",e,o.apiSecret))}else t=o.apiKey,i=o.apiSecret;e.push({name:o.name,apiKey:t,apiSecret:i})}var r;return e}(globalThis.priceProviders),n=new N(t,void 0),u=globalThis.rpcUrl;if(!u||"string"!=typeof u)return Lit.Actions.setResponse({response:JSON.stringify({approved:!1,reason:"rpcUrl jsParam is required but was not provided"})}),void 0;!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(o,u),console.log(` 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}(u)}`);const P=u,C=new ethers.providers.JsonRpcProvider(P);a=o.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:globalThis.devBitcoinProviderUrl,minConfirmations:o.minBitcoinConfirmations,network:o.bitcoinNetwork}]:await ut(o,C,globalThis.contractAddresses.BitcoinProviderRegistry);const U=a[0];console.log(` \u2705 Bitcoin Providers: ${a.length} (${a.map((t=>t.name)).join(", ")})`);const x=new M({providerUrl:U.url});!function(t,e){const r=Q[t],o=[];for(const t of r)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("withdrawBtc",await ot(C,s));const D=(R={contractAddress:E||p,chain:r,chainId:A(i),rpcUrl:P,bitcoinProvider:x,minConfirmations:U.minConfirmations},new q(R));O="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const _=function(t){return new G(t)}({contractAddress:s,termManagerAddress:g,loanOpsManagerAddress:p,liquidationManagerAddress:v,chain:r,chainId:A(i),rpcUrl:P,vaultBalance:D,priceOracle:n}),F=await _.getVaultSnapshot(S.positionId);if(a.length>1){const t=await x.getBalance(F.vaultAddress);for(let e=1;e<a.length;e++){const r=a[e],o=new M({providerUrl:r.url}),i=await o.getBalance(F.vaultAddress);if(i!==t)throw new Error(`Bitcoin provider balance mismatch: ${U.name}=${t.toString()} vs ${r.name}=${i.toString()}`)}console.log(` \u2705 Consensus reached across ${a.length} providers (${t.toString()} sats)`)}console.log(` \u2705 Vault balance: ${F.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${F.ucdDebt.toString()} wei`),e.stepEnd("1"),O="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const z=e.getElapsed();console.log(`[TIMING] Step 2 started at ${z}ms`);const j=A(i),W=new ethers.providers.StaticJsonRpcProvider(P,j);let K;if(5===F.status){if(!b)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(b,["function pkpOwners(bytes32) view returns (address)"],W);if(K=await t.pkpOwners(F.pkpId),!K||K===ethers.constants.AddressZero)throw new Error("No PKP owner registered for this liquidated position in LITActionValidator");console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${K}`)}else K=F.borrower;if(!await $.verifyWithdrawAuthorization(S,K,j,W,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");console.log(" \u2705 Caller authorized"),e.stepEnd("2"),O="2.5",console.log("[Step 2.5] Validating position status..."),e.stepStart("2.5","Validate position status");const J=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${J}ms`);if(![0,1,2,6,5].includes(F.status))throw new Error(`Position status ${m(F.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${m(F.status)}`),e.stepEnd("2.5"),O="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const Z=e.getElapsed();console.log(`[TIMING] Step 3 started at ${Z}ms`);const Y=I;if(0n===F.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(F.btcPriceUsd<c||F.btcPriceUsd>l)throw new Error(`Bitcoin price ${F.btcPriceUsd} is outside acceptable range (${c} - ${l}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(F.btcPriceUsd)/1e8).toFixed(2)}`);const t=F.availableBTCSats-Y,e=V(X(t,F.btcPriceUsd),F.ucdDebt);if(e<F.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${H(e)}% < liquidation threshold ${H(F.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${H(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${H(F.liquidationThresholdBps)}%`)}e.stepEnd("3"),O="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const tt=e.getElapsed();console.log(`[TIMING] Step 4 started at ${tt}ms`);const et="string"==typeof S.amount?BigInt(S.amount):S.amount;if(et!==I)throw new Error(`Authorization amount mismatch: auth.amount=${et.toString()} sats, but requested withdrawal=${I.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),Y>F.availableBTCSats)throw new Error(`Insufficient vault balance: need ${Y.toString()} sats but only ${F.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const rt=F.availableBTCSats-Y,nt=F.ucdDebt,at=X(rt,F.btcPriceUsd),st=nt>0n?V(at,nt):void 0;if(console.log(` Post-withdrawal collateral: ${rt.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(at)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${nt.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${nt>0n&&void 0!==st?H(Number(st)):"\u221e"}%`),rt<0n)throw new Error(`Withdrawal would result in negative balance: ${rt.toString()} sats`);console.log(" \u2705 Withdrawal validation passed"),e.stepEnd("4"),O="4.5",console.log("[Step 4.5] Querying vault UTXOs from Bitcoin network..."),e.stepStart("4.5","Query and select UTXO");const ct=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${ct}ms`);const lt=F.vaultAddress;if(!lt)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${lt}`);let ht=[],pt=null;const gt=d,mt=h;for(let t=1;t<=gt;t++)try{console.log(` \ud83d\udd04 UTXO query attempt ${t}/${gt}...`),ht=await x.getUTXOs(lt),console.log(` \u2705 UTXO query succeeded on attempt ${t}`),pt=null;break}catch(e){pt=e,console.error(` \u274c UTXO query failed on attempt ${t}:`,e.message),t<gt&&(console.log(` \u23f3 Waiting ${mt}ms before retry...`),await new Promise((t=>setTimeout(t,mt))))}if(pt)throw new Error(`Failed to query UTXOs after ${gt} attempts: ${pt.message}`);if(!ht||0===ht.length)throw new Error(`No UTXOs found in vault ${lt}`);console.log(` \u2705 Found ${ht.length} UTXO(s) in vault`);const wt=U.minConfirmations,ft=ht.filter((t=>t.confirmations>=wt));if(0===ft.length)throw new Error(`No confirmed UTXOs found in vault. Required confirmations: ${wt}, found ${ht.length} UTXO(s) with insufficient confirmations.`);console.log(` \u2705 Found ${ft.length} confirmed UTXO(s)`);const yt=ft.filter((t=>t.satoshis>=Y));let bt;if(0===yt.length){const t=ft.reduce(((t,e)=>t+e.satoshis),0n);if(t<Y)throw new Error(`Insufficient vault balance for withdrawal. Need ${Y.toString()} sats, total across ${ft.length} UTXO(s): ${t.toString()} sats.`);bt=[...ft].sort(((t,e)=>Number(e.satoshis-t.satoshis)))[0],console.log(" \u2139\ufe0f No single UTXO covers withdrawal \u2014 multi-UTXO consolidation will be used in Phase 2."),console.log(` Primary UTXO (contract auth): ${bt.txid}:${bt.vout} (${bt.satoshis.toString()} sats)`)}else bt=yt.sort(((t,e)=>Number(t.satoshis-e.satoshis)))[0];console.log(` \u2705 Selected UTXO: ${bt.txid}:${bt.vout}`),console.log(` \u2705 UTXO value: ${bt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${bt.confirmations}`);const Tt=F.availableBTCSats;if(bt.satoshis<Tt&&console.warn(` \u26a0\ufe0f Selected UTXO value (${bt.satoshis.toString()}) < calculated balance (${Tt.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),bt.satoshis<Y)throw new Error(`Selected UTXO value (${bt.satoshis.toString()} sats) < withdrawal amount (${Y.toString()} sats). This should never happen after eligibility filtering.`);console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const vt=dt(lt).toLowerCase(),Pt=await x.getTransactionOutputs(bt.txid);if(!Pt)throw new Error(`Could not fetch transaction outputs for ${bt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);let At=-1;for(const t of Pt){const e=(t.scriptpubkey??"").toLowerCase(),r=e.length>0&&e===vt,o=t.scriptpubkey_address===lt;if(r||o){At=t.index;break}}if(-1===At)throw new Error(`Vault output not found in tx ${bt.txid}. Expected scriptPubKey ${vt} or address ${lt}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);At!==bt.vout?(console.log(` \u26a0\ufe0f Esplora API reported vout=${bt.vout} but vault output is at vout=${At} (matched on hex scriptpubkey). Correcting.`),bt={...bt,vout:At}):console.log(` \u2705 UTXO vout=${bt.vout} confirmed correct`),e.stepEnd("4.5"),O="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const Et=e.getElapsed();console.log(`[TIMING] Step 5 started at ${Et}ms`);const St=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(S.action)),$t=F.authorizedSpendsHash,It=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[F.ucdDebt])),Ct=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[s,p,g,y])),Bt=BigInt(S.timestamp),Ut=rt,xt=F.btcPriceUsd;if(xt<c||xt>l)throw new Error(`BTC price ${xt.toString()} (8 decimals) is outside acceptable range (${c.toString()} - ${l.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",S.positionId),console.log(" action:",S.action),console.log(" actionHash:",St),console.log(" authorizedSpendsHash:",$t),console.log(" ucdDebtHash:",It),console.log(" withdrawalAddress:",B),console.log(" totalDeduction:",Y.toString()),console.log(" newCollateral:",Ut.toString()),console.log(" quantumTimestamp:",Bt.toString()),console.log(" btcPrice:",xt.toString()),console.log(" utxoTxid:",bt.txid),console.log(" utxoVout:",bt.vout);const Dt=it(S.positionId),kt=A(i),Ot={name:w,version:f,chainId:kt,verifyingContract:ethers.utils.getAddress(p)},Mt={WithdrawalAuthorization:[{name:"positionId",type:"bytes32"},{name:"actionHash",type:"bytes32"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractBundleHash",type:"bytes32"},{name:"withdrawalAddress",type:"string"},{name:"totalDeduction",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"utxoTxid",type:"string"},{name:"utxoVout",type:"uint32"},{name:"caller",type:"address"}]},Rt=ethers.utils._TypedDataEncoder.hash(Ot,Mt,{positionId:Dt,actionHash:St,authorizedSpendsHash:$t,ucdDebtHash:It,contractBundleHash:Ct,withdrawalAddress:B,totalDeduction:Y.toString(),newCollateral:Ut.toString(),quantumTimestamp:Bt.toString(),btcPrice:xt.toString(),utxoTxid:bt.txid,utxoVout:bt.vout,caller:ethers.utils.getAddress(K)});console.log("[Step 5] Contract message hash for signing:",Rt),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(Rt).length),e.stepEnd("5"),O="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const Nt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${Nt}ms`),e.log("6","========================================"),e.log("6","\ud83d\udd0d FINAL HASH INPUTS - ALL LIT NODES MUST MATCH"),e.log("6","========================================"),e.log("6",`Position ID: ${S.positionId}`),e.log("6",`Action Hash: ${St}`),e.log("6",`Authorized Spends Hash: ${$t}`),e.log("6",`UCD Debt Hash: ${It}`),e.log("6",`Contract Bundle Hash: ${Ct}`),e.log("6",`Destination Address: ${B}`),e.log("6",`Total Deduction: ${Y.toString()}`),e.log("6",`New Collateral: ${Ut.toString()}`),e.log("6",`Quantum Timestamp: ${Bt.toString()}`),e.log("6",`BTC Price: ${xt.toString()}`),e.log("6",`Selected UTXO Txid: ${bt.txid}`),e.log("6",`Selected UTXO Vout: ${bt.vout}`),e.log("6",`Selected UTXO Satoshis: ${bt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${bt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${Rt}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${Rt}`),e.log("6",`publicKey: ${k}`),e.log("6","publicKey with 0x prefix: "+("0x"+k));const Lt=ethers.utils.arrayify(Rt);e.log("6",`messageBytes length: ${Lt.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(Lt))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const qt=Date.now(),_t=globalThis.validatorWalletAddress;if(!_t||!_t.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Ft=await Lit.Actions.getPrivateKey({pkpId:_t}),zt="string"==typeof Ft?Ft.startsWith("0x")?Ft:`0x${Ft}`:String(Ft),Xt=new ethers.Wallet(zt),Vt=new ethers.utils.SigningKey(zt);e.log("6",`Wallet-derived signer address: ${Xt.address}`),e.log("6",`validatorWalletAddress: ${_t}`);const Ht=Vt.signDigest(Rt),jt=ethers.utils.joinSignature(Ht),Wt=Date.now()-qt;e.log("6",`Chipotle signature created in ${Wt}ms`),e.log("6",`signature: ${jt}`);const Gt=globalThis.contractAddresses.BTCSpendAuthorizer?.trim()||"";let Kt=null;if(Gt){const t=it(S.positionId),r=A(i),o=Ut+Y,n={name:w,version:f,chainId:r,verifyingContract:ethers.utils.getAddress(Gt)},a={BtcSpendAuth:[{name:"positionId",type:"bytes32"},{name:"txid",type:"string"},{name:"vout",type:"uint32"},{name:"satoshis",type:"uint256"},{name:"targetAddress",type:"string"},{name:"targetAmount",type:"uint256"}]},s=ethers.utils._TypedDataEncoder.hash(n,a,{positionId:t,txid:bt.txid,vout:bt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:Y.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${s}`),Kt=await Xt._signTypedData(n,a,{positionId:t,txid:bt.txid,vout:bt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:Y.toString()}),e.log("6",`btcSpendAuth signature: ${Kt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const Qt={approved:!0,positionId:S.positionId,actionHash:St,authorizedSpendsHash:$t,ucdDebtHash:It,contractBundleHash:Ct,totalDeduction:Y.toString(),remainingCollateral:rt.toString(),newCollateralRatioBps:nt>0n&&void 0!==st?Number(st):void 0,destinationAddress:B,signature:jt,btcSpendAuthSignature:Kt,timestamp:Bt.toString(),btcPrice:xt.toString(),utxoTxid:bt.txid,utxoVout:bt.vout,utxoSatoshis:bt.satoshis.toString()};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",Y,"type:",typeof Y,"toString():",Y.toString()),console.log(" remainingCollateral:",rt,"type:",typeof rt,"toString():",rt.toString()),console.log(" btcPrice:",xt,"type:",typeof xt,"toString():",xt.toString()),console.log(" timestamp:",Bt,"type:",typeof Bt,"toString():",Bt.toString()),console.log(" Full response object:",JSON.stringify(Qt,null,2)),Qt}catch(t){return console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${O}`),e.error("error",`Failed: ${t.message}`),{approved:!1,reason:t.message||t.toString(),positionId:S?.positionId,timestamp:Date.now()}}var R}return at=i,((i,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))o.call(i,c)||c===a||t(i,c,{get:()=>n[c],enumerable:!(s=e(n,c))||s.enumerable});return i})(t({},"__esModule",{value:!0}),at)})();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,o=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var n=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,l=100000000000000n,u=546n,d=3,h=500,p=60,g=8e3;function m(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var w="DiamondHands.Protocol",f="1",y=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(y||{}),b={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],v={ethereum:1,sepolia:11155111,hardhat:1337};function P(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(y).join(", ")}`)}function A(t){return v[t]}function E(t){return Math.floor(t/p)*p}async function S(){const t=Math.floor(Date.now()/1e3),e=t%p;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%p;return e<8||e>=52}(t))return;let r;r=e>=52?p-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${E(Math.floor(Date.now()/1e3))}`)}var $=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 r=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,o){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,o){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],o),n=await i.positionDelegate(t);return!(!n||n===ethers.constants.AddressZero)&&n.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,o){const i=Math.floor(Date.now()/1e3);await S();const n=o?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const o=e??Math.floor(Date.now()/1e3),i=E(o),n=E(t);if(r?.strictCurrentQuantum){if(n!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${n}, current quantum: ${i}`);return}const a=i-p,s=i+p;if(n!==a&&n!==i&&n!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${a} (past), ${i} (current), ${s} (next)]`);if(n===a){if(o<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(n===s&&o>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i,n){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,o,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i)}static async verifyPaymentAuthorization(t,e,r,o,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i)}static async verifyWithdrawAuthorization(e,r,o,i,n){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,o,i,n){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}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,r,o,i,n){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,o,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o,i)}static async verifyBtcExecutionAuthorization(e,r,o,i,n){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==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 I(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 C(...t){I()&&console.log(...t)}var B=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}},U=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,o=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${o}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 o=Date.now()-r;this.stepDurations.set(t,o),console.log(`[Step ${t}] Duration: ${o}ms`),o>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${o}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-i;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 o=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${o}%)`)}}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}},x=class{static create(t="LIT Action",e){return I(e)?new U(t):new B}};function D(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function k(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function O(t){return t instanceof Error&&"AbortError"===t.name}var M=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=x.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(),o=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),C(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Failed to fetch block height: ${o.status} ${o.statusText}`);const i=await o.text();if(i.trim().startsWith("<!DOCTYPE")||i.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(i.trim(),10);if(isNaN(n)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),O(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: ${k(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: ${k(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${k(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,o=[];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 i=t.txid,n=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===n||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");o.push({txid:i,vout:n,satoshis:BigInt(a),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.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(i),C(`[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 s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.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(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${k(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const l=this.parseBlockstreamUTXOs(c,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;const i=d,n=h;for(let e=1;e<=i;e++)try{this.logger.log("2",`UTXO query attempt ${e}/${i}...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(k(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${k(t)}`),e<i&&(this.logger.log("2",`Waiting ${n}ms before retry...`),await new Promise((t=>setTimeout(t,n))))}if(o)throw new Error(`Failed to query UTXOs after ${i} attempts: ${o.message}`);const a=r.reduce(((t,e)=>t+e.satoshis),0n),s=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),c=a-s;return{utxos:r,totalBalance:a,totalUTXOs:r.length,confirmedBalance:s,unconfirmedBalance:c}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:o.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(i),C(`[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,s=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(i),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=k(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=k(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 o=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),C(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.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 o=(await r.text()).trim(),i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<=0)return{txid:n.txid??t,confirmations:1};const a=i-n.status.block_height+1;return{txid:n.txid??t,confirmations:a>0?a:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(k(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 o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},R=class t{constructor(e,r,o){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`Price oracle requires exactly ${t.REQUIRED_PROVIDER_COUNT} providers. Currently configured: ${this.sources.length} provider(s). Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(e.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`priceProviders must contain exactly ${t.REQUIRED_PROVIDER_COUNT} entries. Received: ${e.length}. Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`CryptoCompare HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(t){return async(e,r)=>{const o=new AbortController,i=setTimeout((()=>o.abort()),5e3);try{const i=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:o.signal});if(!i.ok)throw new Error(`${t} HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const a=await r(n.toString(),i),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const e=Date.now();if(this.sources.length!==t.REQUIRED_PROVIDER_COUNT)throw new Error(`Price oracle requires exactly ${t.REQUIRED_PROVIDER_COUNT} providers. Currently configured: ${this.sources.length}`);const r=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),o=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([o,r])].sort(((t,e)=>t-e)),n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}const a=Math.round(100*n),s=1000000n*BigInt(a),c=Date.now()-e;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${c}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${s}`),s}};R.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],R.REQUIRED_PROVIDER_COUNT=3;var N=R;async function L(t,e,r,o){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:o});return"string"==typeof t?t:String(t??"")}catch(r){const o=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${o}`)}}var q=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),o=await this.getAuthorizedSpendsFromContract(t),i=o.reduce(((t,e)=>t+e.satoshis),0n),n=r>i?r-i:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:o,authorizedBalance:i,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,o),availableUTXOs:[],availableBalance:n,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const o=this.config.minConfirmations||6,i=await this.bitcoinProvider.getUTXOSet(e,o),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=n.reduce(((t,e)=>t+e.satoshis),0n),s=i.utxos.filter((t=>!this.isUTXOAuthorized(t,n))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:a,authorizedSpendsHash:l,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,o){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===o))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{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"}],o);return(await i.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const o=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,o]))}};function _(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}function F(t,e,r,o){if(!t)return r;const i=o??n,a=Math.min(e,30);return n+a*a*(i-n)/900}function z(t,e,r){const o=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:o,collateralRatioBps:Number(o*s*10000n/r)}}function X(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}function V(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function H(t){return t/100}var W=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.loanOpsManagerAddress,r,e),i=await o.liquidationThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.termManagerAddress,o,r),n=await i.getTermFees(t);return{originationFeeBps:Number(n.originationFee?.toString?.()??n[0]?.toString?.()??n[0]),extensionFeeBps:Number(n.extensionFee?.toString?.()??n[1]?.toString?.()??n[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,i=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await i.getAuthorizedSpendsHash(o)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.liquidationManagerAddress,r,e),i=await o.maxEscalatedThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function j(t){return new W(t)}var G=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=j({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=_(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=z(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),n=j({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=_(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=z(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],o),n=await i.core(),a=new ethers.Contract(n,[{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:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],o),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const l=Number(s.expiryAt),u=Number(s.selectedTerm),d=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=Number(s.lastRenewedAt),m=(f=u,0===(w=l)?0:w-30*f*86400);var w,f;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,P(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d,lastRenewedAt:p}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const o=await this.getVaultSnapshot(t);return function(t,e,r,o){const i=e+r;return 0n===i||Number(t*s*10000n/i)>=o}(o.collateralValueUsd,o.ucdDebt,e,r)}};var K="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))",Q={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 J(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 Z=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=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)"]),tt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),et=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function rt(t,e,r){return t.call({to:e,data:r})}async function ot(t,e){const r=new ethers.utils.Interface([K]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([K]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({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]}):J(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await rt(t,e,Z.encodeFunctionData("views",[])),[o]=Z.decodeFunctionResult("views",r),[i,n,a,s,c,l,u,d]=await Promise.all([rt(t,e,Z.encodeFunctionData("paused",[])),rt(t,e,Z.encodeFunctionData("liquidationPaused",[])),rt(t,e,Z.encodeFunctionData("simplePsm",[])),rt(t,o,Y.encodeFunctionData("core",[])),rt(t,o,Y.encodeFunctionData("loanOps",[])),rt(t,o,Y.encodeFunctionData("collateralManager",[])),rt(t,o,Y.encodeFunctionData("liquidationManager",[])),rt(t,o,Y.encodeFunctionData("circuitBreaker",[]))]),h=Z.decodeFunctionResult("paused",i)[0],p=Z.decodeFunctionResult("liquidationPaused",n)[0],g=Z.decodeFunctionResult("simplePsm",a)[0],m=Y.decodeFunctionResult("core",s)[0],w=Y.decodeFunctionResult("loanOps",c)[0],f=Y.decodeFunctionResult("collateralManager",l)[0],y=Y.decodeFunctionResult("liquidationManager",u)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await rt(t,w,tt.encodeFunctionData("getUcdController",[])),v=await rt(t,w,tt.encodeFunctionData("ucdToken",[])),P=tt.decodeFunctionResult("getUcdController",T)[0],A=tt.decodeFunctionResult("ucdToken",v)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await rt(t,e,et.encodeFunctionData("paused",[]));return et.decodeFunctionResult("paused",r)[0]}catch{return!1}},[S,$,I,C,B,U,x,D]=await Promise.all([E(m),E(w),E(f),E(y),E(b),E(P),E(A),E(g)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:S,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:U,ucdTokenPaused:x,simplePsmPaused:D})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}function it(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}var nt={hardhat:{chain:"hardhat",chainId:v.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:v.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:v.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var at,st=[{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"}],ct=[{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 lt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),o="string"==typeof e?e:String(e??"");if(!o)throw new Error("Decrypt returned empty plaintext");return o}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ut(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=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 o=new ethers.Contract(r,st,e),[i,n]=await o.getProviders(t),a=[];for(let t=0;t<i.length;t++)a.push({providerId:i[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return a}(t.chainId,e,r);if(0===o.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:o}=t;if(!o||"string"!=typeof o)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),a=new ethers.Contract(o,ct,r);let s;try{s=await a.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)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 i=[];for(const e of o){const r=await lt(e.ciphertext,e.pkpId);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}function dt(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const o=t.substring(r+1).toLowerCase(),i=[];for(let t=0;t<o.length;t++){const r=e.indexOf(o[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${o[t]}`);i.push(r)}const n=i.slice(0,-6),a=(n[0],function(t,e,r,o){let i=0,n=0;const a=[],s=(1<<r)-1;for(let o=0;o<t.length;o++){const c=t[o];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,n+=e;n>=r;)n-=r,a.push(i>>n&s)}if(o)n>0&&a.push(i<<r-n&s);else if(n>=e||i<<r-n&s)throw new Error("Invalid padding in bit conversion");return a}(n.slice(1),5,8,!1));return{witnessProgram:a.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let o=0;o<t.length;o++){const i=e.indexOf(t[o]);if(i<0)throw new Error(`Invalid Base58 character: ${t[o]}`);r=58n*r+BigInt(i)}let o=r.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=x.create("BTC Withdrawal Validator");console.log("[Step 0] Validating configuration..."),e.stepStart("0","Validate configuration parameters");const r=globalThis.chain;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');const o=function(t){const e=P(t),r=nt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),i=o.chain,n=o.bitcoinNetwork;let a=[];if(console.log(` \u2705 Chain: ${r} (${i})`),console.log(` \u2705 Bitcoin Network: ${n}`),!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error('Required "contractAddresses" object with: PositionManager, LoanOperationsManagerModule, TermManagerModule');const s=globalThis.contractAddresses.PositionManager,p=globalThis.contractAddresses.LoanOperationsManagerModule,g=globalThis.contractAddresses.TermManagerModule,y=globalThis.contractAddresses.UCDController,b=globalThis.contractAddresses.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",E=globalThis.contractAddresses.BTCSpendAuthorizer??"";if(!(s&&p&&g&&y&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");if(console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${s}`),console.log(` LoanOpsManager: ${p}`),!o.allowArbitraryBitcoinProvider&&!globalThis.contractAddresses.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const S=globalThis.auth;if(!S||"object"!=typeof S)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!S.positionId)throw new Error("auth.positionId is required");if("number"!=typeof S.timestamp)throw new Error("auth.timestamp must be a number");if(!S.signature)throw new Error("auth.signature is required");const I=BigInt(S.amount);if(I<=0n)throw new Error(`Withdrawal amount must be positive, got: ${I.toString()} sats`);const C=u;if(I<C)throw new Error(`Withdrawal amount ${I.toString()} sats is below minimum ${C.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const B=S.destinationAddress;if(!B||"string"!=typeof B)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const U=D().publicKey;if(!U)throw new Error("publicKey must not be blank");if("string"!=typeof U||0===U.length)throw new Error("publicKey must not be blank");const k=U;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(B),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(B);return!(!t&&!e)&&("testnet"===n||"regtest"===n?B.startsWith("m")||B.startsWith("n")||B.startsWith("2")||B.startsWith("tb1")||B.startsWith("bcrt1"):"mainnet"===n&&(B.startsWith("1")||B.startsWith("3")||B.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${B}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);console.log(` \u2705 Destination address validated: ${B} (${n})`);let O="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${S.positionId}`),console.log(` Withdrawal Amount: ${I.toString()} sats`),console.log(` Destination Address: ${B}`);const t=await async function(t){if(!t)return t;const e=[];for(const o of t){if(!o?.name||"string"!=typeof o.name)throw new Error("Each price provider must include a valid name");let t,i;if(o.pkpId&&"string"==typeof o.pkpId){const e=(r=o.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;o.apiKey&&(t=await L(o.name,"apiKey",e,o.apiKey)),o.apiSecret&&(i=await L(o.name,"apiSecret",e,o.apiSecret))}else t=o.apiKey,i=o.apiSecret;e.push({name:o.name,apiKey:t,apiSecret:i})}var r;return e}(globalThis.priceProviders),n=new N(t,void 0),u=globalThis.rpcUrl;if(!u||"string"!=typeof u)return Lit.Actions.setResponse({response:JSON.stringify({approved:!1,reason:"rpcUrl jsParam is required but was not provided"})}),void 0;!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(o,u),console.log(` 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}(u)}`);const P=u,C=new ethers.providers.JsonRpcProvider(P);a=o.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:globalThis.devBitcoinProviderUrl,minConfirmations:o.minBitcoinConfirmations,network:o.bitcoinNetwork}]:await ut(o,C,globalThis.contractAddresses.BitcoinProviderRegistry);const U=a[0];console.log(` \u2705 Bitcoin Providers: ${a.length} (${a.map((t=>t.name)).join(", ")})`);const x=new M({providerUrl:U.url});!function(t,e){const r=Q[t],o=[];for(const t of r)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("withdrawBtc",await ot(C,s));const D=(R={contractAddress:E||p,chain:r,chainId:A(i),rpcUrl:P,bitcoinProvider:x,minConfirmations:U.minConfirmations},new q(R));O="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const _=function(t){return new G(t)}({contractAddress:s,termManagerAddress:g,loanOpsManagerAddress:p,liquidationManagerAddress:v,chain:r,chainId:A(i),rpcUrl:P,vaultBalance:D,priceOracle:n}),F=await _.getVaultSnapshot(S.positionId);if(a.length>1){const t=await x.getBalance(F.vaultAddress);for(let e=1;e<a.length;e++){const r=a[e],o=new M({providerUrl:r.url}),i=await o.getBalance(F.vaultAddress);if(i!==t)throw new Error(`Bitcoin provider balance mismatch: ${U.name}=${t.toString()} vs ${r.name}=${i.toString()}`)}console.log(` \u2705 Consensus reached across ${a.length} providers (${t.toString()} sats)`)}console.log(` \u2705 Vault balance: ${F.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${F.ucdDebt.toString()} wei`),e.stepEnd("1"),O="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const z=e.getElapsed();console.log(`[TIMING] Step 2 started at ${z}ms`);const W=A(i),j=new ethers.providers.StaticJsonRpcProvider(P,W);let K;if(5===F.status){if(!b)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(b,["function pkpOwners(bytes32) view returns (address)"],j);if(K=await t.pkpOwners(F.pkpId),!K||K===ethers.constants.AddressZero)throw new Error("No PKP owner registered for this liquidated position in LITActionValidator");console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${K}`)}else K=F.borrower;if(!await $.verifyWithdrawAuthorization(S,K,W,j,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");console.log(" \u2705 Caller authorized"),e.stepEnd("2"),O="2.5",console.log("[Step 2.5] Validating position status..."),e.stepStart("2.5","Validate position status");const J=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${J}ms`);if(![0,1,2,6,5].includes(F.status))throw new Error(`Position status ${m(F.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${m(F.status)}`),e.stepEnd("2.5"),O="2.6";const Z=globalThis.contractAddresses?.BitcoinWithdrawalAddressRegistry;if(Z&&Z!==ethers.constants.AddressZero){e.stepStart("2.6","Enforce approved-address allowlist"),console.log("[Step 2.6] Checking approved-withdrawal-address allowlist...");const t=new ethers.Contract(Z,["function isApproved(address user, string btcAddress) view returns (bool)"],j);if(!await t.isApproved(K,B))throw new Error(`Withdrawal address ${B} is not an approved destination for controller ${K} (not on the allowlist, or its time-lock delay has not elapsed).`);console.log(` \u2705 Destination on controller's allowlist: ${B}`),e.stepEnd("2.6")}O="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const Y=e.getElapsed();console.log(`[TIMING] Step 3 started at ${Y}ms`);const tt=I;if(0n===F.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(F.btcPriceUsd<c||F.btcPriceUsd>l)throw new Error(`Bitcoin price ${F.btcPriceUsd} is outside acceptable range (${c} - ${l}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(F.btcPriceUsd)/1e8).toFixed(2)}`);const t=F.availableBTCSats-tt,e=V(X(t,F.btcPriceUsd),F.ucdDebt);if(e<F.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${H(e)}% < liquidation threshold ${H(F.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${H(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${H(F.liquidationThresholdBps)}%`)}e.stepEnd("3"),O="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const et=e.getElapsed();console.log(`[TIMING] Step 4 started at ${et}ms`);const rt="string"==typeof S.amount?BigInt(S.amount):S.amount;if(rt!==I)throw new Error(`Authorization amount mismatch: auth.amount=${rt.toString()} sats, but requested withdrawal=${I.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),tt>F.availableBTCSats)throw new Error(`Insufficient vault balance: need ${tt.toString()} sats but only ${F.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const nt=F.availableBTCSats-tt,at=F.ucdDebt,st=X(nt,F.btcPriceUsd),ct=at>0n?V(st,at):void 0;if(console.log(` Post-withdrawal collateral: ${nt.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(st)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${at.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${at>0n&&void 0!==ct?H(Number(ct)):"\u221e"}%`),nt<0n)throw new Error(`Withdrawal would result in negative balance: ${nt.toString()} sats`);console.log(" \u2705 Withdrawal validation passed"),e.stepEnd("4"),O="4.5",console.log("[Step 4.5] Querying vault UTXOs from Bitcoin network..."),e.stepStart("4.5","Query and select UTXO");const lt=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${lt}ms`);const ht=F.vaultAddress;if(!ht)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${ht}`);let pt=[],gt=null;const mt=d,wt=h;for(let t=1;t<=mt;t++)try{console.log(` \ud83d\udd04 UTXO query attempt ${t}/${mt}...`),pt=await x.getUTXOs(ht),console.log(` \u2705 UTXO query succeeded on attempt ${t}`),gt=null;break}catch(e){gt=e,console.error(` \u274c UTXO query failed on attempt ${t}:`,e.message),t<mt&&(console.log(` \u23f3 Waiting ${wt}ms before retry...`),await new Promise((t=>setTimeout(t,wt))))}if(gt)throw new Error(`Failed to query UTXOs after ${mt} attempts: ${gt.message}`);if(!pt||0===pt.length)throw new Error(`No UTXOs found in vault ${ht}`);console.log(` \u2705 Found ${pt.length} UTXO(s) in vault`);const ft=U.minConfirmations,yt=pt.filter((t=>t.confirmations>=ft));if(0===yt.length)throw new Error(`No confirmed UTXOs found in vault. Required confirmations: ${ft}, found ${pt.length} UTXO(s) with insufficient confirmations.`);console.log(` \u2705 Found ${yt.length} confirmed UTXO(s)`);const bt=yt.filter((t=>t.satoshis>=tt));let Tt;if(0===bt.length){const t=yt.reduce(((t,e)=>t+e.satoshis),0n);if(t<tt)throw new Error(`Insufficient vault balance for withdrawal. Need ${tt.toString()} sats, total across ${yt.length} UTXO(s): ${t.toString()} sats.`);Tt=[...yt].sort(((t,e)=>Number(e.satoshis-t.satoshis)))[0],console.log(" \u2139\ufe0f No single UTXO covers withdrawal \u2014 multi-UTXO consolidation will be used in Phase 2."),console.log(` Primary UTXO (contract auth): ${Tt.txid}:${Tt.vout} (${Tt.satoshis.toString()} sats)`)}else Tt=bt.sort(((t,e)=>Number(t.satoshis-e.satoshis)))[0];console.log(` \u2705 Selected UTXO: ${Tt.txid}:${Tt.vout}`),console.log(` \u2705 UTXO value: ${Tt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${Tt.confirmations}`);const vt=F.availableBTCSats;if(Tt.satoshis<vt&&console.warn(` \u26a0\ufe0f Selected UTXO value (${Tt.satoshis.toString()}) < calculated balance (${vt.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),Tt.satoshis<tt)throw new Error(`Selected UTXO value (${Tt.satoshis.toString()} sats) < withdrawal amount (${tt.toString()} sats). This should never happen after eligibility filtering.`);console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const Pt=dt(ht).toLowerCase(),At=await x.getTransactionOutputs(Tt.txid);if(!At)throw new Error(`Could not fetch transaction outputs for ${Tt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);let Et=-1;for(const t of At){const e=(t.scriptpubkey??"").toLowerCase(),r=e.length>0&&e===Pt,o=t.scriptpubkey_address===ht;if(r||o){Et=t.index;break}}if(-1===Et)throw new Error(`Vault output not found in tx ${Tt.txid}. Expected scriptPubKey ${Pt} or address ${ht}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);Et!==Tt.vout?(console.log(` \u26a0\ufe0f Esplora API reported vout=${Tt.vout} but vault output is at vout=${Et} (matched on hex scriptpubkey). Correcting.`),Tt={...Tt,vout:Et}):console.log(` \u2705 UTXO vout=${Tt.vout} confirmed correct`),e.stepEnd("4.5"),O="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const St=e.getElapsed();console.log(`[TIMING] Step 5 started at ${St}ms`);const $t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(S.action)),It=F.authorizedSpendsHash,Ct=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[F.ucdDebt])),Bt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[s,p,g,y])),Ut=BigInt(S.timestamp),xt=nt,Dt=F.btcPriceUsd;if(Dt<c||Dt>l)throw new Error(`BTC price ${Dt.toString()} (8 decimals) is outside acceptable range (${c.toString()} - ${l.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",S.positionId),console.log(" action:",S.action),console.log(" actionHash:",$t),console.log(" authorizedSpendsHash:",It),console.log(" ucdDebtHash:",Ct),console.log(" withdrawalAddress:",B),console.log(" totalDeduction:",tt.toString()),console.log(" newCollateral:",xt.toString()),console.log(" quantumTimestamp:",Ut.toString()),console.log(" btcPrice:",Dt.toString()),console.log(" utxoTxid:",Tt.txid),console.log(" utxoVout:",Tt.vout);const kt=it(S.positionId),Ot=A(i),Mt={name:w,version:f,chainId:Ot,verifyingContract:ethers.utils.getAddress(p)},Rt={WithdrawalAuthorization:[{name:"positionId",type:"bytes32"},{name:"actionHash",type:"bytes32"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractBundleHash",type:"bytes32"},{name:"withdrawalAddress",type:"string"},{name:"totalDeduction",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"utxoTxid",type:"string"},{name:"utxoVout",type:"uint32"},{name:"caller",type:"address"}]},Nt=ethers.utils._TypedDataEncoder.hash(Mt,Rt,{positionId:kt,actionHash:$t,authorizedSpendsHash:It,ucdDebtHash:Ct,contractBundleHash:Bt,withdrawalAddress:B,totalDeduction:tt.toString(),newCollateral:xt.toString(),quantumTimestamp:Ut.toString(),btcPrice:Dt.toString(),utxoTxid:Tt.txid,utxoVout:Tt.vout,caller:ethers.utils.getAddress(K)});console.log("[Step 5] Contract message hash for signing:",Nt),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(Nt).length),e.stepEnd("5"),O="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const Lt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${Lt}ms`),e.log("6","========================================"),e.log("6","\ud83d\udd0d FINAL HASH INPUTS - ALL LIT NODES MUST MATCH"),e.log("6","========================================"),e.log("6",`Position ID: ${S.positionId}`),e.log("6",`Action Hash: ${$t}`),e.log("6",`Authorized Spends Hash: ${It}`),e.log("6",`UCD Debt Hash: ${Ct}`),e.log("6",`Contract Bundle Hash: ${Bt}`),e.log("6",`Destination Address: ${B}`),e.log("6",`Total Deduction: ${tt.toString()}`),e.log("6",`New Collateral: ${xt.toString()}`),e.log("6",`Quantum Timestamp: ${Ut.toString()}`),e.log("6",`BTC Price: ${Dt.toString()}`),e.log("6",`Selected UTXO Txid: ${Tt.txid}`),e.log("6",`Selected UTXO Vout: ${Tt.vout}`),e.log("6",`Selected UTXO Satoshis: ${Tt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${Tt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${Nt}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${Nt}`),e.log("6",`publicKey: ${k}`),e.log("6","publicKey with 0x prefix: "+("0x"+k));const qt=ethers.utils.arrayify(Nt);e.log("6",`messageBytes length: ${qt.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(qt))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const _t=Date.now(),Ft=globalThis.validatorWalletAddress;if(!Ft||!Ft.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const zt=await Lit.Actions.getPrivateKey({pkpId:Ft}),Xt="string"==typeof zt?zt.startsWith("0x")?zt:`0x${zt}`:String(zt),Vt=new ethers.Wallet(Xt),Ht=new ethers.utils.SigningKey(Xt);e.log("6",`Wallet-derived signer address: ${Vt.address}`),e.log("6",`validatorWalletAddress: ${Ft}`);const Wt=Ht.signDigest(Nt),jt=ethers.utils.joinSignature(Wt),Gt=Date.now()-_t;e.log("6",`Chipotle signature created in ${Gt}ms`),e.log("6",`signature: ${jt}`);const Kt=globalThis.contractAddresses.BTCSpendAuthorizer?.trim()||"";let Qt=null;if(Kt){const t=it(S.positionId),r=A(i),o=xt+tt,n={name:w,version:f,chainId:r,verifyingContract:ethers.utils.getAddress(Kt)},a={BtcSpendAuth:[{name:"positionId",type:"bytes32"},{name:"txid",type:"string"},{name:"vout",type:"uint32"},{name:"satoshis",type:"uint256"},{name:"targetAddress",type:"string"},{name:"targetAmount",type:"uint256"}]},s=ethers.utils._TypedDataEncoder.hash(n,a,{positionId:t,txid:Tt.txid,vout:Tt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:tt.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${s}`),Qt=await Vt._signTypedData(n,a,{positionId:t,txid:Tt.txid,vout:Tt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:tt.toString()}),e.log("6",`btcSpendAuth signature: ${Qt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const Jt={approved:!0,positionId:S.positionId,actionHash:$t,authorizedSpendsHash:It,ucdDebtHash:Ct,contractBundleHash:Bt,totalDeduction:tt.toString(),remainingCollateral:nt.toString(),newCollateralRatioBps:at>0n&&void 0!==ct?Number(ct):void 0,destinationAddress:B,signature:jt,btcSpendAuthSignature:Qt,timestamp:Ut.toString(),btcPrice:Dt.toString(),utxoTxid:Tt.txid,utxoVout:Tt.vout,utxoSatoshis:Tt.satoshis.toString()};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",tt,"type:",typeof tt,"toString():",tt.toString()),console.log(" remainingCollateral:",nt,"type:",typeof nt,"toString():",nt.toString()),console.log(" btcPrice:",Dt,"type:",typeof Dt,"toString():",Dt.toString()),console.log(" timestamp:",Ut,"type:",typeof Ut,"toString():",Ut.toString()),console.log(" Full response object:",JSON.stringify(Jt,null,2)),Jt}catch(t){return console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${O}`),e.error("error",`Failed: ${t.message}`),{approved:!1,reason:t.message||t.toString(),positionId:S?.positionId,timestamp:Date.now()}}var R}return at=i,((i,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))o.call(i,c)||c===a||t(i,c,{get:()=>n[c],enumerable:!(s=e(n,c))||s.enumerable});return i})(t({},"__esModule",{value:!0}),at)})();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();
|
package/dist/btc-withdrawal.hash
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
368f9aea32cf2e660b0f75b88b6ee043cf5956319d7b3c6c695d4b984b3bd555
|