@gvnrdao/dh-lit-actions 0.0.294 → 0.0.296

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 (53) hide show
  1. package/dist/address-probe-signer.meta.json +1 -1
  2. package/dist/address-probe.meta.json +1 -1
  3. package/dist/admin-liquidation-validator.action.js +1 -1
  4. package/dist/admin-liquidation-validator.hash +1 -1
  5. package/dist/admin-liquidation-validator.meta.json +5 -5
  6. package/dist/always-signer.meta.json +1 -1
  7. package/dist/authorization-dummy-b.meta.json +1 -1
  8. package/dist/authorization-dummy.meta.json +1 -1
  9. package/dist/btc-transaction-signer.action.js +1 -1
  10. package/dist/btc-transaction-signer.hash +1 -1
  11. package/dist/btc-transaction-signer.meta.json +5 -5
  12. package/dist/btc-utxo-invalidator.action.js +1 -0
  13. package/dist/btc-utxo-invalidator.hash +1 -0
  14. package/dist/btc-utxo-invalidator.meta.json +9 -0
  15. package/dist/btc-withdrawal.action.js +1 -1
  16. package/dist/btc-withdrawal.hash +1 -1
  17. package/dist/btc-withdrawal.meta.json +5 -5
  18. package/dist/encrypt-parameter.meta.json +1 -1
  19. package/dist/ethers-version-probe.meta.json +1 -1
  20. package/dist/extend-position-validator.action.js +1 -1
  21. package/dist/extend-position-validator.hash +1 -1
  22. package/dist/extend-position-validator.meta.json +5 -5
  23. package/dist/liquidation-validator.action.js +1 -1
  24. package/dist/liquidation-validator.hash +1 -1
  25. package/dist/liquidation-validator.meta.json +5 -5
  26. package/dist/loan-vault-btc-balance.action.js +1 -1
  27. package/dist/loan-vault-btc-balance.hash +1 -1
  28. package/dist/loan-vault-btc-balance.meta.json +5 -5
  29. package/dist/pkp-validator.meta.json +1 -1
  30. package/dist/price-oracle.meta.json +1 -1
  31. package/dist/process-payment-sign-only.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 -0
  36. package/dist/stale-spend-recovery-validator.hash +1 -0
  37. package/dist/stale-spend-recovery-validator.meta.json +9 -0
  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 +49 -42
  43. package/pkg-dist/pkg-src/index.js.map +2 -2
  44. package/pkg-dist/src/constants/index.d.ts +1 -1
  45. package/pkg-dist/src/constants/index.d.ts.map +1 -1
  46. package/pkg-dist/src/constants/message-hash-domains.d.ts +15 -0
  47. package/pkg-dist/src/constants/message-hash-domains.d.ts.map +1 -1
  48. package/pkg-dist/src/interfaces/chunks/vault-snapshot.i.d.ts +1 -0
  49. package/pkg-dist/src/interfaces/chunks/vault-snapshot.i.d.ts.map +1 -1
  50. package/pkg-dist/src/modules/authorization.module.d.ts +19 -0
  51. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  52. package/pkg-dist/src/modules/vault-snapshot.d.ts +1 -0
  53. package/pkg-dist/src/modules/vault-snapshot.d.ts.map +1 -1
