@gvnrdao/dh-lit-actions 0.0.308 → 0.0.310
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +150 -77
- 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,d=16,u=10,h=8e3;function p(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 g="liquidation",m="DiamondHands.Protocol",w="1",f=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(f||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["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 P(t){return b[t]}var A="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))",E={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 S=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),I=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)"]),C=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),B=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function U(t,e,r){return t.call({to:e,data:r})}async function k(t,e){const r=new ethers.utils.Interface([A]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([A]).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){i=t}try{return await async function(t,e){const r=await U(t,e,S.encodeFunctionData("views",[])),[i]=S.decodeFunctionResult("views",r),[o,a,n,s,c,l,d,u]=await Promise.all([U(t,e,S.encodeFunctionData("paused",[])),U(t,e,S.encodeFunctionData("liquidationPaused",[])),U(t,e,S.encodeFunctionData("simplePsm",[])),U(t,i,I.encodeFunctionData("core",[])),U(t,i,I.encodeFunctionData("loanOps",[])),U(t,i,I.encodeFunctionData("collateralManager",[])),U(t,i,I.encodeFunctionData("liquidationManager",[])),U(t,i,I.encodeFunctionData("circuitBreaker",[]))]),h=S.decodeFunctionResult("paused",o)[0],p=S.decodeFunctionResult("liquidationPaused",a)[0],g=S.decodeFunctionResult("simplePsm",n)[0],m=I.decodeFunctionResult("core",s)[0],w=I.decodeFunctionResult("loanOps",c)[0],f=I.decodeFunctionResult("collateralManager",l)[0],y=I.decodeFunctionResult("liquidationManager",d)[0],v=I.decodeFunctionResult("circuitBreaker",u)[0],b=await U(t,w,C.encodeFunctionData("getUcdController",[])),T=await U(t,w,C.encodeFunctionData("ucdToken",[])),P=C.decodeFunctionResult("getUcdController",b)[0],A=C.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await U(t,e,B.encodeFunctionData("paused",[]));return B.decodeFunctionResult("paused",r)[0]}catch{return!1}},[k,x,M,D,O,q,R,L]=await Promise.all([E(m),E(w),E(f),E(y),E(v),E(P),E(A),E(g)]);return $({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:k,loanOperationsPaused:x,collateralManagerPaused:M,liquidationManagerPaused:D,circuitBreakerPaused:O,ucdControllerPaused:q,ucdTokenPaused:R,simplePsmPaused:L})}(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 x(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 M(...t){x()&&console.log(...t)}var D=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}},O=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}},q=class{static create(t="LIT Action",e){return x(e)?new O(t):new D}};function R(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function L(t){return t instanceof Error&&"AbortError"===t.name}var N=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=q.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),M(`[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"),L(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: ${R(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: ${R(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${R(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),M(`[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: ${R(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"),L(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(R(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${R(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),M(`[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),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=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=R(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),M(`[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),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(R(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),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function _(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 F(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 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*n*10000n/r)}}function X(t){return t/100}var z=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}};z.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],z.REQUIRED_PROVIDER_COUNT=3;var H=z;async function j(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 G(t){return Math.floor(t/l)*l}function W(){return G(Math.floor(Date.now()/1e3))}async function K(){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 i;i=e>=l-r?l-e+r:r-e,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${W()}`)}var J=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:h},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 Q=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:h},{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:h},{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:h},{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:h},{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 Y(t){return new Q(t)}var Z=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=Y({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)]),d=_(e.termStartTimestamp,e.selectedTerm),u=F(d.isExpired,d.daysIntoGracePeriod,s,c),h=V(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,g=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,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=Y({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)]),d=_(e.termStartTimestamp,e.selectedTerm),u=F(d.isExpired,d.daysIntoGracePeriod,s,c),h=V(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,g=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,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:h},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),d=Number(s.selectedTerm),u=Number(s.totalTerm),p=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),m=(f=d,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:d,status:c,expiryAt:l,previousExpiryAt:p,totalTerm:u,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 tt={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 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){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:o}=t;if(e.allowArbitraryBitcoinProvider){if(!o)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:o,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}]}if(!i)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 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}(e,r,i)}var at,nt="liquidate-position";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;console.log("[Liquidation Validator] ========================================"),console.log("[Liquidation Validator] DEBUG: Received globalThis parameters:"),console.log("[Liquidation Validator] globalThis.contractAddresses:",globalThis.contractAddresses),console.log("[Liquidation Validator] globalThis.contractAddresses:",globalThis.contractAddresses),console.log("[Liquidation Validator] globalThis.positionId:",globalThis.positionId),console.log("[Liquidation Validator] ========================================");let e,r,i,o,a,n,d="0";try{let t,f,y,b,A,$;d="0a",console.log("[Step 0a] Validating configuration..."),console.log("[Liquidation Validator] Starting parameter access..."),console.log("[Liquidation Validator] globalThis keys:",Object.keys(globalThis));const S=globalThis;console.log("[Liquidation Validator] Final params keys:",Object.keys(S)),console.log("[Liquidation Validator] params.priceProviders:",S.priceProviders),t=S.chain,f=S.positionId,y=S.contractAddresses,b=S.rpcUrl,A=S.priceProviders,$=S.liquidatorAddress;const I=S.liquidatorIntent;if(console.log("[Liquidation Validator] Extracted priceProviders:",A),!t)throw new Error(`Missing required parameter: "chain". Available in globalThis: ${Object.keys(globalThis)}`);if(!f)throw new Error(`Missing required parameter: "positionId". Available in globalThis: ${Object.keys(globalThis)}`);if(!$)throw new Error(`Missing required parameter: "liquidatorAddress". Available in globalThis: ${Object.keys(globalThis)}`);d="0b";const C=function(t){const e=T(t),r=tt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),B=C.chain;let U,x,M;if(d="0c",!y||"object"!=typeof y)throw new Error("Missing or invalid 'contractAddresses' parameter");if(r=y.PositionManager,i=y.LoanOperationsManagerModule,o=y.LiquidationManagerModule??y.LiquidationManager??"",a=y.BTCSpendAuthorizer||i,!r||!i||!o)throw new Error("Missing one or more required contract addresses (PositionManager, LoanOperationsManagerModule, LiquidationManagerModule)");b&&"string"==typeof b?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!v.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(C,b),console.log(` Using RPC URL 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}(b)}`),M=b):(M=await Lit.Actions.getRpcUrl({chain:t}),console.log(` Using LIT-provided RPC URL for chain: ${t}`)),e=new ethers.providers.JsonRpcProvider(M),x=await ot({policy:C,ethersProvider:e,registryAddress:y.BitcoinProviderRegistry,devBitcoinProviderUrl:S.devBitcoinProviderUrl}),U=x[0],console.log(` \u2705 Bitcoin Provider: ${U.name} (min confs ${U.minConfirmations})`);!function(t,e){const r=E[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}))}("liquidation",await k(e,r));const D=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 j(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(o=await j(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}(S.priceProviders),O=!0===globalThis.devPriceMode;if(O&&!C.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${C.chain}`);const q=new H(D,void 0,void 0,{devSingleProvider:O&&C.allowDevSinglePriceProvider}),R=new N({providerUrl:U.url}),L=(h={contractAddress:a,chain:t,chainId:C.chainId,rpcUrl:b,bitcoinProvider:R,minConfirmations:U.minConfirmations},new J(h)),_=function(t){return new Z(t)}({contractAddress:r,termManagerAddress:y.TermManagerModule,loanOpsManagerAddress:i,liquidationManagerAddress:o,chain:t,chainId:P(B),rpcUrl:b,vaultBalance:L,priceOracle:q});d="0d",console.log("[Step 0d] Canonicalizing positionId...");const F=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()}(f);console.log(` \u2705 Canonical positionId: ${F}`),d="0e";const V=P(B),z=ethers.utils.getAddress($);if(!I||"number"!=typeof I.timestamp||"number"!=typeof I.chainId||"string"!=typeof I.signature)throw new Error("Missing liquidatorIntent {timestamp, chainId, signature} \u2014 required to bind the LIT signature to the calling liquidator");if(I.chainId!==V)throw new Error(`liquidatorIntent.chainId (${I.chainId}) does not match target chain (${V})`);await K();try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),o=G(i),a=G(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.`)}(I.timestamp)}catch(t){throw new Error(`liquidatorIntent.timestamp outside valid quantum window: ${t.message||t}`)}const Q=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(nt)),Y=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","address","bytes32"],[F,I.timestamp,I.chainId,z,Q]),et=ethers.utils.recoverAddress(ethers.utils.hashMessage(ethers.utils.arrayify(Y)),I.signature);if(et.toLowerCase()!==z.toLowerCase())throw new Error(`liquidatorIntent signature does not recover to liquidatorAddress (recovered=${et}, expected=${z})`);if(console.log(` \u2705 Liquidator intent verified for ${z}`),d="1",console.log("[Step 1] Getting vault snapshot..."),n=await _.getVaultSnapshot(F),await async function(t,e,r,i){if(e.length<=1)return console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null;const o=i??(t=>new N(r?{providerUrl:t,timeout:r}:{providerUrl:t})),a=e[0],n=await o(a.url).getBalance(t);for(let r=1;r<e.length;r++){const i=e[r],s=await o(i.url).getBalance(t);if(s!==n)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${a.name}=${n.toString()} vs ${i.name}=${s.toString()}`)}return console.log(` \u2705 Consensus reached across ${e.length} providers (${n.toString()} sats)`),n}(n.vaultAddress,x),n.btcPriceUsd<s||n.btcPriceUsd>c)throw new Error(`Bitcoin price ${n.btcPriceUsd} is outside acceptable range (${s} - ${c}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(n.btcPriceUsd)/1e8).toFixed(2)}`),d="2",console.log("[Step 2] Validating position state...");if(![2,3,4].includes(n.status))throw new Error(`Invalid position status for liquidation: ${p(n.status)}. Must be ACTIVE, EXPIRED, or LIQUIDATABLE.`);if(console.log(` \u2705 Position status valid for liquidation: ${p(n.status)}`),d="3",console.log("[Step 3] Checking liquidation eligibility..."),!n.isLiquidatable)throw new Error(`Position is not liquidatable (${X(n.collateralRatioBps)}% >= ${X(n.currentLiquidationThreshold)}%) - liquidation rejected.`);console.log(" \u2705 Position is liquidatable"),console.log(` - Current ratio: ${X(n.collateralRatioBps)}%`),console.log(` - Liquidation threshold: ${X(n.currentLiquidationThreshold)}%`),d="4",console.log("[Step 4] Building authorization EIP-712 digest...");const rt=W()+u,it=V,at=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(g)),st={name:m,version:w,chainId:it,verifyingContract:ethers.utils.getAddress(o)},ct={LiquidationAuthorization:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"btcVaultBalance",type:"uint256"},{name:"vaultAddress",type:"string"},{name:"liquidator",type:"address"}]},lt={actionTag:at,positionId:F,quantumTimestamp:rt,btcPrice:n.btcPriceUsd.toString(),btcVaultBalance:n.availableBTCSats.toString(),vaultAddress:n.vaultAddress,liquidator:z};d="5",console.log("[Step 5] Signing authorization...");const dt=globalThis.validatorWalletAddress;if(!dt||!dt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const ut=await Lit.Actions.getPrivateKey({pkpId:dt}),ht="string"==typeof ut?ut.startsWith("0x")?ut:`0x${ut}`:String(ut),pt=new ethers.Wallet(ht),gt=await pt._signTypedData(st,ct,lt);return console.log("[Liquidation Validator] \u2705 Complete"),{approved:!0,positionId:F,btcPrice:n.btcPriceUsd.toString(),btcAmountSats:n.availableBTCSats.toString(),signature:gt,timestamp:rt,validatorPkp:pt.address,liquidatorAddress:z}}catch(t){throw console.error("[Liquidation Validator] \u274c Failed:",t.message),console.error(`[Liquidation Validator] Failed at step: ${d}`),t}var h}return at=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}),at)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
1
|
+
var _LIT_ACTION_=(()=>{var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};((t,r)=>{for(var i in r)e(t,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=11e3,n=1000000000000000000n,s=1000000000000n,c=100000000000000n,l=60,d=16,u=10,h=8e3;function p(e){switch(e){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(${e})`}}var g="liquidation",m="DiamondHands.Protocol",w="1",f=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(f||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["infura.io","drpc.org"],b={ethereum:1,sepolia:11155111,hardhat:1337};function P(e){const t=e.toLowerCase().trim();if("sepolia"===t)return"sepolia";if("ethereum"===t||"mainnet"===t)return"ethereum";if("hardhat"===t)return"hardhat";throw new Error(`Unsupported EVM chain: "${e}". Supported chains: ${Object.values(f).join(", ")}`)}function T(e){return b[e]}var A="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))",E={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 $(e){return{positionManagerPaused:e.positionManagerPaused,positionManagerLiquidationsPaused:e.positionManagerLiquidationsPaused,positionManagerCorePaused:e.positionManagerCorePaused,loanOperationsPaused:e.loanOperationsPaused,collateralManagerPaused:e.collateralManagerPaused,liquidationManagerPaused:e.liquidationManagerPaused,circuitBreakerPaused:e.circuitBreakerPaused,ucdControllerPaused:e.ucdControllerPaused,ucdTokenPaused:e.ucdTokenPaused,simplePsmPaused:e.simplePsmPaused}}var S=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),I=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)"]),C=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),k=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function B(e,t,r){return e.call({to:t,data:r})}async function U(e,t){const r=new ethers.utils.Interface([A]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(e){const t=new ethers.utils.Interface([A]).decodeFunctionResult("getProtocolPauseStatus",e)[0];return Array.isArray(t)?$({positionManagerPaused:t[0],positionManagerLiquidationsPaused:t[1],positionManagerCorePaused:t[2],loanOperationsPaused:t[3],collateralManagerPaused:t[4],liquidationManagerPaused:t[5],circuitBreakerPaused:t[6],ucdControllerPaused:t[7],ucdTokenPaused:t[8],simplePsmPaused:t[9]}):$(t)}(await e.call({to:t,data:r}))}catch(e){i=e}try{return await async function(e,t){const r=await B(e,t,S.encodeFunctionData("views",[])),[i]=S.decodeFunctionResult("views",r),[o,a,n,s,c,l,d,u]=await Promise.all([B(e,t,S.encodeFunctionData("paused",[])),B(e,t,S.encodeFunctionData("liquidationPaused",[])),B(e,t,S.encodeFunctionData("simplePsm",[])),B(e,i,I.encodeFunctionData("core",[])),B(e,i,I.encodeFunctionData("loanOps",[])),B(e,i,I.encodeFunctionData("collateralManager",[])),B(e,i,I.encodeFunctionData("liquidationManager",[])),B(e,i,I.encodeFunctionData("circuitBreaker",[]))]),h=S.decodeFunctionResult("paused",o)[0],p=S.decodeFunctionResult("liquidationPaused",a)[0],g=S.decodeFunctionResult("simplePsm",n)[0],m=I.decodeFunctionResult("core",s)[0],w=I.decodeFunctionResult("loanOps",c)[0],f=I.decodeFunctionResult("collateralManager",l)[0],y=I.decodeFunctionResult("liquidationManager",d)[0],v=I.decodeFunctionResult("circuitBreaker",u)[0],b=await B(e,w,C.encodeFunctionData("getUcdController",[])),P=await B(e,w,C.encodeFunctionData("ucdToken",[])),T=C.decodeFunctionResult("getUcdController",b)[0],A=C.decodeFunctionResult("ucdToken",P)[0],E=async t=>{if(!t||t===ethers.constants.AddressZero)return!1;try{const r=await B(e,t,k.encodeFunctionData("paused",[]));return k.decodeFunctionResult("paused",r)[0]}catch{return!1}},[U,x,M,D,O,q,R,L]=await Promise.all([E(m),E(w),E(f),E(y),E(v),E(T),E(A),E(g)]);return $({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:U,loanOperationsPaused:x,collateralManagerPaused:M,liquidationManagerPaused:D,circuitBreakerPaused:O,ucdControllerPaused:q,ucdTokenPaused:R,simplePsmPaused:L})}(e,t)}catch(e){const t=i instanceof Error?i.message:String(i),r=e instanceof Error?e.message:String(e);throw new Error(`getProtocolPauseStatus failed (aggregate: ${t}; decomposed: ${r})`)}}function x(e){if(!0===e)return!0;if(!1===e)return!1;const t=globalThis;return!0===t.debugAction||(!0===t.LIT_ACTION_DEBUG||("true"===t.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const e=process.env.LIT_ACTION_DEBUG,t=process.env.DEBUG;return"1"===e||"true"===e||"1"===t||"true"===t}catch{return!1}}()))}function M(...e){x()&&console.log(...e)}var D=class{stepStart(e,t){}stepEnd(e,t){}log(e,t,...r){}warn(e,t){}error(e,t){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},O=class{constructor(e){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=e,this.executionStartTime=Date.now();const t=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${t}_${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(e,t){this.stepStartTimes.set(e,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${e}] ${t}...`),console.log(`[Step ${e}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(e,t=5e3){const r=this.stepStartTimes.get(e);if(!r)return console.warn(`[Step ${e}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(e,i),console.log(`[Step ${e}] Duration: ${i}ms`),i>t&&console.warn(`\u26a0\ufe0f [Step ${e}] Took ${i}ms (> ${t}ms threshold)`);const o=Date.now()-this.executionStartTime,a=this.TIMEOUT_MS-o;a<5e3&&console.warn(`\u26a0\ufe0f [Step ${e}] Time remaining: ${a}ms (approaching timeout)`)}log(e,t,...r){r.length>0?console.log(`[Step ${e}] ${t}`,...r):console.log(`[Step ${e}] ${t}`)}warn(e,t){console.warn(`\u26a0\ufe0f [Step ${e}] ${t}`)}error(e,t){console.error(`\u274c [Step ${e}] ${t}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const e=Date.now()-this.executionStartTime,t=this.TIMEOUT_MS-e;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: ${(e/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${t}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[t,r]of this.stepDurations.entries()){const i=(r/e*100).toFixed(1);console.log(`[${this.actionName}] Step ${t}: ${r}ms (${i}%)`)}}e>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(e/1e3).toFixed(2)}s (${t}ms remaining)`),t<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${t}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},q=class{static create(e="LIT Action",t){return x(t)?new O(e):new D}};function R(e){if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function L(e){return e instanceof Error&&"AbortError"===e.name}function N(e,t){if(!/^https:\/\//i.test(e.trim()))throw new Error(`parseProviderPlaintext: ${t} must use https:// (credentials must not be sent over http)`)}function _(e){if("string"!=typeof e||0===e.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const t=e.trim();if(!t.startsWith("{"))return{url:t,auth:{provider:"esplora"}};let r;try{r=JSON.parse(t)}catch(e){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${e?.message??String(e)}`)}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 N(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`");N(i,"blockstream-enterprise provider url");const e="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return e&&N(r.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:r.clientId,clientSecret:r.clientSecret,...e?{tokenUrl:r.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(r.provider)}"`)}}var F=new Map;async function V(e,t){if(!e)return{};switch(e.provider){case"esplora":default:return{};case"maestro":return{"api-key":e.apiKey};case"blockstream-enterprise":{const r=await async function(e,t){const r=e.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${e.clientId}`,o=F.get(i);if(o)return o;const a=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(e.clientId)}&client_secret=${encodeURIComponent(e.clientSecret)}&scope=openid`,o=new AbortController,a=setTimeout((()=>o.abort()),t&&t>0?t:1e4);let n;try{n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:o.signal})}finally{clearTimeout(a)}if(!n.ok)throw new Error(`Blockstream OAuth token exchange failed: ${n.status} ${n.statusText}`);const s=await n.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 a.catch((()=>F.delete(i))),F.set(i,a),a}(e,t);return{Authorization:`Bearer ${r}`}}}}var z=class{constructor(e){this.config=e,this.timeout=e.timeout||15e3,this.logger=q.create("BitcoinDataProvider")}async withAuth(e={}){return{...e,...await V(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const e=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),e}const e=new AbortController,t=setTimeout((()=>e.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(t),M(`[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 e=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${e}`)}return this.logger.stepEnd("0"),a}catch(e){if(clearTimeout(t),this.logger.stepEnd("0"),L(e))throw new Error(`Request timeout after ${this.timeout}ms`);throw e}}async getUTXOs(e){this.logger.log("0",`Original address: "${e}"`);const t=this.stripNetworkPrefix(e);if(this.logger.log("0",`Cleaned address: "${t}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(t);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,t)}catch(e){if(this.logger.warn("0",`Primary provider failed: ${R(e)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const e=[...this.config.fallbackProviders].sort(((e,t)=>e.priority-t.priority));for(const r of e)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,t)}catch(e){this.logger.warn("0",`Fallback ${r.name} failed: ${R(e)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${R(e)}`)}}stripNetworkPrefix(e){return e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(e){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const t=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(t,e)).map((e=>({txid:e.txid,vout:e.vout,satoshis:BigInt(Math.round(1e8*e.amount)),confirmations:e.confirmations})))}parseBlockstreamUTXOs(e,t){if(!Array.isArray(e))throw new Error("Invalid Blockstream response format: expected an array");const r=e,i=[];for(const e of r){let r=0;e.status&&"object"==typeof e.status?e.status.confirmed&&(r=void 0!==e.status.block_height&&e.status.block_height>0?t-e.status.block_height+1:1):void 0!==e.confirmations&&(r=e.confirmations);const o=e.txid,a=void 0!==e.vout?e.vout:e.n,n=void 0!==e.value?e.value:e.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(e,t){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${e}/address/${t}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const e=Date.now(),[a,n]=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),M(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-e}ms endpoint tail .../${t.slice(0,12)}.../utxo (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(e){const t=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${R(e)}. Response: ${t}`)}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(e){if(clearTimeout(o),this.logger.stepEnd("1"),L(e))throw new Error(`Request timeout after ${this.timeout}ms`);throw e}}async getUTXOSet(e,t){let r=[],i=null;for(let t=1;t<=3;t++)try{this.logger.log("2",`UTXO query attempt ${t}/3...`),r=await this.getUTXOs(e),this.logger.log("2",`UTXO query succeeded on attempt ${t}`),i=null;break}catch(e){i=e instanceof Error?e:new Error(R(e)),this.logger.error("2",`UTXO query failed on attempt ${t}: ${R(e)}`),t<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((e=>setTimeout(e,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const o=r.reduce(((e,t)=>e+t.satoshis),0n),a=r.filter((e=>e.confirmations>=t)).reduce(((e,t)=>e+t.satoshis),0n),n=o-a;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:a,unconfirmedBalance:n}}async getBalance(e){const t=this.stripNetworkPrefix(e),r=`${this.config.providerUrl}/address/${t}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const e=Date.now(),t=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),M(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-e}ms (timeout budget ${this.timeout}ms)`),!t.ok)throw new Error(`Bitcoin provider error: ${t.status} ${t.statusText}`);const a=await t.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(e){if(clearTimeout(o),L(e))throw new Error(`Request timeout after ${this.timeout}ms`);const r=R(e);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${t}: ${r}`)}}async getTransaction(e){if(this.config.rpcHelper)try{const t=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(t,e);return{txid:r.txid,confirmations:r.confirmations||0}}catch(e){const t=R(e),r=null!==e&&"object"==typeof e&&"code"in e&&"number"==typeof e.code?e.code:void 0;if(t.includes("Invalid or non-wallet transaction")||-5===r)return null;throw e}const t=new AbortController,r=setTimeout((()=>t.abort()),this.timeout);try{const i=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${e}`,{signal:t.signal,headers:await this.withAuth()});if(clearTimeout(r),M(`[BitcoinDataProvider] GET tx/${e.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??e,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth()});if(!r.ok)return{txid:a.txid??e,confirmations:1};const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)return{txid:a.txid??e,confirmations:1};const n=o-a.status.block_height+1;return{txid:a.txid??e,confirmations:n>0?n:0}}catch{return{txid:a.txid??e,confirmations:1}}}return null}catch(e){if(clearTimeout(r),L(e))throw new Error(`Request timeout after ${this.timeout}ms`);if(R(e).includes("404"))return null;throw e}}async getTransactionOutputs(e){if(!this.config.providerUrl)return null;const t=new AbortController,r=setTimeout((()=>t.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${e}`,{signal:t.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((e,t)=>({index:t,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value??0}))):null}catch(e){if(clearTimeout(r),L(e))throw new Error(`Request timeout after ${this.timeout}ms`);throw e}}};function X(e,t){if(0===e)return{termDurationDays:0,termLengthDays:30*t,isExpired:!1,daysUntilExpiry:30*t,daysIntoGracePeriod:0};const r=30*t,i=Math.floor(Date.now()/1e3)-e,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 j(e,t,r,i){if(!e)return r;const o=i??a,n=Math.min(t,30);return a+n*n*(o-a)/900}function H(e,t,r){const i=e*t/10000000000000000n;if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*n*10000n/r)}}function G(e){return e/100}var K=class e{requiredCount(){return this.devSingleProvider?1:e.REQUIRED_PROVIDER_COUNT}constructor(t,r,i,o){if(this.devSingleProvider=!0===o?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(t))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${e.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+e.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(t)}this.sources.sort(((e,t)=>e.priority-t.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: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(t){if(t.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${t.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let o=1;for(const a of t){if(!a||"string"!=typeof a.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const t=a.name.toLowerCase();if(!e.ACTIVE_PROVIDER_NAMES.includes(t))throw new Error(`Unsupported price provider "${a.name}". Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(t))throw new Error(`Duplicate price provider "${t}" \u2014 the oracle requires ${e.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${e.REQUIRED_PROVIDER_COUNT} different provider names from: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(t),t){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: ${t}`)}}return r}createCryptoCompareSource(e,t){return{name:"CryptoCompare",fetchPrice:async()=>{const t=new URL("https://min-api.cryptocompare.com/data/price");t.searchParams.set("fsym","BTC"),t.searchParams.set("tsyms","USDT"),t.searchParams.set("api_key",e);const r=await(async e=>{const t=new AbortController,r=setTimeout((()=>t.abort()),5e3);try{const i=await fetch(e,{signal:t.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(e){if(clearTimeout(r),"AbortError"===e.name)throw new Error("Request timeout after 5000ms");throw e}})(t.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:t}}createFetchJson(e){return async(t,r)=>{const i=new AbortController,o=setTimeout((()=>i.abort()),5e3);try{const o=await fetch(t,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!o.ok)throw new Error(`${e} HTTP ${o.status} ${o.statusText}`);return await o.json()}finally{clearTimeout(o)}}}createCoinGeckoSource(e,t){if(!e)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const t=e.startsWith("pro:"),i=t?e.slice(4):e,o=t?{"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:t}}createCoinMarketCapSource(e,t){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const t=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");t.searchParams.set("symbol","BTC"),t.searchParams.set("convert","USDT");const i=await r(t.toString(),{"X-CMC_PRO_API_KEY":e}),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:t}}async getBTCPrice(){const e=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 t=new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async e=>{const t=Date.now();try{const r=await e.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-t}ms] ${e.name}: $${r.toLocaleString()}`),r}catch(t){const r=t instanceof Error?t.message:String(t);throw console.log(`[Price Oracle] \u274c ${e.name}: ${r}`),new Error(`${e.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([r,t])].sort(((e,t)=>e-t));let o;if(this.devSingleProvider)o=i[0];else{o=i[1];if((i[2]-i[0])/i[0]>.01){const e=this.sources.map((e=>e.name)).join(", "),t=i.map((e=>`$${e.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${e}]. Prices: [${t}]`)}}const a=Math.round(100*o),n=1000000n*BigInt(a),s=Date.now()-e;return console.log(`[Price Oracle] Median price: $${o.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${n}`),n}};K.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],K.REQUIRED_PROVIDER_COUNT=3;var W=K;async function J(e,t,r,i){try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof e?e:String(e??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${t} for provider ${e}: ${i}`)}}function Q(e){return Math.floor(e/l)*l}function Y(){return Q(Math.floor(Date.now()/1e3))}async function Z(){const e=Math.floor(Date.now()/1e3),t=e%l;if(!function(e){const t=(e??Math.floor(Date.now()/1e3))%l;return t<8||t>=l-8}(e))return;const r=d/2;let i;i=t>=l-r?l-t+r:r-t,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${t}s)`),await new Promise((e=>setTimeout(e,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${Y()}`)}var ee=class{constructor(e){this.config=e,this.bitcoinProvider=e.bitcoinProvider}async calculateBalance(e,t){const r=await this.bitcoinProvider.getBalance(t),i=await this.getAuthorizedSpendsFromContract(e),o=i.reduce(((e,t)=>e+t.satoshis),0n),a=r>o?r-o:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:o,authorizedSpendsHash:this.computeAuthorizedSpendsHash(e,i),availableUTXOs:[],availableBalance:a,vaultAddress:t,positionId:e,timestamp:Date.now()}}async calculateTrustedBalance(e,t,r){if(r)return await this.calculateBalance(e,t);const i=this.config.minConfirmations||6,o=await this.bitcoinProvider.getUTXOSet(t,i),a=await this.getAuthorizedSpendsFromContract(e);for(const e of a){if(o.utxos.some((t=>t.txid===e.txid&&t.vout===e.vout)))throw new Error(`Authorized UTXO ${e.txid}:${e.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(((e,t)=>e+t.satoshis),0n),s=o.utxos.filter((e=>!this.isUTXOAuthorized(e,a))),c=s.reduce(((e,t)=>e+t.satoshis),0n),l=this.computeAuthorizedSpendsHash(e,a);return{totalUTXOs:o.utxos,totalBalance:o.totalBalance,authorizedUTXOs:a,authorizedBalance:n,authorizedSpendsHash:l,availableUTXOs:s,availableBalance:c,vaultAddress:t,positionId:e,timestamp:Date.now()}}async getTrustedBalance(e,t){return(await this.calculateTrustedBalance(e,t)).availableBalance}async getAvailableUTXOs(e,t){return(await this.calculateTrustedBalance(e,t)).availableUTXOs}async isUTXOAvailable(e,t,r,i){return(await this.getAvailableUTXOs(e,t)).some((e=>e.txid===r&&e.vout===i))}isUTXOAuthorized(e,t){return t.some((t=>t.txid===e.txid&&t.vout===e.vout))}async getAuthorizedSpendsFromContract(e){const t=e.startsWith("0x")?e:`0x${e.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:h},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(t)).map((t=>({txid:t.txid,vout:Number(t.vout),satoshis:BigInt(t.satoshis.toString()),positionId:e,targetAddress:t.targetAddress,targetAmount:BigInt(t.targetAmount.toString()),timestamp:Number(t.authorizedAt)})))}computeAuthorizedSpendsHash(e,t){const r=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`;if(0===t.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=t.map((e=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[t,e.vout,e.satoshis.toString(),r,e.targetAmount.toString(),e.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var te=class{constructor(e){this.termManagerAddress=e.termManagerAddress,this.loanOpsManagerAddress=e.loanOpsManagerAddress,this.liquidationManagerAddress=e.liquidationManagerAddress,this.chain=e.chain,this.chainId=e.chainId,this.rpcUrl=e.rpcUrl}async getLiquidationThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const t=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:h},{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,t),o=await i.liquidationThreshold();return Number(o.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",e.message),new Error(`Failed to fetch liquidation threshold: ${e.message}`)}}async getTermFees(e){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:h},{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(e);return{originationFeeBps:Number(a.originationFee?.toString?.()??a[0]?.toString?.()??a[0]),extensionFeeBps:Number(a.extensionFee?.toString?.()??a[1]?.toString?.()??a[1])}}catch(e){throw console.error("[ProtocolParameters] Error fetching term fees:",e.message),new Error(`Failed to fetch term fees: ${e.message}`)}}async getAuthorizedSpendsHash(e){try{const t=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:h},{name:"any",chainId:this.chainId}),i=e.startsWith("0x")?e:`0x${e.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(e){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",e.message),new Error(`Failed to fetch authorized spends hash: ${e.message}`)}}async getMaxEscalatedThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const t=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:h},{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,t),o=await i.maxEscalatedThreshold();return Number(o.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",e.message),new Error(`Failed to fetch max escalated threshold: ${e.message}`)}}};function re(e){return new te(e)}var ie=class{constructor(e){this.config=e}async getVaultSnapshot(e){const t=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${t.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,o]=r?this.buildStubbedBtcSnapshotInputs(t):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,t.vaultAddress),this.config.priceOracle.getBTCPrice()]),a=re({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??t.selectedTerm,[s,c,l]=await Promise.all([a.getLiquidationThreshold(),a.getMaxEscalatedThreshold(),a.getTermFees(n)]),d=X(t.termStartTimestamp,t.selectedTerm),u=j(d.isExpired,d.daysIntoGracePeriod,s,c),h=H(i.availableBalance,o,t.ucdDebt),p=h.collateralRatioBps<u,g=h.collateralRatioBps-u;return{positionId:t.positionId,pkpId:t.pkpId,borrower:t.borrower,vaultAddress:t.vaultAddress,ucdDebt:t.ucdDebt,termStartTimestamp:t.termStartTimestamp,selectedTerm:t.selectedTerm,status:t.status,expiryAt:t.expiryAt,previousExpiryAt:t.previousExpiryAt,totalTerm:t.totalTerm,lastRenewedAt:t.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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(e){const t=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${t.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,o]=r?this.buildStubbedBtcSnapshotInputs(t):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,t.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),a=re({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??t.selectedTerm,[s,c,l]=await Promise.all([a.getLiquidationThreshold(),a.getMaxEscalatedThreshold(),a.getTermFees(n)]),d=X(t.termStartTimestamp,t.selectedTerm),u=j(d.isExpired,d.daysIntoGracePeriod,s,c),h=H(i.availableBalance,o,t.ucdDebt),p=h.collateralRatioBps<u,g=h.collateralRatioBps-u;return{positionId:t.positionId,pkpId:t.pkpId,borrower:t.borrower,vaultAddress:t.vaultAddress,ucdDebt:t.ucdDebt,termStartTimestamp:t.termStartTimestamp,selectedTerm:t.selectedTerm,status:t.status,expiryAt:t.expiryAt,previousExpiryAt:t.previousExpiryAt,totalTerm:t.totalTerm,lastRenewedAt:t.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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(e){const t=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:t,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[e.positionId,[]])),availableUTXOs:[],availableBalance:t,vaultAddress:e.vaultAddress,positionId:e.positionId,timestamp:Date.now()},r]}async queryPositionState(e){const t=e.startsWith("0x")?e:`0x${e.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:h},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(t),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",t),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: ${t}`);const l=Number(s.expiryAt),d=Number(s.selectedTerm),u=Number(s.totalTerm),p=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),m=(f=d,0===(w=l)?0:w-30*f*86400);var w,f;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,P(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:d,status:c,expiryAt:l,previousExpiryAt:p,totalTerm:u,lastRenewedAt:g}}parseVaultAddress(e,t){try{const r=JSON.parse(e);if("object"==typeof r&&null!==r){if("sepolia"===t.toLowerCase())return r.regtest||r.testnet||r.mainnet;const e=function(e){return y[e]}(t);return"testnet"===e&&(r.testnet||r.regtest)||r.mainnet}}catch(e){}return e}async isLiquidatable(e){return(await this.getVaultSnapshot(e)).isLiquidatable}async getCollateralRatio(e){return(await this.getVaultSnapshot(e)).collateralRatioBps}async getAvailableBalance(e){return(await this.getVaultSnapshot(e)).availableBTCSats}async hasSufficientCollateral(e,t,r){const i=await this.getVaultSnapshot(e);return function(e,t,r,i){const o=t+r;return 0n===o||Number(e*n*10000n/o)>=i}(i.collateralValueUsd,i.ucdDebt,t,r)}};var oe={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 ae=[{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"}],ne=[{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 se(e,t){const r=66===t.length?"0x"+t.slice(-40):t;try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:e}),i="string"==typeof t?t:String(t??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(e){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${t}): ${e?.message??String(e)}`)}}async function ce(e){const{policy:t,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:o}=e;if(t.allowArbitraryBitcoinProvider){if(!o)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:o,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork}]}if(!i)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${t.chain}"`);return async function(e,t,r){if(e.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(e,t,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!t)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,ae,t),[o,a]=await i.getProviders(e),n=[];for(let e=0;e<o.length;e++)n.push({providerId:o[e],ciphertext:a[e].ciphertext,pkpId:a[e].pkpId,addedAt:Number(a[e].addedAt)});return n}(e.chainId,t,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${e.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(e){const{chainId:t,ethersProvider:r,registryAddress:i}=e;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,ne,r);let s;try{s=await n.isAllowedCid(t,a)}catch(e){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${e?.message??String(e)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${t} (cidHash=${a.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:e.chainId,ethersProvider:t,registryAddress:r});const o=[];for(const t of i){const r=await se(t.ciphertext,t.pkpId),{url:i,auth:a}=_(r);o.push({name:`Registry Provider ${t.providerId.slice(0,10)}`,url:i,auth:a,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork})}return o}(t,r,i)}async function le(e,t,r,i){return t.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${t.length} provider(s) registered`),null):async function(e,t,r,i){if(0===t.length)throw new Error("readConsensusBalance: at least one provider is required");const o=i??(e=>new z({providerUrl:e.url,auth:e.auth,...r?{timeout:r}:{}})),a=await Promise.allSettled(t.map((t=>o(t).getBalance(e)))),n=a.map(((e,r)=>({r:e,name:t[r].name}))).filter((e=>"rejected"===e.r.status)).map((({r:e,name:t})=>`${t} \u2192 ${e.reason?.message??String(e.reason)}`));if(n.length>0)throw new Error(`Bitcoin balance read failed for ${e} on ${n.length}/${t.length} provider(s): ${n.join("; ")}`);const s=a.map((e=>e.value)),c=s[0],l=s.map(((e,r)=>({bal:e,name:t[r].name}))).slice(1).filter((e=>e.bal!==c)).map((e=>`${t[0].name}=${c.toString()} vs ${e.name}=${e.bal.toString()}`));if(l.length>0)throw new Error(`Bitcoin provider balance mismatch for ${e}: ${l.join("; ")}`);t.length>1&&console.log(` \u2705 Consensus reached across ${t.length} providers (${c.toString()} sats)`);return c}(e,t,r,i)}var de,ue="liquidate-position";async function main(e){for(const[t,r]of Object.entries(e))globalThis[t]=r;console.log("[Liquidation Validator] ========================================"),console.log("[Liquidation Validator] DEBUG: Received globalThis parameters:"),console.log("[Liquidation Validator] globalThis.contractAddresses:",globalThis.contractAddresses),console.log("[Liquidation Validator] globalThis.contractAddresses:",globalThis.contractAddresses),console.log("[Liquidation Validator] globalThis.positionId:",globalThis.positionId),console.log("[Liquidation Validator] ========================================");let t,r,i,o,a,n,d="0";try{let e,f,y,b,A,$;d="0a",console.log("[Step 0a] Validating configuration..."),console.log("[Liquidation Validator] Starting parameter access..."),console.log("[Liquidation Validator] globalThis keys:",Object.keys(globalThis));const S=globalThis;console.log("[Liquidation Validator] Final params keys:",Object.keys(S)),console.log("[Liquidation Validator] params.priceProviders:",S.priceProviders),e=S.chain,f=S.positionId,y=S.contractAddresses,b=S.rpcUrl,A=S.priceProviders,$=S.liquidatorAddress;const I=S.liquidatorIntent;if(console.log("[Liquidation Validator] Extracted priceProviders:",A),!e)throw new Error(`Missing required parameter: "chain". Available in globalThis: ${Object.keys(globalThis)}`);if(!f)throw new Error(`Missing required parameter: "positionId". Available in globalThis: ${Object.keys(globalThis)}`);if(!$)throw new Error(`Missing required parameter: "liquidatorAddress". Available in globalThis: ${Object.keys(globalThis)}`);d="0b";const C=function(e){const t=P(e),r=oe[t];if(!r)throw new Error(`No chain policy registered for "${e}"`);return r}(e),k=C.chain;let B,x,M;if(d="0c",!y||"object"!=typeof y)throw new Error("Missing or invalid 'contractAddresses' parameter");if(r=y.PositionManager,i=y.LoanOperationsManagerModule,o=y.LiquidationManagerModule??y.LiquidationManager??"",a=y.BTCSpendAuthorizer||i,!r||!i||!o)throw new Error("Missing one or more required contract addresses (PositionManager, LoanOperationsManagerModule, LiquidationManagerModule)");b&&"string"==typeof b?(!function(e,t){if(e.allowArbitraryEvmRpc)return;if(!t||"string"!=typeof t)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(t).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!v.some((e=>r===e||r.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(C,b),console.log(` Using RPC URL override: ${function(e){if(null==e||"string"!=typeof e)return"[missing]";let t=e.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const e=new URL(t);(e.username||e.password)&&(e.username="",e.password="",t=e.toString())}catch{}return t}(b)}`),M=b):(M=await Lit.Actions.getRpcUrl({chain:e}),console.log(` Using LIT-provided RPC URL for chain: ${e}`)),t=new ethers.providers.JsonRpcProvider(M),x=await ce({policy:C,ethersProvider:t,registryAddress:y.BitcoinProviderRegistry,devBitcoinProviderUrl:S.devBitcoinProviderUrl}),B=x[0],console.log(` \u2705 Bitcoin Provider: ${B.name} (min confs ${B.minConfirmations})`);!function(e,t){const r=E[e],i=[];for(const e of r)t[e]&&i.push(e);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:e,paused:i,status:t}))}("liquidation",await U(t,r));const D=await async function(e){if(!e)return e;const t=[];for(const i of e){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let e,o;if(i.pkpId&&"string"==typeof i.pkpId){const t=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(e=await J(i.name,"apiKey",t,i.apiKey)),i.apiSecret&&(o=await J(i.name,"apiSecret",t,i.apiSecret))}else e=i.apiKey,o=i.apiSecret;t.push({name:i.name,apiKey:e,apiSecret:o})}var r;return t}(S.priceProviders),O=!0===globalThis.devPriceMode;if(O&&!C.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${C.chain}`);const q=new W(D,void 0,void 0,{devSingleProvider:O&&C.allowDevSinglePriceProvider}),R=new z({providerUrl:B.url,auth:B.auth}),L=(h={contractAddress:a,chain:e,chainId:C.chainId,rpcUrl:b,bitcoinProvider:R,minConfirmations:B.minConfirmations},new ee(h)),N=function(e){return new ie(e)}({contractAddress:r,termManagerAddress:y.TermManagerModule,loanOpsManagerAddress:i,liquidationManagerAddress:o,chain:e,chainId:T(k),rpcUrl:b,vaultBalance:L,priceOracle:q});d="0d",console.log("[Step 0d] Canonicalizing positionId...");const _=function(e){if("string"!=typeof e)throw new Error("positionId must be a string");const t=e.trim(),r=/^0x/i.test(t)?t.slice(2):t;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()}(f);console.log(` \u2705 Canonical positionId: ${_}`),d="0e";const F=T(k),V=ethers.utils.getAddress($);if(!I||"number"!=typeof I.timestamp||"number"!=typeof I.chainId||"string"!=typeof I.signature)throw new Error("Missing liquidatorIntent {timestamp, chainId, signature} \u2014 required to bind the LIT signature to the calling liquidator");if(I.chainId!==F)throw new Error(`liquidatorIntent.chainId (${I.chainId}) does not match target chain (${F})`);await Z();try{!function(e,t,r){const i=t??Math.floor(Date.now()/1e3),o=Q(i),a=Q(e);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.`)}(I.timestamp)}catch(e){throw new Error(`liquidatorIntent.timestamp outside valid quantum window: ${e.message||e}`)}const X=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(ue)),j=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","address","bytes32"],[_,I.timestamp,I.chainId,V,X]),H=ethers.utils.recoverAddress(ethers.utils.hashMessage(ethers.utils.arrayify(j)),I.signature);if(H.toLowerCase()!==V.toLowerCase())throw new Error(`liquidatorIntent signature does not recover to liquidatorAddress (recovered=${H}, expected=${V})`);if(console.log(` \u2705 Liquidator intent verified for ${V}`),d="1",console.log("[Step 1] Getting vault snapshot..."),n=await N.getVaultSnapshot(_),await le(n.vaultAddress,x),n.btcPriceUsd<s||n.btcPriceUsd>c)throw new Error(`Bitcoin price ${n.btcPriceUsd} is outside acceptable range (${s} - ${c}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(n.btcPriceUsd)/1e8).toFixed(2)}`),d="2",console.log("[Step 2] Validating position state...");if(![2,3,4].includes(n.status))throw new Error(`Invalid position status for liquidation: ${p(n.status)}. Must be ACTIVE, EXPIRED, or LIQUIDATABLE.`);if(console.log(` \u2705 Position status valid for liquidation: ${p(n.status)}`),d="3",console.log("[Step 3] Checking liquidation eligibility..."),!n.isLiquidatable)throw new Error(`Position is not liquidatable (${G(n.collateralRatioBps)}% >= ${G(n.currentLiquidationThreshold)}%) - liquidation rejected.`);console.log(" \u2705 Position is liquidatable"),console.log(` - Current ratio: ${G(n.collateralRatioBps)}%`),console.log(` - Liquidation threshold: ${G(n.currentLiquidationThreshold)}%`),d="4",console.log("[Step 4] Building authorization EIP-712 digest...");const K=Y()+u,te=F,re=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(g)),ae={name:m,version:w,chainId:te,verifyingContract:ethers.utils.getAddress(o)},ne={LiquidationAuthorization:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"btcVaultBalance",type:"uint256"},{name:"vaultAddress",type:"string"},{name:"liquidator",type:"address"}]},se={actionTag:re,positionId:_,quantumTimestamp:K,btcPrice:n.btcPriceUsd.toString(),btcVaultBalance:n.availableBTCSats.toString(),vaultAddress:n.vaultAddress,liquidator:V};d="5",console.log("[Step 5] Signing authorization...");const de=globalThis.validatorWalletAddress;if(!de||!de.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const he=await Lit.Actions.getPrivateKey({pkpId:de}),pe="string"==typeof he?he.startsWith("0x")?he:`0x${he}`:String(he),ge=new ethers.Wallet(pe),me=await ge._signTypedData(ae,ne,se);return console.log("[Liquidation Validator] \u2705 Complete"),{approved:!0,positionId:_,btcPrice:n.btcPriceUsd.toString(),btcAmountSats:n.availableBTCSats.toString(),signature:me,timestamp:K,validatorPkp:ge.address,liquidatorAddress:V}}catch(e){throw console.error("[Liquidation Validator] \u274c Failed:",e.message),console.error(`[Liquidation Validator] Failed at step: ${d}`),e}var h}return de=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||e(o,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return o})(e({},"__esModule",{value:!0}),de)})();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
|
+
0f42e9f8984433fef95875d35eb3c8d985e7ce15ad309e6aa1093d6fd1ba0bb5
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "liquidation-validator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 130556,
|
|
4
|
+
"minifiedSize": 58444,
|
|
5
|
+
"compressionRatio": 0.5523453537179448,
|
|
6
|
+
"hash": "0f42e9f8984433fef95875d35eb3c8d985e7ce15ad309e6aa1093d6fd1ba0bb5",
|
|
7
|
+
"buildTime": 1781559388037,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function a(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 n(...t){a()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{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,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}},l=class{static create(t="LIT Action",e){return a(e)?new c(t):new s}},d=11e3,u=1000000000000000000n,h=1000000000000n,p=100000000000000n,m=60,g=8e3,y="DiamondHands.Protocol",w="1",f="balance-confirmation",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),b={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],A={ethereum:1,sepolia:11155111,hardhat:1337};function E(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(v).join(", ")}`)}function S(t){return A[t]}function $(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function P(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function I(t){return t instanceof Error&&"AbortError"===t.name}var C=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),n(`[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"),I(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: ${P(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: ${P(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${P(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,s]=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),n(`[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}`),!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 l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${P(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,a);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),I(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(P(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${P(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),n(`[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 s=a.chain_stats.funded_txo_sum,c=a.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 l=BigInt(s-c);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),I(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=P(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=P(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),n(`[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),I(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(P(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),I(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},B=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}};B.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],B.REQUIRED_PROVIDER_COUNT=3;var x=B;async function U(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}`)}}var D=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:g},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]))}};function k(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 O(t,e,r,i){if(!t)return r;const o=i??d,a=Math.min(e,30);return d+a*a*(o-d)/900}function R(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*u*10000n/r)}}var M=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],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:g},{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:g},{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:g},{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 N(t){return new M(t)}var _=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=N({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)]),d=k(e.termStartTimestamp,e.selectedTerm),u=O(d.isExpired,d.daysIntoGracePeriod,s,c),h=R(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,m=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:m,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=N({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)]),d=k(e.termStartTimestamp,e.selectedTerm),u=O(d.isExpired,d.daysIntoGracePeriod,s,c),h=R(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,m=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:m,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:g},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),d=Number(s.selectedTerm),u=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=Number(s.lastRenewedAt),m=(w=d,0===(y=l)?0:y-30*w*86400);var y,w;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,E(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:d,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:u,lastRenewedAt:p}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const i=await this.getVaultSnapshot(t);return function(t,e,r,i){const o=e+r;return 0n===o||Number(t*u*10000n/o)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};function q(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/m)*m;var e}var L={hardhat:{chain:"hardhat",chainId:A.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:A.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:A.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var F,V=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],X=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function z(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 H(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,V,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,X,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 z(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=$();n("[BTC Deposit Validator] Starting...");const r=e.chain,i=e.positionId,o=e.publicKey,a=q(),s=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "positionId"');if(!o)throw new Error('Missing required parameter: "publicKey"');const c=function(t){const e=E(t),r=L[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),l=c.chain,d=c.bitcoinNetwork;let u;if(s&&"string"==typeof s?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(c,s),u=s):u=await Lit.Actions.getRpcUrl({chain:r}),c.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!e.contractAddresses?.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");if(n(` \u2705 Chain: ${r} (${l})`),n(` \u2705 Bitcoin Network: ${d}`),n(` \u2705 Position ID: ${i}`),!e.contractAddresses)throw new Error('Missing required parameter: "contractAddresses" (PositionManager, LoanOperationsManagerModule, TermManagerModule)');const m=e.contractAddresses.PositionManager,g=e.contractAddresses.LoanOperationsManagerModule,v=e.contractAddresses.TermManagerModule,b=e.contractAddresses.LiquidationManagerModule??e.contractAddresses.LiquidationManager??"";if(!b)throw new Error("contractAddresses must include LiquidationManager or LiquidationManagerModule");const A=e.contractAddresses.BTCSpendAuthorizer||g;try{n("[Step 1] Getting vault snapshot...");const t=new ethers.providers.JsonRpcProvider(u);let r;r=c.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:c.minBitcoinConfirmations,network:c.bitcoinNetwork}]:await H(c,t,e.contractAddresses.BitcoinProviderRegistry),n(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const o=r[0],s=new C({providerUrl:o.url}),d=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 U(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(o=await U(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}(e.priceProviders||void 0),T=!0===globalThis.devPriceMode;if(T&&!c.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${c.chain}`);const E=new x(d,void 0,void 0,{devSingleProvider:T&&c.allowDevSinglePriceProvider}),$=function(t){return new _(t)}({contractAddress:m,termManagerAddress:v,loanOpsManagerAddress:g,liquidationManagerAddress:b,chain:l,vaultBalance:(P={contractAddress:A,chain:l,chainId:S(l),bitcoinProvider:s,minConfirmations:o.minConfirmations,rpcUrl:u},new D(P)),priceOracle:E,rpcUrl:u}),I=await $.getVaultSnapshot(i);if(I.btcPriceUsd<h||I.btcPriceUsd>p)throw new Error(`Bitcoin price ${I.btcPriceUsd} is outside acceptable range`);if(r.length>1){const t=await s.getBalance(I.vaultAddress);for(let e=1;e<r.length;e++){const i=r[e],a=new C({providerUrl:i.url}),n=await a.getBalance(I.vaultAddress);if(n!==t)throw new Error(`Bitcoin provider balance mismatch: ${o.name}=${t.toString()} vs ${i.name}=${n.toString()}`)}n(` \u2705 Consensus reached across ${r.length} providers (${t.toString()} sats)`)}n(` \u2705 Vault balance: ${I.availableBTCSats} sats`),n(` \u2705 BTC price: $${(Number(I.btcPriceUsd)/1e8).toFixed(2)}`);const B=I.vaultAddress;n("[Step 2] Signing vault data...");const k=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()}(i),O={name:y,version:w,chainId:S(l),verifyingContract:ethers.utils.getAddress(g)},R=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),M={BalanceConfirmation:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"collateralValue",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},N=globalThis.validatorWalletAddress;if(!N||!N.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const q=await Lit.Actions.getPrivateKey({pkpId:N}),L="string"==typeof q?q.startsWith("0x")?q:`0x${q}`:String(q),F=new ethers.Wallet(L),V=await F._signTypedData(O,M,{actionTag:R,positionId:k,collateralValue:I.availableBTCSats.toString(),btcPrice:I.btcPriceUsd.toString(),quantumTimestamp:a,borrower:ethers.utils.getAddress(I.borrower)});return n("[BTC Deposit Validator] \u2705 Complete"),{vaultAddress:B,vaultBalance:I.availableBTCSats.toString(),positionId:i,btcPrice:I.btcPriceUsd.toString(),signature:V,timestamp:a,validatorPkp:F.address}}catch(t){throw console.error("[BTC Deposit Validator] \u274c Failed:",t.message),t}var P}return F=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}),F)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
1
|
+
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function n(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function a(...t){n()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{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,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},l=class{static create(t="LIT Action",e){return n(e)?new c(t):new s}},d=11e3,u=1000000000000000000n,h=1000000000000n,p=100000000000000n,m=60,g=8e3,w="DiamondHands.Protocol",y="1",f="balance-confirmation",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),b={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],A={ethereum:1,sepolia:11155111,hardhat:1337};function E(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(v).join(", ")}`)}function S(t){return A[t]}function $(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function P(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function I(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 x(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 B=new Map;async function U(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=B.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((()=>B.delete(i))),B.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}var k=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await U(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"),I(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: ${P(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: ${P(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${P(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,s]=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}`),!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 l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${P(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,n);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),I(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(P(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${P(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 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 l=BigInt(s-c);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),I(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=P(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=P(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),I(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(P(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),I(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 k({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 M(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}`)}}var N=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:g},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]))}};function _(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 q(t,e,r,i){if(!t)return r;const o=i??d,n=Math.min(e,30);return d+n*n*(o-d)/900}function L(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*u*10000n/r)}}var F=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],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:g},{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:g},{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:g},{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 V(t){return new F(t)}var X=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=V({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)]),d=_(e.termStartTimestamp,e.selectedTerm),u=q(d.isExpired,d.daysIntoGracePeriod,s,c),h=L(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,m=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:m,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=V({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)]),d=_(e.termStartTimestamp,e.selectedTerm),u=q(d.isExpired,d.daysIntoGracePeriod,s,c),h=L(i.availableBalance,o,e.ucdDebt),p=h.collateralRatioBps<u,m=h.collateralRatioBps-u;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:u,isLiquidatable:p,marginToLiquidationBps:m,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:g},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),d=Number(s.selectedTerm),u=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=Number(s.lastRenewedAt),m=(y=d,0===(w=l)?0:w-30*y*86400);var w,y;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,E(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:d,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:u,lastRenewedAt:p}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const i=await this.getVaultSnapshot(t);return function(t,e,r,i){const o=e+r;return 0n===o||Number(t*u*10000n/o)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};function z(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/m)*m;var e}var H={hardhat:{chain:"hardhat",chainId:A.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:A.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:A.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var j,G=[{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"}],K=[{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 W(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 J(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,G,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,K,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 W(e.ciphertext,e.pkpId),{url:i,auth:n}=x(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=$();a("[BTC Deposit Validator] Starting...");const r=e.chain,i=e.positionId,o=e.publicKey,n=z(),s=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "positionId"');if(!o)throw new Error('Missing required parameter: "publicKey"');const c=function(t){const e=E(t),r=H[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),l=c.chain,d=c.bitcoinNetwork;let u;if(s&&"string"==typeof s?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(c,s),u=s):u=await Lit.Actions.getRpcUrl({chain:r}),c.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!e.contractAddresses?.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");if(a(` \u2705 Chain: ${r} (${l})`),a(` \u2705 Bitcoin Network: ${d}`),a(` \u2705 Position ID: ${i}`),!e.contractAddresses)throw new Error('Missing required parameter: "contractAddresses" (PositionManager, LoanOperationsManagerModule, TermManagerModule)');const m=e.contractAddresses.PositionManager,g=e.contractAddresses.LoanOperationsManagerModule,v=e.contractAddresses.TermManagerModule,b=e.contractAddresses.LiquidationManagerModule??e.contractAddresses.LiquidationManager??"";if(!b)throw new Error("contractAddresses must include LiquidationManager or LiquidationManagerModule");const A=e.contractAddresses.BTCSpendAuthorizer||g;try{a("[Step 1] Getting vault snapshot...");const t=new ethers.providers.JsonRpcProvider(u);let r;r=c.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:c.minBitcoinConfirmations,network:c.bitcoinNetwork}]:await J(c,t,e.contractAddresses.BitcoinProviderRegistry),a(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const o=r[0],s=new k({providerUrl:o.url,auth:o.auth}),d=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 M(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(o=await M(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}(e.priceProviders||void 0),T=!0===globalThis.devPriceMode;if(T&&!c.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${c.chain}`);const E=new R(d,void 0,void 0,{devSingleProvider:T&&c.allowDevSinglePriceProvider}),$=function(t){return new X(t)}({contractAddress:m,termManagerAddress:v,loanOpsManagerAddress:g,liquidationManagerAddress:b,chain:l,vaultBalance:(P={contractAddress:A,chain:l,chainId:S(l),bitcoinProvider:s,minConfirmations:o.minConfirmations,rpcUrl:u},new N(P)),priceOracle:E,rpcUrl:u}),I=await $.getVaultSnapshot(i);if(I.btcPriceUsd<h||I.btcPriceUsd>p)throw new Error(`Bitcoin price ${I.btcPriceUsd} is outside acceptable range`);await D(I.vaultAddress,r),a(` \u2705 Vault balance: ${I.availableBTCSats} sats`),a(` \u2705 BTC price: $${(Number(I.btcPriceUsd)/1e8).toFixed(2)}`);const C=I.vaultAddress;a("[Step 2] Signing vault data...");const x=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()}(i),B={name:w,version:y,chainId:S(l),verifyingContract:ethers.utils.getAddress(g)},U=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),O={BalanceConfirmation:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"collateralValue",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},_=globalThis.validatorWalletAddress;if(!_||!_.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const q=await Lit.Actions.getPrivateKey({pkpId:_}),L="string"==typeof q?q.startsWith("0x")?q:`0x${q}`:String(q),F=new ethers.Wallet(L),V=await F._signTypedData(B,O,{actionTag:U,positionId:x,collateralValue:I.availableBTCSats.toString(),btcPrice:I.btcPriceUsd.toString(),quantumTimestamp:n,borrower:ethers.utils.getAddress(I.borrower)});return a("[BTC Deposit Validator] \u2705 Complete"),{vaultAddress:C,vaultBalance:I.availableBTCSats.toString(),positionId:i,btcPrice:I.btcPriceUsd.toString(),signature:V,timestamp:n,validatorPkp:F.address}}catch(t){throw console.error("[BTC Deposit Validator] \u274c Failed:",t.message),t}var P}return j=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}),j)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
da3750a70e532b87f3590a3e2d8c2d51e700589f6e111bb291384ab01304af35
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "loan-vault-btc-balance",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 110593,
|
|
4
|
+
"minifiedSize": 48397,
|
|
5
|
+
"compressionRatio": 0.5623864078196631,
|
|
6
|
+
"hash": "da3750a70e532b87f3590a3e2d8c2d51e700589f6e111bb291384ab01304af35",
|
|
7
|
+
"buildTime": 1781559388205,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|