@gvnrdao/dh-lit-actions 0.0.309 → 0.0.310
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a_dev_address-probe-signer.meta.json +1 -1
- package/dist/a_dev_address-probe.meta.json +1 -1
- package/dist/a_dev_always-signer.meta.json +1 -1
- package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
- package/dist/a_dev_authorization-dummy.meta.json +1 -1
- package/dist/a_dev_ethers-version-probe.meta.json +1 -1
- package/dist/a_dev_process-payment-sign-only.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.action.js +1 -1
- package/dist/btc-transaction-signer.hash +1 -1
- package/dist/btc-transaction-signer.meta.json +5 -5
- package/dist/btc-utxo-invalidator.action.js +1 -1
- package/dist/btc-utxo-invalidator.hash +1 -1
- package/dist/btc-utxo-invalidator.meta.json +5 -5
- 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/extend-position-validator.action.js +1 -1
- package/dist/extend-position-validator.hash +1 -1
- package/dist/extend-position-validator.meta.json +5 -5
- package/dist/liquidation-validator.action.js +1 -1
- package/dist/liquidation-validator.hash +1 -1
- package/dist/liquidation-validator.meta.json +5 -5
- package/dist/loan-vault-btc-balance.action.js +1 -1
- package/dist/loan-vault-btc-balance.hash +1 -1
- package/dist/loan-vault-btc-balance.meta.json +5 -5
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-validator.action.js +1 -1
- package/dist/process-payment-validator.hash +1 -1
- package/dist/process-payment-validator.meta.json +5 -5
- package/dist/stale-spend-recovery-validator.action.js +1 -1
- package/dist/stale-spend-recovery-validator.hash +1 -1
- package/dist/stale-spend-recovery-validator.meta.json +5 -5
- 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 +1 -1
- package/pkg-dist/pkg-src/index.js +138 -65
- package/pkg-dist/pkg-src/index.js.map +4 -4
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +7 -0
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +5 -0
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts +23 -2
- package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts +8 -1
- package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts +70 -0
- package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts.map +1 -0
- package/pkg-dist/src/modules/bitcoin-provider-registry.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={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=11e3,n=1000000000000000000n,s=1000000000000n,c=100000000000000n,l=60,u=10,d=8e3;function h(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 p="partial-payment",g="DiamondHands.Protocol",m="1",f=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(f||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},w=["infura.io","drpc.org"],b={ethereum:1,sepolia:11155111,hardhat:1337};function T(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(f).join(", ")}`)}function v(t){return b[t]}function P(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 A(...t){P()&&console.log(...t)}var I=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}},E=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,a=this.TIMEOUT_MS-o;a<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${a}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}},S=class{static create(t="LIT Action",e){return P(e)?new E(t):new I}};function $(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function C(t){return t instanceof Error&&"AbortError"===t.name}var k=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=S.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),A(`[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 a=parseInt(o.trim(),10);if(isNaN(a)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),a}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),C(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${$(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${$(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${$(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,a=void 0!==t.vout?t.vout:t.n,n=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===a||void 0===n)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:o,vout:a,satoshis:BigInt(n),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(),[a,n]=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),A(`[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: ${a}`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const s=await n.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: ${$(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const l=this.parseBlockstreamUTXOs(c,a);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),C(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error($(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${$(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),a=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),n=o-a;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:a,unconfirmedBalance:n}}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),A(`[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 a=await e.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const n=a.chain_stats.funded_txo_sum,s=a.chain_stats.spent_txo_sum;if(void 0===n||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${n}, spent_txo_sum: ${s}`);const c=BigInt(n-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${n} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(o),C(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=$(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=$(t),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),A(`[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 a=await o.json();if(a.status){if(!a.status.confirmed||!a.status.block_height)return{txid:a.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:a.txid??t,confirmations:1};const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)return{txid:a.txid??t,confirmations:1};const n=o-a.status.block_height+1;return{txid:a.txid??t,confirmations:n>0?n:0}}catch{return{txid:a.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),C(t))throw new Error(`Request timeout after ${this.timeout}ms`);if($(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),C(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},M=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,o){if(this.devSingleProvider=!0===o?.devSingleProvider,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!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let o=1;for(const a of e){if(!a||"string"!=typeof a.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=a.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${a.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.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(i.add(e),e){case"cryptocompare":if(!a.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(a.apiKey,o++));break;case"coinmarketcap":if(!a.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(a.apiKey,o++));break;case"coingecko":if(!a.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(a.apiKey,o++));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 i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{const o=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!o.ok)throw new Error(`${t} HTTP ${o.status} ${o.statusText}`);return await o.json()}finally{clearTimeout(o)}}}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:"),i=e?t.slice(4):t,o=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},a=new URL("https://api.coingecko.com/api/v3/simple/price");a.searchParams.set("ids","bitcoin"),a.searchParams.set("vs_currencies","usd");const n=await r(a.toString(),o),s=Number(n?.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 i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),o=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CoinMarketCap price payload");return o},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=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([r,e])].sort(((t,e)=>t-e));let o;if(this.devSingleProvider)o=i[0];else{o=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*o),n=1000000n*BigInt(a),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${o.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${n}`),n}};M.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],M.REQUIRED_PROVIDER_COUNT=3;var B=M;async function x(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}function D(t){return Math.floor(t/l)*l}async function U(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-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: ${D(Math.floor(Date.now()/1e3))}`)}var O=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),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const o=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await o.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const o=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),a=await o.positionDelegate(t);return!(!a||a===ethers.constants.AddressZero)&&a.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const o=Math.floor(Date.now()/1e3);await U();const a=i?.strictCurrentQuantum?o:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),o=D(i),a=D(t);if(r?.strictCurrentQuantum){if(a!==o)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${a}, current quantum: ${o}`);return}const n=o-l,s=o+l;if(a!==n&&a!==o&&a!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${a}, Valid range: [${n} (past), ${o} (current), ${s} (next)]`);if(a===n){if(i<n+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${n}). This is unsafe due to boundary instability.`)}else if(a===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,a,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const n=e(),s=await this.recoverSigner(n,t.signature);return await r(s,n,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,o,a){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,n,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,n,s,o))return!0;if(a)return t.checkPositionDelegate(e.positionId,i,a,o)}return!1}))}static async verifyMintAuthorization(t,e,r,i,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,o)}static async verifyPaymentAuthorization(t,e,r,i,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,o)}static async verifyWithdrawAuthorization(e,r,i,o,a){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,n,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,n,s,o))return!0;if(a)return t.checkPositionDelegate(e.positionId,i,a,o)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,o,a){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,n,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,n,s,o))return!0;if(a)return t.checkPositionDelegate(e.positionId,i,a,o)}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,i,o,a){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,n,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,n,s,o))return!0;if(a)return t.checkPositionDelegate(e.positionId,i,a,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,o)}static async verifyBtcExecutionAuthorization(e,r,i,o,a){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[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"],i)}),(async(i,n,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,n,s,o))return!0;if(a)return t.checkPositionDelegate(e.positionId,i,a,o)}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 R(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,i=Math.floor(Date.now()/1e3)-t,o=Math.floor(i/86400);return{termDurationDays:o,termLengthDays:r,isExpired:o>r,daysUntilExpiry:Math.max(0,r-o),daysIntoGracePeriod:Math.max(0,o-r)}}function N(t,e,r,i){if(!t)return r;const o=i??a,n=Math.min(e,30);return a+n*n*(o-a)/900}function q(t,e,r){const i=t*e/10000000000000000n;if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*n*10000n/r)}}var L=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:d},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),o=await i.liquidationThreshold();return Number(o.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:d},{name:"any",chainId:this.chainId}),i=[{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"}],o=new ethers.Contract(this.termManagerAddress,i,r),a=await o.getTermFees(t);return{originationFeeBps:Number(a.originationFee?.toString?.()??a[0]?.toString?.()??a[0]),extensionFeeBps:Number(a.extensionFee?.toString?.()??a[1]?.toString?.()??a[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:d},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,o=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await o.getAuthorizedSpendsHash(i)}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:d},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),o=await i.maxEscalatedThreshold();return Number(o.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 _(t){return new L(t)}var F=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,[i,o]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),a=_({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}),n=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([a.getLiquidationThreshold(),a.getMaxEscalatedThreshold(),a.getTermFees(n)]),u=R(e.termStartTimestamp,e.selectedTerm),d=N(u.isExpired,u.daysIntoGracePeriod,s,c),h=q(i.availableBalance,o,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:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:o,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,[i,o]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),a=_({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}),n=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([a.getLiquidationThreshold(),a.getMaxEscalatedThreshold(),a.getTermFees(n)]),u=R(e.termStartTimestamp,e.selectedTerm),d=N(u.isExpired,u.daysIntoGracePeriod,s,c),h=q(i.availableBalance,o,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:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:o,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 i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:d},this.config.chainId),o=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),a=await o.core(),n=new ethers.Contract(a,[{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"}],i),s=await n.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),h=Number(s.totalTerm),p=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),m=(y=u,0===(f=l)?0:f-30*y*86400);var f,y;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,T(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:p,totalTerm:h,lastRenewedAt:g}}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 y[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 i=await this.getVaultSnapshot(t);return function(t,e,r,i){const o=e+r;return 0n===o||Number(t*n*10000n/o)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var z=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),i=await this.getAuthorizedSpendsFromContract(t),o=i.reduce(((t,e)=>t+e.satoshis),0n),a=r>o?r-o:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:o,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:a,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const i=this.config.minConfirmations||6,o=await this.bitcoinProvider.getUTXOSet(e,i),a=await this.getAuthorizedSpendsFromContract(t);for(const t of a){if(o.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 n=a.reduce(((t,e)=>t+e.satoshis),0n),s=o.utxos.filter((t=>!this.isUTXOAuthorized(t,a))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,a);return{totalUTXOs:o.utxos,totalBalance:o.totalBalance,authorizedUTXOs:a,authorizedBalance:n,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,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}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 i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:d},this.config.chainId),o=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"}],i);return(await o.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 i=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,i]))}};var V="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))",X={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 H(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 j=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),G=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)"]),K=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function J(t,e,r){return t.call({to:e,data:r})}async function Q(t,e){const r=new ethers.utils.Interface([V]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([V]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?H({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]}):H(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await J(t,e,j.encodeFunctionData("views",[])),[i]=j.decodeFunctionResult("views",r),[o,a,n,s,c,l,u,d]=await Promise.all([J(t,e,j.encodeFunctionData("paused",[])),J(t,e,j.encodeFunctionData("liquidationPaused",[])),J(t,e,j.encodeFunctionData("simplePsm",[])),J(t,i,G.encodeFunctionData("core",[])),J(t,i,G.encodeFunctionData("loanOps",[])),J(t,i,G.encodeFunctionData("collateralManager",[])),J(t,i,G.encodeFunctionData("liquidationManager",[])),J(t,i,G.encodeFunctionData("circuitBreaker",[]))]),h=j.decodeFunctionResult("paused",o)[0],p=j.decodeFunctionResult("liquidationPaused",a)[0],g=j.decodeFunctionResult("simplePsm",n)[0],m=G.decodeFunctionResult("core",s)[0],f=G.decodeFunctionResult("loanOps",c)[0],y=G.decodeFunctionResult("collateralManager",l)[0],w=G.decodeFunctionResult("liquidationManager",u)[0],b=G.decodeFunctionResult("circuitBreaker",d)[0],T=await J(t,f,K.encodeFunctionData("getUcdController",[])),v=await J(t,f,K.encodeFunctionData("ucdToken",[])),P=K.decodeFunctionResult("getUcdController",T)[0],A=K.decodeFunctionResult("ucdToken",v)[0],I=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await J(t,e,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,S,$,C,k,M,B,x]=await Promise.all([I(m),I(f),I(y),I(w),I(b),I(P),I(A),I(g)]);return H({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:S,collateralManagerPaused:$,liquidationManagerPaused:C,circuitBreakerPaused:k,ucdControllerPaused:M,ucdTokenPaused:B,simplePsmPaused:x})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}function Z(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 Y={hardhat:{chain:"hardhat",chainId:b.hardhat,bitcoinNetwork:y.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:b.sepolia,bitcoinNetwork:y.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:b.ethereum,bitcoinNetwork:y.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var tt,et=[{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"}],rt=[{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 it(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 ot(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,et,e),[o,a]=await i.getProviders(t),n=[];for(let t=0;t<o.length;t++)n.push({providerId:o[t],ciphertext:a[t].ciphertext,pkpId:a[t].pkpId,addedAt:Number(a[t].addedAt)});return n}(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 a=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),n=new ethers.Contract(i,rt,r);let s;try{s=await n.isAllowedCid(e,a)}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=${a.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 it(e.ciphertext,e.pkpId);o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return o}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=S.create("Process Payment Validator");e.log("0","========================================");let r,i,o,a,n,d;e.log("0","Payment Validator v1.0.2 (deployed: 2026-01-23T23:45:00Z)"),e.log("0","DEBUG: Received globalThis parameters:"),e.log("0","globalThis.contractAddresses:",JSON.stringify(globalThis.contractAddresses)),e.log("0","globalThis.positionId:",globalThis.positionId),e.log("0","globalThis.paymentAmount:",globalThis.paymentAmount),e.log("0","globalThis.priceProviders:",JSON.stringify(globalThis.priceProviders)),e.log("0","globalThis.priceProviders type:",typeof globalThis.priceProviders),e.log("0","globalThis.priceProviders isArray:",Array.isArray(globalThis.priceProviders)),e.log("0","All globalThis keys:",Object.keys(globalThis).filter((t=>!t.startsWith("_")&&"console"!==t&&"require"!==t&&"module"!==t&&"exports"!==t&&"process"!==t&&"Buffer"!==t&&"setTimeout"!==t&&"clearTimeout"!==t&&"setInterval"!==t&&"clearInterval"!==t))),e.log("0","========================================");try{e.log("0a","Validating configuration...");const t=globalThis.chain,y=globalThis.positionId,P=globalThis.paymentAmount;if(!t)throw new Error('Missing required parameter: "chain"');if(!y)throw new Error('Missing required parameter: "positionId"');if(!P)throw new Error('Missing required parameter: "paymentAmount"');const I=BigInt(P);if(I<=0n)throw new Error(`Payment amount must be positive, got: ${I.toString()} wei`);const E=function(t){const e=T(t),r=Y[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),S=E.chain,$=E.bitcoinNetwork;let C=[];A(` \u2705 Chain: ${t} (${S})`),A(` \u2705 Bitcoin Network: ${$}`),e.log("0",` \u2705 Payment Amount: ${I.toString()} wei`),e.log("0c","Loading contract addresses...");const M=globalThis.contractAddresses;if(!M||"object"!=typeof M)throw new Error("contractAddresses is required (PositionManager, LoanOperationsManagerModule, LiquidationManager...).");if(i=M.PositionManager,o=M.LoanOperationsManagerModule,a=M.LiquidationManagerModule??M.LiquidationManager??"",n=M.BTCSpendAuthorizer||o,!i||!o||!a)throw new Error("Missing required contract addresses in contractAddresses object");if(!E.allowArbitraryBitcoinProvider&&!M?.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.log("0"," \u2705 Contract addresses loaded from parameters"),e.log("0d","Initializing modules...");const U=globalThis.rpcUrl,R=v(S);let N;U&&"string"==typeof U?(N=U,e.log("0",` Using RPC URL override: ${N}`)):(N=await Lit.Actions.getRpcUrl({chain:t}),e.log("0",` Using LIT-provided RPC URL for chain: ${t}`));const q="hardhat"===t?{chainId:b.hardhat,name:"hardhat"}:"sepolia"===t?{chainId:b.sepolia,name:"sepolia"}:{chainId:R,name:t};e.log("0",` Using StaticJsonRpcProvider for ${t} to skip network detection`),e.log("0"," Network config:",q),r=new ethers.providers.StaticJsonRpcProvider(N,q);!function(t,e){const r=X[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("processPayment",await Q(r,i)),e.log("0","[DEBUG] Before PriceOracleModule init:"),e.log("0"," globalThis.priceProviders:",JSON.stringify(globalThis.priceProviders)),e.log("0"," typeof globalThis.priceProviders:",typeof globalThis.priceProviders),e.log("0"," Array.isArray(globalThis.priceProviders):",Array.isArray(globalThis.priceProviders));const L=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,o;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await x(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(o=await x(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,o=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:o})}var r;return e}(globalThis.priceProviders),_=!0===globalThis.devPriceMode;if(_&&!E.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${E.chain}`);const V=new B(L,void 0,void 0,{devSingleProvider:_&&E.allowDevSinglePriceProvider});N&&"string"==typeof N&&!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(!w.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${w.join(", ")}`)}(E,N),C=E.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:globalThis.devBitcoinProviderUrl,minConfirmations:E.minBitcoinConfirmations,network:E.bitcoinNetwork}]:await ot(E,r,globalThis.contractAddresses.BitcoinProviderRegistry);const H=C[0];A(` \u2705 Bitcoin Providers: ${C.length} (${C.map((t=>t.name)).join(", ")})`),e.log("0","[DEBUG] After PriceOracleModule init:"),e.log("0"," PriceOracleModule sources count:",V.sources?.length||0),e.log("0"," PriceOracleModule first source:",V.sources?.[0]?.name||"none");const j=new k({providerUrl:H.url}),G=(f={contractAddress:n,chain:t,chainId:R,rpcUrl:N,bitcoinProvider:j,minConfirmations:H.minConfirmations},new z(f));if(!globalThis.authMessage||!globalThis.userSignature)throw new Error("Missing authorization parameters: authMessage and userSignature are required");const K=Z(y);if(K!==Z(globalThis.authMessage.positionId))throw new Error("positionId must match authMessage.positionId (canonical bytes32: 0x + 64 hex, case-insensitive, short forms padded)");d=K,e.log("1","Getting vault snapshot...");const W=function(t){return new F(t)}({contractAddress:i,termManagerAddress:globalThis.contractAddresses?.TermManagerModule||i,loanOpsManagerAddress:o,liquidationManagerAddress:a,chain:t,chainId:R,rpcUrl:N,vaultBalance:G,priceOracle:V}),J=await W.getVaultSnapshot(d);if(C.length>1){const t=await j.getBalance(J.vaultAddress);for(let e=1;e<C.length;e++){const r=C[e],i=new k({providerUrl:r.url}),o=await i.getBalance(J.vaultAddress);if(o!==t)throw new Error(`Bitcoin provider balance mismatch: ${H.name}=${t.toString()} vs ${r.name}=${o.toString()}`)}e.log("1",` \u2705 Consensus reached across ${C.length} providers (${t.toString()} sats)`)}const tt=J.btcPriceUsd;if(tt<s||tt>c)throw new Error(`Bitcoin price ${tt} is outside acceptable range (${s} - ${c}). This may indicate oracle manipulation or stale price data. Please try again later.`);e.log("0",` \u2705 BTC price validation passed: $${(Number(tt)/1e8).toFixed(2)}`),e.log("0"," \u2705 Vault snapshot retrieved"),e.log("0",` - Position status: ${h(J.status)}`),e.log("0",` - Total debt: ${J.ucdDebt.toString()} wei`),e.log("1.5","Authenticating caller authorization...");if(!await O.verifyPaymentAuthorization({positionId:globalThis.authMessage.positionId,timestamp:globalThis.authMessage.timestamp,chainId:globalThis.authMessage.chainId,amount:globalThis.authMessage.paymentAmount,action:globalThis.authMessage.action,signature:globalThis.userSignature},J.borrower,R,r,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized to make payment on this position");e.log("0"," \u2705 Caller authorization validated"),O.assertPaymentAmountMatchesAuth(I,globalThis.authMessage.paymentAmount),e.log("2","Validating position state...");const et=h(J.status);if(!["PENDING_MINT","ACTIVE","EXPIRED","LIQUIDATABLE"].includes(et))throw new Error(`Invalid position status for payment: ${et}. Must be PENDING_MINT, ACTIVE, EXPIRED, or LIQUIDATABLE.`);e.log("0",` \u2705 Position status valid for payment: ${et}`),e.log("3","Validating payment amount...");const rt=BigInt(J.ucdDebt.toString());if(I>rt)throw new Error(`Payment amount ${I.toString()} wei exceeds total debt ${rt.toString()} wei. Payment amount must be less than or equal to total debt.`);e.log("0",` \u2705 Payment amount valid: ${I.toString()} wei`),e.log("0",` - Total debt: ${rt.toString()} wei`),e.log("0","[Step 3.25] Circuit breaker check..."),e.log("0"," \u26a0\ufe0f Circuit breaker validation deferred to contract (state-changing function)"),e.log("0"," \u2705 Payment amount within bounds for circuit breaker check"),e.log("0","[Step 3.5] UCD validation skipped (pre-validated by SDK \u2014 accepted, contract-backstopped risk)"),e.log("4","Collateral ratio validation skipped for repayment (handled off-chain / by business rules)"),e.log("5","Building authorization message...");const it=globalThis.quantumTimestamp,at=Number(globalThis.authMessage.timestamp),nt=D(at>1e11?Math.floor(at/1e3):at),st=3;if(null!=it){const t=D(Number(it)),e=Math.abs(t-nt)/l;if(!Number.isFinite(e)||e>st)throw new Error("quantumTimestamp is not bound to the authorization timestamp (outside the allowed quantum-window horizon) \u2014 refusing to sign (replay protection)")}const ct=it?Number(it):nt+u;e.log("5",`Using quantum timestamp: ${ct} ${it?"(from authorization)":"(generated)"}`);const lt=v(S),ut={name:g,version:m,chainId:lt,verifyingContract:ethers.utils.getAddress(o)},dt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(p)),ht={PartialPayment:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"paymentAmount",type:"uint256"},{name:"borrower",type:"address"}]},pt=ethers.utils._TypedDataEncoder.hash(ut,ht,{actionTag:dt,positionId:d,quantumTimestamp:ct,btcPrice:tt.toString(),paymentAmount:I.toString(),borrower:ethers.utils.getAddress(J.borrower)}),gt=globalThis.publicKey;if(!gt)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof gt||0===gt.length)throw new Error("Invalid publicKey: expected non-empty string, got "+typeof gt);const mt=gt;e.log("0",`[Step 6] PublicKey length: ${mt.length}, starts with: ${mt.substring(0,10)}...`),e.log("6","Signing authorization..."),e.log("0",` Message hash: ${pt}`),e.log("0",` Message hash bytes length: ${ethers.utils.arrayify(pt).length}`),e.log("0",` Public key: ${mt.substring(0,20)}...`),e.log("0",` Public key length: ${mt.length}`),e.log("0","======= PKP AUTHORIZATION DIAGNOSTICS ======="),e.log("0","globalThis.publicKey:",mt?`${mt.substring(0,20)}...`:"MISSING"),e.log("0","globalThis.publicKey length:",mt?.length||0),e.log("0","globalThis.publicKey has 0x prefix:",mt?.startsWith("0x")||!1);const ft=globalThis.pkpTokenId;e.log("0","globalThis.pkpTokenId:",ft||"NOT SET"),ft&&(e.log("0","globalThis.pkpTokenId type:",typeof ft),e.log("0","globalThis.pkpTokenId value:",ft),e.log("0","NOTE: pkpTokenId is used for session signature scoping in LitOps, not as a signEcdsa parameter."));const yt=globalThis.positionId;e.log("0","globalThis.positionId:",yt||"NOT SET");const wt=globalThis.ipfsId;e.log("0","globalThis.ipfsId:",wt||"NOT SET");const bt=ethers.utils.arrayify("0x"+mt),Tt=ethers.utils.computeAddress(bt);e.log("0","Computed ETH Address from publicKey:",Tt),e.log("0","Message hash to sign:",pt),e.log("0","Signature name: paymentAuth"),e.log("0","=============================================");const vt=globalThis.pkpTokenId;let Pt;try{"pkpTokenId"in globalThis&&delete globalThis.pkpTokenId;const t=globalThis.validatorWalletAddress;if(!t||!t.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const e=await Lit.Actions.getPrivateKey({pkpId:t}),r="string"==typeof e?e.startsWith("0x")?e:`0x${e}`:String(e),i=new ethers.Wallet(r);Pt=await i._signTypedData(ut,ht,{actionTag:dt,positionId:d,quantumTimestamp:ct,btcPrice:tt.toString(),paymentAmount:I.toString(),borrower:ethers.utils.getAddress(J.borrower)})}finally{void 0!==vt&&(globalThis.pkpTokenId=vt)}return e.log("0"," \u2705 Signature obtained: "+(Pt?"present":"missing")),e.log("0","\u2705 Complete"),{approved:!0,positionId:d,paymentAmount:I.toString(),btcPrice:tt.toString(),messageHash:pt,signature:Pt,timestamp:ct,validatorPkp:mt}}catch(t){throw console.error("[Process Payment Validator] Failed:",t.message),t}var f}return tt=o,((o,a,n,s)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of r(a))i.call(o,c)||c===n||t(o,c,{get:()=>a[c],enumerable:!(s=e(a,c))||s.enumerable});return o})(t({},"__esModule",{value:!0}),tt)})();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={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var n=11e3,a=1000000000000000000n,s=1000000000000n,c=100000000000000n,l=60,u=10,d=8e3;function h(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 p="partial-payment",g="DiamondHands.Protocol",m="1",w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),f={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org"],b={ethereum:1,sepolia:11155111,hardhat:1337};function T(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(w).join(", ")}`)}function v(t){return b[t]}function P(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 A(...t){P()&&console.log(...t)}var I=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}},E=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}},S=class{static create(t="LIT Action",e){return P(e)?new E(t):new I}};function $(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function k(t){return t instanceof Error&&"AbortError"===t.name}function C(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function B(t){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const e=t.trim();if(!e.startsWith("{"))return{url:e,auth:{provider:"esplora"}};let r;try{r=JSON.parse(e)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof r.url||0===r.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=r.url.trim();switch(r.provider){case void 0:case"esplora":return{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof r.apiKey||0===r.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return C(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:r.apiKey}};case"blockstream-enterprise":{if("string"!=typeof r.clientId||0===r.clientId.length||"string"!=typeof r.clientSecret||0===r.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");C(i,"blockstream-enterprise provider url");const t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&C(r.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:r.clientId,clientSecret:r.clientSecret,...t?{tokenUrl:r.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(r.provider)}"`)}}var x=new Map;async function M(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,o=x.get(i);if(o)return o;const n=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,n=setTimeout((()=>o.abort()),e&&e>0?e:1e4);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:o.signal})}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>x.delete(i))),x.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}var U=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=S.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await M(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),A(`[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"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${$(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${$(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${$(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,a=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===n||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:o,vout:n,satoshis:BigInt(a),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(o),A(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const 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: ${$(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(o),this.logger.stepEnd("1"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error($(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${$(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),a=o-n;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),A(`[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(o),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=$(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=$(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),A(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const n=await o.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:n.txid??t,confirmations:1};const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)return{txid:n.txid??t,confirmations:1};const a=o-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),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);if($(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function D(t,e,r,i){return e.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null):async function(t,e,r,i){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");const o=i??(t=>new U({providerUrl:t.url,auth:t.auth,...r?{timeout:r}:{}})),n=await Promise.allSettled(e.map((e=>o(e).getBalance(t)))),a=n.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const s=n.map((t=>t.value)),c=s[0],l=s.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==c)).map((t=>`${e[0].name}=${c.toString()} vs ${t.name}=${t.bal.toString()}`));if(l.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${l.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${c.toString()} sats)`);return c}(t,e,r,i)}var O=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,o){if(this.devSingleProvider=!0===o?.devSingleProvider,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!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let o=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(i.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(i.add(e),e){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,o++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,o++));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,o++));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 i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{const o=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!o.ok)throw new Error(`${t} HTTP ${o.status} ${o.statusText}`);return await o.json()}finally{clearTimeout(o)}}}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:"),i=e?t.slice(4):t,o=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},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(),o),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 i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),o=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CoinMarketCap price payload");return o},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=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([r,e])].sort(((t,e)=>t-e));let o;if(this.devSingleProvider)o=i[0];else{o=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 n=Math.round(100*o),a=1000000n*BigInt(n),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${o.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};O.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],O.REQUIRED_PROVIDER_COUNT=3;var R=O;async function N(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}function q(t){return Math.floor(t/l)*l}async function L(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-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: ${q(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),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const o=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await o.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const o=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),n=await o.positionDelegate(t);return!(!n||n===ethers.constants.AddressZero)&&n.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const o=Math.floor(Date.now()/1e3);await L();const n=i?.strictCurrentQuantum?o:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),o=q(i),n=q(t);if(r?.strictCurrentQuantum){if(n!==o)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${n}, current quantum: ${o}`);return}const a=o-l,s=o+l;if(n!==a&&n!==o&&n!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${a} (past), ${o} (current), ${s} (next)]`);if(n===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(n===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===i?.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,i,o,n){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(n)return t.checkPositionDelegate(e.positionId,i,n,o)}return!1}))}static async verifyMintAuthorization(t,e,r,i,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,o)}static async verifyPaymentAuthorization(t,e,r,i,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,o)}static async verifyWithdrawAuthorization(e,r,i,o,n){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(n)return t.checkPositionDelegate(e.positionId,i,n,o)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,o,n){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(n)return t.checkPositionDelegate(e.positionId,i,n,o)}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,i,o,n){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(n)return t.checkPositionDelegate(e.positionId,i,n,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,o)}static async verifyBtcExecutionAuthorization(e,r,i,o,n){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[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"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(n)return t.checkPositionDelegate(e.positionId,i,n,o)}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 F(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,i=Math.floor(Date.now()/1e3)-t,o=Math.floor(i/86400);return{termDurationDays:o,termLengthDays:r,isExpired:o>r,daysUntilExpiry:Math.max(0,r-o),daysIntoGracePeriod:Math.max(0,o-r)}}function z(t,e,r,i){if(!t)return r;const o=i??n,a=Math.min(e,30);return n+a*a*(o-n)/900}function V(t,e,r){const i=t*e/10000000000000000n;if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*a*10000n/r)}}var X=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:d},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),o=await i.liquidationThreshold();return Number(o.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:d},{name:"any",chainId:this.chainId}),i=[{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"}],o=new ethers.Contract(this.termManagerAddress,i,r),n=await o.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:d},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,o=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await o.getAuthorizedSpendsHash(i)}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:d},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),o=await i.maxEscalatedThreshold();return Number(o.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 H(t){return new X(t)}var j=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,[i,o]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=H({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=F(e.termStartTimestamp,e.selectedTerm),d=z(u.isExpired,u.daysIntoGracePeriod,s,c),h=V(i.availableBalance,o,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:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:o,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,[i,o]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),n=H({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=F(e.termStartTimestamp,e.selectedTerm),d=z(u.isExpired,u.daysIntoGracePeriod,s,c),h=V(i.availableBalance,o,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:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:o,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 i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:d},this.config.chainId),o=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),n=await o.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"}],i),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),h=Number(s.totalTerm),p=Number(s.previousExpiryAt),g=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,T(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:p,totalTerm:h,lastRenewedAt:g}}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 f[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 i=await this.getVaultSnapshot(t);return function(t,e,r,i){const o=e+r;return 0n===o||Number(t*a*10000n/o)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var K=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),i=await this.getAuthorizedSpendsFromContract(t),o=i.reduce(((t,e)=>t+e.satoshis),0n),n=r>o?r-o:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:o,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:n,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const i=this.config.minConfirmations||6,o=await this.bitcoinProvider.getUTXOSet(e,i),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(o.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=o.utxos.filter((t=>!this.isUTXOAuthorized(t,n))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:o.utxos,totalBalance:o.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,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}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 i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:d},this.config.chainId),o=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"}],i);return(await o.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 i=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,i]))}};var G="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))",W={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 Q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Z=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)"]),Y=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),tt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function et(t,e,r){return t.call({to:e,data:r})}async function rt(t,e){const r=new ethers.utils.Interface([G]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([G]).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){i=t}try{return await async function(t,e){const r=await et(t,e,Q.encodeFunctionData("views",[])),[i]=Q.decodeFunctionResult("views",r),[o,n,a,s,c,l,u,d]=await Promise.all([et(t,e,Q.encodeFunctionData("paused",[])),et(t,e,Q.encodeFunctionData("liquidationPaused",[])),et(t,e,Q.encodeFunctionData("simplePsm",[])),et(t,i,Z.encodeFunctionData("core",[])),et(t,i,Z.encodeFunctionData("loanOps",[])),et(t,i,Z.encodeFunctionData("collateralManager",[])),et(t,i,Z.encodeFunctionData("liquidationManager",[])),et(t,i,Z.encodeFunctionData("circuitBreaker",[]))]),h=Q.decodeFunctionResult("paused",o)[0],p=Q.decodeFunctionResult("liquidationPaused",n)[0],g=Q.decodeFunctionResult("simplePsm",a)[0],m=Z.decodeFunctionResult("core",s)[0],w=Z.decodeFunctionResult("loanOps",c)[0],f=Z.decodeFunctionResult("collateralManager",l)[0],y=Z.decodeFunctionResult("liquidationManager",u)[0],b=Z.decodeFunctionResult("circuitBreaker",d)[0],T=await et(t,w,Y.encodeFunctionData("getUcdController",[])),v=await et(t,w,Y.encodeFunctionData("ucdToken",[])),P=Y.decodeFunctionResult("getUcdController",T)[0],A=Y.decodeFunctionResult("ucdToken",v)[0],I=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await et(t,e,tt.encodeFunctionData("paused",[]));return tt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,S,$,k,C,B,x,M]=await Promise.all([I(m),I(w),I(f),I(y),I(b),I(P),I(A),I(g)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:S,collateralManagerPaused:$,liquidationManagerPaused:k,circuitBreakerPaused:C,ucdControllerPaused:B,ucdTokenPaused:x,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),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 ot={hardhat:{chain:"hardhat",chainId:b.hardhat,bitcoinNetwork:f.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:b.sepolia,bitcoinNetwork:f.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:b.ethereum,bitcoinNetwork:f.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var nt,at=[{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"}],st=[{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 ct(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 lt(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,at,e),[o,n]=await i.getProviders(t),a=[];for(let t=0;t<o.length;t++)a.push({providerId:o[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return a}(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)),a=new ethers.Contract(i,st,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 o=[];for(const e of i){const r=await ct(e.ciphertext,e.pkpId),{url:i,auth:n}=B(r);o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return o}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=S.create("Process Payment Validator");e.log("0","========================================");let r,i,o,n,a,d;e.log("0","Payment Validator v1.0.2 (deployed: 2026-01-23T23:45:00Z)"),e.log("0","DEBUG: Received globalThis parameters:"),e.log("0","globalThis.contractAddresses:",JSON.stringify(globalThis.contractAddresses)),e.log("0","globalThis.positionId:",globalThis.positionId),e.log("0","globalThis.paymentAmount:",globalThis.paymentAmount),e.log("0","globalThis.priceProviders:",JSON.stringify(globalThis.priceProviders)),e.log("0","globalThis.priceProviders type:",typeof globalThis.priceProviders),e.log("0","globalThis.priceProviders isArray:",Array.isArray(globalThis.priceProviders)),e.log("0","All globalThis keys:",Object.keys(globalThis).filter((t=>!t.startsWith("_")&&"console"!==t&&"require"!==t&&"module"!==t&&"exports"!==t&&"process"!==t&&"Buffer"!==t&&"setTimeout"!==t&&"clearTimeout"!==t&&"setInterval"!==t&&"clearInterval"!==t))),e.log("0","========================================");try{e.log("0a","Validating configuration...");const t=globalThis.chain,f=globalThis.positionId,P=globalThis.paymentAmount;if(!t)throw new Error('Missing required parameter: "chain"');if(!f)throw new Error('Missing required parameter: "positionId"');if(!P)throw new Error('Missing required parameter: "paymentAmount"');const I=BigInt(P);if(I<=0n)throw new Error(`Payment amount must be positive, got: ${I.toString()} wei`);const E=function(t){const e=T(t),r=ot[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),S=E.chain,$=E.bitcoinNetwork;let k=[];A(` \u2705 Chain: ${t} (${S})`),A(` \u2705 Bitcoin Network: ${$}`),e.log("0",` \u2705 Payment Amount: ${I.toString()} wei`),e.log("0c","Loading contract addresses...");const C=globalThis.contractAddresses;if(!C||"object"!=typeof C)throw new Error("contractAddresses is required (PositionManager, LoanOperationsManagerModule, LiquidationManager...).");if(i=C.PositionManager,o=C.LoanOperationsManagerModule,n=C.LiquidationManagerModule??C.LiquidationManager??"",a=C.BTCSpendAuthorizer||o,!i||!o||!n)throw new Error("Missing required contract addresses in contractAddresses object");if(!E.allowArbitraryBitcoinProvider&&!C?.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.log("0"," \u2705 Contract addresses loaded from parameters"),e.log("0d","Initializing modules...");const B=globalThis.rpcUrl,x=v(S);let M;B&&"string"==typeof B?(M=B,e.log("0",` Using RPC URL override: ${M}`)):(M=await Lit.Actions.getRpcUrl({chain:t}),e.log("0",` Using LIT-provided RPC URL for chain: ${t}`));const O="hardhat"===t?{chainId:b.hardhat,name:"hardhat"}:"sepolia"===t?{chainId:b.sepolia,name:"sepolia"}:{chainId:x,name:t};e.log("0",` Using StaticJsonRpcProvider for ${t} to skip network detection`),e.log("0"," Network config:",O),r=new ethers.providers.StaticJsonRpcProvider(M,O);!function(t,e){const r=W[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("processPayment",await rt(r,i)),e.log("0","[DEBUG] Before PriceOracleModule init:"),e.log("0"," globalThis.priceProviders:",JSON.stringify(globalThis.priceProviders)),e.log("0"," typeof globalThis.priceProviders:",typeof globalThis.priceProviders),e.log("0"," Array.isArray(globalThis.priceProviders):",Array.isArray(globalThis.priceProviders));const L=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,o;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await N(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(o=await N(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,o=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:o})}var r;return e}(globalThis.priceProviders),F=!0===globalThis.devPriceMode;if(F&&!E.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${E.chain}`);const z=new R(L,void 0,void 0,{devSingleProvider:F&&E.allowDevSinglePriceProvider});M&&"string"==typeof M&&!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(!y.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${y.join(", ")}`)}(E,M),k=E.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:globalThis.devBitcoinProviderUrl,minConfirmations:E.minBitcoinConfirmations,network:E.bitcoinNetwork}]:await lt(E,r,globalThis.contractAddresses.BitcoinProviderRegistry);const V=k[0];A(` \u2705 Bitcoin Providers: ${k.length} (${k.map((t=>t.name)).join(", ")})`),e.log("0","[DEBUG] After PriceOracleModule init:"),e.log("0"," PriceOracleModule sources count:",z.sources?.length||0),e.log("0"," PriceOracleModule first source:",z.sources?.[0]?.name||"none");const X=new U({providerUrl:V.url,auth:V.auth}),H=(w={contractAddress:a,chain:t,chainId:x,rpcUrl:M,bitcoinProvider:X,minConfirmations:V.minConfirmations},new K(w));if(!globalThis.authMessage||!globalThis.userSignature)throw new Error("Missing authorization parameters: authMessage and userSignature are required");const G=it(f);if(G!==it(globalThis.authMessage.positionId))throw new Error("positionId must match authMessage.positionId (canonical bytes32: 0x + 64 hex, case-insensitive, short forms padded)");d=G,e.log("1","Getting vault snapshot...");const J=function(t){return new j(t)}({contractAddress:i,termManagerAddress:globalThis.contractAddresses?.TermManagerModule||i,loanOpsManagerAddress:o,liquidationManagerAddress:n,chain:t,chainId:x,rpcUrl:M,vaultBalance:H,priceOracle:z}),Q=await J.getVaultSnapshot(d);await D(Q.vaultAddress,k);const Z=Q.btcPriceUsd;if(Z<s||Z>c)throw new Error(`Bitcoin price ${Z} is outside acceptable range (${s} - ${c}). This may indicate oracle manipulation or stale price data. Please try again later.`);e.log("0",` \u2705 BTC price validation passed: $${(Number(Z)/1e8).toFixed(2)}`),e.log("0"," \u2705 Vault snapshot retrieved"),e.log("0",` - Position status: ${h(Q.status)}`),e.log("0",` - Total debt: ${Q.ucdDebt.toString()} wei`),e.log("1.5","Authenticating caller authorization...");if(!await _.verifyPaymentAuthorization({positionId:globalThis.authMessage.positionId,timestamp:globalThis.authMessage.timestamp,chainId:globalThis.authMessage.chainId,amount:globalThis.authMessage.paymentAmount,action:globalThis.authMessage.action,signature:globalThis.userSignature},Q.borrower,x,r,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized to make payment on this position");e.log("0"," \u2705 Caller authorization validated"),_.assertPaymentAmountMatchesAuth(I,globalThis.authMessage.paymentAmount),e.log("2","Validating position state...");const Y=h(Q.status);if(!["PENDING_MINT","ACTIVE","EXPIRED","LIQUIDATABLE"].includes(Y))throw new Error(`Invalid position status for payment: ${Y}. Must be PENDING_MINT, ACTIVE, EXPIRED, or LIQUIDATABLE.`);e.log("0",` \u2705 Position status valid for payment: ${Y}`),e.log("3","Validating payment amount...");const tt=BigInt(Q.ucdDebt.toString());if(I>tt)throw new Error(`Payment amount ${I.toString()} wei exceeds total debt ${tt.toString()} wei. Payment amount must be less than or equal to total debt.`);e.log("0",` \u2705 Payment amount valid: ${I.toString()} wei`),e.log("0",` - Total debt: ${tt.toString()} wei`),e.log("0","[Step 3.25] Circuit breaker check..."),e.log("0"," \u26a0\ufe0f Circuit breaker validation deferred to contract (state-changing function)"),e.log("0"," \u2705 Payment amount within bounds for circuit breaker check"),e.log("0","[Step 3.5] UCD validation skipped (pre-validated by SDK \u2014 accepted, contract-backstopped risk)"),e.log("4","Collateral ratio validation skipped for repayment (handled off-chain / by business rules)"),e.log("5","Building authorization message...");const et=globalThis.quantumTimestamp,nt=Number(globalThis.authMessage.timestamp),at=q(nt>1e11?Math.floor(nt/1e3):nt),st=3;if(null!=et){const t=q(Number(et)),e=Math.abs(t-at)/l;if(!Number.isFinite(e)||e>st)throw new Error("quantumTimestamp is not bound to the authorization timestamp (outside the allowed quantum-window horizon) \u2014 refusing to sign (replay protection)")}const ct=et?Number(et):at+u;e.log("5",`Using quantum timestamp: ${ct} ${et?"(from authorization)":"(generated)"}`);const ut=v(S),dt={name:g,version:m,chainId:ut,verifyingContract:ethers.utils.getAddress(o)},ht=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(p)),pt={PartialPayment:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"paymentAmount",type:"uint256"},{name:"borrower",type:"address"}]},gt=ethers.utils._TypedDataEncoder.hash(dt,pt,{actionTag:ht,positionId:d,quantumTimestamp:ct,btcPrice:Z.toString(),paymentAmount:I.toString(),borrower:ethers.utils.getAddress(Q.borrower)}),mt=globalThis.publicKey;if(!mt)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof mt||0===mt.length)throw new Error("Invalid publicKey: expected non-empty string, got "+typeof mt);const wt=mt;e.log("0",`[Step 6] PublicKey length: ${wt.length}, starts with: ${wt.substring(0,10)}...`),e.log("6","Signing authorization..."),e.log("0",` Message hash: ${gt}`),e.log("0",` Message hash bytes length: ${ethers.utils.arrayify(gt).length}`),e.log("0",` Public key: ${wt.substring(0,20)}...`),e.log("0",` Public key length: ${wt.length}`),e.log("0","======= PKP AUTHORIZATION DIAGNOSTICS ======="),e.log("0","globalThis.publicKey:",wt?`${wt.substring(0,20)}...`:"MISSING"),e.log("0","globalThis.publicKey length:",wt?.length||0),e.log("0","globalThis.publicKey has 0x prefix:",wt?.startsWith("0x")||!1);const ft=globalThis.pkpTokenId;e.log("0","globalThis.pkpTokenId:",ft||"NOT SET"),ft&&(e.log("0","globalThis.pkpTokenId type:",typeof ft),e.log("0","globalThis.pkpTokenId value:",ft),e.log("0","NOTE: pkpTokenId is used for session signature scoping in LitOps, not as a signEcdsa parameter."));const yt=globalThis.positionId;e.log("0","globalThis.positionId:",yt||"NOT SET");const bt=globalThis.ipfsId;e.log("0","globalThis.ipfsId:",bt||"NOT SET");const Tt=ethers.utils.arrayify("0x"+wt),vt=ethers.utils.computeAddress(Tt);e.log("0","Computed ETH Address from publicKey:",vt),e.log("0","Message hash to sign:",gt),e.log("0","Signature name: paymentAuth"),e.log("0","=============================================");const Pt=globalThis.pkpTokenId;let At;try{"pkpTokenId"in globalThis&&delete globalThis.pkpTokenId;const t=globalThis.validatorWalletAddress;if(!t||!t.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const e=await Lit.Actions.getPrivateKey({pkpId:t}),r="string"==typeof e?e.startsWith("0x")?e:`0x${e}`:String(e),i=new ethers.Wallet(r);At=await i._signTypedData(dt,pt,{actionTag:ht,positionId:d,quantumTimestamp:ct,btcPrice:Z.toString(),paymentAmount:I.toString(),borrower:ethers.utils.getAddress(Q.borrower)})}finally{void 0!==Pt&&(globalThis.pkpTokenId=Pt)}return e.log("0"," \u2705 Signature obtained: "+(At?"present":"missing")),e.log("0","\u2705 Complete"),{approved:!0,positionId:d,paymentAmount:I.toString(),btcPrice:Z.toString(),messageHash:gt,signature:At,timestamp:ct,validatorPkp:wt}}catch(t){throw console.error("[Process Payment Validator] Failed:",t.message),t}var w}return nt=o,((o,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))i.call(o,c)||c===a||t(o,c,{get:()=>n[c],enumerable:!(s=e(n,c))||s.enumerable});return o})(t({},"__esModule",{value:!0}),nt)})();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
|
+
ada27fea57aa3f3b861c49e75ed1f80b72500fdccc1d6e88ee1a3c1396b81867
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "process-payment-validator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 160543,
|
|
4
|
+
"minifiedSize": 68239,
|
|
5
|
+
"compressionRatio": 0.57494876761989,
|
|
6
|
+
"hash": "ada27fea57aa3f3b861c49e75ed1f80b72500fdccc1d6e88ee1a3c1396b81867",
|
|
7
|
+
"buildTime": 1781559388456,
|
|
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={};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 a(...t){n()&&console.log(...t)}((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var s=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,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}},u=class{static create(t="LIT Action",e){return n(e)?new c(t):new s}},l=60,d=16,p="DiamondHands.Protocol",h="1",g=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(g||{}),m={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},f={ethereum:1,sepolia:11155111,hardhat:1337};function w(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function y(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function v(t){return t instanceof Error&&"AbortError"===t.name}var P=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=u.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),a(`[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"),v(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: ${y(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: ${y(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${y(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,s]=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),a(`[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}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const c=await s.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 u;try{u=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${y(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(u,null,2)}`);const l=this.parseBlockstreamUTXOs(u,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=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}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(y(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${y(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(o)throw new Error(`Failed to query UTXOs after 3 attempts: ${o.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=i-n;return{utxos:r,totalBalance:i,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:a}}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),a(`[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 s=n.chain_stats.funded_txo_sum,c=n.chain_stats.spent_txo_sum;if(void 0===s||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${c}`);const u=BigInt(s-c);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),u}catch(t){if(clearTimeout(i),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=y(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=y(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),a(`[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),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(y(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),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},T=[{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 $(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 E(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}]}if(!o)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(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,T,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,b,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 $(e.ciphertext,e.pkpId);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o)}var x={hardhat:{chain:"hardhat",chainId:f.hardhat,bitcoinNetwork:m.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:m.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:m.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function A(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(g).join(", ")}`)}(t),r=x[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var S="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",I={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 k(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var C=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),B=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)"]),M=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),D=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function O(t,e,r){return t.call({to:e,data:r})}async function R(t,e){const r=new ethers.utils.Interface([S]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([S]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?k({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]}):k(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await O(t,e,C.encodeFunctionData("views",[])),[o]=C.decodeFunctionResult("views",r),[i,n,a,s,c,u,l,d]=await Promise.all([O(t,e,C.encodeFunctionData("paused",[])),O(t,e,C.encodeFunctionData("liquidationPaused",[])),O(t,e,C.encodeFunctionData("simplePsm",[])),O(t,o,B.encodeFunctionData("core",[])),O(t,o,B.encodeFunctionData("loanOps",[])),O(t,o,B.encodeFunctionData("collateralManager",[])),O(t,o,B.encodeFunctionData("liquidationManager",[])),O(t,o,B.encodeFunctionData("circuitBreaker",[]))]),p=C.decodeFunctionResult("paused",i)[0],h=C.decodeFunctionResult("liquidationPaused",n)[0],g=C.decodeFunctionResult("simplePsm",a)[0],m=B.decodeFunctionResult("core",s)[0],f=B.decodeFunctionResult("loanOps",c)[0],w=B.decodeFunctionResult("collateralManager",u)[0],y=B.decodeFunctionResult("liquidationManager",l)[0],v=B.decodeFunctionResult("circuitBreaker",d)[0],P=await O(t,f,M.encodeFunctionData("getUcdController",[])),T=await O(t,f,M.encodeFunctionData("ucdToken",[])),b=M.decodeFunctionResult("getUcdController",P)[0],$=M.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await O(t,e,D.encodeFunctionData("paused",[]));return D.decodeFunctionResult("paused",r)[0]}catch{return!1}},[x,A,S,I,R,N,U,_]=await Promise.all([E(m),E(f),E(w),E(y),E(v),E(b),E($),E(g)]);return k({positionManagerPaused:p,positionManagerLiquidationsPaused:h,positionManagerCorePaused:x,loanOperationsPaused:A,collateralManagerPaused:S,liquidationManagerPaused:I,circuitBreakerPaused:R,ucdControllerPaused:N,ucdTokenPaused:U,simplePsmPaused:_})}(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 N(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/l)*l;var e}async function U(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;const r=d/2;let o;o=e>=l-r?l-e+r:r-e,console.log(`[Quantum] Waiting ${o}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*o))),console.log(`[Quantum] Safe quantum ready: ${N()}`)}var _,F=6,L=[{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 BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],q=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],z=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=u.create("Stale Spend Recovery Validator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing "chain"');const o=A(t),i=w().validatorWalletAddress;if(!i||!i.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be the stale-spend validator PKP wallet address");const n=globalThis.contractAddresses;if(!n?.PositionManager||!n?.BTCSpendAuthorizer)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const a=globalThis.positionId,s=globalThis.utxoTxid,c=Number(globalThis.utxoVout),u=globalThis.invalidatorTxid;if(!a||!s||Number.isNaN(c)||!u)throw new Error("Missing required params: positionId, utxoTxid, utxoVout, invalidatorTxid");const l=function(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()}(a),d=globalThis.minConfirmations??F;let g;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(g=globalThis.rpcUrl,console.log(` RPC override: ${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}(g)}`)):g=await Lit.Actions.getRpcUrl({chain:t});const m=new ethers.providers.JsonRpcProvider(g),f=await async function(t){return(await E(t))[0]}({policy:o,ethersProvider:m,registryAddress:n.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),y=new P({providerUrl:f.url});!function(t,e){const r=I[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}))}("btcTransactionSign",await R(m,n.PositionManager)),e.stepEnd("1"),r="2",e.stepStart("2","Read AuthorizedSpend");const v=new ethers.Contract(n.BTCSpendAuthorizer,L,m),T=await v.getAuthorizedSpends(l);let b=null;for(const t of T)if(t.txid.toLowerCase()===s.toLowerCase()&&Number(t.vout)===c){b=t;break}if(!b)throw new Error(`No AuthorizedSpend on-chain for ${s}:${c} under position ${l}`);const $=BigInt(b.authorizedAt.toString()),x=b.targetAddress,S=BigInt(b.targetAmount.toString());e.stepEnd("2"),r="3",e.stepStart("3","Read position vaultAddress");const k=new ethers.Contract(n.PositionManager,z,m),C=await k.core(),B=new ethers.Contract(C,q,m),M=await B.getPositionDetails(l),D=M.vaultAddress??M[3];if(!D)throw new Error(`Position ${l} has no vaultAddress`);e.stepEnd("3"),r="4",e.stepStart("4","Verify invalidator tx + confirmations");const O=await y.getTransaction(u);if(!O)throw new Error(`Invalidator tx ${u} not found on Bitcoin`);if(O.confirmations<d)throw new Error(`Invalidator tx has ${O.confirmations} confirmations; require \u2265 ${d}`);e.stepEnd("4"),r="5",e.stepStart("5","Verify inputs + classify outputs");const _=await fetch(`${f.url}/tx/${u}`);if(!_.ok)throw new Error(`Bitcoin provider GET /tx/${u} \u2192 ${_.status}`);const H=await _.json();if(!H.vin.some((t=>t.txid.toLowerCase()===s.toLowerCase()&&Number(t.vout)===c)))throw new Error(`Invalidator tx ${u} does not consume the authorized UTXO ${s}:${c}`);const j=D.toLowerCase(),X=x.toLowerCase(),W=H.vout.filter((t=>(t.scriptpubkey_address??"").toLowerCase()===j)),G=H.vout.filter((t=>(t.scriptpubkey_address??"").toLowerCase()===X)),V=H.vout.filter((t=>{const e=(t.scriptpubkey_address??"").toLowerCase();return e!==j&&e!==X}));let J;if(V.length>0)throw new Error(`Suspicious invalidator tx \u2014 has ${V.length} output(s) to neither vault nor authorized target`);if(0===G.length&&W.length>0)J="invalidated";else{if(!(G.length>0))throw new Error("Invalidator tx has no outputs to either vault or authorized target");{if(1!==G.length)throw new Error(`Suspicious invalidator tx \u2014 has ${G.length} outputs to authorized target (expected exactly 1)`);if(W.length>1)throw new Error(`Suspicious invalidator tx \u2014 has ${W.length} outputs to vault (expected 0 or 1)`);let t=0n;for(const e of H.vin){if(void 0!==e.prevout){t+=BigInt(e.prevout.value);continue}const r=await fetch(`${f.url}/tx/${e.txid}`);if(!r.ok)throw new Error(`Bitcoin provider GET /tx/${e.txid} (vin prevout lookup) \u2192 ${r.status}`);const o=await r.json(),i=o.vout?.[e.vout];if(!i||"number"!=typeof i.value)throw new Error(`Bitcoin provider returned no vout[${e.vout}] for source tx ${e.txid} \u2014 cannot verify input value`);t+=BigInt(i.value)}if(t<S)throw new Error(`Suspicious invalidator tx \u2014 sum(inputs)=${t} < authorizedTargetAmount(${S})`);const e=t-S,r=1===W.length?BigInt(W[0].value):0n;if(r!==e)throw new Error(`Suspicious invalidator tx \u2014 vault output ${r} != expected ${e} (inputs=${t}, authorized=${S}); the amount leaving the vault must equal the borrower-signed authorized amount.`);J="consumed-as-authorized"}}e.stepEnd("5"),r="6",e.stepStart("6","Sign StaleSpendRecovery attestation");const K=ethers.utils.solidityKeccak256(["string","uint32"],[s,c]);await U();const Q=N(),Y={name:p,version:h,chainId:o.chainId,verifyingContract:ethers.utils.getAddress(n.BTCSpendAuthorizer)},Z={StaleSpendRecovery:[{name:"positionId",type:"bytes32"},{name:"utxoKey",type:"bytes32"},{name:"authorizedAt",type:"uint256"},{name:"invalidatorTxid",type:"string"},{name:"attestationTimestamp",type:"uint256"}]},tt={positionId:l,utxoKey:K,authorizedAt:$.toString(),invalidatorTxid:u,attestationTimestamp:Q},et=await Lit.Actions.getPrivateKey({pkpId:i}),rt="string"==typeof et?et.startsWith("0x")?et:`0x${et}`:String(et),ot=new ethers.Wallet(rt),it=await ot._signTypedData(Y,Z,tt);return e.stepEnd("6"),console.log(`[Stale Spend Recovery Validator] \u2705 Signed (${J})`),{success:!0,classification:J,attestation:{positionId:l,utxoKey:K,authorizedAt:$.toString(),invalidatorTxid:u,attestationTimestamp:Q},signature:it,validatorPkp:ot.address,confirmations:O.confirmations,timestamp:Date.now(),action:"stale-spend-recovery-validator"}}catch(t){return console.error(`[Stale Spend Recovery Validator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"stale-spend-recovery-validator"}}}return _=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}),_)})();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={};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 a(...t){n()&&console.log(...t)}((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var s=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,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}},u=class{static create(t="LIT Action",e){return n(e)?new c(t):new s}},l=60,d=16,p="DiamondHands.Protocol",h="1",g=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(g||{}),m={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},w={ethereum:1,sepolia:11155111,hardhat:1337};function f(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function y(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function v(t){return t instanceof Error&&"AbortError"===t.name}var P="https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token";function T(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function b(t){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const e=t.trim();if(!e.startsWith("{"))return{url:e,auth:{provider:"esplora"}};let r;try{r=JSON.parse(e)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof r.url||0===r.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=r.url.trim();switch(r.provider){case void 0:case"esplora":return{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof r.apiKey||0===r.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return T(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:r.apiKey}};case"blockstream-enterprise":{if("string"!=typeof r.clientId||0===r.clientId.length||"string"!=typeof r.clientSecret||0===r.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");T(o,"blockstream-enterprise provider url");const t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&T(r.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:r.clientId,clientSecret:r.clientSecret,...t?{tokenUrl:r.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(r.provider)}"`)}}var $=new Map,E=1e4;async function x(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||P,o=`${r}\n${t.clientId}`,i=$.get(o);if(i)return i;const n=(async()=>{const o=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,i=new AbortController,n=setTimeout((()=>i.abort()),e&&e>0?e:E);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,signal:i.signal})}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>$.delete(o))),$.set(o,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}async function k(t,e,r){const o=Date.now()+r,i=await x(e,r),n=Math.max(1,o-Date.now()),a=new AbortController,s=setTimeout((()=>a.abort()),n);try{return await fetch(t,{headers:i,signal:a.signal})}finally{clearTimeout(s)}}var A=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=u.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await x(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),a(`[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"),v(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: ${y(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: ${y(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${y(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}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(i),a(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const c=await s.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 u;try{u=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${y(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(u,null,2)}`);const l=this.parseBlockstreamUTXOs(u,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=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}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(y(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${y(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(o)throw new Error(`Failed to query UTXOs after 3 attempts: ${o.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=i-n;return{utxos:r,totalBalance:i,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:a}}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:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(i),a(`[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 s=n.chain_stats.funded_txo_sum,c=n.chain_stats.spent_txo_sum;if(void 0===s||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${c}`);const u=BigInt(s-c);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),u}catch(t){if(clearTimeout(i),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=y(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=y(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,headers:await this.withAuth()});if(clearTimeout(r),a(`[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,headers:await this.withAuth()});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),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(y(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,headers:await this.withAuth()});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),v(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},S=[{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"}],I=[{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 C(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 B(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}]}if(!o)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(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,S,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,I,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 C(e.ciphertext,e.pkpId),{url:o,auth:n}=b(r);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:o,auth:n,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o)}var M={hardhat:{chain:"hardhat",chainId:w.hardhat,bitcoinNetwork:m.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:w.sepolia,bitcoinNetwork:m.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:w.ethereum,bitcoinNetwork:m.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function D(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(g).join(", ")}`)}(t),r=M[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var O="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))",U={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 _(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 N=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),R=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)"]),F=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),L=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function q(t,e,r){return t.call({to:e,data:r})}async function z(t,e){const r=new ethers.utils.Interface([O]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([O]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?_({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]}):_(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await q(t,e,N.encodeFunctionData("views",[])),[o]=N.decodeFunctionResult("views",r),[i,n,a,s,c,u,l,d]=await Promise.all([q(t,e,N.encodeFunctionData("paused",[])),q(t,e,N.encodeFunctionData("liquidationPaused",[])),q(t,e,N.encodeFunctionData("simplePsm",[])),q(t,o,R.encodeFunctionData("core",[])),q(t,o,R.encodeFunctionData("loanOps",[])),q(t,o,R.encodeFunctionData("collateralManager",[])),q(t,o,R.encodeFunctionData("liquidationManager",[])),q(t,o,R.encodeFunctionData("circuitBreaker",[]))]),p=N.decodeFunctionResult("paused",i)[0],h=N.decodeFunctionResult("liquidationPaused",n)[0],g=N.decodeFunctionResult("simplePsm",a)[0],m=R.decodeFunctionResult("core",s)[0],w=R.decodeFunctionResult("loanOps",c)[0],f=R.decodeFunctionResult("collateralManager",u)[0],y=R.decodeFunctionResult("liquidationManager",l)[0],v=R.decodeFunctionResult("circuitBreaker",d)[0],P=await q(t,w,F.encodeFunctionData("getUcdController",[])),T=await q(t,w,F.encodeFunctionData("ucdToken",[])),b=F.decodeFunctionResult("getUcdController",P)[0],$=F.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await q(t,e,L.encodeFunctionData("paused",[]));return L.decodeFunctionResult("paused",r)[0]}catch{return!1}},[x,k,A,S,I,C,B,M]=await Promise.all([E(m),E(w),E(f),E(y),E(v),E(b),E($),E(g)]);return _({positionManagerPaused:p,positionManagerLiquidationsPaused:h,positionManagerCorePaused:x,loanOperationsPaused:k,collateralManagerPaused:A,liquidationManagerPaused:S,circuitBreakerPaused:I,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(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 H(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/l)*l;var e}async function j(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;const r=d/2;let o;o=e>=l-r?l-e+r:r-e,console.log(`[Quantum] Waiting ${o}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*o))),console.log(`[Quantum] Safe quantum ready: ${H()}`)}var X,W=6,G=[{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 BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],K=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],V=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=u.create("Stale Spend Recovery Validator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing "chain"');const o=D(t),i=f().validatorWalletAddress;if(!i||!i.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be the stale-spend validator PKP wallet address");const n=globalThis.contractAddresses;if(!n?.PositionManager||!n?.BTCSpendAuthorizer)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const a=globalThis.positionId,s=globalThis.utxoTxid,c=Number(globalThis.utxoVout),u=globalThis.invalidatorTxid;if(!a||!s||Number.isNaN(c)||!u)throw new Error("Missing required params: positionId, utxoTxid, utxoVout, invalidatorTxid");const l=function(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()}(a),d=globalThis.minConfirmations??W;let g;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(g=globalThis.rpcUrl,console.log(` RPC override: ${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}(g)}`)):g=await Lit.Actions.getRpcUrl({chain:t});const m=new ethers.providers.JsonRpcProvider(g),w=await async function(t){return(await B(t))[0]}({policy:o,ethersProvider:m,registryAddress:n.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),y=new A({providerUrl:w.url,auth:w.auth});!function(t,e){const r=U[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}))}("btcTransactionSign",await z(m,n.PositionManager)),e.stepEnd("1"),r="2",e.stepStart("2","Read AuthorizedSpend");const v=new ethers.Contract(n.BTCSpendAuthorizer,G,m),P=await v.getAuthorizedSpends(l);let T=null;for(const t of P)if(t.txid.toLowerCase()===s.toLowerCase()&&Number(t.vout)===c){T=t;break}if(!T)throw new Error(`No AuthorizedSpend on-chain for ${s}:${c} under position ${l}`);const b=BigInt(T.authorizedAt.toString()),$=T.targetAddress,E=BigInt(T.targetAmount.toString());e.stepEnd("2"),r="3",e.stepStart("3","Read position vaultAddress");const x=new ethers.Contract(n.PositionManager,V,m),S=await x.core(),I=new ethers.Contract(S,K,m),C=await I.getPositionDetails(l),M=C.vaultAddress??C[3];if(!M)throw new Error(`Position ${l} has no vaultAddress`);e.stepEnd("3"),r="4",e.stepStart("4","Verify invalidator tx + confirmations");const O=await y.getTransaction(u);if(!O)throw new Error(`Invalidator tx ${u} not found on Bitcoin`);if(O.confirmations<d)throw new Error(`Invalidator tx has ${O.confirmations} confirmations; require \u2265 ${d}`);e.stepEnd("4"),r="5",e.stepStart("5","Verify inputs + classify outputs");const _=15e3,N=await k(`${w.url}/tx/${u}`,w.auth,_);if(!N.ok)throw new Error(`Bitcoin provider GET /tx/${u} \u2192 ${N.status}`);const R=await N.json();if(!R.vin.some((t=>t.txid.toLowerCase()===s.toLowerCase()&&Number(t.vout)===c)))throw new Error(`Invalidator tx ${u} does not consume the authorized UTXO ${s}:${c}`);const F=M.toLowerCase(),L=$.toLowerCase(),q=R.vout.filter((t=>(t.scriptpubkey_address??"").toLowerCase()===F)),X=R.vout.filter((t=>(t.scriptpubkey_address??"").toLowerCase()===L)),J=R.vout.filter((t=>{const e=(t.scriptpubkey_address??"").toLowerCase();return e!==F&&e!==L}));let Q;if(J.length>0)throw new Error(`Suspicious invalidator tx \u2014 has ${J.length} output(s) to neither vault nor authorized target`);if(0===X.length&&q.length>0)Q="invalidated";else{if(!(X.length>0))throw new Error("Invalidator tx has no outputs to either vault or authorized target");{if(1!==X.length)throw new Error(`Suspicious invalidator tx \u2014 has ${X.length} outputs to authorized target (expected exactly 1)`);if(q.length>1)throw new Error(`Suspicious invalidator tx \u2014 has ${q.length} outputs to vault (expected 0 or 1)`);let t=0n;for(const e of R.vin){if(void 0!==e.prevout){t+=BigInt(e.prevout.value);continue}const r=await k(`${w.url}/tx/${e.txid}`,w.auth,_);if(!r.ok)throw new Error(`Bitcoin provider GET /tx/${e.txid} (vin prevout lookup) \u2192 ${r.status}`);const o=await r.json(),i=o.vout?.[e.vout];if(!i||"number"!=typeof i.value)throw new Error(`Bitcoin provider returned no vout[${e.vout}] for source tx ${e.txid} \u2014 cannot verify input value`);t+=BigInt(i.value)}if(t<E)throw new Error(`Suspicious invalidator tx \u2014 sum(inputs)=${t} < authorizedTargetAmount(${E})`);const e=t-E,r=1===q.length?BigInt(q[0].value):0n;if(r!==e)throw new Error(`Suspicious invalidator tx \u2014 vault output ${r} != expected ${e} (inputs=${t}, authorized=${E}); the amount leaving the vault must equal the borrower-signed authorized amount.`);Q="consumed-as-authorized"}}e.stepEnd("5"),r="6",e.stepStart("6","Sign StaleSpendRecovery attestation");const Y=ethers.utils.solidityKeccak256(["string","uint32"],[s,c]);await j();const Z=H(),tt={name:p,version:h,chainId:o.chainId,verifyingContract:ethers.utils.getAddress(n.BTCSpendAuthorizer)},et={StaleSpendRecovery:[{name:"positionId",type:"bytes32"},{name:"utxoKey",type:"bytes32"},{name:"authorizedAt",type:"uint256"},{name:"invalidatorTxid",type:"string"},{name:"attestationTimestamp",type:"uint256"}]},rt={positionId:l,utxoKey:Y,authorizedAt:b.toString(),invalidatorTxid:u,attestationTimestamp:Z},ot=await Lit.Actions.getPrivateKey({pkpId:i}),it="string"==typeof ot?ot.startsWith("0x")?ot:`0x${ot}`:String(ot),nt=new ethers.Wallet(it),at=await nt._signTypedData(tt,et,rt);return e.stepEnd("6"),console.log(`[Stale Spend Recovery Validator] \u2705 Signed (${Q})`),{success:!0,classification:Q,attestation:{positionId:l,utxoKey:Y,authorizedAt:b.toString(),invalidatorTxid:u,attestationTimestamp:Z},signature:at,validatorPkp:nt.address,confirmations:O.confirmations,timestamp:Date.now(),action:"stale-spend-recovery-validator"}}catch(t){return console.error(`[Stale Spend Recovery Validator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"stale-spend-recovery-validator"}}}return X=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}),X)})();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
|
+
26b11730cf5d9eb4af0b1fe65192d26ccee50369c0472211a0ea11e26ef51cc5
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "stale-spend-recovery-validator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 68745,
|
|
4
|
+
"minifiedSize": 34413,
|
|
5
|
+
"compressionRatio": 0.4994108662448178,
|
|
6
|
+
"hash": "26b11730cf5d9eb4af0b1fe65192d26ccee50369c0472211a0ea11e26ef51cc5",
|
|
7
|
+
"buildTime": 1781559388557,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|