@gvnrdao/dh-lit-actions 0.0.309 → 0.0.310

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/btc-address-balance.action.js +1 -1
  9. package/dist/btc-address-balance.hash +1 -1
  10. package/dist/btc-address-balance.meta.json +5 -5
  11. package/dist/btc-transaction-signer.action.js +1 -1
  12. package/dist/btc-transaction-signer.hash +1 -1
  13. package/dist/btc-transaction-signer.meta.json +5 -5
  14. package/dist/btc-utxo-invalidator.action.js +1 -1
  15. package/dist/btc-utxo-invalidator.hash +1 -1
  16. package/dist/btc-utxo-invalidator.meta.json +5 -5
  17. package/dist/btc-withdrawal.action.js +1 -1
  18. package/dist/btc-withdrawal.hash +1 -1
  19. package/dist/btc-withdrawal.meta.json +5 -5
  20. package/dist/encrypt-parameter.meta.json +1 -1
  21. package/dist/extend-position-validator.action.js +1 -1
  22. package/dist/extend-position-validator.hash +1 -1
  23. package/dist/extend-position-validator.meta.json +5 -5
  24. package/dist/liquidation-validator.action.js +1 -1
  25. package/dist/liquidation-validator.hash +1 -1
  26. package/dist/liquidation-validator.meta.json +5 -5
  27. package/dist/loan-vault-btc-balance.action.js +1 -1
  28. package/dist/loan-vault-btc-balance.hash +1 -1
  29. package/dist/loan-vault-btc-balance.meta.json +5 -5
  30. package/dist/pkp-validator.meta.json +1 -1
  31. package/dist/price-oracle.meta.json +1 -1
  32. package/dist/process-payment-validator.action.js +1 -1
  33. package/dist/process-payment-validator.hash +1 -1
  34. package/dist/process-payment-validator.meta.json +5 -5
  35. package/dist/stale-spend-recovery-validator.action.js +1 -1
  36. package/dist/stale-spend-recovery-validator.hash +1 -1
  37. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  38. package/dist/ucd-mint-validator.action.js +1 -1
  39. package/dist/ucd-mint-validator.hash +1 -1
  40. package/dist/ucd-mint-validator.meta.json +5 -5
  41. package/package.json +1 -1
  42. package/pkg-dist/pkg-src/index.js +138 -65
  43. package/pkg-dist/pkg-src/index.js.map +4 -4
  44. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +7 -0
  45. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
  46. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +5 -0
  47. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
  48. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts +23 -2
  49. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts.map +1 -1
  50. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts +8 -1
  51. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
  52. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts +70 -0
  53. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts.map +1 -0
  54. package/pkg-dist/src/modules/bitcoin-provider-registry.d.ts.map +1 -1
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,u=100000000000000n,l=60,d=86400,h=30,p=12,m=365,g=8e3;function w(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 f="DiamondHands.Protocol",y="1",b="mint-ucd",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),P={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],A={ethereum:1,sepolia:11155111,hardhat:1337};function S(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 E(t){return A[t]}function $(t){return Math.floor(t/l)*l}async function I(){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>=52}(t))return;let r;r=e>=52?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${$(Math.floor(Date.now()/1e3))}`)}var C=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await I();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=$(i),o=$(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return t.action===b&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function B(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){B()&&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}},k=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 n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}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}},x=class{static create(t="LIT Action",e){return B(e)?new k(t):new D}};function U(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function O(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function R(t){return t instanceof Error&&"AbortError"===t.name}var N=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=x.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),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 n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.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 o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),R(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: ${O(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: ${O(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${O(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 n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(a),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,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),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: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${O(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),R(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(O(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${O(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 n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,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,n=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(n),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 o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=o.chain_stats.funded_txo_sum,s=o.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(n),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=O(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=O(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(),n=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)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(O(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 n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function L(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=Math.floor(Date.now()/1e3),i=e*h,n=r-t,o=Math.floor(n/d);return{termDurationDays:o,termLengthDays:i,isExpired:o>i,daysUntilExpiry:Math.max(0,i-o),daysIntoGracePeriod:Math.max(0,o-i)}}function q(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function _(t,e,r){const i=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}function F(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function z(t){return t/100}var V=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.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 n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.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(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.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(o.apiKey,n++));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,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}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,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),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}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},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 n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};V.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],V.REQUIRED_PROVIDER_COUNT=3;var H=V;async function X(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}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),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,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,n=await this.bitcoinProvider.getUTXOSet(e,i),o=await this.getAuthorizedSpendsFromContract(t);for(const t of o){if(n.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=o.reduce(((t,e)=>t+e.satoshis),0n),s=n.utxos.filter((t=>!this.isUTXOAuthorized(t,o))),c=s.reduce(((t,e)=>t+e.satoshis),0n),u=this.computeAuthorizedSpendsHash(t,o);return{totalUTXOs:n.utxos,totalBalance:n.totalBalance,authorizedUTXOs:o,authorizedBalance:a,authorizedSpendsHash:u,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),n=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 n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var G=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),n=await i.liquidationThreshold();return Number(n.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"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[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")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.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),n=await i.maxEscalatedThreshold();return Number(n.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 K(t){return new G(t)}var W=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,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),o=K({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,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=L(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=_(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.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,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),o=K({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,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=L(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=_(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.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),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{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 u=Number(s.expiryAt),l=Number(s.selectedTerm),p=Number(s.totalTerm),m=Number(s.previousExpiryAt),w=Number(s.lastRenewedAt),f=(b=l,0===(y=u)?0:y-b*h*d);var y,b;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,S(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:f,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:p,lastRenewedAt:w}}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 P[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 n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var J="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",Q={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function Y(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var Z=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),tt=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)"]),et=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),rt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function it(t,e,r){return t.call({to:e,data:r})}async function nt(t,e){const r=new ethers.utils.Interface([J]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([J]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?Y({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]}):Y(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await it(t,e,Z.encodeFunctionData("views",[])),[i]=Z.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([it(t,e,Z.encodeFunctionData("paused",[])),it(t,e,Z.encodeFunctionData("liquidationPaused",[])),it(t,e,Z.encodeFunctionData("simplePsm",[])),it(t,i,tt.encodeFunctionData("core",[])),it(t,i,tt.encodeFunctionData("loanOps",[])),it(t,i,tt.encodeFunctionData("collateralManager",[])),it(t,i,tt.encodeFunctionData("liquidationManager",[])),it(t,i,tt.encodeFunctionData("circuitBreaker",[]))]),h=Z.decodeFunctionResult("paused",n)[0],p=Z.decodeFunctionResult("liquidationPaused",o)[0],m=Z.decodeFunctionResult("simplePsm",a)[0],g=tt.decodeFunctionResult("core",s)[0],w=tt.decodeFunctionResult("loanOps",c)[0],f=tt.decodeFunctionResult("collateralManager",u)[0],y=tt.decodeFunctionResult("liquidationManager",l)[0],b=tt.decodeFunctionResult("circuitBreaker",d)[0],v=await it(t,w,et.encodeFunctionData("getUcdController",[])),P=await it(t,w,et.encodeFunctionData("ucdToken",[])),T=et.decodeFunctionResult("getUcdController",v)[0],A=et.decodeFunctionResult("ucdToken",P)[0],S=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await it(t,e,rt.encodeFunctionData("paused",[]));return rt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,$,I,C,B,M,D,k]=await Promise.all([S(g),S(w),S(f),S(y),S(b),S(T),S(A),S(m)]);return Y({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:M,ucdTokenPaused:D,simplePsmPaused:k})}(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})`)}}var ot={hardhat:{chain:"hardhat",chainId:A.hardhat,bitcoinNetwork:P.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:A.sepolia,bitcoinNetwork:P.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:A.ethereum,bitcoinNetwork:P.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var at,st=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],ct=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function ut(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function lt(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,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,st,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[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 n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,ct,r);let s;try{s=await a.isAllowedCid(e,o)}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=${o.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 n=[];for(const e of i){const r=await ut(e.ciphertext,e.pkpId);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=x.create("UCD Mint Validator");let r,i="init";try{const t=[{inputs:[],name:"getRemainingMintCapacity",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=[{inputs:[],name:"maxSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],s=[{inputs:[],name:"getCurrentSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],l=[{inputs:[],name:"getProtocolConfig",outputs:[{internalType:"uint256",name:"_liquidationThreshold",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueUcd",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueWei",type:"uint256"},{internalType:"uint256",name:"_maximumLoanValueUcd",type:"uint256"}],stateMutability:"view",type:"function"}];e.stepStart("0","Validating configuration");const v=U(),P=v.chain;if(!P)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');r=C.verifyAmountPositionActionAuthorizationStructure(v.auth);const A=function(t){const e=S(t),r=ot[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(P),$=A.chain,I=A.bitcoinNetwork;let B,D;if(M(` \u2705 Chain: ${P} (${$})`),M(` \u2705 Bitcoin Network: ${I}`),e.log("0","Validating contract addresses..."),e.log("0",`contractAddresses exists: ${!!v.contractAddresses}`),e.log("0","contractAddresses type: "+typeof v.contractAddresses),!v.contractAddresses||"object"!=typeof v.contractAddresses)throw e.error("0",`\u274c ERROR: No valid contractAddresses object found: ${JSON.stringify(v.contractAddresses)}`),new Error("contractAddresses is required and must include: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController");e.log("0","\u2705 Found valid contractAddresses object"),e.log("0",`Available keys: ${Object.keys(v.contractAddresses)}`);const k=v.contractAddresses.PositionManager,x=v.contractAddresses.LoanOperationsManagerModule,O=v.contractAddresses.TermManagerModule,R=v.contractAddresses.UCDController,L=v.contractAddresses.LiquidationManagerModule??v.contractAddresses.LiquidationManager??"",q=v.contractAddresses.BTCSpendAuthorizer??"",_=v.contractAddresses.BitcoinProviderRegistry;if(e.log("0","Extracted addresses:"),e.log("0",`POSITION_MANAGER_ADDRESS: ${k||"MISSING"}`),e.log("0",`LOAN_OPS_MANAGER_ADDRESS: ${x||"MISSING"}`),e.log("0",`TERM_MANAGER_ADDRESS: ${O||"MISSING"}`),e.log("0",`UCD_CONTROLLER_ADDRESS: ${R||"MISSING"}`),!(k&&x&&O&&R&&L))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");M(" \u2705 Contract addresses loaded and validated"),M(` PositionManager: ${k}`),M(` LoanOpsManager: ${x}`),e.stepEnd("0"),M("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const V=BigInt(r.amount);if(V<=0n)throw new Error(`Amount must be positive, got: ${V.toString()} wei`);M(" Fetching protocol mint limits..."),e.log("0","Fetching protocol mint limits...");const G=v.rpcUrl;let K;G&&"string"==typeof G?(!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(", ")}`)}(A,G),M(` 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}(G)}`),K=G):(K=await Lit.Actions.getRpcUrl({chain:P}),M(` Using LIT-provided RPC URL for chain: ${P}`));const J=new ethers.providers.JsonRpcProvider({url:K,timeout:g});D=await lt({policy:A,ethersProvider:J,registryAddress:_,devBitcoinProviderUrl:v.devBitcoinProviderUrl}),B=D[0],M(` \u2705 Bitcoin Provider: ${B.name} (min confs ${B.minConfirmations})`);!function(t,e){const r=Q[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}))}("mintUcd",await nt(J,k));const Y=new ethers.Contract(x,l,J);let Z,tt;try{const t=await Y.getProtocolConfig();Z=BigInt(t[2].toString());tt=1000000000000000000n*BigInt(t[3].toString()),M(" \u2705 Protocol limits loaded from LoanOperationsManager (consolidated call)"),M(` - Minimum: ${Z.toString()} wei`),M(` - Maximum: ${tt.toString()} wei`),e.log("0","\u2705 Protocol limits loaded from LoanOperationsManager")}catch(t){const r=t?.message||String(t);throw M(` \u274c Failed to get protocol config (${r}); refusing to sign`),e.log("0","\u274c Protocol config unavailable \u2014 refusing to mint"),new Error(`getProtocolConfig failed; cannot validate mint limits: ${r}`)}if(V<Z)throw new Error(`Amount too small: ${V.toString()} wei. Minimum: ${Z.toString()} wei`);if(V>tt)throw new Error(`Amount too large: ${V.toString()} wei. Maximum: ${tt.toString()} wei`);const et=v.publicKey;if(!et)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof et||0===et.length)throw new Error("Invalid publicKey: must be non-empty string");i="0.5",M("[UCD Mint Validator] Started"),M(` Position: ${r.positionId}`),M(` Amount: ${V.toString()} wei`),e.log("0","Validator Started");const rt=new N({providerUrl:B.url,timeout:8e3}),it=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,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await X(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await X(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(v.priceProviders),at=!0===globalThis.devPriceMode;if(at&&!A.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${A.chain}`);const st=new H(it,void 0,void 0,{devSingleProvider:at&&A.allowDevSinglePriceProvider}),ct=(n={contractAddress:q||x,chain:P,chainId:E($),rpcUrl:G,bitcoinProvider:rt,minConfirmations:B.minConfirmations},new j(n));if(i="1",M("[Step 1] Getting vault snapshot..."),e.stepStart("1","Getting vault snapshot"),v.debugOverrides?.useStubbedBtcData&&31337!==E($))throw new Error("debugOverrides.useStubbedBtcData is not permitted on live networks");const ut=function(t){return new W(t)}({contractAddress:k,termManagerAddress:O,loanOpsManagerAddress:x,liquidationManagerAddress:L,chain:P,chainId:E($),rpcUrl:G,vaultBalance:ct,priceOracle:st,debugOverrides:v.debugOverrides}),dt=await ut.getVaultSnapshot(r.positionId);if(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 n=i??(t=>new N(r?{providerUrl:t,timeout:r}:{providerUrl:t})),o=e[0],a=await n(o.url).getBalance(t);for(let r=1;r<e.length;r++){const i=e[r],s=await n(i.url).getBalance(t);if(s!==a)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${o.name}=${a.toString()} vs ${i.name}=${s.toString()}`)}return console.log(` \u2705 Consensus reached across ${e.length} providers (${a.toString()} sats)`),a}(dt.vaultAddress,D,8e3),dt.btcPriceUsd<c||dt.btcPriceUsd>u)throw new Error(`Bitcoin price ${dt.btcPriceUsd} is outside acceptable range (${c} - ${u}). This may indicate oracle manipulation or stale price data. Please try again later.`);M(` \u2705 BTC price validation passed: $${(Number(dt.btcPriceUsd)/1e8).toFixed(2)}`),e.stepEnd("1"),i="2",M("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticating caller");if(!await C.verifyMintAuthorization(r,dt.borrower,E($),J,v.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");M(" \u2705 Caller authorized"),e.stepEnd("2"),i="3",M("[Step 3] Validating position state..."),e.stepStart("3","Validating position state");if(![0,1,2].includes(dt.status))throw new Error(`Invalid position status for minting: ${w(dt.status)}. Must be PENDING_DEPOSIT, PENDING_MINT, or ACTIVE. Current status prevents minting operations.`);if(M(` \u2705 Position status valid for minting: ${w(dt.status)}`),dt.isExpired)throw new Error(`Loan term expired ${dt.daysIntoGracePeriod} days ago - minting rejected. Must repay or extend term first.`);if(dt.isLiquidatable)throw new Error(`Position is liquidatable (${z(dt.collateralRatioBps)}% < ${z(dt.currentLiquidationThreshold)}%) - minting rejected. Add collateral first.`);M(" \u2705 Position is healthy"),M(` - Term: ${dt.daysUntilExpiry} days remaining`),M(` - Current ratio: ${z(dt.collateralRatioBps)}%`),M(` - Liquidation threshold: ${z(dt.currentLiquidationThreshold)}%`),e.stepEnd("3"),i="4",M("[Step 4] Calculating fees..."),e.stepStart("4","Calculating fees");let ht=function(t,e){if(t<0n)throw new Error("Amount cannot be negative");if(e<0||e>1e4)throw new Error("Fee basis points must be between 0 and 10000 (0% to 100%)");return t*BigInt(e)/10000n}(V,dt.originationFeeBps);const pt=Number(r.timestamp),mt=dt.previousExpiryAt??0,gt=dt.totalTerm??0;if(mt>0&&pt<mt){const t=BigInt(mt)-BigInt(pt),e=gt-(dt.selectedTerm??0),r=BigInt(e===p?m*d:e*h*d);if(0n===r)throw new Error(`Scenario B tail fee: original term length is zero (totalTerm=${gt}, selectedTerm=${dt.selectedTerm??0}). Cannot compute tail fee.`);const i=t*BigInt(dt.originationFeeBps)*V/(10000n*r);ht+=i,M(` Scenario B tail fee: ${i.toString()} wei (${e}mo original term, ${t}s remaining)`)}M(` Mint fee: ${ht.toString()} wei (${z(dt.originationFeeBps)}% base${mt>0&&pt<mt?" + tail":""})`),e.stepEnd("4"),i="4a",M("[Step 4a & 4b] Validating capacity limits..."),e.stepStart("4ab","Validating capacity limits");const wt=V+ht,ft=new ethers.Contract(R,[...t,...o,...s],J),[yt,bt,vt]=await Promise.all([ft.getRemainingMintCapacity(),ft.maxSupply(),ft.getCurrentSupply()]),Pt=BigInt(yt.toString()),Tt=BigInt(bt.toString()),At=BigInt(vt.toString());if(wt>Pt)throw new Error(`Daily mint limit would be exceeded: attempting to mint ${wt.toString()} wei (${V.toString()} + ${ht.toString()} fee), but only ${Pt.toString()} wei remaining in daily capacity`);if(M(" \u2705 Daily mint limit check passed"),M(` - Mint amount (with fee): ${wt.toString()} wei`),M(` - Remaining capacity: ${Pt.toString()} wei`),Tt>0n){const t=At+wt;if(t>Tt)throw new Error(`Max supply would be exceeded: minting ${wt.toString()} wei (${V.toString()} + ${ht.toString()} fee) would result in total supply of ${t.toString()} wei, exceeding max supply of ${Tt.toString()} wei`);M(" \u2705 Max supply check passed"),M(` - Current supply: ${At.toString()} wei`),M(` - After mint: ${t.toString()} wei`),M(` - Max supply: ${Tt.toString()} wei`),M(` - Remaining capacity: ${(Tt-At).toString()} wei`)}else M(" \u2705 Max supply unlimited (not enforced)");e.stepEnd("4ab"),i="5",M("[Step 5] Calculating new state..."),e.stepStart("5","Calculating new state");const St=dt.ucdDebt+V+ht,Et=dt.availableBTCSats;M(` Current debt: ${dt.ucdDebt.toString()} wei`),M(` New debt: ${St.toString()} wei`),M(` Available collateral: ${Et.toString()} sats`),e.stepEnd("5"),i="6",M("[Step 6] Validating collateral ratio after mint..."),e.stepStart("6","Validating collateral ratio after mint");const $t=function(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}(Et,dt.btcPriceUsd),It=F($t,St);if(M(` New collateral ratio: ${z(It)}%`),M(` Minimum required: ${z(dt.liquidationThresholdBps)}%`),!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return F(t,e)>=r}($t,St,dt.liquidationThresholdBps))throw new Error(`Insufficient collateral: ${z(It)}% < ${z(dt.liquidationThresholdBps)}%`);M(" \u2705 Sufficient collateral");const Ct=BigInt("340282366920938463463374607431768211455");if(St>Ct)throw new Error(`New debt exceeds maximum allowed value: ${St.toString()} > ${Ct.toString()} (type(uint128).max). The contract will revert with DebtOverflow error.`);M(` \u2705 New debt within bounds: ${St.toString()} <= ${Ct.toString()}`),e.stepEnd("6"),i="7",M("[Step 7] Building authorization message..."),e.stepStart("7","Building authorization message");const Bt=dt.authorizedSpendsHash,Mt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[dt.ucdDebt])),Dt={authorizedSpendsHash:Bt,ucdDebtHash:Mt,contractBundleHash:ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[k,x,O,R])),btcPrice:dt.btcPriceUsd.toString(),mintAmount:V.toString(),mintFee:ht.toString(),newCollateral:Et.toString(),newDebt:St.toString()};if(r.action!==b)throw new Error(`Invalid mint authorization action: expected "${b}", got "${r.action}"`);const kt=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()}(r.positionId),xt=E($),Ut={name:f,version:y,chainId:xt,verifyingContract:ethers.utils.getAddress(x)},Ot=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Rt={MintUcd:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"mintFee",type:"uint256"},{name:"newDebt",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractHash",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},Nt={actionTag:Ot,positionId:kt,mintAmount:Dt.mintAmount,mintFee:Dt.mintFee,newDebt:Dt.newDebt,newCollateral:Dt.newCollateral,btcPrice:Dt.btcPrice,authorizedSpendsHash:Dt.authorizedSpendsHash,ucdDebtHash:Dt.ucdDebtHash,contractHash:Dt.contractBundleHash,quantumTimestamp:r.timestamp,borrower:ethers.utils.getAddress(dt.borrower)};e.stepEnd("7"),i="8",e.stepStart("8","Signing authorization");const Lt=globalThis.validatorWalletAddress;if(!Lt||!Lt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const qt=await Lit.Actions.getPrivateKey({pkpId:Lt}),_t="string"==typeof qt?qt.startsWith("0x")?qt:`0x${qt}`:String(qt),Ft=new ethers.Wallet(_t),zt=await Ft._signTypedData(Ut,Rt,Nt);return e.stepEnd("8"),e.summary(),M("[UCD Mint Validator] \u2705 Complete"),{approved:!0,positionId:r.positionId,mintAmount:V.toString(),mintFee:ht.toString(),newDebt:St.toString(),newCollateral:Et.toString(),newCollateralRatioBps:It,btcPrice:dt.btcPriceUsd.toString(),authorizedSpendsHash:Bt,signature:zt,timestamp:r.timestamp,validatorPkp:Ft.address}}catch(t){throw console.error("[UCD Mint Validator] \u274c Failed:",t.message),console.error(`[UCD Mint Validator] Failed at step: ${i}`),t}var n}return at=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),at)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,u=100000000000000n,l=60,d=86400,h=30,p=12,m=365,g=8e3;function w(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 f="DiamondHands.Protocol",y="1",b="mint-ucd",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),P={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],S={ethereum:1,sepolia:11155111,hardhat:1337};function A(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 E(t){return S[t]}function $(t){return Math.floor(t/l)*l}async function I(){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>=52}(t))return;let r;r=e>=52?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${$(Math.floor(Date.now()/1e3))}`)}var C=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await I();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=$(i),o=$(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return t.action===b&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function k(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function B(...t){k()&&console.log(...t)}var M=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}},x=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 n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}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}},D=class{static create(t="LIT Action",e){return k(e)?new x(t):new M}};function U(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function O(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function R(t){return t instanceof Error&&"AbortError"===t.name}function N(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function q(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 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 t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&N(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 L=new Map;async function _(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}`,n=L.get(i);if(n)return n;const o=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,n=new AbortController,o=setTimeout((()=>n.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:n.signal})}finally{clearTimeout(o)}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 o.catch((()=>L.delete(i))),L.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}var F=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await _(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),B(`[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 n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.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 o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),R(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: ${O(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: ${O(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${O(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 n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,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,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(n),B(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${O(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),R(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(O(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${O(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 n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,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,n=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(n),B(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=o.chain_stats.funded_txo_sum,s=o.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(n),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=O(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=O(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(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),B(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.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:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(O(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 n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function z(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=Math.floor(Date.now()/1e3),i=e*h,n=r-t,o=Math.floor(n/d);return{termDurationDays:o,termLengthDays:i,isExpired:o>i,daysUntilExpiry:Math.max(0,i-o),daysIntoGracePeriod:Math.max(0,o-i)}}function V(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function H(t,e,r){const i=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}function X(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function j(t){return t/100}var G=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.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 n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.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(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.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(o.apiKey,n++));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,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}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,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),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}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},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 n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};G.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],G.REQUIRED_PROVIDER_COUNT=3;var K=G;async function W(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 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),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,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,n=await this.bitcoinProvider.getUTXOSet(e,i),o=await this.getAuthorizedSpendsFromContract(t);for(const t of o){if(n.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=o.reduce(((t,e)=>t+e.satoshis),0n),s=n.utxos.filter((t=>!this.isUTXOAuthorized(t,o))),c=s.reduce(((t,e)=>t+e.satoshis),0n),u=this.computeAuthorizedSpendsHash(t,o);return{totalUTXOs:n.utxos,totalBalance:n.totalBalance,authorizedUTXOs:o,authorizedBalance:a,authorizedSpendsHash:u,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),n=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 n.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: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),n=await i.liquidationThreshold();return Number(n.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"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[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")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.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),n=await i.maxEscalatedThreshold();return Number(n.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,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),o=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}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=z(e.termStartTimestamp,e.selectedTerm),d=V(l.isExpired,l.daysIntoGracePeriod,s,c),h=H(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.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,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPrice()]),o=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}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=z(e.termStartTimestamp,e.selectedTerm),d=V(l.isExpired,l.daysIntoGracePeriod,s,c),h=H(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.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),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{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 u=Number(s.expiryAt),l=Number(s.selectedTerm),p=Number(s.totalTerm),m=Number(s.previousExpiryAt),w=Number(s.lastRenewedAt),f=(b=l,0===(y=u)?0:y-b*h*d);var y,b;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,A(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:f,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:p,lastRenewedAt:w}}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 P[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 n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var tt="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))",et={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 rt(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 it=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),nt=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)"]),ot=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),at=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function st(t,e,r){return t.call({to:e,data:r})}async function ct(t,e){const r=new ethers.utils.Interface([tt]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([tt]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?rt({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]}):rt(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await st(t,e,it.encodeFunctionData("views",[])),[i]=it.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([st(t,e,it.encodeFunctionData("paused",[])),st(t,e,it.encodeFunctionData("liquidationPaused",[])),st(t,e,it.encodeFunctionData("simplePsm",[])),st(t,i,nt.encodeFunctionData("core",[])),st(t,i,nt.encodeFunctionData("loanOps",[])),st(t,i,nt.encodeFunctionData("collateralManager",[])),st(t,i,nt.encodeFunctionData("liquidationManager",[])),st(t,i,nt.encodeFunctionData("circuitBreaker",[]))]),h=it.decodeFunctionResult("paused",n)[0],p=it.decodeFunctionResult("liquidationPaused",o)[0],m=it.decodeFunctionResult("simplePsm",a)[0],g=nt.decodeFunctionResult("core",s)[0],w=nt.decodeFunctionResult("loanOps",c)[0],f=nt.decodeFunctionResult("collateralManager",u)[0],y=nt.decodeFunctionResult("liquidationManager",l)[0],b=nt.decodeFunctionResult("circuitBreaker",d)[0],v=await st(t,w,ot.encodeFunctionData("getUcdController",[])),P=await st(t,w,ot.encodeFunctionData("ucdToken",[])),T=ot.decodeFunctionResult("getUcdController",v)[0],S=ot.decodeFunctionResult("ucdToken",P)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await st(t,e,at.encodeFunctionData("paused",[]));return at.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,$,I,C,k,B,M,x]=await Promise.all([A(g),A(w),A(f),A(y),A(b),A(T),A(S),A(m)]);return rt({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:k,ucdControllerPaused:B,ucdTokenPaused:M,simplePsmPaused:x})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var ut={hardhat:{chain:"hardhat",chainId:S.hardhat,bitcoinNetwork:P.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:S.sepolia,bitcoinNetwork:P.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:S.ethereum,bitcoinNetwork:P.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var lt,dt=[{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"}],ht=[{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 pt(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 mt(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,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,dt,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[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 n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,ht,r);let s;try{s=await a.isAllowedCid(e,o)}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=${o.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 n=[];for(const e of i){const r=await pt(e.ciphertext,e.pkpId),{url:i,auth:o}=q(r);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:o,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i)}async function gt(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 n=i??(t=>new F({providerUrl:t.url,auth:t.auth,...r?{timeout:r}:{}})),o=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=o.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=o.map((t=>t.value)),c=s[0],u=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(u.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${u.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${c.toString()} sats)`);return c}(t,e,r,i)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=D.create("UCD Mint Validator");let r,i="init";try{const t=[{inputs:[],name:"getRemainingMintCapacity",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=[{inputs:[],name:"maxSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],s=[{inputs:[],name:"getCurrentSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],l=[{inputs:[],name:"getProtocolConfig",outputs:[{internalType:"uint256",name:"_liquidationThreshold",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueUcd",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueWei",type:"uint256"},{internalType:"uint256",name:"_maximumLoanValueUcd",type:"uint256"}],stateMutability:"view",type:"function"}];e.stepStart("0","Validating configuration");const v=U(),P=v.chain;if(!P)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');r=C.verifyAmountPositionActionAuthorizationStructure(v.auth);const S=function(t){const e=A(t),r=ut[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(P),$=S.chain,I=S.bitcoinNetwork;let k,M;if(B(` \u2705 Chain: ${P} (${$})`),B(` \u2705 Bitcoin Network: ${I}`),e.log("0","Validating contract addresses..."),e.log("0",`contractAddresses exists: ${!!v.contractAddresses}`),e.log("0","contractAddresses type: "+typeof v.contractAddresses),!v.contractAddresses||"object"!=typeof v.contractAddresses)throw e.error("0",`\u274c ERROR: No valid contractAddresses object found: ${JSON.stringify(v.contractAddresses)}`),new Error("contractAddresses is required and must include: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController");e.log("0","\u2705 Found valid contractAddresses object"),e.log("0",`Available keys: ${Object.keys(v.contractAddresses)}`);const x=v.contractAddresses.PositionManager,D=v.contractAddresses.LoanOperationsManagerModule,O=v.contractAddresses.TermManagerModule,R=v.contractAddresses.UCDController,N=v.contractAddresses.LiquidationManagerModule??v.contractAddresses.LiquidationManager??"",q=v.contractAddresses.BTCSpendAuthorizer??"",L=v.contractAddresses.BitcoinProviderRegistry;if(e.log("0","Extracted addresses:"),e.log("0",`POSITION_MANAGER_ADDRESS: ${x||"MISSING"}`),e.log("0",`LOAN_OPS_MANAGER_ADDRESS: ${D||"MISSING"}`),e.log("0",`TERM_MANAGER_ADDRESS: ${O||"MISSING"}`),e.log("0",`UCD_CONTROLLER_ADDRESS: ${R||"MISSING"}`),!(x&&D&&O&&R&&N))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");B(" \u2705 Contract addresses loaded and validated"),B(` PositionManager: ${x}`),B(` LoanOpsManager: ${D}`),e.stepEnd("0"),B("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const _=BigInt(r.amount);if(_<=0n)throw new Error(`Amount must be positive, got: ${_.toString()} wei`);B(" Fetching protocol mint limits..."),e.log("0","Fetching protocol mint limits...");const z=v.rpcUrl;let V;z&&"string"==typeof z?(!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(", ")}`)}(S,z),B(` 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}(z)}`),V=z):(V=await Lit.Actions.getRpcUrl({chain:P}),B(` Using LIT-provided RPC URL for chain: ${P}`));const H=new ethers.providers.JsonRpcProvider({url:V,timeout:g});M=await mt({policy:S,ethersProvider:H,registryAddress:L,devBitcoinProviderUrl:v.devBitcoinProviderUrl}),k=M[0],B(` \u2705 Bitcoin Provider: ${k.name} (min confs ${k.minConfirmations})`);!function(t,e){const r=et[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}))}("mintUcd",await ct(H,x));const G=new ethers.Contract(D,l,H);let Q,Y;try{const t=await G.getProtocolConfig();Q=BigInt(t[2].toString());Y=1000000000000000000n*BigInt(t[3].toString()),B(" \u2705 Protocol limits loaded from LoanOperationsManager (consolidated call)"),B(` - Minimum: ${Q.toString()} wei`),B(` - Maximum: ${Y.toString()} wei`),e.log("0","\u2705 Protocol limits loaded from LoanOperationsManager")}catch(t){const r=t?.message||String(t);throw B(` \u274c Failed to get protocol config (${r}); refusing to sign`),e.log("0","\u274c Protocol config unavailable \u2014 refusing to mint"),new Error(`getProtocolConfig failed; cannot validate mint limits: ${r}`)}if(_<Q)throw new Error(`Amount too small: ${_.toString()} wei. Minimum: ${Q.toString()} wei`);if(_>Y)throw new Error(`Amount too large: ${_.toString()} wei. Maximum: ${Y.toString()} wei`);const tt=v.publicKey;if(!tt)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof tt||0===tt.length)throw new Error("Invalid publicKey: must be non-empty string");i="0.5",B("[UCD Mint Validator] Started"),B(` Position: ${r.positionId}`),B(` Amount: ${_.toString()} wei`),e.log("0","Validator Started");const rt=new F({providerUrl:k.url,auth:k.auth,timeout:8e3}),it=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,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await W(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await W(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(v.priceProviders),nt=!0===globalThis.devPriceMode;if(nt&&!S.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${S.chain}`);const ot=new K(it,void 0,void 0,{devSingleProvider:nt&&S.allowDevSinglePriceProvider}),at=(n={contractAddress:q||D,chain:P,chainId:E($),rpcUrl:z,bitcoinProvider:rt,minConfirmations:k.minConfirmations},new J(n));if(i="1",B("[Step 1] Getting vault snapshot..."),e.stepStart("1","Getting vault snapshot"),v.debugOverrides?.useStubbedBtcData&&31337!==E($))throw new Error("debugOverrides.useStubbedBtcData is not permitted on live networks");const st=function(t){return new Z(t)}({contractAddress:x,termManagerAddress:O,loanOpsManagerAddress:D,liquidationManagerAddress:N,chain:P,chainId:E($),rpcUrl:z,vaultBalance:at,priceOracle:ot,debugOverrides:v.debugOverrides}),lt=await st.getVaultSnapshot(r.positionId);if(await gt(lt.vaultAddress,M,8e3),lt.btcPriceUsd<c||lt.btcPriceUsd>u)throw new Error(`Bitcoin price ${lt.btcPriceUsd} is outside acceptable range (${c} - ${u}). This may indicate oracle manipulation or stale price data. Please try again later.`);B(` \u2705 BTC price validation passed: $${(Number(lt.btcPriceUsd)/1e8).toFixed(2)}`),e.stepEnd("1"),i="2",B("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticating caller");if(!await C.verifyMintAuthorization(r,lt.borrower,E($),H,v.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");B(" \u2705 Caller authorized"),e.stepEnd("2"),i="3",B("[Step 3] Validating position state..."),e.stepStart("3","Validating position state");if(![0,1,2].includes(lt.status))throw new Error(`Invalid position status for minting: ${w(lt.status)}. Must be PENDING_DEPOSIT, PENDING_MINT, or ACTIVE. Current status prevents minting operations.`);if(B(` \u2705 Position status valid for minting: ${w(lt.status)}`),lt.isExpired)throw new Error(`Loan term expired ${lt.daysIntoGracePeriod} days ago - minting rejected. Must repay or extend term first.`);if(lt.isLiquidatable)throw new Error(`Position is liquidatable (${j(lt.collateralRatioBps)}% < ${j(lt.currentLiquidationThreshold)}%) - minting rejected. Add collateral first.`);B(" \u2705 Position is healthy"),B(` - Term: ${lt.daysUntilExpiry} days remaining`),B(` - Current ratio: ${j(lt.collateralRatioBps)}%`),B(` - Liquidation threshold: ${j(lt.currentLiquidationThreshold)}%`),e.stepEnd("3"),i="4",B("[Step 4] Calculating fees..."),e.stepStart("4","Calculating fees");let dt=function(t,e){if(t<0n)throw new Error("Amount cannot be negative");if(e<0||e>1e4)throw new Error("Fee basis points must be between 0 and 10000 (0% to 100%)");return t*BigInt(e)/10000n}(_,lt.originationFeeBps);const ht=Number(r.timestamp),pt=lt.previousExpiryAt??0,wt=lt.totalTerm??0;if(pt>0&&ht<pt){const t=BigInt(pt)-BigInt(ht),e=wt-(lt.selectedTerm??0),r=BigInt(e===p?m*d:e*h*d);if(0n===r)throw new Error(`Scenario B tail fee: original term length is zero (totalTerm=${wt}, selectedTerm=${lt.selectedTerm??0}). Cannot compute tail fee.`);const i=t*BigInt(lt.originationFeeBps)*_/(10000n*r);dt+=i,B(` Scenario B tail fee: ${i.toString()} wei (${e}mo original term, ${t}s remaining)`)}B(` Mint fee: ${dt.toString()} wei (${j(lt.originationFeeBps)}% base${pt>0&&ht<pt?" + tail":""})`),e.stepEnd("4"),i="4a",B("[Step 4a & 4b] Validating capacity limits..."),e.stepStart("4ab","Validating capacity limits");const ft=_+dt,yt=new ethers.Contract(R,[...t,...o,...s],H),[bt,vt,Pt]=await Promise.all([yt.getRemainingMintCapacity(),yt.maxSupply(),yt.getCurrentSupply()]),Tt=BigInt(bt.toString()),St=BigInt(vt.toString()),At=BigInt(Pt.toString());if(ft>Tt)throw new Error(`Daily mint limit would be exceeded: attempting to mint ${ft.toString()} wei (${_.toString()} + ${dt.toString()} fee), but only ${Tt.toString()} wei remaining in daily capacity`);if(B(" \u2705 Daily mint limit check passed"),B(` - Mint amount (with fee): ${ft.toString()} wei`),B(` - Remaining capacity: ${Tt.toString()} wei`),St>0n){const t=At+ft;if(t>St)throw new Error(`Max supply would be exceeded: minting ${ft.toString()} wei (${_.toString()} + ${dt.toString()} fee) would result in total supply of ${t.toString()} wei, exceeding max supply of ${St.toString()} wei`);B(" \u2705 Max supply check passed"),B(` - Current supply: ${At.toString()} wei`),B(` - After mint: ${t.toString()} wei`),B(` - Max supply: ${St.toString()} wei`),B(` - Remaining capacity: ${(St-At).toString()} wei`)}else B(" \u2705 Max supply unlimited (not enforced)");e.stepEnd("4ab"),i="5",B("[Step 5] Calculating new state..."),e.stepStart("5","Calculating new state");const Et=lt.ucdDebt+_+dt,$t=lt.availableBTCSats;B(` Current debt: ${lt.ucdDebt.toString()} wei`),B(` New debt: ${Et.toString()} wei`),B(` Available collateral: ${$t.toString()} sats`),e.stepEnd("5"),i="6",B("[Step 6] Validating collateral ratio after mint..."),e.stepStart("6","Validating collateral ratio after mint");const It=function(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}($t,lt.btcPriceUsd),Ct=X(It,Et);if(B(` New collateral ratio: ${j(Ct)}%`),B(` Minimum required: ${j(lt.liquidationThresholdBps)}%`),!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return X(t,e)>=r}(It,Et,lt.liquidationThresholdBps))throw new Error(`Insufficient collateral: ${j(Ct)}% < ${j(lt.liquidationThresholdBps)}%`);B(" \u2705 Sufficient collateral");const kt=BigInt("340282366920938463463374607431768211455");if(Et>kt)throw new Error(`New debt exceeds maximum allowed value: ${Et.toString()} > ${kt.toString()} (type(uint128).max). The contract will revert with DebtOverflow error.`);B(` \u2705 New debt within bounds: ${Et.toString()} <= ${kt.toString()}`),e.stepEnd("6"),i="7",B("[Step 7] Building authorization message..."),e.stepStart("7","Building authorization message");const Bt=lt.authorizedSpendsHash,Mt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[lt.ucdDebt])),xt={authorizedSpendsHash:Bt,ucdDebtHash:Mt,contractBundleHash:ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[x,D,O,R])),btcPrice:lt.btcPriceUsd.toString(),mintAmount:_.toString(),mintFee:dt.toString(),newCollateral:$t.toString(),newDebt:Et.toString()};if(r.action!==b)throw new Error(`Invalid mint authorization action: expected "${b}", got "${r.action}"`);const Dt=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()}(r.positionId),Ut=E($),Ot={name:f,version:y,chainId:Ut,verifyingContract:ethers.utils.getAddress(D)},Rt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Nt={MintUcd:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"mintFee",type:"uint256"},{name:"newDebt",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractHash",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},qt={actionTag:Rt,positionId:Dt,mintAmount:xt.mintAmount,mintFee:xt.mintFee,newDebt:xt.newDebt,newCollateral:xt.newCollateral,btcPrice:xt.btcPrice,authorizedSpendsHash:xt.authorizedSpendsHash,ucdDebtHash:xt.ucdDebtHash,contractHash:xt.contractBundleHash,quantumTimestamp:r.timestamp,borrower:ethers.utils.getAddress(lt.borrower)};e.stepEnd("7"),i="8",e.stepStart("8","Signing authorization");const Lt=globalThis.validatorWalletAddress;if(!Lt||!Lt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const _t=await Lit.Actions.getPrivateKey({pkpId:Lt}),Ft="string"==typeof _t?_t.startsWith("0x")?_t:`0x${_t}`:String(_t),zt=new ethers.Wallet(Ft),Vt=await zt._signTypedData(Ot,Nt,qt);return e.stepEnd("8"),e.summary(),B("[UCD Mint Validator] \u2705 Complete"),{approved:!0,positionId:r.positionId,mintAmount:_.toString(),mintFee:dt.toString(),newDebt:Et.toString(),newCollateral:$t.toString(),newCollateralRatioBps:Ct,btcPrice:lt.btcPriceUsd.toString(),authorizedSpendsHash:Bt,signature:Vt,timestamp:r.timestamp,validatorPkp:zt.address}}catch(t){throw console.error("[UCD Mint Validator] \u274c Failed:",t.message),console.error(`[UCD Mint Validator] Failed at step: ${i}`),t}var n}return lt=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),lt)})();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
- 5a955863b32c003314ab29c37b157e06d00a2f93c2d9085a02ca73b71838a72f
1
+ 567a51d3beaedbda4f0af2636835ca8a2af89c2264e91f8dc31f522c1a424b7b
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "ucd-mint-validator",
3
- "originalSize": 162737,
4
- "minifiedSize": 68521,
5
- "compressionRatio": 0.5789463981761984,
6
- "hash": "5a955863b32c003314ab29c37b157e06d00a2f93c2d9085a02ca73b71838a72f",
7
- "buildTime": 1781255700772,
3
+ "originalSize": 169014,
4
+ "minifiedSize": 72074,
5
+ "compressionRatio": 0.5735619534476434,
6
+ "hash": "567a51d3beaedbda4f0af2636835ca8a2af89c2264e91f8dc31f522c1a424b7b",
7
+ "buildTime": 1781559388720,
8
8
  "version": "0.1.0"
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gvnrdao/dh-lit-actions",
3
- "version": "0.0.309",
3
+ "version": "0.0.310",
4
4
  "type": "commonjs",
5
5
  "description": "Diamond Hands Protocol LIT Actions - Deterministic, Auditable Builds",
6
6
  "main": "pkg-dist/pkg-src/index.js",