@@ -0,0 +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})},o={};async function s(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const i="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=[];for(let t=0;t<r.length;t+=2)n.push(parseInt(r.substr(t,2),16));const o=c(n,8,5,!0),s=[e,...o],a=function(t,e){const r=function(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}(t).concat(e).concat([0,0,0,0,0,0]),i=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let i=0;i<t.length;i++){const n=r>>25;r=(33554431&r)<<5^t[i];for(let t=0;t<5;t++)n>>t&1&&(r^=e[t])}return r}(r),n=[];for(let t=0;t<6;t++)n.push(i>>5*(5-t)&31);return n}(t,s),u=[...s,...a];let l=t+"1";for(let t=0;t<u.length;t++)l+=i[u[t]];return l}(s,0,ethers.utils.ripemd160(o).slice(2));return a}async function a(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"00":"6f";const a=s+ethers.utils.ripemd160(o).slice(2),u=ethers.utils.sha256("0x"+a);return function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=BigInt("0x"+t),i="";for(;r>0n;){i=e[Number(r%58n)]+i,r/=58n}for(let e=0;e<t.length&&"00"===t.substr(e,2);e+=2)i="1"+i;return i}(a+ethers.utils.sha256(u).slice(2,10))}function u(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const i=t.substring(r+1).toLowerCase(),n=[];for(let t=0;t<i.length;t++){const r=e.indexOf(i[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${i[t]}`);n.push(r)}const o=n.slice(0,-6),s=(o[0],c(o.slice(1),5,8,!1));return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let i=0;i<t.length;i++){const n=e.indexOf(t[i]);if(n<0)throw new Error(`Invalid Base58 character: ${t[i]}`);r=58n*r+BigInt(n)}let i=r.toString(16);i.length%2&&(i="0"+i);for(let e=0;e<t.length&&"1"===t[e];e++)i="00"+i;return i}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function c(t,e,r,i){let n=0,o=0;const s=[],a=(1<<r)-1;for(let i=0;i<t.length;i++){const u=t[i];if(u<0||u>>e)throw new Error("Invalid data for bit conversion");for(n=n<<e|u,o+=e;o>=r;)o-=r,s.push(n>>o&a)}if(i)o>0&&s.push(n<<r-o&a);else if(o>=e||n<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}n(o,{addressToScriptPubKey:()=>u,deriveBitcoinAddress:()=>s,deriveBitcoinAddressP2PKH:()=>a});var l,d,h=(l={"src/modules/bitcoin/address.ts"(){"use strict"}},function(){return l&&(d=(0,l[r(l)[0]])(l=0)),d}),p={};n(p,{main:()=>main});var g=546n,f=100,m=1e5,w=60,y="btc-utxo-invalidator",b=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(b||{}),P={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},v={ethereum:1,sepolia:11155111,hardhat:1337};function T(t){return Math.floor(t/w)*w}async function E(){const t=Math.floor(Date.now()/1e3),e=t%w;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%w;return e<8||e>=52}(t))return;let r;r=e>=52?w-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: ${T(Math.floor(Date.now()/1e3))}`)}var $=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const 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 E();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=T(i),o=T(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 s=n-w,a=n+w;if(o!==s&&o!==n&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${n} (current), ${a} (next)]`);if(o===s){if(i<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&i>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n){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(o,s,a)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyPaymentAuthorization(t,e,r,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyWithdrawAuthorization(e,r,i,n){if("withdraw-btc"!==e.action)return!1;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(o,s,a)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n){if(e.action!==y)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(o,s,a)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,s,a)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i)}static async verifyBtcExecutionAuthorization(e,r,i,n){if("execute-btc-withdrawal"!==e.action)return!1;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(o,s,a)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}),{strictCurrentQuantum:!0})}};function I(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function A(...t){I()&&console.log(...t)}var x=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}},S=class{static create(t="LIT Action",e){return I(e)?new k(t):new x}};function C(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function B(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function M(t){return t instanceof Error&&"AbortError"===t.name}var D=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=S.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),A(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const 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"),M(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: ${B(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: ${B(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${B(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,s=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),A(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let u;try{u=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${B(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(u,null,2)}`);const c=this.parseBlockstreamUTXOs(u,o);return this.logger.stepEnd("1"),c}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),M(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(B(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${B(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),s=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,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),A(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=o.chain_stats.funded_txo_sum,a=o.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const u=BigInt(s-a);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),u}catch(t){if(clearTimeout(n),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=B(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=B(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),A(`[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();return o.status?{txid:o.txid??t,confirmations:o.status.confirmed&&o.status.block_height?1:0}:null}catch(t){if(clearTimeout(r),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(B(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),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function O(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function U(t,e){const r=t.toString(16).padStart(2*e,"0").match(/../g);if(!r)throw new Error(`Invalid hex conversion: ${t}`);return r.reverse().join("")}function N(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+U(t,2):t<=4294967295?"fe"+U(t,4):"ff"+U(t,8)}h(),h();var _=[{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"}];async function q(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 R(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveDefaultBitcoinProvider: 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(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const o=await 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,_,e),[n,o]=await i.getProviders(t),s=[];for(let t=0;t<n.length;t++)s.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(t.chainId,e,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const n=[];for(const e of i){const r=await q(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);return o[0]}var L={hardhat:{chain:"hardhat",chainId:v.hardhat,bitcoinNetwork:P.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:v.sepolia,bitcoinNetwork:P.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:v.ethereum,bitcoinNetwork:P.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};function F(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(b).join(", ")}`)}(t),r=L[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var z="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))",j={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"],adminLiquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function H(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var X=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),K=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)"]),V=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function Q(t,e,r){return t.call({to:e,data:r})}async function G(t,e){const r=new ethers.utils.Interface([z]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([z]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?H({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):H(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await Q(t,e,X.encodeFunctionData("views",[])),[i]=X.decodeFunctionResult("views",r),[n,o,s,a,u,c,l,d]=await Promise.all([Q(t,e,X.encodeFunctionData("paused",[])),Q(t,e,X.encodeFunctionData("liquidationPaused",[])),Q(t,e,X.encodeFunctionData("simplePsm",[])),Q(t,i,K.encodeFunctionData("core",[])),Q(t,i,K.encodeFunctionData("loanOps",[])),Q(t,i,K.encodeFunctionData("collateralManager",[])),Q(t,i,K.encodeFunctionData("liquidationManager",[])),Q(t,i,K.encodeFunctionData("circuitBreaker",[]))]),h=X.decodeFunctionResult("paused",n)[0],p=X.decodeFunctionResult("liquidationPaused",o)[0],g=X.decodeFunctionResult("simplePsm",s)[0],f=K.decodeFunctionResult("core",a)[0],m=K.decodeFunctionResult("loanOps",u)[0],w=K.decodeFunctionResult("collateralManager",c)[0],y=K.decodeFunctionResult("liquidationManager",l)[0],b=K.decodeFunctionResult("circuitBreaker",d)[0],P=await Q(t,m,V.encodeFunctionData("getUcdController",[])),v=await Q(t,m,V.encodeFunctionData("ucdToken",[])),T=V.decodeFunctionResult("getUcdController",P)[0],E=V.decodeFunctionResult("ucdToken",v)[0],$=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await Q(t,e,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,A,x,k,S,C,B,M]=await Promise.all([$(f),$(m),$(w),$(y),$(b),$(T),$(E),$(g)]);return H({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:A,collateralManagerPaused:x,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var J,Z=3600,Y=1500,tt=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],et=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],rt=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=S.create("BTC UTXO Invalidator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing required parameter "chain"');const i=F(t),n=C(),a=n.publicKey;if(!a||"string"!=typeof a)throw new Error('Missing required parameter "publicKey"');const c=globalThis.contractAddresses;if(!c)throw new Error('Missing "contractAddresses"');const l=c.PositionManager,d=c.BTCSpendAuthorizer;if(!l||!d)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const p=globalThis.auth;if(!p||"object"!=typeof p)throw new Error('Missing or invalid "auth" parameter');const{positionId:w,utxoTxid:b,utxoVout:P,timestamp:v,signature:T,chainId:E,action:I}=p;if(!w||!b||"number"!=typeof P)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof v||!T||"number"!=typeof E)throw new Error("auth requires { timestamp, signature, chainId }");if(I!==y)throw new Error(`auth.action must be "${y}" (got "${I}")`);const A=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()}(w);let x;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(x=globalThis.rpcUrl,console.log(` RPC override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(x)}`)):x=await Lit.Actions.getRpcUrl({chain:t});const k=new ethers.providers.JsonRpcProvider(x),S=await R({policy:i,ethersProvider:k,registryAddress:c.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});new D({providerUrl:S.url});!function(t,e){const r=j[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}))}("btcTransactionSign",await G(k,l)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const B=new ethers.Contract(d,tt,k),M=await B.getAuthorizedSpends(A);let _=null;for(const t of M)if(t.txid.toLowerCase()===b.toLowerCase()&&Number(t.vout)===P){_=t;break}if(!_)throw new Error(`No AuthorizedSpend on-chain for ${b}:${P} under position ${A}`);const q=BigInt(_.authorizedAt.toString()),L=BigInt(_.satoshis.toString()),z=BigInt(Math.floor(Date.now()/1e3));if(z-q<BigInt(Z))throw new Error(`AuthorizedSpend not yet stale: age=${(z-q).toString()}s, required=${Z}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const H=new ethers.Contract(l,rt,k),X=await H.core(),K=new ethers.Contract(X,et,k),V=await K.getPositionDetails(A),W=V.borrower??V[1],Q=V.vaultAddress??V[3];if(!W||W===ethers.constants.AddressZero)throw new Error(`Position ${A} not found or no borrower set`);if(!Q)throw new Error(`Position ${A} missing vaultAddress`);if(E!==i.chainId)throw new Error(`auth.chainId (${E}) \u2260 policy.chainId (${i.chainId})`);if(!await $.verifyRecoveryAuthorization({positionId:A,timestamp:v,chainId:E,utxoTxid:b,utxoVout:P,action:I,signature:T},W,k,c.PositionDelegateRegistry))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const J=await(async()=>{try{const t=await fetch(`${S.url}/tx/${b}/outspends`);return t.ok?await t.json():null}catch{return null}})();if(J&&J[P]&&J[P].spent){const t=J[P].txid??"unknown";return console.log(` \u2139\ufe0f UTXO already spent by ${t}; short-circuiting to recovery-validator path`),e.stepEnd("4"),{success:!0,alreadySpent:{spendingTxid:t},positionId:A,utxoTxid:b,utxoVout:P,authorizedAt:q.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const it=await s(a,i.bitcoinNetwork);if(Q&&it.toLowerCase()!==Q.toLowerCase())throw new Error(`Derived PKP address ${it} \u2260 on-chain vaultAddress ${Q}`);if(e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx"),Y<f)throw new Error(`INVALIDATOR_FEE_SATS (${Y}) < MIN_BTC_FEE_SATS (${f})`);if(Y>m)throw new Error(`INVALIDATOR_FEE_SATS (${Y}) > MAX_BTC_FEE_SATS (${m})`);const nt=Number(L)-Y;if(nt<Number(g))throw new Error(`Invalidator output (${nt} sats) below dust limit; UTXO too small to recover`);const ot={txid:b,vout:P,value:Number(L),scriptPubKey:""},{addressToScriptPubKey:st}=await Promise.resolve().then((()=>(h(),o)));ot.scriptPubKey=st(it);const{txHex:at,sigHashes:ut}=function(t){const{utxos:e,destination:r,amount:i,changeAddress:n,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",a="ffffffff",c="00000000",l=N(e.length),d=e.map((t=>O(t.txid)+U(t.vout,4)+"00"+a)).join(""),h=[],p=u(r);if(h.push(U(i,8)+N(p.length/2)+p),o>0){const t=u(n);h.push(U(o,8)+N(t.length/2)+t)}const g=N(h.length),f=h.join(""),m=s+l+d+g+f+c,w=e.map((t=>O(t.txid)+U(t.vout,4))).join(""),y=ethers.utils.sha256(ethers.utils.sha256("0x"+w)),b=e.map((()=>a)).join(""),P=ethers.utils.sha256(ethers.utils.sha256("0x"+b)),v=ethers.utils.sha256(ethers.utils.sha256("0x"+f));return{txHex:m,sigHashes:e.map((t=>{const e=O(t.txid)+U(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",i=s+y.slice(2)+P.slice(2)+e+r+U(t.value,8)+a+v.slice(2)+c+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+i))}))}}({utxos:[ot],destination:it,amount:nt,changeAddress:it,changeAmount:0,network:i.bitcoinNetwork,pkpPublicKey:a});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const ct=n.pkpId;if(!ct)throw new Error('Missing required parameter "pkpId"');const lt=await Lit.Actions.getPrivateKey({pkpId:ct}),dt="string"==typeof lt?lt.startsWith("0x")?lt:`0x${lt}`:String(lt),ht=new ethers.utils.SigningKey(dt),pt=[];for(let t=0;t<ut.length;t++){const e=ht.signDigest(ut[t]);pt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:at,sigHashes:ut,signatures:pt,pkpPublicKey:a,pkpBtcAddress:it,invalidatorAmount:nt,networkFee:Y,utxo:{txid:b,vout:P,value:Number(L)},authorization:{authorizedAt:q.toString(),positionId:A},timestamp:Date.now(),action:"btc-utxo-invalidator"}}catch(t){return console.error(`[BTC UTXO Invalidator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"btc-utxo-invalidator"}}}return J=p,((n,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let u of r(o))i.call(n,u)||u===s||t(n,u,{get:()=>o[u],enumerable:!(a=e(o,u))||a.enumerable});return n})(t({},"__esModule",{value:!0}),J)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -0,0 +1 @@
1
+ 5342c93640d63ad3ff18edd0836f890cbe55a67b26dfcc6d27bd9c2cefe4eb6d
@@ -0,0 +1,9 @@
1
+ {
2
+ "actionName": "btc-utxo-invalidator",
3
+ "originalSize": 94731,
4
+ "minifiedSize": 40281,
5
+ "compressionRatio": 0.574785445102448,
6
+ "hash": "5342c93640d63ad3ff18edd0836f890cbe55a67b26dfcc6d27bd9c2cefe4eb6d",
7
+ "buildTime": 1779034976126,
8
+ "version": "0.1.0"
9
+ }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var n=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,l=100000000000000n,u=546n,d=3,h=500,p=60,g=8e3;function m(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var w="DiamondHands.Protocol",f="1",y=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(y||{}),b={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],v={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(y).join(", ")}`)}function P(t){return v[t]}function E(t){return Math.floor(t/p)*p}async function A(){const t=Math.floor(Date.now()/1e3),e=t%p;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%p;return e<8||e>=52}(t))return;let r;r=e>=52?p-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${E(Math.floor(Date.now()/1e3))}`)}var $=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,o){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,o){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],o),n=await i.positionDelegate(t);return!(!n||n===ethers.constants.AddressZero)&&n.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,o){const i=Math.floor(Date.now()/1e3);await A();const n=o?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const o=e??Math.floor(Date.now()/1e3),i=E(o),n=E(t);if(r?.strictCurrentQuantum){if(n!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${n}, current quantum: ${i}`);return}const a=i-p,s=i+p;if(n!==a&&n!==i&&n!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${a} (past), ${i} (current), ${s} (next)]`);if(n===a){if(o<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(n===s&&o>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyMintAuthorization(t,e,r,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o)}static async verifyPaymentAuthorization(t,e,r,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o)}static async verifyWithdrawAuthorization(e,r,o,i){if("withdraw-btc"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,o,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(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o)}static async verifyBtcExecutionAuthorization(e,r,o,i){if("execute-btc-withdrawal"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}),{strictCurrentQuantum:!0})}};function I(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function C(...t){I()&&console.log(...t)}var B=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},U=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${o}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const o=Date.now()-r;this.stepDurations.set(t,o),console.log(`[Step ${t}] Duration: ${o}ms`),o>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${o}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-i;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const o=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${o}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},D=class{static create(t="LIT Action",e){return I(e)?new U(t):new B}};function M(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function x(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function k(t){return t instanceof Error&&"AbortError"===t.name}var O=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),C(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Failed to fetch block height: ${o.status} ${o.statusText}`);const i=await o.text();if(i.trim().startsWith("<!DOCTYPE")||i.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const n=parseInt(i.trim(),10);if(isNaN(n)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${x(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: ${x(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${x(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,o=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const i=t.txid,n=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===n||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");o.push({txid:i,vout:n,satoshis:BigInt(a),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(i),C(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${x(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const l=this.parseBlockstreamUTXOs(c,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;const i=d,n=h;for(let e=1;e<=i;e++)try{this.logger.log("2",`UTXO query attempt ${e}/${i}...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(x(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${x(t)}`),e<i&&(this.logger.log("2",`Waiting ${n}ms before retry...`),await new Promise((t=>setTimeout(t,n))))}if(o)throw new Error(`Failed to query UTXOs after ${i} attempts: ${o.message}`);const a=r.reduce(((t,e)=>t+e.satoshis),0n),s=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),c=a-s;return{utxos:r,totalBalance:a,totalUTXOs:r.length,confirmedBalance:s,unconfirmedBalance:c}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:o.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(i),C(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const n=await e.json();if(!n.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=n.chain_stats.funded_txo_sum,s=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(i),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=x(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=x(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),C(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.status?{txid:n.txid??t,confirmations:n.status.confirmed&&n.status.block_height?1:0}:null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(x(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},N=class t{constructor(e,r,o){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error("Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass 3 distinct {name, apiKey} entries from the supported set: "+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Price oracle requires at least ${t.MIN_DISTINCT_PROVIDERS} eligible providers for consensus. Currently configured: ${this.sources.length} provider(s). Supported active providers: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(0===e.length)throw new Error("priceProviders must be a non-empty array of 3 distinct providers, each with an apiKey.");const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Supported: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires 3 DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use 3 different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"binance":if(!n.apiKey)throw new Error("Binance provider requires an apiKey");r.push(this.createBinanceSource(n.apiKey,i++));break;case"coinbase":if(!n.apiKey)throw new Error("Coinbase provider requires an apiKey");r.push(this.createCoinbaseSource(n.apiKey,i++));break;case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}if(r.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Insufficient price providers: need at least ${t.MIN_DISTINCT_PROVIDERS} distinct entries, got ${r.length}.`);return this.selectSampledSources(r)}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(){return async(t,e)=>{const r=new AbortController,o=setTimeout((()=>r.abort()),5e3);try{const o=await fetch(t,{headers:{Accept:"application/json",...e||{}},signal:r.signal});if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);return await o.json()}finally{clearTimeout(o)}}}getSelectionSeed(){const t="undefined"!=typeof process?process.env.PRICE_PROVIDER_SELECTION_SEED:void 0,e=t?Number(t):NaN;return Number.isFinite(e)?e:("undefined"!=typeof process,0,Math.floor(Date.now()+1e6*Math.random()))}selectSampledSources(t){const e=[...t];let r=this.getSelectionSeed()>>>0;for(let t=e.length-1;t>0;t--){const o=Math.floor((r=1664525*r+1013904223>>>0,r/4294967296*(t+1)));[e[t],e[o]]=[e[o],e[t]]}return e.slice(0,3).map(((t,e)=>({...t,priority:e+1})))}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson();return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const a=await r(n.toString(),i),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createBinanceSource(t,e){if(!t)throw new Error("createBinanceSource requires an apiKey");const r=this.createFetchJson();return{name:"Binance",fetchPrice:async()=>{const e=new URL("https://api.binance.com/api/v3/ticker/price");e.searchParams.set("symbol","BTCUSDT");const o=await r(e.toString(),{"X-MBX-APIKEY":t}),i=Number(o?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid Binance price payload");return i},priority:e}}createCoinbaseSource(t,e){if(!t)throw new Error("createCoinbaseSource requires an apiKey");const r=this.createFetchJson();return{name:"Coinbase",fetchPrice:async()=>{const e=await r("https://api.coinbase.com/v2/prices/BTC-USDT/spot",{"CB-ACCESS-KEY":t}),o=Number(e?.data?.amount);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid Coinbase price payload");return o},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson();return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const t=Date.now();if(3!==this.sources.length)throw new Error(`Price oracle requires exactly 3 providers. 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(),r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}))),o=[...await Promise.race([r,e])].sort(((t,e)=>t-e)),i=o[1];if((o[2]-o[0])/o[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=o.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}const n=Math.round(100*i),a=1000000n*BigInt(n),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${i.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}async getBTCPriceConsensus(){console.log("[Price Oracle] Fetching BTC price with consensus...");const t=(await Promise.allSettled(this.sources.map((async t=>{const e=await t.fetchPrice();return{source:t.name,price:e}})))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===t.length)throw new Error("No price sources returned data");console.log(`[Price Oracle] Got prices from ${t.length}/${this.sources.length} sources:`),t.forEach((t=>{console.log(` ${t.source}: $${t.price.toLocaleString()}`)}));const e=t.map((t=>t.price));e.sort(((t,e)=>t-e));const r=e[Math.floor(e.length/2)],o=e[0],i=e[e.length-1]/o,n=t.filter((t=>Math.abs(t.price-r)/r<=.02));if(i>1.05&&n.length===t.length)throw new Error(`Price consensus failed: sources too dispersed (${(100*(i-1)).toFixed(1)}% spread)`);if(n.length<t.length){const e=t.filter((t=>!n.find((e=>e.source===t.source))));if(console.log(`[Price Oracle] \u26a0\ufe0f Detected ${e.length} outlier(s):`),e.forEach((t=>{const e=Math.abs(t.price-r)/r;console.log(` ${t.source}: $${t.price.toLocaleString()} (${(100*e).toFixed(1)}% deviation)`)})),n.length<2)throw new Error("Price consensus failed: insufficient valid sources after outlier removal");console.log(`[Price Oracle] \u2705 Outliers filtered, continuing with ${n.length} valid sources`);const o=n.map((t=>t.price));o.sort(((t,e)=>t-e));const i=o[Math.floor(o.length/2)];console.log(`[Price Oracle] \u2705 Consensus price (median): $${i.toLocaleString()}`);const a=Math.round(100*i);return 1000000n*BigInt(a)}console.log(`[Price Oracle] \u2705 Consensus price (median): $${r.toLocaleString()}`);const a=Math.round(100*r);return 1000000n*BigInt(a)}};N.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinbase","binance","coinmarketcap","coingecko"],N.MIN_DISTINCT_PROVIDERS=3;var R=N,q=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),o=await this.getAuthorizedSpendsFromContract(t),i=o.reduce(((t,e)=>t+e.satoshis),0n),n=r>i?r-i:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:o,authorizedBalance:i,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,o),availableUTXOs:[],availableBalance:n,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const o=this.config.minConfirmations||6,i=await this.bitcoinProvider.getUTXOSet(e,o),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=n.reduce(((t,e)=>t+e.satoshis),0n),s=i.utxos.filter((t=>!this.isUTXOAuthorized(t,n))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:a,authorizedSpendsHash:l,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,o){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===o))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],o);return(await i.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const o=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,o]))}};function L(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}function F(t,e,r,o){if(!t)return r??13e3;const i=o??n,a=Math.min(e,30);return n+a*a*(i-n)/900}function _(t,e,r){const o=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:o,collateralRatioBps:Number(o*s*10000n/r)}}function z(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}function 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 V(t){return t/100}var H=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.loanOpsManagerAddress,r,e),i=await o.liquidationThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.termManagerAddress,o,r),n=await i.getTermFees(t);return{originationFeeBps:Number(n.originationFee?.toString?.()??n[0]?.toString?.()??n[0]),extensionFeeBps:Number(n.extensionFee?.toString?.()??n[1]?.toString?.()??n[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,i=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await i.getAuthorizedSpendsHash(o)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.liquidationManagerAddress,r,e),i=await o.maxEscalatedThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function W(t){return new H(t)}var j=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPriceConsensus()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=L(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=_(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPriceConsensus()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=L(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=_(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],o),n=await i.core(),a=new ethers.Contract(n,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],o),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const l=Number(s.expiryAt),u=Number(s.selectedTerm),d=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=(w=u,0===(m=l)?0:m-30*w*86400);var m,w;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:p,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const o=await this.getVaultSnapshot(t);return function(t,e,r,o){const i=e+r;return 0n===i||Number(t*s*10000n/i)>=o}(o.collateralValueUsd,o.ucdDebt,e,r)}};var G="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",K={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],adminLiquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function J(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var Q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),Z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),tt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function et(t,e,r){return t.call({to:e,data:r})}async function rt(t,e){const r=new ethers.utils.Interface([G]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([G]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):J(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await et(t,e,Q.encodeFunctionData("views",[])),[o]=Q.decodeFunctionResult("views",r),[i,n,a,s,c,l,u,d]=await Promise.all([et(t,e,Q.encodeFunctionData("paused",[])),et(t,e,Q.encodeFunctionData("liquidationPaused",[])),et(t,e,Q.encodeFunctionData("simplePsm",[])),et(t,o,Y.encodeFunctionData("core",[])),et(t,o,Y.encodeFunctionData("loanOps",[])),et(t,o,Y.encodeFunctionData("collateralManager",[])),et(t,o,Y.encodeFunctionData("liquidationManager",[])),et(t,o,Y.encodeFunctionData("circuitBreaker",[]))]),h=Q.decodeFunctionResult("paused",i)[0],p=Q.decodeFunctionResult("liquidationPaused",n)[0],g=Q.decodeFunctionResult("simplePsm",a)[0],m=Y.decodeFunctionResult("core",s)[0],w=Y.decodeFunctionResult("loanOps",c)[0],f=Y.decodeFunctionResult("collateralManager",l)[0],y=Y.decodeFunctionResult("liquidationManager",u)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await et(t,w,Z.encodeFunctionData("getUcdController",[])),v=await et(t,w,Z.encodeFunctionData("ucdToken",[])),S=Z.decodeFunctionResult("getUcdController",T)[0],P=Z.decodeFunctionResult("ucdToken",v)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await et(t,e,tt.encodeFunctionData("paused",[]));return tt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[A,$,I,C,B,U,D,M]=await Promise.all([E(m),E(w),E(f),E(y),E(b),E(S),E(P),E(g)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:A,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:U,ucdTokenPaused:D,simplePsmPaused:M})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}function ot(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}var it={hardhat:{chain:"hardhat",chainId:v.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:v.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:v.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var nt,at=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}];async function st(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),o="string"==typeof e?e:String(e??"");if(!o)throw new Error("Decrypt returned empty plaintext");return o}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ct(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!o)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const n=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const o=new ethers.Contract(r,at,e),[i,n]=await o.getProviders(t),a=[];for(let t=0;t<i.length;t++)a.push({providerId:i[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return a}(t.chainId,e,r);if(0===o.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const i=[];for(const e of o){const r=await st(e.ciphertext,e.pkpId);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o);return n[0]}function lt(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const o=t.substring(r+1).toLowerCase(),i=[];for(let t=0;t<o.length;t++){const r=e.indexOf(o[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${o[t]}`);i.push(r)}const n=i.slice(0,-6),a=(n[0],function(t,e,r,o){let i=0,n=0;const a=[],s=(1<<r)-1;for(let o=0;o<t.length;o++){const c=t[o];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,n+=e;n>=r;)n-=r,a.push(i>>n&s)}if(o)n>0&&a.push(i<<r-n&s);else if(n>=e||i<<r-n&s)throw new Error("Invalid padding in bit conversion");return a}(n.slice(1),5,8,!1));return{witnessProgram:a.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let o=0;o<t.length;o++){const i=e.indexOf(t[o]);if(i<0)throw new Error(`Invalid Base58 character: ${t[o]}`);r=58n*r+BigInt(i)}let o=r.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=D.create("BTC Withdrawal Validator");console.log("[Step 0] Validating configuration..."),e.stepStart("0","Validate configuration parameters");const r=globalThis.chain;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');const o=function(t){const e=S(t),r=it[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),i=o.chain,n=o.bitcoinNetwork;let a;if(console.log(` \u2705 Chain: ${r} (${i})`),console.log(` \u2705 Bitcoin Network: ${n}`),!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error('Required "contractAddresses" object with: PositionManager, LoanOperationsManagerModule, TermManagerModule');const s=globalThis.contractAddresses.PositionManager,p=globalThis.contractAddresses.LoanOperationsManagerModule,g=globalThis.contractAddresses.TermManagerModule,y=globalThis.contractAddresses.UCDController,b=globalThis.contractAddresses.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",E=globalThis.contractAddresses.BTCSpendAuthorizer??"";if(!(s&&p&&g&&y&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${s}`),console.log(` LoanOpsManager: ${p}`),e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const A=globalThis.auth;if(!A||"object"!=typeof A)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!A.positionId)throw new Error("auth.positionId is required");if("number"!=typeof A.timestamp)throw new Error("auth.timestamp must be a number");if(!A.signature)throw new Error("auth.signature is required");const I=BigInt(A.amount);if(I<=0n)throw new Error(`Withdrawal amount must be positive, got: ${I.toString()} sats`);const C=u;if(I<C)throw new Error(`Withdrawal amount ${I.toString()} sats is below minimum ${C.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const B=A.destinationAddress;if(!B||"string"!=typeof B)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const U=M().publicKey;if(!U)throw new Error("publicKey must not be blank");if("string"!=typeof U||0===U.length)throw new Error("publicKey must not be blank");const x=U;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(B),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(B);return!(!t&&!e)&&("testnet"===n||"regtest"===n?B.startsWith("m")||B.startsWith("n")||B.startsWith("2")||B.startsWith("tb1")||B.startsWith("bcrt1"):"mainnet"===n&&(B.startsWith("1")||B.startsWith("3")||B.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${B}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);console.log(` \u2705 Destination address validated: ${B} (${n})`);let k="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${A.positionId}`),console.log(` Withdrawal Amount: ${I.toString()} sats`),console.log(` Destination Address: ${B}`);const t=new R(globalThis.priceProviders,void 0),n=globalThis.rpcUrl;let u;n&&"string"==typeof n?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(o,n),console.log(` Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(n)}`),u=n):(u=await Lit.Actions.getRpcUrl({chain:r}),console.log(` Using LIT-provided RPC URL for chain: ${r}`));const S=new ethers.providers.JsonRpcProvider(u);a=await ct({policy:o,ethersProvider:S,registryAddress:globalThis.contractAddresses.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),console.log(` \u2705 Bitcoin Provider: ${a.name} (min confs ${a.minConfirmations})`);const C=new O({providerUrl:a.url});!function(t,e){const r=K[t],o=[];for(const t of r)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("withdrawBtc",await rt(S,s));const U=(N={contractAddress:E||p,chain:r,chainId:P(i),rpcUrl:u,bitcoinProvider:C,minConfirmations:a.minConfirmations},new q(N));k="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const D=function(t){return new j(t)}({contractAddress:s,termManagerAddress:g,loanOpsManagerAddress:p,liquidationManagerAddress:v,chain:r,chainId:P(i),rpcUrl:u,vaultBalance:U,priceOracle:t}),M=await D.getVaultSnapshot(A.positionId);console.log(` \u2705 Vault balance: ${M.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${M.ucdDebt.toString()} wei`),e.stepEnd("1"),k="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const L=e.getElapsed();console.log(`[TIMING] Step 2 started at ${L}ms`);const F=P(i),_=new ethers.providers.StaticJsonRpcProvider(u,F);let H;if(5===M.status){if(!b)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(b,["function pkpOwners(bytes32) view returns (address)"],_);if(H=await t.pkpOwners(M.pkpId),!H||H===ethers.constants.AddressZero)throw new Error("No PKP owner registered for this liquidated position in LITActionValidator");console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${H}`)}else H=M.borrower;if(!await $.verifyWithdrawAuthorization(A,H,_,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");console.log(" \u2705 Caller authorized"),e.stepEnd("2"),k="2.5",console.log("[Step 2.5] Validating position status..."),e.stepStart("2.5","Validate position status");const W=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${W}ms`);if(![0,1,2,6,5].includes(M.status))throw new Error(`Position status ${m(M.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${m(M.status)}`),e.stepEnd("2.5"),k="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const G=e.getElapsed();console.log(`[TIMING] Step 3 started at ${G}ms`);const J=I;if(0n===M.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(M.btcPriceUsd<c||M.btcPriceUsd>l)throw new Error(`Bitcoin price ${M.btcPriceUsd} is outside acceptable range (${c} - ${l}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(M.btcPriceUsd)/1e8).toFixed(2)}`);const t=M.availableBTCSats-J,e=X(z(t,M.btcPriceUsd),M.ucdDebt);if(e<M.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${V(e)}% < liquidation threshold ${V(M.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${V(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${V(M.liquidationThresholdBps)}%`)}e.stepEnd("3"),k="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const Q=e.getElapsed();console.log(`[TIMING] Step 4 started at ${Q}ms`);const Y="string"==typeof A.amount?BigInt(A.amount):A.amount;if(Y!==I)throw new Error(`Authorization amount mismatch: auth.amount=${Y.toString()} sats, but requested withdrawal=${I.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),J>M.availableBTCSats)throw new Error(`Insufficient vault balance: need ${J.toString()} sats but only ${M.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const Z=M.availableBTCSats-J,tt=M.ucdDebt,et=z(Z,M.btcPriceUsd),it=tt>0n?X(et,tt):void 0;if(console.log(` Post-withdrawal collateral: ${Z.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(et)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${tt.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${tt>0n&&void 0!==it?V(Number(it)):"\u221e"}%`),Z<0n)throw new Error(`Withdrawal would result in negative balance: ${Z.toString()} sats`);console.log(" \u2705 Withdrawal validation passed"),e.stepEnd("4"),k="4.5",console.log("[Step 4.5] Querying vault UTXOs from Bitcoin network..."),e.stepStart("4.5","Query and select UTXO");const nt=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${nt}ms`);const at=M.vaultAddress;if(!at)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${at}`);let st=[],ut=null;const dt=d,ht=h;for(let t=1;t<=dt;t++)try{console.log(` \ud83d\udd04 UTXO query attempt ${t}/${dt}...`),st=await C.getUTXOs(at),console.log(` \u2705 UTXO query succeeded on attempt ${t}`),ut=null;break}catch(e){ut=e,console.error(` \u274c UTXO query failed on attempt ${t}:`,e.message),t<dt&&(console.log(` \u23f3 Waiting ${ht}ms before retry...`),await new Promise((t=>setTimeout(t,ht))))}if(ut)throw new Error(`Failed to query UTXOs after ${dt} attempts: ${ut.message}`);if(!st||0===st.length)throw new Error(`No UTXOs found in vault ${at}`);console.log(` \u2705 Found ${st.length} UTXO(s) in vault`);const pt=a.minConfirmations,gt=st.filter((t=>t.confirmations>=pt));if(0===gt.length)throw new Error(`No confirmed UTXOs found in vault. Required confirmations: ${pt}, found ${st.length} UTXO(s) with insufficient confirmations.`);console.log(` \u2705 Found ${gt.length} confirmed UTXO(s)`);const mt=gt.filter((t=>t.satoshis>=J));let wt;if(0===mt.length){const t=gt.reduce(((t,e)=>t+e.satoshis),0n);if(t<J)throw new Error(`Insufficient vault balance for withdrawal. Need ${J.toString()} sats, total across ${gt.length} UTXO(s): ${t.toString()} sats.`);wt=[...gt].sort(((t,e)=>Number(e.satoshis-t.satoshis)))[0],console.log(" \u2139\ufe0f No single UTXO covers withdrawal \u2014 multi-UTXO consolidation will be used in Phase 2."),console.log(` Primary UTXO (contract auth): ${wt.txid}:${wt.vout} (${wt.satoshis.toString()} sats)`)}else wt=mt.sort(((t,e)=>Number(t.satoshis-e.satoshis)))[0];console.log(` \u2705 Selected UTXO: ${wt.txid}:${wt.vout}`),console.log(` \u2705 UTXO value: ${wt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${wt.confirmations}`);const ft=M.availableBTCSats;if(wt.satoshis<ft&&console.warn(` \u26a0\ufe0f Selected UTXO value (${wt.satoshis.toString()}) < calculated balance (${ft.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),wt.satoshis<J)throw new Error(`Selected UTXO value (${wt.satoshis.toString()} sats) < withdrawal amount (${J.toString()} sats). This should never happen after eligibility filtering.`);console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const yt=lt(at).toLowerCase(),bt=await C.getTransactionOutputs(wt.txid);if(!bt)throw new Error(`Could not fetch transaction outputs for ${wt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);let Tt=-1;for(const t of bt){const e=(t.scriptpubkey??"").toLowerCase(),r=e.length>0&&e===yt,o=t.scriptpubkey_address===at;if(r||o){Tt=t.index;break}}if(-1===Tt)throw new Error(`Vault output not found in tx ${wt.txid}. Expected scriptPubKey ${yt} or address ${at}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);Tt!==wt.vout?(console.log(` \u26a0\ufe0f Esplora API reported vout=${wt.vout} but vault output is at vout=${Tt} (matched on hex scriptpubkey). Correcting.`),wt={...wt,vout:Tt}):console.log(` \u2705 UTXO vout=${wt.vout} confirmed correct`),e.stepEnd("4.5"),k="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const vt=e.getElapsed();console.log(`[TIMING] Step 5 started at ${vt}ms`);const St=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(A.action)),Pt=M.authorizedSpendsHash,Et=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[M.ucdDebt])),At=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[s,p,g,y])),$t=BigInt(A.timestamp),It=Z,Ct=M.btcPriceUsd;if(Ct<c||Ct>l)throw new Error(`BTC price ${Ct.toString()} (8 decimals) is outside acceptable range (${c.toString()} - ${l.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",A.positionId),console.log(" action:",A.action),console.log(" actionHash:",St),console.log(" authorizedSpendsHash:",Pt),console.log(" ucdDebtHash:",Et),console.log(" withdrawalAddress:",B),console.log(" totalDeduction:",J.toString()),console.log(" newCollateral:",It.toString()),console.log(" quantumTimestamp:",$t.toString()),console.log(" btcPrice:",Ct.toString()),console.log(" utxoTxid:",wt.txid),console.log(" utxoVout:",wt.vout);const Bt=ot(A.positionId),Ut=P(i),Dt={name:w,version:f,chainId:Ut,verifyingContract:ethers.utils.getAddress(p)},Mt={WithdrawalAuthorization:[{name:"positionId",type:"bytes32"},{name:"actionHash",type:"bytes32"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractBundleHash",type:"bytes32"},{name:"withdrawalAddress",type:"string"},{name:"totalDeduction",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"utxoTxid",type:"string"},{name:"utxoVout",type:"uint32"},{name:"caller",type:"address"}]},xt=ethers.utils._TypedDataEncoder.hash(Dt,Mt,{positionId:Bt,actionHash:St,authorizedSpendsHash:Pt,ucdDebtHash:Et,contractBundleHash:At,withdrawalAddress:B,totalDeduction:J.toString(),newCollateral:It.toString(),quantumTimestamp:$t.toString(),btcPrice:Ct.toString(),utxoTxid:wt.txid,utxoVout:wt.vout,caller:ethers.utils.getAddress(H)});console.log("[Step 5] Contract message hash for signing:",xt),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(xt).length),e.stepEnd("5"),k="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const kt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${kt}ms`),e.log("6","========================================"),e.log("6","\ud83d\udd0d FINAL HASH INPUTS - ALL LIT NODES MUST MATCH"),e.log("6","========================================"),e.log("6",`Position ID: ${A.positionId}`),e.log("6",`Action Hash: ${St}`),e.log("6",`Authorized Spends Hash: ${Pt}`),e.log("6",`UCD Debt Hash: ${Et}`),e.log("6",`Contract Bundle Hash: ${At}`),e.log("6",`Destination Address: ${B}`),e.log("6",`Total Deduction: ${J.toString()}`),e.log("6",`New Collateral: ${It.toString()}`),e.log("6",`Quantum Timestamp: ${$t.toString()}`),e.log("6",`BTC Price: ${Ct.toString()}`),e.log("6",`Selected UTXO Txid: ${wt.txid}`),e.log("6",`Selected UTXO Vout: ${wt.vout}`),e.log("6",`Selected UTXO Satoshis: ${wt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${wt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${xt}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${xt}`),e.log("6",`publicKey: ${x}`),e.log("6","publicKey with 0x prefix: "+("0x"+x));const Ot=ethers.utils.arrayify(xt);e.log("6",`messageBytes length: ${Ot.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(Ot))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const Nt=Date.now(),Rt=globalThis.validatorWalletAddress;if(!Rt||!Rt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const qt=await Lit.Actions.getPrivateKey({pkpId:Rt}),Lt="string"==typeof qt?qt.startsWith("0x")?qt:`0x${qt}`:String(qt),Ft=new ethers.Wallet(Lt),_t=new ethers.utils.SigningKey(Lt);e.log("6",`Wallet-derived signer address: ${Ft.address}`),e.log("6",`validatorWalletAddress: ${Rt}`);const zt=_t.signDigest(xt),Xt=ethers.utils.joinSignature(zt),Vt=Date.now()-Nt;e.log("6",`Chipotle signature created in ${Vt}ms`),e.log("6",`signature: ${Xt}`);const Ht=globalThis.contractAddresses.BTCSpendAuthorizer?.trim()||"";let Wt=null;if(Ht){const t=ot(A.positionId),r=P(i),o=It+J,n={name:w,version:f,chainId:r,verifyingContract:ethers.utils.getAddress(Ht)},a={BtcSpendAuth:[{name:"positionId",type:"bytes32"},{name:"txid",type:"string"},{name:"vout",type:"uint32"},{name:"satoshis",type:"uint256"},{name:"targetAddress",type:"string"},{name:"targetAmount",type:"uint256"}]},s=ethers.utils._TypedDataEncoder.hash(n,a,{positionId:t,txid:wt.txid,vout:wt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:J.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${s}`),Wt=await Ft._signTypedData(n,a,{positionId:t,txid:wt.txid,vout:wt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:J.toString()}),e.log("6",`btcSpendAuth signature: ${Wt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const jt={approved:!0,positionId:A.positionId,actionHash:St,authorizedSpendsHash:Pt,ucdDebtHash:Et,contractBundleHash:At,totalDeduction:J.toString(),remainingCollateral:Z.toString(),newCollateralRatioBps:tt>0n&&void 0!==it?Number(it):void 0,destinationAddress:B,signature:Xt,btcSpendAuthSignature:Wt,timestamp:$t.toString(),btcPrice:Ct.toString(),utxoTxid:wt.txid,utxoVout:wt.vout,utxoSatoshis:wt.satoshis.toString()};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",J,"type:",typeof J,"toString():",J.toString()),console.log(" remainingCollateral:",Z,"type:",typeof Z,"toString():",Z.toString()),console.log(" btcPrice:",Ct,"type:",typeof Ct,"toString():",Ct.toString()),console.log(" timestamp:",$t,"type:",typeof $t,"toString():",$t.toString()),console.log(" Full response object:",JSON.stringify(jt,null,2)),jt}catch(t){return console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${k}`),e.error("error",`Failed: ${t.message}`),{approved:!1,reason:t.message||t.toString(),positionId:A?.positionId,timestamp:Date.now()}}var N}return nt=i,((i,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))o.call(i,c)||c===a||t(i,c,{get:()=>n[c],enumerable:!(s=e(n,c))||s.enumerable});return i})(t({},"__esModule",{value:!0}),nt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})})(i,{main:()=>main});var n=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,l=100000000000000n,u=546n,d=3,h=500,p=60,g=8e3;function m(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var w="DiamondHands.Protocol",f="1",y=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(y||{}),b={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],v={ethereum:1,sepolia:11155111,hardhat:1337};function P(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(y).join(", ")}`)}function S(t){return v[t]}function A(t){return Math.floor(t/p)*p}async function E(){const t=Math.floor(Date.now()/1e3),e=t%p;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%p;return e<8||e>=52}(t))return;let r;r=e>=52?p-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${A(Math.floor(Date.now()/1e3))}`)}var $=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,o){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,o){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],o),n=await i.positionDelegate(t);return!(!n||n===ethers.constants.AddressZero)&&n.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,o){const i=Math.floor(Date.now()/1e3);await E();const n=o?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const o=e??Math.floor(Date.now()/1e3),i=A(o),n=A(t);if(r?.strictCurrentQuantum){if(n!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${n}, current quantum: ${i}`);return}const a=i-p,s=i+p;if(n!==a&&n!==i&&n!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${a} (past), ${i} (current), ${s} (next)]`);if(n===a){if(o<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(n===s&&o>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyMintAuthorization(t,e,r,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o)}static async verifyPaymentAuthorization(t,e,r,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o)}static async verifyWithdrawAuthorization(e,r,o,i){if("withdraw-btc"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyRecoveryAuthorization(e,r,o,i){if("btc-utxo-invalidator"!==e.action)return!1;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(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,o,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(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o)}static async verifyBtcExecutionAuthorization(e,r,o,i){if("execute-btc-withdrawal"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(n,a,s)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,s,o))return!0;if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}),{strictCurrentQuantum:!0})}};function I(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function C(...t){I()&&console.log(...t)}var B=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},U=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${o}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const o=Date.now()-r;this.stepDurations.set(t,o),console.log(`[Step ${t}] Duration: ${o}ms`),o>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${o}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-i;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const o=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${o}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},D=class{static create(t="LIT Action",e){return I(e)?new U(t):new B}};function x(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function M(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function k(t){return t instanceof Error&&"AbortError"===t.name}var O=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),C(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Failed to fetch block height: ${o.status} ${o.statusText}`);const i=await o.text();if(i.trim().startsWith("<!DOCTYPE")||i.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const n=parseInt(i.trim(),10);if(isNaN(n)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${M(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: ${M(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${M(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,o=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const i=t.txid,n=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===n||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");o.push({txid:i,vout:n,satoshis:BigInt(a),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(i),C(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${M(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const l=this.parseBlockstreamUTXOs(c,n);return this.logger.stepEnd("1"),l}catch(t){if(clearTimeout(i),this.logger.stepEnd("1"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;const i=d,n=h;for(let e=1;e<=i;e++)try{this.logger.log("2",`UTXO query attempt ${e}/${i}...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(M(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${M(t)}`),e<i&&(this.logger.log("2",`Waiting ${n}ms before retry...`),await new Promise((t=>setTimeout(t,n))))}if(o)throw new Error(`Failed to query UTXOs after ${i} attempts: ${o.message}`);const a=r.reduce(((t,e)=>t+e.satoshis),0n),s=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),c=a-s;return{utxos:r,totalBalance:a,totalUTXOs:r.length,confirmedBalance:s,unconfirmedBalance:c}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:o.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(i),C(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const n=await e.json();if(!n.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=n.chain_stats.funded_txo_sum,s=n.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(i),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=M(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=M(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),C(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.status?{txid:n.txid??t,confirmations:n.status.confirmed&&n.status.block_height?1:0}:null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(M(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},N=class t{constructor(e,r,o){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error("Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass 3 distinct {name, apiKey} entries from the supported set: "+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Price oracle requires at least ${t.MIN_DISTINCT_PROVIDERS} eligible providers for consensus. Currently configured: ${this.sources.length} provider(s). Supported active providers: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(0===e.length)throw new Error("priceProviders must be a non-empty array of 3 distinct providers, each with an apiKey.");const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Supported: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires 3 DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use 3 different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"binance":if(!n.apiKey)throw new Error("Binance provider requires an apiKey");r.push(this.createBinanceSource(n.apiKey,i++));break;case"coinbase":if(!n.apiKey)throw new Error("Coinbase provider requires an apiKey");r.push(this.createCoinbaseSource(n.apiKey,i++));break;case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}if(r.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Insufficient price providers: need at least ${t.MIN_DISTINCT_PROVIDERS} distinct entries, got ${r.length}.`);return this.selectSampledSources(r)}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(){return async(t,e)=>{const r=new AbortController,o=setTimeout((()=>r.abort()),5e3);try{const o=await fetch(t,{headers:{Accept:"application/json",...e||{}},signal:r.signal});if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);return await o.json()}finally{clearTimeout(o)}}}getSelectionSeed(){const t="undefined"!=typeof process?process.env.PRICE_PROVIDER_SELECTION_SEED:void 0,e=t?Number(t):NaN;return Number.isFinite(e)?e:("undefined"!=typeof process,0,Math.floor(Date.now()+1e6*Math.random()))}selectSampledSources(t){const e=[...t];let r=this.getSelectionSeed()>>>0;for(let t=e.length-1;t>0;t--){const o=Math.floor((r=1664525*r+1013904223>>>0,r/4294967296*(t+1)));[e[t],e[o]]=[e[o],e[t]]}return e.slice(0,3).map(((t,e)=>({...t,priority:e+1})))}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson();return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const a=await r(n.toString(),i),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createBinanceSource(t,e){if(!t)throw new Error("createBinanceSource requires an apiKey");const r=this.createFetchJson();return{name:"Binance",fetchPrice:async()=>{const e=new URL("https://api.binance.com/api/v3/ticker/price");e.searchParams.set("symbol","BTCUSDT");const o=await r(e.toString(),{"X-MBX-APIKEY":t}),i=Number(o?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid Binance price payload");return i},priority:e}}createCoinbaseSource(t,e){if(!t)throw new Error("createCoinbaseSource requires an apiKey");const r=this.createFetchJson();return{name:"Coinbase",fetchPrice:async()=>{const e=await r("https://api.coinbase.com/v2/prices/BTC-USDT/spot",{"CB-ACCESS-KEY":t}),o=Number(e?.data?.amount);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid Coinbase price payload");return o},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson();return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const t=Date.now();if(3!==this.sources.length)throw new Error(`Price oracle requires exactly 3 providers. 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(),r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}))),o=[...await Promise.race([r,e])].sort(((t,e)=>t-e)),i=o[1];if((o[2]-o[0])/o[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=o.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}const n=Math.round(100*i),a=1000000n*BigInt(n),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${i.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}async getBTCPriceConsensus(){console.log("[Price Oracle] Fetching BTC price with consensus...");const t=(await Promise.allSettled(this.sources.map((async t=>{const e=await t.fetchPrice();return{source:t.name,price:e}})))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===t.length)throw new Error("No price sources returned data");console.log(`[Price Oracle] Got prices from ${t.length}/${this.sources.length} sources:`),t.forEach((t=>{console.log(` ${t.source}: $${t.price.toLocaleString()}`)}));const e=t.map((t=>t.price));e.sort(((t,e)=>t-e));const r=e[Math.floor(e.length/2)],o=e[0],i=e[e.length-1]/o,n=t.filter((t=>Math.abs(t.price-r)/r<=.02));if(i>1.05&&n.length===t.length)throw new Error(`Price consensus failed: sources too dispersed (${(100*(i-1)).toFixed(1)}% spread)`);if(n.length<t.length){const e=t.filter((t=>!n.find((e=>e.source===t.source))));if(console.log(`[Price Oracle] \u26a0\ufe0f Detected ${e.length} outlier(s):`),e.forEach((t=>{const e=Math.abs(t.price-r)/r;console.log(` ${t.source}: $${t.price.toLocaleString()} (${(100*e).toFixed(1)}% deviation)`)})),n.length<2)throw new Error("Price consensus failed: insufficient valid sources after outlier removal");console.log(`[Price Oracle] \u2705 Outliers filtered, continuing with ${n.length} valid sources`);const o=n.map((t=>t.price));o.sort(((t,e)=>t-e));const i=o[Math.floor(o.length/2)];console.log(`[Price Oracle] \u2705 Consensus price (median): $${i.toLocaleString()}`);const a=Math.round(100*i);return 1000000n*BigInt(a)}console.log(`[Price Oracle] \u2705 Consensus price (median): $${r.toLocaleString()}`);const a=Math.round(100*r);return 1000000n*BigInt(a)}};N.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinbase","binance","coinmarketcap","coingecko"],N.MIN_DISTINCT_PROVIDERS=3;var R=N,q=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),o=await this.getAuthorizedSpendsFromContract(t),i=o.reduce(((t,e)=>t+e.satoshis),0n),n=r>i?r-i:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:o,authorizedBalance:i,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,o),availableUTXOs:[],availableBalance:n,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const o=this.config.minConfirmations||6,i=await this.bitcoinProvider.getUTXOSet(e,o),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=n.reduce(((t,e)=>t+e.satoshis),0n),s=i.utxos.filter((t=>!this.isUTXOAuthorized(t,n))),c=s.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:a,authorizedSpendsHash:l,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,o){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===o))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],o);return(await i.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const o=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,o]))}};function L(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}function F(t,e,r,o){if(!t)return r??13e3;const i=o??n,a=Math.min(e,30);return n+a*a*(i-n)/900}function _(t,e,r){const o=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:o,collateralRatioBps:Number(o*s*10000n/r)}}function z(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}function 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 V(t){return t/100}var H=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.loanOpsManagerAddress,r,e),i=await o.liquidationThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.termManagerAddress,o,r),n=await i.getTermFees(t);return{originationFeeBps:Number(n.originationFee?.toString?.()??n[0]?.toString?.()??n[0]),extensionFeeBps:Number(n.extensionFee?.toString?.()??n[1]?.toString?.()??n[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:g},{name:"any",chainId:this.chainId}),o=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,i=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await i.getAuthorizedSpendsHash(o)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:g},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.liquidationManagerAddress,r,e),i=await o.maxEscalatedThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function W(t){return new H(t)}var j=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPriceConsensus()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=L(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=_(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPriceConsensus()]),n=W({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,l]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getTermFees(a)]),u=L(e.termStartTimestamp,e.selectedTerm),d=F(u.isExpired,u.daysIntoGracePeriod,s,c),h=_(o.availableBalance,i,e.ucdDebt),p=h.collateralRatioBps<d,g=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:o.totalBalance,totalUTXOs:o.totalUTXOs,authorizedSpendsSats:o.authorizedBalance,authorizedSpendsHash:o.authorizedSpendsHash,availableBTCSats:o.availableBalance,availableUTXOs:o.availableUTXOs,btcPriceUsd:i,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:u.termDurationDays,termLengthDays:u.termLengthDays,isExpired:u.isExpired,daysUntilExpiry:u.daysUntilExpiry,daysIntoGracePeriod:u.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:g,liquidationThresholdBps:s,originationFeeBps:l.originationFeeBps,extensionFeeBps:l.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const o=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:g},this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],o),n=await i.core(),a=new ethers.Contract(n,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],o),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const l=Number(s.expiryAt),u=Number(s.selectedTerm),d=Number(s.totalTerm),h=Number(s.previousExpiryAt),p=Number(s.lastRenewedAt),m=(f=u,0===(w=l)?0:w-30*f*86400);var w,f;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,P(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d,lastRenewedAt:p}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return b[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const o=await this.getVaultSnapshot(t);return function(t,e,r,o){const i=e+r;return 0n===i||Number(t*s*10000n/i)>=o}(o.collateralValueUsd,o.ucdDebt,e,r)}};var G="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",K={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],adminLiquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function J(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var Q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),Z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),tt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function et(t,e,r){return t.call({to:e,data:r})}async function rt(t,e){const r=new ethers.utils.Interface([G]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([G]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):J(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await et(t,e,Q.encodeFunctionData("views",[])),[o]=Q.decodeFunctionResult("views",r),[i,n,a,s,c,l,u,d]=await Promise.all([et(t,e,Q.encodeFunctionData("paused",[])),et(t,e,Q.encodeFunctionData("liquidationPaused",[])),et(t,e,Q.encodeFunctionData("simplePsm",[])),et(t,o,Y.encodeFunctionData("core",[])),et(t,o,Y.encodeFunctionData("loanOps",[])),et(t,o,Y.encodeFunctionData("collateralManager",[])),et(t,o,Y.encodeFunctionData("liquidationManager",[])),et(t,o,Y.encodeFunctionData("circuitBreaker",[]))]),h=Q.decodeFunctionResult("paused",i)[0],p=Q.decodeFunctionResult("liquidationPaused",n)[0],g=Q.decodeFunctionResult("simplePsm",a)[0],m=Y.decodeFunctionResult("core",s)[0],w=Y.decodeFunctionResult("loanOps",c)[0],f=Y.decodeFunctionResult("collateralManager",l)[0],y=Y.decodeFunctionResult("liquidationManager",u)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await et(t,w,Z.encodeFunctionData("getUcdController",[])),v=await et(t,w,Z.encodeFunctionData("ucdToken",[])),P=Z.decodeFunctionResult("getUcdController",T)[0],S=Z.decodeFunctionResult("ucdToken",v)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await et(t,e,tt.encodeFunctionData("paused",[]));return tt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,$,I,C,B,U,D,x]=await Promise.all([A(m),A(w),A(f),A(y),A(b),A(P),A(S),A(g)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:$,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:U,ucdTokenPaused:D,simplePsmPaused:x})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}function ot(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}var it={hardhat:{chain:"hardhat",chainId:v.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:v.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:v.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var nt,at=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}];async function st(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),o="string"==typeof e?e:String(e??"");if(!o)throw new Error("Decrypt returned empty plaintext");return o}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ct(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!o)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const n=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const o=new ethers.Contract(r,at,e),[i,n]=await o.getProviders(t),a=[];for(let t=0;t<i.length;t++)a.push({providerId:i[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return a}(t.chainId,e,r);if(0===o.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const i=[];for(const e of o){const r=await st(e.ciphertext,e.pkpId);i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o);return n[0]}function lt(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const o=t.substring(r+1).toLowerCase(),i=[];for(let t=0;t<o.length;t++){const r=e.indexOf(o[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${o[t]}`);i.push(r)}const n=i.slice(0,-6),a=(n[0],function(t,e,r,o){let i=0,n=0;const a=[],s=(1<<r)-1;for(let o=0;o<t.length;o++){const c=t[o];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,n+=e;n>=r;)n-=r,a.push(i>>n&s)}if(o)n>0&&a.push(i<<r-n&s);else if(n>=e||i<<r-n&s)throw new Error("Invalid padding in bit conversion");return a}(n.slice(1),5,8,!1));return{witnessProgram:a.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let o=0;o<t.length;o++){const i=e.indexOf(t[o]);if(i<0)throw new Error(`Invalid Base58 character: ${t[o]}`);r=58n*r+BigInt(i)}let o=r.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=D.create("BTC Withdrawal Validator");console.log("[Step 0] Validating configuration..."),e.stepStart("0","Validate configuration parameters");const r=globalThis.chain;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');const o=function(t){const e=P(t),r=it[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),i=o.chain,n=o.bitcoinNetwork;let a;if(console.log(` \u2705 Chain: ${r} (${i})`),console.log(` \u2705 Bitcoin Network: ${n}`),!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error('Required "contractAddresses" object with: PositionManager, LoanOperationsManagerModule, TermManagerModule');const s=globalThis.contractAddresses.PositionManager,p=globalThis.contractAddresses.LoanOperationsManagerModule,g=globalThis.contractAddresses.TermManagerModule,y=globalThis.contractAddresses.UCDController,b=globalThis.contractAddresses.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",A=globalThis.contractAddresses.BTCSpendAuthorizer??"";if(!(s&&p&&g&&y&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${s}`),console.log(` LoanOpsManager: ${p}`),e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const E=globalThis.auth;if(!E||"object"!=typeof E)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!E.positionId)throw new Error("auth.positionId is required");if("number"!=typeof E.timestamp)throw new Error("auth.timestamp must be a number");if(!E.signature)throw new Error("auth.signature is required");const I=BigInt(E.amount);if(I<=0n)throw new Error(`Withdrawal amount must be positive, got: ${I.toString()} sats`);const C=u;if(I<C)throw new Error(`Withdrawal amount ${I.toString()} sats is below minimum ${C.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const B=E.destinationAddress;if(!B||"string"!=typeof B)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const U=x().publicKey;if(!U)throw new Error("publicKey must not be blank");if("string"!=typeof U||0===U.length)throw new Error("publicKey must not be blank");const M=U;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(B),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(B);return!(!t&&!e)&&("testnet"===n||"regtest"===n?B.startsWith("m")||B.startsWith("n")||B.startsWith("2")||B.startsWith("tb1")||B.startsWith("bcrt1"):"mainnet"===n&&(B.startsWith("1")||B.startsWith("3")||B.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${B}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);console.log(` \u2705 Destination address validated: ${B} (${n})`);let k="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${E.positionId}`),console.log(` Withdrawal Amount: ${I.toString()} sats`),console.log(` Destination Address: ${B}`);const t=new R(globalThis.priceProviders,void 0),n=globalThis.rpcUrl;let u;n&&"string"==typeof n?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(o,n),console.log(` Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(n)}`),u=n):(u=await Lit.Actions.getRpcUrl({chain:r}),console.log(` Using LIT-provided RPC URL for chain: ${r}`));const P=new ethers.providers.JsonRpcProvider(u);a=await ct({policy:o,ethersProvider:P,registryAddress:globalThis.contractAddresses.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),console.log(` \u2705 Bitcoin Provider: ${a.name} (min confs ${a.minConfirmations})`);const C=new O({providerUrl:a.url});!function(t,e){const r=K[t],o=[];for(const t of r)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("withdrawBtc",await rt(P,s));const U=(N={contractAddress:A||p,chain:r,chainId:S(i),rpcUrl:u,bitcoinProvider:C,minConfirmations:a.minConfirmations},new q(N));k="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const D=function(t){return new j(t)}({contractAddress:s,termManagerAddress:g,loanOpsManagerAddress:p,liquidationManagerAddress:v,chain:r,chainId:S(i),rpcUrl:u,vaultBalance:U,priceOracle:t}),x=await D.getVaultSnapshot(E.positionId);console.log(` \u2705 Vault balance: ${x.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${x.ucdDebt.toString()} wei`),e.stepEnd("1"),k="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const L=e.getElapsed();console.log(`[TIMING] Step 2 started at ${L}ms`);const F=S(i),_=new ethers.providers.StaticJsonRpcProvider(u,F);let H;if(5===x.status){if(!b)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(b,["function pkpOwners(bytes32) view returns (address)"],_);if(H=await t.pkpOwners(x.pkpId),!H||H===ethers.constants.AddressZero)throw new Error("No PKP owner registered for this liquidated position in LITActionValidator");console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${H}`)}else H=x.borrower;if(!await $.verifyWithdrawAuthorization(E,H,_,globalThis.contractAddresses?.PositionDelegateRegistry))throw new Error("Caller not authorized");console.log(" \u2705 Caller authorized"),e.stepEnd("2"),k="2.5",console.log("[Step 2.5] Validating position status..."),e.stepStart("2.5","Validate position status");const W=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${W}ms`);if(![0,1,2,6,5].includes(x.status))throw new Error(`Position status ${m(x.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${m(x.status)}`),e.stepEnd("2.5"),k="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const G=e.getElapsed();console.log(`[TIMING] Step 3 started at ${G}ms`);const J=I;if(0n===x.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(x.btcPriceUsd<c||x.btcPriceUsd>l)throw new Error(`Bitcoin price ${x.btcPriceUsd} is outside acceptable range (${c} - ${l}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(x.btcPriceUsd)/1e8).toFixed(2)}`);const t=x.availableBTCSats-J,e=X(z(t,x.btcPriceUsd),x.ucdDebt);if(e<x.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${V(e)}% < liquidation threshold ${V(x.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${V(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${V(x.liquidationThresholdBps)}%`)}e.stepEnd("3"),k="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const Q=e.getElapsed();console.log(`[TIMING] Step 4 started at ${Q}ms`);const Y="string"==typeof E.amount?BigInt(E.amount):E.amount;if(Y!==I)throw new Error(`Authorization amount mismatch: auth.amount=${Y.toString()} sats, but requested withdrawal=${I.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),J>x.availableBTCSats)throw new Error(`Insufficient vault balance: need ${J.toString()} sats but only ${x.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const Z=x.availableBTCSats-J,tt=x.ucdDebt,et=z(Z,x.btcPriceUsd),it=tt>0n?X(et,tt):void 0;if(console.log(` Post-withdrawal collateral: ${Z.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(et)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${tt.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${tt>0n&&void 0!==it?V(Number(it)):"\u221e"}%`),Z<0n)throw new Error(`Withdrawal would result in negative balance: ${Z.toString()} sats`);console.log(" \u2705 Withdrawal validation passed"),e.stepEnd("4"),k="4.5",console.log("[Step 4.5] Querying vault UTXOs from Bitcoin network..."),e.stepStart("4.5","Query and select UTXO");const nt=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${nt}ms`);const at=x.vaultAddress;if(!at)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${at}`);let st=[],ut=null;const dt=d,ht=h;for(let t=1;t<=dt;t++)try{console.log(` \ud83d\udd04 UTXO query attempt ${t}/${dt}...`),st=await C.getUTXOs(at),console.log(` \u2705 UTXO query succeeded on attempt ${t}`),ut=null;break}catch(e){ut=e,console.error(` \u274c UTXO query failed on attempt ${t}:`,e.message),t<dt&&(console.log(` \u23f3 Waiting ${ht}ms before retry...`),await new Promise((t=>setTimeout(t,ht))))}if(ut)throw new Error(`Failed to query UTXOs after ${dt} attempts: ${ut.message}`);if(!st||0===st.length)throw new Error(`No UTXOs found in vault ${at}`);console.log(` \u2705 Found ${st.length} UTXO(s) in vault`);const pt=a.minConfirmations,gt=st.filter((t=>t.confirmations>=pt));if(0===gt.length)throw new Error(`No confirmed UTXOs found in vault. Required confirmations: ${pt}, found ${st.length} UTXO(s) with insufficient confirmations.`);console.log(` \u2705 Found ${gt.length} confirmed UTXO(s)`);const mt=gt.filter((t=>t.satoshis>=J));let wt;if(0===mt.length){const t=gt.reduce(((t,e)=>t+e.satoshis),0n);if(t<J)throw new Error(`Insufficient vault balance for withdrawal. Need ${J.toString()} sats, total across ${gt.length} UTXO(s): ${t.toString()} sats.`);wt=[...gt].sort(((t,e)=>Number(e.satoshis-t.satoshis)))[0],console.log(" \u2139\ufe0f No single UTXO covers withdrawal \u2014 multi-UTXO consolidation will be used in Phase 2."),console.log(` Primary UTXO (contract auth): ${wt.txid}:${wt.vout} (${wt.satoshis.toString()} sats)`)}else wt=mt.sort(((t,e)=>Number(t.satoshis-e.satoshis)))[0];console.log(` \u2705 Selected UTXO: ${wt.txid}:${wt.vout}`),console.log(` \u2705 UTXO value: ${wt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${wt.confirmations}`);const ft=x.availableBTCSats;if(wt.satoshis<ft&&console.warn(` \u26a0\ufe0f Selected UTXO value (${wt.satoshis.toString()}) < calculated balance (${ft.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),wt.satoshis<J)throw new Error(`Selected UTXO value (${wt.satoshis.toString()} sats) < withdrawal amount (${J.toString()} sats). This should never happen after eligibility filtering.`);console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const yt=lt(at).toLowerCase(),bt=await C.getTransactionOutputs(wt.txid);if(!bt)throw new Error(`Could not fetch transaction outputs for ${wt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);let Tt=-1;for(const t of bt){const e=(t.scriptpubkey??"").toLowerCase(),r=e.length>0&&e===yt,o=t.scriptpubkey_address===at;if(r||o){Tt=t.index;break}}if(-1===Tt)throw new Error(`Vault output not found in tx ${wt.txid}. Expected scriptPubKey ${yt} or address ${at}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);Tt!==wt.vout?(console.log(` \u26a0\ufe0f Esplora API reported vout=${wt.vout} but vault output is at vout=${Tt} (matched on hex scriptpubkey). Correcting.`),wt={...wt,vout:Tt}):console.log(` \u2705 UTXO vout=${wt.vout} confirmed correct`),e.stepEnd("4.5"),k="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const vt=e.getElapsed();console.log(`[TIMING] Step 5 started at ${vt}ms`);const Pt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(E.action)),St=x.authorizedSpendsHash,At=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[x.ucdDebt])),Et=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[s,p,g,y])),$t=BigInt(E.timestamp),It=Z,Ct=x.btcPriceUsd;if(Ct<c||Ct>l)throw new Error(`BTC price ${Ct.toString()} (8 decimals) is outside acceptable range (${c.toString()} - ${l.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",E.positionId),console.log(" action:",E.action),console.log(" actionHash:",Pt),console.log(" authorizedSpendsHash:",St),console.log(" ucdDebtHash:",At),console.log(" withdrawalAddress:",B),console.log(" totalDeduction:",J.toString()),console.log(" newCollateral:",It.toString()),console.log(" quantumTimestamp:",$t.toString()),console.log(" btcPrice:",Ct.toString()),console.log(" utxoTxid:",wt.txid),console.log(" utxoVout:",wt.vout);const Bt=ot(E.positionId),Ut=S(i),Dt={name:w,version:f,chainId:Ut,verifyingContract:ethers.utils.getAddress(p)},xt={WithdrawalAuthorization:[{name:"positionId",type:"bytes32"},{name:"actionHash",type:"bytes32"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractBundleHash",type:"bytes32"},{name:"withdrawalAddress",type:"string"},{name:"totalDeduction",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"utxoTxid",type:"string"},{name:"utxoVout",type:"uint32"},{name:"caller",type:"address"}]},Mt=ethers.utils._TypedDataEncoder.hash(Dt,xt,{positionId:Bt,actionHash:Pt,authorizedSpendsHash:St,ucdDebtHash:At,contractBundleHash:Et,withdrawalAddress:B,totalDeduction:J.toString(),newCollateral:It.toString(),quantumTimestamp:$t.toString(),btcPrice:Ct.toString(),utxoTxid:wt.txid,utxoVout:wt.vout,caller:ethers.utils.getAddress(H)});console.log("[Step 5] Contract message hash for signing:",Mt),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(Mt).length),e.stepEnd("5"),k="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const kt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${kt}ms`),e.log("6","========================================"),e.log("6","\ud83d\udd0d FINAL HASH INPUTS - ALL LIT NODES MUST MATCH"),e.log("6","========================================"),e.log("6",`Position ID: ${E.positionId}`),e.log("6",`Action Hash: ${Pt}`),e.log("6",`Authorized Spends Hash: ${St}`),e.log("6",`UCD Debt Hash: ${At}`),e.log("6",`Contract Bundle Hash: ${Et}`),e.log("6",`Destination Address: ${B}`),e.log("6",`Total Deduction: ${J.toString()}`),e.log("6",`New Collateral: ${It.toString()}`),e.log("6",`Quantum Timestamp: ${$t.toString()}`),e.log("6",`BTC Price: ${Ct.toString()}`),e.log("6",`Selected UTXO Txid: ${wt.txid}`),e.log("6",`Selected UTXO Vout: ${wt.vout}`),e.log("6",`Selected UTXO Satoshis: ${wt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${wt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${Mt}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${Mt}`),e.log("6",`publicKey: ${M}`),e.log("6","publicKey with 0x prefix: "+("0x"+M));const Ot=ethers.utils.arrayify(Mt);e.log("6",`messageBytes length: ${Ot.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(Ot))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const Nt=Date.now(),Rt=globalThis.validatorWalletAddress;if(!Rt||!Rt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const qt=await Lit.Actions.getPrivateKey({pkpId:Rt}),Lt="string"==typeof qt?qt.startsWith("0x")?qt:`0x${qt}`:String(qt),Ft=new ethers.Wallet(Lt),_t=new ethers.utils.SigningKey(Lt);e.log("6",`Wallet-derived signer address: ${Ft.address}`),e.log("6",`validatorWalletAddress: ${Rt}`);const zt=_t.signDigest(Mt),Xt=ethers.utils.joinSignature(zt),Vt=Date.now()-Nt;e.log("6",`Chipotle signature created in ${Vt}ms`),e.log("6",`signature: ${Xt}`);const Ht=globalThis.contractAddresses.BTCSpendAuthorizer?.trim()||"";let Wt=null;if(Ht){const t=ot(E.positionId),r=S(i),o=It+J,n={name:w,version:f,chainId:r,verifyingContract:ethers.utils.getAddress(Ht)},a={BtcSpendAuth:[{name:"positionId",type:"bytes32"},{name:"txid",type:"string"},{name:"vout",type:"uint32"},{name:"satoshis",type:"uint256"},{name:"targetAddress",type:"string"},{name:"targetAmount",type:"uint256"}]},s=ethers.utils._TypedDataEncoder.hash(n,a,{positionId:t,txid:wt.txid,vout:wt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:J.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${s}`),Wt=await Ft._signTypedData(n,a,{positionId:t,txid:wt.txid,vout:wt.vout,satoshis:o.toString(),targetAddress:B,targetAmount:J.toString()}),e.log("6",`btcSpendAuth signature: ${Wt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const jt={approved:!0,positionId:E.positionId,actionHash:Pt,authorizedSpendsHash:St,ucdDebtHash:At,contractBundleHash:Et,totalDeduction:J.toString(),remainingCollateral:Z.toString(),newCollateralRatioBps:tt>0n&&void 0!==it?Number(it):void 0,destinationAddress:B,signature:Xt,btcSpendAuthSignature:Wt,timestamp:$t.toString(),btcPrice:Ct.toString(),utxoTxid:wt.txid,utxoVout:wt.vout,utxoSatoshis:wt.satoshis.toString()};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",J,"type:",typeof J,"toString():",J.toString()),console.log(" remainingCollateral:",Z,"type:",typeof Z,"toString():",Z.toString()),console.log(" btcPrice:",Ct,"type:",typeof Ct,"toString():",Ct.toString()),console.log(" timestamp:",$t,"type:",typeof $t,"toString():",$t.toString()),console.log(" Full response object:",JSON.stringify(jt,null,2)),jt}catch(t){return console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${k}`),e.error("error",`Failed: ${t.message}`),{approved:!1,reason:t.message||t.toString(),positionId:E?.positionId,timestamp:Date.now()}}var N}return nt=i,((i,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))o.call(i,c)||c===a||t(i,c,{get:()=>n[c],enumerable:!(s=e(n,c))||s.enumerable});return i})(t({},"__esModule",{value:!0}),nt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -1 +1 @@
1
- c87585e6a5bd6fa2062b584b4a994e01c90bec02c69bb142e7c1019007fb3db7
1
+ 033e698b572f62f49bc34be94f4355957e3fe46d98001744805b44e74655b9ac
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-withdrawal",
3
- "originalSize": 169579,
4
- "minifiedSize": 73094,
5
- "compressionRatio": 0.5689678556896786,
6
- "hash": "c87585e6a5bd6fa2062b584b4a994e01c90bec02c69bb142e7c1019007fb3db7",
7
- "buildTime": 1778598693083,
3
+ "originalSize": 172354,
4
+ "minifiedSize": 73808,
5
+ "compressionRatio": 0.5717650881325644,
6
+ "hash": "033e698b572f62f49bc34be94f4355957e3fe46d98001744805b44e74655b9ac",
7
+ "buildTime": 1779034976560,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 832,
5
5
  "compressionRatio": 0.5026897788404064,
6
6
  "hash": "700f8992a20357ac718df78f82a75641e892d24bcb925357087cf062cf521ae0",
7
- "buildTime": 1778598693092,
7
+ "buildTime": 1779034976566,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1046,
5
5
  "compressionRatio": 0.473313192346425,
6
6
  "hash": "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72",
7
- "buildTime": 1778598693100,
7
+ "buildTime": 1779034976575,
8
8
  "version": "0.1.0"
9
9
  }