@gvnrdao/dh-lit-actions 0.0.320 → 0.0.321

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 (35) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/agent-module-executor.action.js +1 -1
  9. package/dist/agent-module-executor.hash +1 -1
  10. package/dist/agent-module-executor.meta.json +5 -5
  11. package/dist/btc-address-balance.meta.json +1 -1
  12. package/dist/btc-transaction-signer.meta.json +1 -1
  13. package/dist/btc-utxo-invalidator.meta.json +1 -1
  14. package/dist/btc-withdrawal.action.js +1 -1
  15. package/dist/btc-withdrawal.hash +1 -1
  16. package/dist/btc-withdrawal.meta.json +5 -5
  17. package/dist/encrypt-parameter.meta.json +1 -1
  18. package/dist/extend-position-validator.meta.json +1 -1
  19. package/dist/liquidation-validator.meta.json +1 -1
  20. package/dist/loan-vault-btc-balance.meta.json +1 -1
  21. package/dist/pkp-validator.meta.json +1 -1
  22. package/dist/price-oracle.meta.json +1 -1
  23. package/dist/process-payment-validator.meta.json +1 -1
  24. package/dist/stale-spend-recovery-validator.meta.json +1 -1
  25. package/dist/ucd-mint-validator.meta.json +1 -1
  26. package/package.json +4 -2
  27. package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
  28. package/pkg-dist/pkg-src/index.js +18 -24
  29. package/pkg-dist/pkg-src/index.js.map +2 -2
  30. package/pkg-dist/src/constants/chunks/deployment-addresses.d.ts +7 -0
  31. package/pkg-dist/src/constants/chunks/deployment-addresses.d.ts.map +1 -1
  32. package/pkg-dist/src/modules/business-rules-math.module.d.ts +30 -0
  33. package/pkg-dist/src/modules/business-rules-math.module.d.ts.map +1 -1
  34. package/pkg-dist/src/modules/pinned-addresses.d.ts +39 -1
  35. package/pkg-dist/src/modules/pinned-addresses.d.ts.map +1 -1
@@ -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,s=100000000n,a=1000000000000000000n,c=25e14,l=1000000000000n,u=100000000000000n,d=546n,h=60,p=8e3,g={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};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 f="DiamondHands.Protocol",w="1",y=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(y||{}),v={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},b=["infura.io","drpc.org"],$={ethereum:1,sepolia:11155111,hardhat:1337};function T(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(y).join(", ")}`)}function P(t){return $[t]}function S(t){return Math.floor(t/h)*h}async function E(){const t=Math.floor(Date.now()/1e3),e=t%h;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%h;return e<8||e>=52}(t))return;let r;r=e>=52?h-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: ${S(Math.floor(Date.now()/1e3))}`)}var A=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 checkAgentDelegationGrant(t,e,r,o,i){try{const n=new ethers.Contract(o,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],i);if("renew"===r){const[r]=await n.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await n.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[s,,a]=await n.canMint(t,e);return{ok:!0===s,effectiveFloorBps:Number(a)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,o,i){if(!o.module||!o.factory||!o.registry)return!1;const n=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],i);if(!0!==await n.isModuleEnabled(o.module))return!1;const s=new ethers.Contract(o.factory,["function isFromFactory(address) view returns (bool)"],i);if(!0!==await s.isFromFactory(o.module))return!1;const a=new ethers.Contract(o.module,["function safe() view returns (address)","function agent() view returns (address)"],i),c=await a.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const l=await a.agent();if(!l||l.toLowerCase()!==e.toLowerCase())return!1;const u=new ethers.Contract(o.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],i),[d,,h]=await u.canWithdraw(t,l);return!0===d&&(o.outcome={effectiveFloorBps:Number(h)},!0)}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=S(o),n=S(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 s=i-h,a=i+h;if(n!==s&&n!==i&&n!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${n}, Valid range: [${s} (past), ${i} (current), ${a} (next)]`);if(n===s){if(o<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(n===a&&o>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,n,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const s=e();let a="0x0000000000000000000000000000000000000000";try{a=await this.recoverSigner(s,t.signature)}catch{}return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i,n,s){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,a,c)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,o,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,o,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i,n)}static async verifyPaymentAuthorization(t,e,r,o,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i,n)}static async verifyWithdrawAuthorization(e,r,o,i,n){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,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.checkSafeAgentWithdrawAuthorization(e.positionId,o,r,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,o,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,o,n)=>e.toLowerCase()===r.toLowerCase()||!(!i||!await t.checkEIP1271(r,o,n,i))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,o,i,n,s){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,a,c)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,o,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,o,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o,i,n)}static async verifyBtcExecutionAuthorization(e,r,o,i,n){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");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(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],o)}),(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.checkSafeAgentWithdrawAuthorization(e.positionId,o,r,n,i)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function C(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 I(...t){C()&&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}},B=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}},k=class{static create(t="LIT Action",e){return C(e)?new B(t):new x}};function U(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function D(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}function O(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function R(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&O(r,"provider url"),{url:r,auth:{provider:"esplora"}};let o;try{o=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof o.url||0===o.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=o.url.trim();switch(o.provider){case void 0:case"esplora":return e?.requireHttps&&O(i,"esplora provider url"),{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof o.apiKey||0===o.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return O(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:o.apiKey}};case"blockstream-enterprise":{if("string"!=typeof o.clientId||0===o.clientId.length||"string"!=typeof o.clientSecret||0===o.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");O(i,"blockstream-enterprise provider url");const t="string"==typeof o.tokenUrl&&o.tokenUrl.length>0;return t&&O(o.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:o.clientId,clientSecret:o.clientSecret,...t?{tokenUrl:o.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(o.provider)}"`)}}var N=new Map;async function F(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",o=`${r}\n${t.clientId}`,i=N.get(o);if(i)return i;const n=(async()=>{const o=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,i=new AbortController,n=setTimeout((()=>i.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,signal:i.signal})}finally{clearTimeout(n)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>N.delete(o))),N.set(o,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function q(t,e){if(!Number.isSafeInteger(t)||t<0||t>c)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var L=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=k.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await F(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),I(`[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"),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: ${D(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: ${D(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${D(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=>{const e=Math.round(1e8*t.amount);return q(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),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,s=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===n||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");q(s,`parseBlockstreamUTXOs ${i}:${n}`),o.push({txid:i,vout:n,satoshis:BigInt(s),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(i),I(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const 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 c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${D(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"),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(D(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${D(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(o)throw new Error(`Failed to query UTXOs after 3 attempts: ${o.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=i-n;return{utxos:r,totalBalance:i,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:o.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(i),I(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const s=await n.json();if(!s.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=s.chain_stats.funded_txo_sum,c=s.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);q(a,`getBalance ${e} funded_txo_sum`),q(c,`getBalance ${e} spent_txo_sum`);const l=a-c;q(l,`getBalance ${e} confirmed balance`);const u=BigInt(l);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),u}catch(t){if(clearTimeout(i),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=D(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=D(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),I(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:n.txid??t,confirmations:1};const o=(await r.text()).trim(),i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<=0)return{txid:n.txid??t,confirmations:1};const s=i-n.status.block_height+1;return{txid:n.txid??t,confirmations:s>0?s:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(D(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return q(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),M(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},_=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,o,i){if(this.devSingleProvider=!0===i?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`CryptoCompare HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(t){return async(e,r)=>{const o=new AbortController,i=setTimeout((()=>o.abort()),5e3);try{const i=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:o.signal});if(!i.ok)throw new Error(`${t} HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const s=await r(n.toString(),i),a=Number(s?.bitcoin?.usd);if(!Number.isFinite(a)||a<=0)throw new Error("Invalid CoinGecko price payload");return a},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),o=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let i;if(this.devSingleProvider)i=o[0];else{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),s=1000000n*BigInt(n),a=Date.now()-t;return console.log(`[Price Oracle] Median price: $${i.toLocaleString()} \u2014 total time: ${a}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${s}`),s}};_.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],_.REQUIRED_PROVIDER_COUNT=3;var z=_;async function X(t,e,r,o){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:o});return"string"==typeof t?t:String(t??"")}catch(r){const o=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${o}`)}}var H=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new L({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const o=this.providerConfigs,i=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const n=new Set,s=t.filter((t=>t.confirmations>=r));for(const t of s)n.add(`${t.txid}:${t.vout}`);if(!o||o.length<=1||!i)return n;const a=t=>o[t].name||o[t].providerUrl,c=await Promise.allSettled(i.slice(1).map((t=>t.getUTXOSet(e,r)))),l=c.map(((t,e)=>({r:t,name:a(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(l.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${l.length}/${o.length-1} secondary provider(s): ${l.join("; ")}`);const u=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of s){const e=`${t.txid}:${t.vout}`;let o=t.confirmations,i=t.confirmations;for(let r=0;r<u.length;r++){const n=u[r].get(e),s=a(r+1);if(!n)throw new Error(`Confirmed UTXO ${e} present on ${a(0)} but absent on ${s}; refusing to sign (possible fabricated UTXO).`);if(n.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${s}=${n.value.toString()}; refusing to sign.`);n.confirmations<o&&(o=n.confirmations),n.confirmations>i&&(i=n.confirmations)}if(i-o>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${i-o} exceeds tolerance 3 (min ${o}, max ${i}); providers disagree on depth, refusing to sign.`);o<r&&(n.delete(e),d.push(e))}d.length>0&&I(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<u.length;t++){const e=a(t+1);for(const[o,i]of u[t]){if(i.confirmations<r)continue;const t=h.get(o);if(!t)throw new Error(`Confirmed UTXO ${o} present on ${e} (${i.confirmations} confs) but absent on ${a(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==i.value)throw new Error(`Confirmed UTXO ${o} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${e}=${i.value.toString()}; refusing to sign.`);if(i.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${o} depth disagreement: ${a(0)}=${t.confirmations} vs ${e}=${i.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return n}async classifySelfChange(t,e,r){const o=this.providerConfigs,i=this.readers,n=new Set,s=t.filter((t=>t.confirmations<r));if(0===s.length)return n;if(this.assertProviderFloor("classifySelfChange"),!o||0===o.length||!i)return I(`[VaultBalance] ${s.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),n;const a=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of s){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const l=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),u=[...c.keys()].sort(((t,e)=>{const r=l(e)-l(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),d=u.slice(0,5),h=u.length-d.length;h>0&&I(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const o=new Array(t.length);let i=0;const n=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=i++;if(e>=t.length)return;o[e]=await r(t[e])}}));return await Promise.all(n),o}(d,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),a,r,o,i)}))),g=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of s)g.has(t.txid)&&n.add(`${t.txid}:${t.vout}`);return g.size>0&&I(`[VaultBalance] self-change: ${n.size}/${s.length} unconfirmed UTXO(s) verified as protocol change by ${o.length} provider(s)`),n}async verifyParentIsSelfSpendConsensus(t,e,r,o,i,n){const s=t=>i[t].name||i[t].providerUrl,a=await Promise.allSettled(i.map(((i,s)=>this.evaluateParentForProvider(t,e,r,o,n[s],i)))),c=a.map(((t,e)=>({r:t,name:s(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${i.length} provider(s): ${c.join("; ")}`);const l=a.map((t=>t.value)),u=l.map((t=>t.selfSpend)),d=u.map(((t,e)=>({vote:t,name:s(e)}))).filter((t=>t.vote!==u[0])).map((t=>`${s(0)}=${u[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!u[0])return!1;const h=l.map(((t,e)=>t.outputMismatch?`${s(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,o,i,n){const s=await this.fetchParentTransaction(t,n);if(!s||0===s.inputs.length)return{selfSpend:!1,outputMismatch:null};const a=await this.verifyInputsAreSelfSpend(s.inputs,r,o,i),c=a?function(t,e,r){for(const o of t){const t=e.find((t=>t.index===o.vout));if(!t)return`claimed output ${o.txid}:${o.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${o.txid}:${o.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==o.satoshis)return`claimed output ${o.txid}:${o.vout} value ${t.value?.toString()??"<missing>"} != reported ${o.satoshis.toString()}`}return null}(e,s.outputs,r):null;return{selfSpend:a,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,o){const i=[...new Set(t.map((t=>t.txid)))],n=new Map,s=i.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(s.map((async t=>{n.set(t,await o.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=n.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const a=await Promise.all(i.map((t=>o.getTransaction(t))));for(const t of a)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,o=new AbortController,i=setTimeout((()=>o.abort()),r);try{const i=await fetch(`${e.providerUrl}/tx/${t}`,{signal:o.signal,headers:await F(e.auth,r)});if(!i.ok){if(404===i.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();if(!n.vin||!Array.isArray(n.vin)||0===n.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const s=[];for(const e of n.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);s.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:s,outputs:Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(M(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(i)}}},V=class{constructor(t){if(!Number.isInteger(t.minConfirmations)||t.minConfirmations<1)throw new Error(`VaultBalanceModule: minConfirmations must be a positive integer (got ${t.minConfirmations}). Pass the policy-derived balance-confirmation threshold \u2014 there is no default.`);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){const r=this.config.minConfirmations,o=await this.bitcoinProvider.getUTXOSet(e,r),i=await this.getAuthorizedSpendsFromContract(t);for(const t of i){if(o.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const n=i.reduce(((t,e)=>t+e.satoshis),0n),s=new H(this.bitcoinProvider,this.config.bitcoinProviderConfigs,this.config.minConsensusProviders??1),a=await s.confirmedUtxoConsensus(o.utxos,e,r),c=await s.classifySelfChange(o.utxos,e,r),l=o.utxos.filter((t=>(a.has(`${t.txid}:${t.vout}`)||c.has(`${t.txid}:${t.vout}`))&&!this.isUTXOAuthorized(t,i))),u=l.reduce(((t,e)=>t+e.satoshis),0n),d=this.computeAuthorizedSpendsHash(t,i);return{totalUTXOs:o.utxos,totalBalance:o.totalBalance,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:d,availableUTXOs:l,availableBalance:u,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:p},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 j(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/s}function W(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 K(t){return t/100}var G=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:p},{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:p},{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:p},{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:p},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=new ethers.Contract(this.liquidationManagerAddress,r,e),i=await o.maxEscalatedThreshold();return Number(i.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function J(t,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 v[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var Q=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),c=(l={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},new G(l));var l;const u=this.config.termOverride??e.selectedTerm,[d,h,p]=await Promise.all([c.getLiquidationThreshold(),c.getMaxEscalatedThreshold(),c.getTermFees(u)]),g=function(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}(e.termStartTimestamp,e.selectedTerm),m=function(t,e,r,o){if(!t)return r;const i=o??n,s=Math.min(e,30);return n+s*s*(i-n)/900}(g.isExpired,g.daysIntoGracePeriod,d,h),f=function(t,e,r){const o=t*e/(100000000n*s);return 0n===r?{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:o,collateralRatioBps:Number(o*a*10000n/r)}}(o.availableBalance,i,e.ucdDebt),w=f.collateralRatioBps<m,y=f.collateralRatioBps-m;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:f.collateralValueUsd,collateralRatioBps:f.collateralRatioBps,termDurationDays:g.termDurationDays,termLengthDays:g.termLengthDays,isExpired:g.isExpired,daysUntilExpiry:g.daysUntilExpiry,daysIntoGracePeriod:g.daysIntoGracePeriod,currentLiquidationThreshold:m,isLiquidatable:w,marginToLiquidationBps:y,liquidationThresholdBps:d,originationFeeBps:p.originationFeeBps,extensionFeeBps:p.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:p},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(),s=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),a=await s.getPositionDetails(e),c=Number(a.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(a,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(a.expiryAt),u=Number(a.selectedTerm),d=Number(a.totalTerm),h=Number(a.previousExpiryAt),g=Number(a.lastRenewedAt),m=(w=u,0===(f=l)?0:f-30*w*86400);var f,w;const y=J(a.vaultAddress,T(this.config.chain));if("string"!=typeof y||0===y.length)throw new Error(`Position ${e} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:a.positionId,pkpId:a.pkpId,borrower:a.borrower,vaultAddress:y,ucdDebt:BigInt(a.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d,lastRenewedAt:g}}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*a*10000n/i)>=o}(o.collateralValueUsd,o.ucdDebt,e,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))",Y={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function tt(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 et=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),rt=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),ot=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),it=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function nt(t,e,r){return t.call({to:e,data:r})}async function st(t,e){const r=new ethers.utils.Interface([Z]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([Z]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?tt({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]}):tt(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await nt(t,e,et.encodeFunctionData("views",[])),[o]=et.decodeFunctionResult("views",r),[i,n,s,a,c,l,u,d]=await Promise.all([nt(t,e,et.encodeFunctionData("paused",[])),nt(t,e,et.encodeFunctionData("liquidationPaused",[])),nt(t,e,et.encodeFunctionData("simplePsm",[])),nt(t,o,rt.encodeFunctionData("core",[])),nt(t,o,rt.encodeFunctionData("loanOps",[])),nt(t,o,rt.encodeFunctionData("collateralManager",[])),nt(t,o,rt.encodeFunctionData("liquidationManager",[])),nt(t,o,rt.encodeFunctionData("circuitBreaker",[]))]),h=et.decodeFunctionResult("paused",i)[0],p=et.decodeFunctionResult("liquidationPaused",n)[0],g=et.decodeFunctionResult("simplePsm",s)[0],m=rt.decodeFunctionResult("core",a)[0],f=rt.decodeFunctionResult("loanOps",c)[0],w=rt.decodeFunctionResult("collateralManager",l)[0],y=rt.decodeFunctionResult("liquidationManager",u)[0],v=rt.decodeFunctionResult("circuitBreaker",d)[0],b=await nt(t,f,ot.encodeFunctionData("getUcdController",[])),$=await nt(t,f,ot.encodeFunctionData("ucdToken",[])),T=ot.decodeFunctionResult("getUcdController",b)[0],P=ot.decodeFunctionResult("ucdToken",$)[0],S=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await nt(t,e,it.encodeFunctionData("paused",[]));return it.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,A,C,I,x,B,k,U]=await Promise.all([S(m),S(f),S(w),S(y),S(v),S(T),S(P),S(g)]);return tt({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:A,collateralManagerPaused:C,liquidationManagerPaused:I,circuitBreakerPaused:x,ucdControllerPaused:B,ucdTokenPaused:k,simplePsmPaused:U})}(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 at(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 ct={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var lt=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry"];function ut(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const o=(i=t.chainId,g[i]??null);var i;if(!o)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of lt){const i=o[e];if(!i)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${i}); refusing to sign`);r[e]=i}return r}var dt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],ht=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function pt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),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 gt(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!o)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const o=new ethers.Contract(r,dt,e),[i,n]=await o.getProviders(t),s=[];for(let t=0;t<i.length;t++)s.push({providerId:i[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return s}(t.chainId,e,r);if(o.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${o.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:o}=t;if(!o||"string"!=typeof o)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),s=new ethers.Contract(o,ht,r);let a;try{a=await s.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${n.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const i=[];for(const e of o){const r=await pt(e.ciphertext,e.pkpId),{url:o,auth:n}=R(r,{requireHttps:!0});i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:o,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o)}async function mt(t,e,r,o,i){if(e.length<r)throw new Error(`Bitcoin balance consensus requires at least ${r} provider(s) on this chain; ${e.length} configured. Refusing to sign a balance without cross-check.`);return e.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null):async function(t,e,r,o,i){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=i??(t=>new L({providerUrl:t.url,auth:t.auth,...o?{timeout:o}:{}})),s=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=s.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const c=s.map((t=>t.value)),l=c[0],u=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(u.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${u.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`);return l}(t,e,r,o,i)}function ft(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),o=t.toUpperCase();if(t!==r&&t!==o)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const i=r;if(i.length>90)throw new Error(`Bech32 address too long (${i.length} > 90): ${t}`);const n=i.lastIndexOf("1");if(n<1||n+7>i.length)throw new Error(`Invalid bech32 separator position in ${t}`);const s=i.slice(0,n),a=i.slice(n+1),c=[];for(let r=0;r<a.length;r++){const o=e.indexOf(a[r]);if(-1===o)throw new Error(`Invalid bech32 character '${a[r]}' in ${t}`);c.push(o)}const l=c[0];if(void 0===l||l<0||l>16)throw new Error(`Invalid witness version ${l} in ${t}`);const u=0===l?yt:vt;if(function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let o=0;o<t.length;o++){const i=r>>25;r=(33554431&r)<<5^t[o];for(let t=0;t<5;t++)i>>t&1&&(r^=e[t])}return 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}(s).concat(c))!==u)throw new Error(`Invalid bech32${0===l?"":"m"} checksum for ${t}`);const d=function(t,e,r,o){let i=0,n=0;const s=[],a=(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,s.push(i>>n&a)}if(o)n>0&&s.push(i<<r-n&a);else if(n>=e||i<<r-n&a)throw new Error("Invalid padding in bit conversion");return s}(c.slice(1,c.length-6),5,8,!1);if(d.length<2||d.length>40)throw new Error(`Invalid witness program length ${d.length} in ${t}`);if(0===l&&20!==d.length&&32!==d.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${d.length} in ${t}`);const h=d.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:l,program:h}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){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);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),o=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==o)throw new Error(`Invalid Base58Check checksum for ${t}`);const i=parseInt(r.slice(0,2),16),n=r.slice(2);return{version:i,hash:n}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}var wt,yt=1,vt=734539939;async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=k.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=T(t),r=ct[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(r),i=o.chain,n=o.bitcoinNetwork;let s=[];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 a=ut(o,globalThis.contractAddresses),c=a.PositionManager,h=a.LoanOperationsManagerModule,p=globalThis.contractAddresses.TermManagerModule,g=globalThis.contractAddresses.UCDController,y=a.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",$=a.BTCSpendAuthorizer??"";if(!(c&&h&&p&&g&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");if(console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${c}`),console.log(` LoanOpsManager: ${h}`),!o.allowArbitraryBitcoinProvider&&!a.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const S=globalThis.auth;if(!S||"object"!=typeof S)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!S.positionId)throw new Error("auth.positionId is required");if("number"!=typeof S.timestamp)throw new Error("auth.timestamp must be a number");if(!S.signature)throw new Error("auth.signature is required");const E=BigInt(S.amount);if(E<=0n)throw new Error(`Withdrawal amount must be positive, got: ${E.toString()} sats`);const C=d;if(E<C)throw new Error(`Withdrawal amount ${E.toString()} sats is below minimum ${C.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const I=S.destinationAddress;if(!I||"string"!=typeof I)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const x=U().publicKey;if(!x)throw new Error("publicKey must not be blank");if("string"!=typeof x||0===x.length)throw new Error("publicKey must not be blank");const B=x;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(I),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(I);return!(!t&&!e)&&("testnet"===n||"regtest"===n?I.startsWith("m")||I.startsWith("n")||I.startsWith("2")||I.startsWith("tb1")||I.startsWith("bcrt1"):"mainnet"===n&&(I.startsWith("1")||I.startsWith("3")||I.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${I}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);try{ft(I)}catch(t){throw new Error(`Destination address ${I} passed format validation but cannot be encoded to a scriptPubKey (Phase 2 would reject it after authorization): ${t?.message??String(t)}`)}console.log(` \u2705 Destination address validated: ${I} (${n})`);let D="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${S.positionId}`),console.log(` Withdrawal Amount: ${E.toString()} sats`),console.log(` Destination Address: ${I}`);const t=await async function(t){if(!t)return t;const e=[];for(const o of t){if(!o?.name||"string"!=typeof o.name)throw new Error("Each price provider must include a valid name");let t,i;if(o.pkpId&&"string"==typeof o.pkpId){const e=(r=o.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;o.apiKey&&(t=await X(o.name,"apiKey",e,o.apiKey)),o.apiSecret&&(i=await X(o.name,"apiSecret",e,o.apiSecret))}else t=o.apiKey,i=o.apiSecret;e.push({name:o.name,apiKey:t,apiSecret:i})}var r;return e}(globalThis.priceProviders),n=!0===globalThis.devPriceMode;if(n&&!o.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${o.chain}`);const d=new z(t,void 0,void 0,{devSingleProvider:n&&o.allowDevSinglePriceProvider}),T=globalThis.rpcUrl;if(!T||"string"!=typeof T)throw new Error("rpcUrl is required for btc-withdrawal validation");!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(!b.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${b.join(", ")}`)}(o,T),console.log(` Using RPC URL: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(T)}`);const C=T,x=new ethers.providers.JsonRpcProvider(C);s=await gt({policy:o,ethersProvider:x,registryAddress:a.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});const k=s[0];console.log(` \u2705 Bitcoin Providers: ${s.length} (${s.map((t=>t.name)).join(", ")})`);const U=new L({providerUrl:k.url,auth:k.auth});!function(t,e){const r=Y[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 st(x,c));const O=(M={contractAddress:$||h,chain:r,chainId:P(i),rpcUrl:C,bitcoinProvider:U,minConfirmations:k.minConfirmations,bitcoinProviderConfigs:s.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),minConsensusProviders:o.minConsensusProviders},new V(M));D="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const R=function(t){return new Q(t)}({contractAddress:c,termManagerAddress:p,loanOpsManagerAddress:h,liquidationManagerAddress:v,chain:r,chainId:P(i),rpcUrl:C,vaultBalance:O,priceOracle:d}),N=await R.getVaultSnapshot(S.positionId);await mt(N.vaultAddress,s,o.minConsensusProviders),console.log(` \u2705 Vault balance: ${N.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${N.ucdDebt.toString()} wei`),e.stepEnd("1"),D="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const F=e.getElapsed();console.log(`[TIMING] Step 2 started at ${F}ms`);const q=P(i),_=new ethers.providers.StaticJsonRpcProvider(C,q);let H;if(5===N.status){if(!y)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(y,["function pkpOwners(bytes32) view returns (address)"],_);if(H=await t.pkpOwners(N.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=N.borrower;if(!await A.verifyWithdrawAuthorization(S,H,q,_))throw new Error("Caller not authorized");console.log(" \u2705 Caller authorized"),e.stepEnd("2"),D="2.5",console.log("[Step 2.5] Validating position status..."),e.stepStart("2.5","Validate position status");const G=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${G}ms`);if(![0,1,2,6,5].includes(N.status))throw new Error(`Position status ${m(N.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${m(N.status)}`),e.stepEnd("2.5"),D="2.6";const J=globalThis.contractAddresses?.BitcoinWithdrawalAddressRegistry;if(J&&J!==ethers.constants.AddressZero){e.stepStart("2.6","Enforce approved-address allowlist"),console.log("[Step 2.6] Checking approved-withdrawal-address allowlist...");const t=new ethers.Contract(J,["function isApproved(address user, string btcAddress) view returns (bool)"],_);if(!await t.isApproved(H,I))throw new Error(`Withdrawal address ${I} is not an approved destination for controller ${H} (not on the allowlist, or its time-lock delay has not elapsed).`);console.log(` \u2705 Destination on controller's allowlist: ${I}`),e.stepEnd("2.6")}D="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const Z=e.getElapsed();console.log(`[TIMING] Step 3 started at ${Z}ms`);const tt=E;if(0n===N.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(N.btcPriceUsd<l||N.btcPriceUsd>u)throw new Error(`Bitcoin price ${N.btcPriceUsd} is outside acceptable range (${l} - ${u}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(N.btcPriceUsd)/1e8).toFixed(2)}`);const t=N.availableBTCSats-tt,e=W(j(t,N.btcPriceUsd),N.ucdDebt);if(e<N.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${K(e)}% < liquidation threshold ${K(N.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${K(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${K(N.liquidationThresholdBps)}%`)}e.stepEnd("3"),D="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const et=e.getElapsed();console.log(`[TIMING] Step 4 started at ${et}ms`);const rt="string"==typeof S.amount?BigInt(S.amount):S.amount;if(rt!==E)throw new Error(`Authorization amount mismatch: auth.amount=${rt.toString()} sats, but requested withdrawal=${E.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),tt>N.availableBTCSats)throw new Error(`Insufficient vault balance: need ${tt.toString()} sats but only ${N.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const ot=N.availableBTCSats-tt,it=N.ucdDebt,nt=j(ot,N.btcPriceUsd),ct=it>0n?W(nt,it):void 0;if(console.log(` Post-withdrawal collateral: ${ot.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(nt)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${it.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${it>0n&&void 0!==ct?K(Number(ct)):"\u221e"}%`),ot<0n)throw new Error(`Withdrawal would result in negative balance: ${ot.toString()} sats`);console.log(" \u2705 Withdrawal validation passed"),e.stepEnd("4"),D="4.5",console.log("[Step 4.5] Querying vault UTXOs from Bitcoin network..."),e.stepStart("4.5","Query and select UTXO");const lt=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${lt}ms`);const ut=N.vaultAddress;if(!ut)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${ut}`);const dt=o.minBitcoinSpendConfirmations,ht=function(t,e){if(!Number.isInteger(e)||e<1)throw new Error(`filterSpendableUtxos: minConf must be a positive integer (got ${e})`);return t.filter((t=>t.confirmations>=e))}(N.availableUTXOs,dt);if(0===ht.length)throw new Error(`No spendable consensus UTXOs in vault ${ut} at >= ${dt} confirmations (snapshot availableUTXOs: ${N.availableUTXOs.length}).`);console.log(` \u2705 ${ht.length} spendable consensus UTXO(s) (>= ${dt} confs)`);const{selectedUTXO:pt,multiUtxoConsolidation:wt}=function(t,e){const r=(t,e)=>{const r=t.txid.toLowerCase(),o=e.txid.toLowerCase();return r<o?-1:r>o?1:t.vout-e.vout};if(!Array.isArray(t)||0===t.length)throw new Error("selectWithdrawalUtxo: at least one confirmed UTXO is required");if("bigint"!=typeof e||e<=0n)throw new Error(`selectWithdrawalUtxo: totalDeduction must be a positive bigint (got ${String(e)})`);const o=t.filter((t=>t.satoshis>=e));if(0===o.length){const o=t.reduce(((t,e)=>t+e.satoshis),0n);if(o<e)throw new Error(`Insufficient vault balance for withdrawal. Need ${e.toString()} sats, total across ${t.length} confirmed UTXO(s): ${o.toString()} sats.`);return{selectedUTXO:[...t].sort(((t,e)=>(e.satoshis>t.satoshis?1:e.satoshis<t.satoshis?-1:0)||r(t,e)))[0],multiUtxoConsolidation:!0}}const i=[...o].sort(((t,e)=>(t.satoshis>e.satoshis?1:t.satoshis<e.satoshis?-1:0)||r(t,e)))[0];if(i.satoshis<e)throw new Error(`Selected UTXO value (${i.satoshis.toString()} sats) < withdrawal amount (${e.toString()} sats) on the single-UTXO path. This should never happen after eligibility filtering.`);return{selectedUTXO:i,multiUtxoConsolidation:!1}}(ht,tt);let yt=pt;wt&&(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): ${yt.txid}:${yt.vout} (${yt.satoshis.toString()} sats)`)),console.log(` \u2705 Selected UTXO: ${yt.txid}:${yt.vout}`),console.log(` \u2705 UTXO value: ${yt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${yt.confirmations}`);const vt=N.availableBTCSats;yt.satoshis<vt&&console.warn(` \u26a0\ufe0f Selected UTXO value (${yt.satoshis.toString()}) < calculated balance (${vt.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const bt=ft(ut).toLowerCase(),$t=await U.getTransactionOutputs(yt.txid);if(!$t)throw new Error(`Could not fetch transaction outputs for ${yt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);const Tt=yt.vout;yt=function(t,e,r,o){const i=r.toLowerCase(),n=e=>{if(!Number.isSafeInteger(e.value)||e.value<0)throw new Error(`Vault output ${t.txid}:${e.index} has a non-sane value (${String(e.value)}) \u2014 corrupt provider response, refusing to canonicalize against it.`);return BigInt(e.value)===t.satoshis},s=e.filter((t=>{const e=(t.scriptpubkey??"").toLowerCase();return e.length>0&&e===i||t.scriptpubkey_address===o}));if(0===s.length)throw new Error(`Vault output not found in tx ${t.txid}. Expected scriptPubKey ${i} or address ${o}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);const a=s.find((e=>e.index===t.vout));if(a&&n(a))return t;const c=s.filter(n);if(0===c.length)throw new Error(`No vault output in tx ${t.txid} carries the selected value ${t.satoshis.toString()} sats (scriptPubKey ${i} / address ${o}). Refusing to authorize a corrupted (vout, value) pair.`);if(c.length>1)throw new Error(`Ambiguous vout correction in tx ${t.txid}: reported vout ${t.vout} is not a vault output carrying the selected value, and ${c.length} vault outputs (vouts ${c.map((t=>t.index)).join(", ")}) all carry ${t.satoshis.toString()} sats. Refusing to guess \u2014 an index-order pick could authorize an outpoint that collides with authorized-spend bookkeeping.`);return{...t,vout:c[0].index}}(yt,$t,bt,ut),yt.vout!==Tt?console.log(` \u26a0\ufe0f Esplora API reported vout=${Tt} but the vault output carrying ${yt.satoshis.toString()} sats is at vout=${yt.vout} (matched on scriptPubKey + value). Correcting.`):console.log(` \u2705 UTXO vout=${yt.vout} confirmed correct`),e.stepEnd("4.5"),D="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const Pt=e.getElapsed();console.log(`[TIMING] Step 5 started at ${Pt}ms`);const St=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(S.action)),Et=N.authorizedSpendsHash,At=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[N.ucdDebt])),Ct=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[c,h,p,g])),It=BigInt(S.timestamp),xt=ot,Bt=N.btcPriceUsd;if(Bt<l||Bt>u)throw new Error(`BTC price ${Bt.toString()} (8 decimals) is outside acceptable range (${l.toString()} - ${u.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",S.positionId),console.log(" action:",S.action),console.log(" actionHash:",St),console.log(" authorizedSpendsHash:",Et),console.log(" ucdDebtHash:",At),console.log(" withdrawalAddress:",I),console.log(" totalDeduction:",tt.toString()),console.log(" newCollateral:",xt.toString()),console.log(" quantumTimestamp:",It.toString()),console.log(" btcPrice:",Bt.toString()),console.log(" utxoTxid:",yt.txid),console.log(" utxoVout:",yt.vout);const kt=at(S.positionId),Ut=P(i),Dt={name:f,version:w,chainId:Ut,verifyingContract:ethers.utils.getAddress(h)},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"}]},Ot=ethers.utils._TypedDataEncoder.hash(Dt,Mt,{positionId:kt,actionHash:St,authorizedSpendsHash:Et,ucdDebtHash:At,contractBundleHash:Ct,withdrawalAddress:I,totalDeduction:tt.toString(),newCollateral:xt.toString(),quantumTimestamp:It.toString(),btcPrice:Bt.toString(),utxoTxid:yt.txid,utxoVout:yt.vout,caller:ethers.utils.getAddress(H)});console.log("[Step 5] Contract message hash for signing:",Ot),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(Ot).length),e.stepEnd("5"),D="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const Rt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${Rt}ms`),e.log("6","========================================"),e.log("6","\ud83d\udd0d FINAL HASH INPUTS - ALL LIT NODES MUST MATCH"),e.log("6","========================================"),e.log("6",`Position ID: ${S.positionId}`),e.log("6",`Action Hash: ${St}`),e.log("6",`Authorized Spends Hash: ${Et}`),e.log("6",`UCD Debt Hash: ${At}`),e.log("6",`Contract Bundle Hash: ${Ct}`),e.log("6",`Destination Address: ${I}`),e.log("6",`Total Deduction: ${tt.toString()}`),e.log("6",`New Collateral: ${xt.toString()}`),e.log("6",`Quantum Timestamp: ${It.toString()}`),e.log("6",`BTC Price: ${Bt.toString()}`),e.log("6",`Selected UTXO Txid: ${yt.txid}`),e.log("6",`Selected UTXO Vout: ${yt.vout}`),e.log("6",`Selected UTXO Satoshis: ${yt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${yt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${Ot}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${Ot}`),e.log("6",`publicKey: ${B}`),e.log("6","publicKey with 0x prefix: "+("0x"+B));const Nt=ethers.utils.arrayify(Ot);e.log("6",`messageBytes length: ${Nt.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(Nt))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const Ft=Date.now(),qt=globalThis.validatorWalletAddress;if(!qt||!qt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Lt=await Lit.Actions.getPrivateKey({pkpId:qt}),_t="string"==typeof Lt?Lt.startsWith("0x")?Lt:`0x${Lt}`:String(Lt),zt=new ethers.Wallet(_t),Xt=new ethers.utils.SigningKey(_t);e.log("6",`Wallet-derived signer address: ${zt.address}`),e.log("6",`validatorWalletAddress: ${qt}`);const Ht=Xt.signDigest(Ot),Vt=ethers.utils.joinSignature(Ht),jt=Date.now()-Ft;e.log("6",`Chipotle signature created in ${jt}ms`),e.log("6",`signature: ${Vt}`);const Wt=$?.trim()||"";let Kt=null;if(Wt){const t=at(S.positionId),r=P(i),o=xt+tt,n={name:f,version:w,chainId:r,verifyingContract:ethers.utils.getAddress(Wt)},s={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"}]},a=ethers.utils._TypedDataEncoder.hash(n,s,{positionId:t,txid:yt.txid,vout:yt.vout,satoshis:o.toString(),targetAddress:I,targetAmount:tt.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${a}`),Kt=await zt._signTypedData(n,s,{positionId:t,txid:yt.txid,vout:yt.vout,satoshis:o.toString(),targetAddress:I,targetAmount:tt.toString()}),e.log("6",`btcSpendAuth signature: ${Kt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const Gt=ht.map((t=>({txid:t.txid,vout:t.txid===yt.txid&&t.vout===pt.vout?yt.vout:t.vout,value:t.satoshis.toString()}))),Jt=new Set;for(const t of Gt){const e=`${t.txid.toLowerCase()}:${t.vout}`;if(Jt.has(e))throw new Error(`confirmedUtxos: duplicate outpoint ${e} after representative vout remap \u2014 refusing to emit a spend set the SDK would silently dedupe.`);Jt.add(e)}const Qt=$t.find((t=>t.index===yt.vout));if(!Qt||BigInt(Qt.value)!==yt.satoshis)throw new Error(`Representative UTXO ${yt.txid}:${yt.vout} declares ${yt.satoshis.toString()} sats but the funding tx output at that vout is ${Qt?Qt.value:"absent"} \u2014 (vout, value) decoupled; refusing to authorize.`);const Zt={approved:!0,positionId:S.positionId,actionHash:St,authorizedSpendsHash:Et,ucdDebtHash:At,contractBundleHash:Ct,totalDeduction:tt.toString(),remainingCollateral:ot.toString(),newCollateralRatioBps:it>0n&&void 0!==ct?Number(ct):void 0,destinationAddress:I,signature:Vt,btcSpendAuthSignature:Kt,timestamp:It.toString(),btcPrice:Bt.toString(),utxoTxid:yt.txid,utxoVout:yt.vout,utxoSatoshis:yt.satoshis.toString(),confirmedUtxos:Gt};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",tt,"type:",typeof tt,"toString():",tt.toString()),console.log(" remainingCollateral:",ot,"type:",typeof ot,"toString():",ot.toString()),console.log(" btcPrice:",Bt,"type:",typeof Bt,"toString():",Bt.toString()),console.log(" timestamp:",It,"type:",typeof It,"toString():",It.toString()),console.log(" Full response object:",JSON.stringify(Zt,null,2)),Zt}catch(t){throw console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${D}`),e.error("error",`Failed: ${t.message}`),t}var M}return wt=i,((i,n,s,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))o.call(i,c)||c===s||t(i,c,{get:()=>n[c],enumerable:!(a=e(n,c))||a.enumerable});return i})(t({},"__esModule",{value:!0}),wt)})();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=25e14,l=1000000000000n,u=100000000000000n,d=546n,h=60,p=8e3,g={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};var m={1:{AgentDelegationRegistry:"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa",BitcoinWithdrawalAddressRegistry:"0xf667f77FDba7458345f227eB6Bfe4148243E7270"},11155111:{AgentModuleFactory:"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5",AgentDelegationRegistry:"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",BitcoinWithdrawalAddressRegistry:"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe"}};function f(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",y="1",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),b={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},$=["infura.io","drpc.org"],T={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(v).join(", ")}`)}function A(t){return T[t]}function S(t){return Math.floor(t/h)*h}async function E(){const t=Math.floor(Date.now()/1e3),e=t%h;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%h;return e<8||e>=52}(t))return;let r;r=e>=52?h-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: ${S(Math.floor(Date.now()/1e3))}`)}var C=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),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 checkAgentDelegationGrant(t,e,r,o,i){try{const n=new ethers.Contract(o,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],i);if("renew"===r){const[r]=await n.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await n.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[a,,s]=await n.canMint(t,e);return{ok:!0===a,effectiveFloorBps:Number(s)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,o,i){if(!o.module||!o.factory||!o.registry)return!1;const n=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],i);if(!0!==await n.isModuleEnabled(o.module))return!1;const a=new ethers.Contract(o.factory,["function isFromFactory(address) view returns (bool)"],i);if(!0!==await a.isFromFactory(o.module))return!1;const s=new ethers.Contract(o.module,["function safe() view returns (address)","function agent() view returns (address)"],i),c=await s.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const l=await s.agent();if(!l||l.toLowerCase()!==e.toLowerCase())return!1;const u=new ethers.Contract(o.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],i),[d,,h]=await u.canWithdraw(t,l);return!0===d&&(o.outcome={effectiveFloorBps:Number(h)},!0)}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=S(o),n=S(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-h,s=i+h;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();let s="0x0000000000000000000000000000000000000000";try{s=await this.recoverSigner(a,t.signature)}catch{}return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,o,i,n,a){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,s,c)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,c,i))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,o,a.op,a.registry,i);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,o,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i,n)}static async verifyPaymentAuthorization(t,e,r,o,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,o,i,n)}static async verifyWithdrawAuthorization(e,r,o,i,n){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkSafeAgentWithdrawAuthorization(e.positionId,o,r,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,o,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,o,n)=>e.toLowerCase()===r.toLowerCase()||!(!i||!await t.checkEIP1271(r,o,n,i))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,o,i,n,a){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,s,c)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,c,i))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,o,a.op,a.registry,i);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,o,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,o,i,n)}static async verifyBtcExecutionAuthorization(e,r,o,i,n){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");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(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkSafeAgentWithdrawAuthorization(e.positionId,o,r,n,i)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function I(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function x(...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}},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,o=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${o}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const o=Date.now()-r;this.stepDurations.set(t,o),console.log(`[Step ${t}] Duration: ${o}ms`),o>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${o}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-i;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const o=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${o}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},U=class{static create(t="LIT Action",e){return I(e)?new k(t):new B}};function D(){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 O(t){return t instanceof Error&&"AbortError"===t.name}function R(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function N(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&R(r,"provider url"),{url:r,auth:{provider:"esplora"}};let o;try{o=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof o.url||0===o.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=o.url.trim();switch(o.provider){case void 0:case"esplora":return e?.requireHttps&&R(i,"esplora provider url"),{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof o.apiKey||0===o.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return R(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:o.apiKey}};case"blockstream-enterprise":{if("string"!=typeof o.clientId||0===o.clientId.length||"string"!=typeof o.clientSecret||0===o.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");R(i,"blockstream-enterprise provider url");const t="string"==typeof o.tokenUrl&&o.tokenUrl.length>0;return t&&R(o.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:o.clientId,clientSecret:o.clientSecret,...t?{tokenUrl:o.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(o.provider)}"`)}}var F=new Map;async function L(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",o=`${r}\n${t.clientId}`,i=F.get(o);if(i)return i;const n=(async()=>{const o=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,i=new AbortController,n=setTimeout((()=>i.abort()),e&&e>0?e:1e4);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o,signal:i.signal})}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return n.catch((()=>F.delete(o))),F.set(o,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function q(t,e){if(!Number.isSafeInteger(t)||t<0||t>c)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var _=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=U.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await L(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),o=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),x(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Failed to fetch block height: ${o.status} ${o.statusText}`);const i=await o.text();if(i.trim().startsWith("<!DOCTYPE")||i.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const n=parseInt(i.trim(),10);if(isNaN(n)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${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=>{const e=Math.round(1e8*t.amount);return q(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),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");q(a,`parseBlockstreamUTXOs ${i}:${n}`),o.push({txid:i,vout:n,satoshis:BigInt(a),confirmations:r})}return o}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:o.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(i),x(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${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"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],o=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),o=null;break}catch(t){o=t instanceof Error?t:new Error(M(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${M(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(o)throw new Error(`Failed to query UTXOs after 3 attempts: ${o.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=i-n;return{utxos:r,totalBalance:i,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const o=new AbortController,i=setTimeout((()=>o.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:o.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(i),x(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const a=await n.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=a.chain_stats.funded_txo_sum,c=a.chain_stats.spent_txo_sum;if(void 0===s||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${c}`);q(s,`getBalance ${e} funded_txo_sum`),q(c,`getBalance ${e} spent_txo_sum`);const l=s-c;q(l,`getBalance ${e} confirmed balance`);const u=BigInt(l);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),u}catch(t){if(clearTimeout(i),O(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,headers:await this.withAuth()});if(clearTimeout(r),x(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-o}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:n.txid??t,confirmations:1};const o=(await r.text()).trim(),i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<=0)return{txid:n.txid??t,confirmations:1};const a=i-n.status.block_height+1;return{txid:n.txid??t,confirmations:a>0?a:0}}catch{return{txid:n.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),O(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,headers:await this.withAuth()});if(clearTimeout(r),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return q(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},z=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,o,i){if(this.devSingleProvider=!0===i?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],o=new Set;let i=1;for(const n of e){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=n.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${n.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(o.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(o.add(e),e){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const o=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!o.ok)throw new Error(`CryptoCompare HTTP ${o.status} ${o.statusText}`);return await o.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),o=Number(r?.USDT);if(!Number.isFinite(o)||o<=0)throw new Error("Invalid CryptoCompare price payload");return o},priority:e}}createFetchJson(t){return async(e,r)=>{const o=new AbortController,i=setTimeout((()=>o.abort()),5e3);try{const i=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:o.signal});if(!i.ok)throw new Error(`${t} HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),o=e?t.slice(4):t,i=e?{"x-cg-pro-api-key":o}:{"x-cg-demo-api-key":o},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const a=await r(n.toString(),i),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const o=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),i=Number(o?.data?.BTC?.[0]?.quote?.USDT?.price??o?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),o=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let i;if(this.devSingleProvider)i=o[0];else{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}};z.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],z.REQUIRED_PROVIDER_COUNT=3;var X=z;async function H(t,e,r,o){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:o});return"string"==typeof t?t:String(t??"")}catch(r){const o=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${o}`)}}var V=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new _({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const o=this.providerConfigs,i=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const n=new Set,a=t.filter((t=>t.confirmations>=r));for(const t of a)n.add(`${t.txid}:${t.vout}`);if(!o||o.length<=1||!i)return n;const s=t=>o[t].name||o[t].providerUrl,c=await Promise.allSettled(i.slice(1).map((t=>t.getUTXOSet(e,r)))),l=c.map(((t,e)=>({r:t,name:s(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(l.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${l.length}/${o.length-1} secondary provider(s): ${l.join("; ")}`);const u=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of a){const e=`${t.txid}:${t.vout}`;let o=t.confirmations,i=t.confirmations;for(let r=0;r<u.length;r++){const n=u[r].get(e),a=s(r+1);if(!n)throw new Error(`Confirmed UTXO ${e} present on ${s(0)} but absent on ${a}; refusing to sign (possible fabricated UTXO).`);if(n.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${a}=${n.value.toString()}; refusing to sign.`);n.confirmations<o&&(o=n.confirmations),n.confirmations>i&&(i=n.confirmations)}if(i-o>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${i-o} exceeds tolerance 3 (min ${o}, max ${i}); providers disagree on depth, refusing to sign.`);o<r&&(n.delete(e),d.push(e))}d.length>0&&x(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<u.length;t++){const e=s(t+1);for(const[o,i]of u[t]){if(i.confirmations<r)continue;const t=h.get(o);if(!t)throw new Error(`Confirmed UTXO ${o} present on ${e} (${i.confirmations} confs) but absent on ${s(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==i.value)throw new Error(`Confirmed UTXO ${o} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${e}=${i.value.toString()}; refusing to sign.`);if(i.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${o} depth disagreement: ${s(0)}=${t.confirmations} vs ${e}=${i.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return n}async classifySelfChange(t,e,r){const o=this.providerConfigs,i=this.readers,n=new Set,a=t.filter((t=>t.confirmations<r));if(0===a.length)return n;if(this.assertProviderFloor("classifySelfChange"),!o||0===o.length||!i)return x(`[VaultBalance] ${a.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),n;const s=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of a){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const l=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),u=[...c.keys()].sort(((t,e)=>{const r=l(e)-l(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),d=u.slice(0,5),h=u.length-d.length;h>0&&x(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const o=new Array(t.length);let i=0;const n=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=i++;if(e>=t.length)return;o[e]=await r(t[e])}}));return await Promise.all(n),o}(d,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),s,r,o,i)}))),g=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of a)g.has(t.txid)&&n.add(`${t.txid}:${t.vout}`);return g.size>0&&x(`[VaultBalance] self-change: ${n.size}/${a.length} unconfirmed UTXO(s) verified as protocol change by ${o.length} provider(s)`),n}async verifyParentIsSelfSpendConsensus(t,e,r,o,i,n){const a=t=>i[t].name||i[t].providerUrl,s=await Promise.allSettled(i.map(((i,a)=>this.evaluateParentForProvider(t,e,r,o,n[a],i)))),c=s.map(((t,e)=>({r:t,name:a(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${i.length} provider(s): ${c.join("; ")}`);const l=s.map((t=>t.value)),u=l.map((t=>t.selfSpend)),d=u.map(((t,e)=>({vote:t,name:a(e)}))).filter((t=>t.vote!==u[0])).map((t=>`${a(0)}=${u[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!u[0])return!1;const h=l.map(((t,e)=>t.outputMismatch?`${a(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,o,i,n){const a=await this.fetchParentTransaction(t,n);if(!a||0===a.inputs.length)return{selfSpend:!1,outputMismatch:null};const s=await this.verifyInputsAreSelfSpend(a.inputs,r,o,i),c=s?function(t,e,r){for(const o of t){const t=e.find((t=>t.index===o.vout));if(!t)return`claimed output ${o.txid}:${o.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${o.txid}:${o.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==o.satoshis)return`claimed output ${o.txid}:${o.vout} value ${t.value?.toString()??"<missing>"} != reported ${o.satoshis.toString()}`}return null}(e,a.outputs,r):null;return{selfSpend:s,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,o){const i=[...new Set(t.map((t=>t.txid)))],n=new Map,a=i.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(a.map((async t=>{n.set(t,await o.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=n.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const s=await Promise.all(i.map((t=>o.getTransaction(t))));for(const t of s)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,o=new AbortController,i=setTimeout((()=>o.abort()),r);try{const i=await fetch(`${e.providerUrl}/tx/${t}`,{signal:o.signal,headers:await L(e.auth,r)});if(!i.ok){if(404===i.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();if(!n.vin||!Array.isArray(n.vin)||0===n.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const a=[];for(const e of n.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);a.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:a,outputs:Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(O(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(i)}}},W=class{constructor(t){if(!Number.isInteger(t.minConfirmations)||t.minConfirmations<1)throw new Error(`VaultBalanceModule: minConfirmations must be a positive integer (got ${t.minConfirmations}). Pass the policy-derived balance-confirmation threshold \u2014 there is no default.`);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){const r=this.config.minConfirmations,o=await this.bitcoinProvider.getUTXOSet(e,r),i=await this.getAuthorizedSpendsFromContract(t);for(const t of i){if(o.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const n=i.reduce(((t,e)=>t+e.satoshis),0n),a=new V(this.bitcoinProvider,this.config.bitcoinProviderConfigs,this.config.minConsensusProviders??1),s=await a.confirmedUtxoConsensus(o.utxos,e,r),c=await a.classifySelfChange(o.utxos,e,r),l=o.utxos.filter((t=>(s.has(`${t.txid}:${t.vout}`)||c.has(`${t.txid}:${t.vout}`))&&!this.isUTXOAuthorized(t,i))),u=l.reduce(((t,e)=>t+e.satoshis),0n),d=this.computeAuthorizedSpendsHash(t,i);return{totalUTXOs:o.utxos,totalBalance:o.totalBalance,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:d,availableUTXOs:l,availableBalance:u,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:p},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 j(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 K(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 G(t){return t/100}var J=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:p},{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:p},{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:p},{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:p},{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 Q(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"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var Z=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[o,i]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),c=(l={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},new J(l));var l;const u=this.config.termOverride??e.selectedTerm,[d,h,p]=await Promise.all([c.getLiquidationThreshold(),c.getMaxEscalatedThreshold(),c.getTermFees(u)]),g=function(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=30*e,o=Math.floor(Date.now()/1e3)-t,i=Math.floor(o/86400);return{termDurationDays:i,termLengthDays:r,isExpired:i>r,daysUntilExpiry:Math.max(0,r-i),daysIntoGracePeriod:Math.max(0,i-r)}}(e.termStartTimestamp,e.selectedTerm),m=function(t,e,r,o){if(!t)return r;const i=o??n,a=Math.min(e,30);return n+a*a*(i-n)/900}(g.isExpired,g.daysIntoGracePeriod,d,h),f=function(t,e,r){const o=t*e/(100000000n*a);return 0n===r?{collateralValueUsd:o,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:o,collateralRatioBps:Number(o*s*10000n/r)}}(o.availableBalance,i,e.ucdDebt),w=f.collateralRatioBps<m,y=f.collateralRatioBps-m;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:f.collateralValueUsd,collateralRatioBps:f.collateralRatioBps,termDurationDays:g.termDurationDays,termLengthDays:g.termLengthDays,isExpired:g.isExpired,daysUntilExpiry:g.daysUntilExpiry,daysIntoGracePeriod:g.daysIntoGracePeriod,currentLiquidationThreshold:m,isLiquidatable:w,marginToLiquidationBps:y,liquidationThresholdBps:d,originationFeeBps:p.originationFeeBps,extensionFeeBps:p.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:p},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),g=Number(s.lastRenewedAt),m=(w=u,0===(f=l)?0:f-30*w*86400);var f,w;const y=Q(s.vaultAddress,P(this.config.chain));if("string"!=typeof y||0===y.length)throw new Error(`Position ${e} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:y,ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:u,status:c,expiryAt:l,previousExpiryAt:h,totalTerm:d,lastRenewedAt:g}}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 Y="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))",tt={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function et(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 rt=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),ot=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)"]),it=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),nt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function at(t,e,r){return t.call({to:e,data:r})}async function st(t,e){const r=new ethers.utils.Interface([Y]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([Y]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?et({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]}):et(e)}(await t.call({to:e,data:r}))}catch(t){o=t}try{return await async function(t,e){const r=await at(t,e,rt.encodeFunctionData("views",[])),[o]=rt.decodeFunctionResult("views",r),[i,n,a,s,c,l,u,d]=await Promise.all([at(t,e,rt.encodeFunctionData("paused",[])),at(t,e,rt.encodeFunctionData("liquidationPaused",[])),at(t,e,rt.encodeFunctionData("simplePsm",[])),at(t,o,ot.encodeFunctionData("core",[])),at(t,o,ot.encodeFunctionData("loanOps",[])),at(t,o,ot.encodeFunctionData("collateralManager",[])),at(t,o,ot.encodeFunctionData("liquidationManager",[])),at(t,o,ot.encodeFunctionData("circuitBreaker",[]))]),h=rt.decodeFunctionResult("paused",i)[0],p=rt.decodeFunctionResult("liquidationPaused",n)[0],g=rt.decodeFunctionResult("simplePsm",a)[0],m=ot.decodeFunctionResult("core",s)[0],f=ot.decodeFunctionResult("loanOps",c)[0],w=ot.decodeFunctionResult("collateralManager",l)[0],y=ot.decodeFunctionResult("liquidationManager",u)[0],v=ot.decodeFunctionResult("circuitBreaker",d)[0],b=await at(t,f,it.encodeFunctionData("getUcdController",[])),$=await at(t,f,it.encodeFunctionData("ucdToken",[])),T=it.decodeFunctionResult("getUcdController",b)[0],P=it.decodeFunctionResult("ucdToken",$)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await at(t,e,nt.encodeFunctionData("paused",[]));return nt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[S,E,C,I,x,B,k,U]=await Promise.all([A(m),A(f),A(w),A(y),A(v),A(T),A(P),A(g)]);return et({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:S,loanOperationsPaused:E,collateralManagerPaused:C,liquidationManagerPaused:I,circuitBreakerPaused:x,ucdControllerPaused:B,ucdTokenPaused:k,simplePsmPaused:U})}(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 ct(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 lt={hardhat:{chain:"hardhat",chainId:T.hardhat,bitcoinNetwork:b.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:T.sepolia,bitcoinNetwork:b.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:T.ethereum,bitcoinNetwork:b.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var ut=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry"];function dt(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const o=(i=t.chainId,g[i]??null);var i;if(!o)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of ut){const i=o[e];if(!i)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${i}); refusing to sign`);r[e]=i}return r}var ht=["AgentModuleFactory","AgentDelegationRegistry","BitcoinWithdrawalAddressRegistry"];function pt(t,e){if(!t.pinContractAddresses){const t={};for(const r of ht){const o=e?.[r];"string"==typeof o&&o.length>0&&(t[r]=o)}return t}const r=(o=t.chainId,m[o]??{});var o;const i={};for(const o of ht){const n=r[o];if(!n)continue;const a=e?.[o];if("string"==typeof a&&a.length>0&&a.toLowerCase()!==n.toLowerCase())throw new Error(`Caller-supplied "${o}" (${a}) contradicts the pinned ${t.chain} address (${n}); refusing to evaluate the Safe-agent authorization arm`);i[o]=n}return i}var gt="0x0000000000000000000000000000000000000000";function mt(t){return"string"==typeof t&&t.length>0&&t.toLowerCase()!==gt}var ft=[{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"}],wt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function yt(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 vt(t){const{policy:e,ethersProvider:r,registryAddress:o,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!o)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const o=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const o=new ethers.Contract(r,ft,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(o.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${o.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:o}=t;if(!o||"string"!=typeof o)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),a=new ethers.Contract(o,wt,r);let s;try{s=await a.isAllowedCid(e,n)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${n.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const i=[];for(const e of o){const r=await yt(e.ciphertext,e.pkpId),{url:o,auth:n}=N(r,{requireHttps:!0});i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:o,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return i}(e,r,o)}async function bt(t,e,r,o,i){if(e.length<r)throw new Error(`Bitcoin balance consensus requires at least ${r} provider(s) on this chain; ${e.length} configured. Refusing to sign a balance without cross-check.`);return e.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null):async function(t,e,r,o,i){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=i??(t=>new _({providerUrl:t.url,auth:t.auth,...o?{timeout:o}:{}})),a=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),s=a.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(s.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${s.length}/${e.length} provider(s): ${s.join("; ")}`);const c=a.map((t=>t.value)),l=c[0],u=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(u.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${u.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`);return l}(t,e,r,o,i)}function $t(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),o=t.toUpperCase();if(t!==r&&t!==o)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const i=r;if(i.length>90)throw new Error(`Bech32 address too long (${i.length} > 90): ${t}`);const n=i.lastIndexOf("1");if(n<1||n+7>i.length)throw new Error(`Invalid bech32 separator position in ${t}`);const a=i.slice(0,n),s=i.slice(n+1),c=[];for(let r=0;r<s.length;r++){const o=e.indexOf(s[r]);if(-1===o)throw new Error(`Invalid bech32 character '${s[r]}' in ${t}`);c.push(o)}const l=c[0];if(void 0===l||l<0||l>16)throw new Error(`Invalid witness version ${l} in ${t}`);const u=0===l?Pt:At;if(function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let o=0;o<t.length;o++){const i=r>>25;r=(33554431&r)<<5^t[o];for(let t=0;t<5;t++)i>>t&1&&(r^=e[t])}return 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}(a).concat(c))!==u)throw new Error(`Invalid bech32${0===l?"":"m"} checksum for ${t}`);const d=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}(c.slice(1,c.length-6),5,8,!1);if(d.length<2||d.length>40)throw new Error(`Invalid witness program length ${d.length} in ${t}`);if(0===l&&20!==d.length&&32!==d.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${d.length} in ${t}`);const h=d.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:l,program:h}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){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);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),o=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==o)throw new Error(`Invalid Base58Check checksum for ${t}`);const i=parseInt(r.slice(0,2),16),n=r.slice(2);return{version:i,hash:n}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}var Tt,Pt=1,At=734539939;async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=U.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=lt[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=dt(o,globalThis.contractAddresses),c=s.PositionManager,h=s.LoanOperationsManagerModule,p=globalThis.contractAddresses.TermManagerModule,g=globalThis.contractAddresses.UCDController,m=s.LITActionValidator,v=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",b=s.BTCSpendAuthorizer??"";if(!(c&&h&&p&&g&&v))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");if(console.log(" \u2705 Contract addresses loaded and validated"),console.log(` PositionManager: ${c}`),console.log(` LoanOpsManager: ${h}`),!o.allowArbitraryBitcoinProvider&&!s.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 action pulls all registered providers from on-chain registry");e.stepEnd("0"),console.log("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const T=globalThis.auth;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.timestamp)throw new Error("auth.timestamp must be a number");if(!T.signature)throw new Error("auth.signature is required");const S=BigInt(T.amount);if(S<=0n)throw new Error(`Withdrawal amount must be positive, got: ${S.toString()} sats`);const E=d;if(S<E)throw new Error(`Withdrawal amount ${S.toString()} sats is below minimum ${E.toString()} sats (Bitcoin dust limit). This amount is not economically viable for Bitcoin network transactions.`);const I=T.destinationAddress;if(!I||"string"!=typeof I)throw new Error('Missing or invalid "destinationAddress" parameter - must be a valid Bitcoin address');const x=D().publicKey;if(!x)throw new Error("publicKey must not be blank");if("string"!=typeof x||0===x.length)throw new Error("publicKey must not be blank");const B=x;if(!(()=>{try{const t=/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{26,35}$/.test(I),e=/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(I);return!(!t&&!e)&&("testnet"===n||"regtest"===n?I.startsWith("m")||I.startsWith("n")||I.startsWith("2")||I.startsWith("tb1")||I.startsWith("bcrt1"):"mainnet"===n&&(I.startsWith("1")||I.startsWith("3")||I.startsWith("bc1")))}catch(t){return!1}})())throw new Error(`Invalid Bitcoin address format for ${n} network: ${I}. Expected ${"mainnet"===n?"address starting with 1, 3, or bc1":"address starting with m, n, 2, tb1, or bcrt1"}`);try{$t(I)}catch(t){throw new Error(`Destination address ${I} passed format validation but cannot be encoded to a scriptPubKey (Phase 2 would reject it after authorization): ${t?.message??String(t)}`)}console.log(` \u2705 Destination address validated: ${I} (${n})`);let k="0.5";try{console.log("[BTC Withdrawal] Started"),console.log(` Position: ${T.positionId}`),console.log(` Withdrawal Amount: ${S.toString()} sats`),console.log(` Destination Address: ${I}`);const t=await async function(t){if(!t)return t;const e=[];for(const o of t){if(!o?.name||"string"!=typeof o.name)throw new Error("Each price provider must include a valid name");let t,i;if(o.pkpId&&"string"==typeof o.pkpId){const e=(r=o.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;o.apiKey&&(t=await H(o.name,"apiKey",e,o.apiKey)),o.apiSecret&&(i=await H(o.name,"apiSecret",e,o.apiSecret))}else t=o.apiKey,i=o.apiSecret;e.push({name:o.name,apiKey:t,apiSecret:i})}var r;return e}(globalThis.priceProviders),n=!0===globalThis.devPriceMode;if(n&&!o.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${o.chain}`);const d=new X(t,void 0,void 0,{devSingleProvider:n&&o.allowDevSinglePriceProvider}),P=globalThis.rpcUrl;if(!P||"string"!=typeof P)throw new Error("rpcUrl is required for btc-withdrawal validation");!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(!$.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${$.join(", ")}`)}(o,P),console.log(` Using RPC URL: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(P)}`);const E=P,x=new ethers.providers.JsonRpcProvider(E);a=await vt({policy:o,ethersProvider:x,registryAddress:s.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});const U=a[0];console.log(` \u2705 Bitcoin Providers: ${a.length} (${a.map((t=>t.name)).join(", ")})`);const D=new _({providerUrl:U.url,auth:U.auth});!function(t,e){const r=tt[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 st(x,c));const O=(M={contractAddress:b||h,chain:r,chainId:A(i),rpcUrl:E,bitcoinProvider:D,minConfirmations:U.minConfirmations,bitcoinProviderConfigs:a.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),minConsensusProviders:o.minConsensusProviders},new W(M));k="1",console.log("[Step 1] Getting vault snapshot..."),e.stepStart("1","Get vault snapshot");const R=function(t){return new Z(t)}({contractAddress:c,termManagerAddress:p,loanOpsManagerAddress:h,liquidationManagerAddress:v,chain:r,chainId:A(i),rpcUrl:E,vaultBalance:O,priceOracle:d}),N=await R.getVaultSnapshot(T.positionId);await bt(N.vaultAddress,a,o.minConsensusProviders),console.log(` \u2705 Vault balance: ${N.availableBTCSats.toString()} sats`),console.log(` \u2705 Current debt: ${N.ucdDebt.toString()} wei`),e.stepEnd("1"),k="2",console.log("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticate caller");const F=e.getElapsed();console.log(`[TIMING] Step 2 started at ${F}ms`);const L=A(i),q=new ethers.providers.StaticJsonRpcProvider(E,L);let z;if(5===N.status){if(!m)throw new Error("LITActionValidator address required for LIQUIDATED position withdrawals. Pass contractAddresses.LITActionValidator in jsParams.");const t=new ethers.Contract(m,["function pkpOwners(bytes32) view returns (address)"],q);if(z=await t.pkpOwners(N.pkpId),!z||z===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: ${z}`)}else z=N.borrower;const V=pt(o,globalThis.contractAddresses),J=globalThis.agentModule?{module:globalThis.agentModule,factory:V.AgentModuleFactory,registry:V.AgentDelegationRegistry,outcome:void 0}:void 0;if(!await C.verifyWithdrawAuthorization(T,z,L,q,J))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 Q=e.getElapsed();console.log(`[TIMING] Step 2.5 started at ${Q}ms`);if(![0,1,2,6,5].includes(N.status))throw new Error(`Position status ${f(N.status)} does not allow withdrawal. Valid statuses: PENDING_DEPOSIT, PENDING_MINT, ACTIVE, REPAID, LIQUIDATED.`);console.log(` \u2705 Position status valid for withdrawal: ${f(N.status)}`),e.stepEnd("2.5"),k="2.6";const Y=function(t,e,r){if(t){if(!mt(e))throw new Error("Delegated (Safe-agent) withdrawal refused: no pinned BitcoinWithdrawalAddressRegistry on this chain to enforce the destination allowlist against \u2014 the destination is the only bound on an agent withdrawal and must be verified against a trusted registry, never skipped or taken from the caller.");return e}return mt(r)?r:void 0}(void 0!==J?.outcome,V.BitcoinWithdrawalAddressRegistry,globalThis.contractAddresses?.BitcoinWithdrawalAddressRegistry);if(Y&&Y!==ethers.constants.AddressZero){e.stepStart("2.6","Enforce approved-address allowlist"),console.log("[Step 2.6] Checking approved-withdrawal-address allowlist...");const t=new ethers.Contract(Y,["function isApproved(address user, string btcAddress) view returns (bool)"],q);if(!await t.isApproved(z,I))throw new Error(`Withdrawal address ${I} is not an approved destination for controller ${z} (not on the allowlist, or its time-lock delay has not elapsed).`);console.log(` \u2705 Destination on controller's allowlist: ${I}`),e.stepEnd("2.6")}k="3",console.log("[Step 3] Validating post-withdrawal collateral ratio..."),e.stepStart("3","Validate collateral ratio");const et=e.getElapsed();console.log(`[TIMING] Step 3 started at ${et}ms`);const rt=S;if(0n===N.ucdDebt)console.log(" \u2705 Position has zero debt - withdrawal allowed");else{if(N.btcPriceUsd<l||N.btcPriceUsd>u)throw new Error(`Bitcoin price ${N.btcPriceUsd} is outside acceptable range (${l} - ${u}). This may indicate oracle manipulation or stale price data. Please try again later.`);console.log(` \u2705 BTC price validation passed: $${(Number(N.btcPriceUsd)/1e8).toFixed(2)}`);const t=N.availableBTCSats-rt,e=K(j(t,N.btcPriceUsd),N.ucdDebt);if(e<N.liquidationThresholdBps)throw new Error(`Insufficient collateral: post-withdrawal ratio ${G(e)}% < liquidation threshold ${G(N.liquidationThresholdBps)}%. Withdrawal would result in insufficient collateralization.`);console.log(` \u2705 Post-withdrawal collateral ratio: ${G(e)}%`),console.log(` \u2705 Exceeds liquidation threshold: ${G(N.liquidationThresholdBps)}%`),function(t,e){if(Number.isFinite(t)&&!(t<=0)){if(!Number.isFinite(e))throw new Error(`Agent withdrawal refused: post-withdrawal collateral ratio is not a finite number (${String(e)}) \u2014 refusing to evaluate the delegation floor of ${G(t)}% against it`);if(e<t)throw new Error(`Agent withdrawal refused: post-withdrawal collateral ratio ${G(e)}% is below the delegation floor ${G(t)}%`)}}(J?.outcome?.effectiveFloorBps??0,e)}e.stepEnd("3"),k="4",console.log("[Step 4] Validating withdrawal amount and balance..."),e.stepStart("4","Validate withdrawal amount and balance");const ot=e.getElapsed();console.log(`[TIMING] Step 4 started at ${ot}ms`);const it="string"==typeof T.amount?BigInt(T.amount):T.amount;if(it!==S)throw new Error(`Authorization amount mismatch: auth.amount=${it.toString()} sats, but requested withdrawal=${S.toString()} sats. The signed authorization must match the requested withdrawal amount.`);if(console.log(" \u2705 Authorization amount matches withdrawal amount"),rt>N.availableBTCSats)throw new Error(`Insufficient vault balance: need ${rt.toString()} sats but only ${N.availableBTCSats.toString()} sats available`);console.log(" \u2705 Total deduction is within available balance");const nt=N.availableBTCSats-rt,at=N.ucdDebt,lt=j(nt,N.btcPriceUsd),ut=at>0n?K(lt,at):void 0;if(console.log(` Post-withdrawal collateral: ${nt.toString()} sats`),console.log(` Post-withdrawal collateral value: $${(Number(lt)/1e8).toFixed(2)}`),console.log(` Post-withdrawal debt: ${at.toString()} wei`),console.log(` Post-withdrawal collateral ratio: ${at>0n&&void 0!==ut?G(Number(ut)):"\u221e"}%`),nt<0n)throw new Error(`Withdrawal would result in negative balance: ${nt.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 dt=e.getElapsed();console.log(`[TIMING] Step 4.5 started at ${dt}ms`);const ht=N.vaultAddress;if(!ht)throw new Error("Vault address not found in snapshot");console.log(` Vault address: ${ht}`);const gt=o.minBitcoinSpendConfirmations,ft=function(t,e){if(!Number.isInteger(e)||e<1)throw new Error(`filterSpendableUtxos: minConf must be a positive integer (got ${e})`);return t.filter((t=>t.confirmations>=e))}(N.availableUTXOs,gt);if(0===ft.length)throw new Error(`No spendable consensus UTXOs in vault ${ht} at >= ${gt} confirmations (snapshot availableUTXOs: ${N.availableUTXOs.length}).`);console.log(` \u2705 ${ft.length} spendable consensus UTXO(s) (>= ${gt} confs)`);const{selectedUTXO:wt,multiUtxoConsolidation:yt}=function(t,e){const r=(t,e)=>{const r=t.txid.toLowerCase(),o=e.txid.toLowerCase();return r<o?-1:r>o?1:t.vout-e.vout};if(!Array.isArray(t)||0===t.length)throw new Error("selectWithdrawalUtxo: at least one confirmed UTXO is required");if("bigint"!=typeof e||e<=0n)throw new Error(`selectWithdrawalUtxo: totalDeduction must be a positive bigint (got ${String(e)})`);const o=t.filter((t=>t.satoshis>=e));if(0===o.length){const o=t.reduce(((t,e)=>t+e.satoshis),0n);if(o<e)throw new Error(`Insufficient vault balance for withdrawal. Need ${e.toString()} sats, total across ${t.length} confirmed UTXO(s): ${o.toString()} sats.`);return{selectedUTXO:[...t].sort(((t,e)=>(e.satoshis>t.satoshis?1:e.satoshis<t.satoshis?-1:0)||r(t,e)))[0],multiUtxoConsolidation:!0}}const i=[...o].sort(((t,e)=>(t.satoshis>e.satoshis?1:t.satoshis<e.satoshis?-1:0)||r(t,e)))[0];if(i.satoshis<e)throw new Error(`Selected UTXO value (${i.satoshis.toString()} sats) < withdrawal amount (${e.toString()} sats) on the single-UTXO path. This should never happen after eligibility filtering.`);return{selectedUTXO:i,multiUtxoConsolidation:!1}}(ft,rt);let Tt=wt;yt&&(console.log(" \u2139\ufe0f No single UTXO covers withdrawal \u2014 multi-UTXO consolidation will be used in Phase 2."),console.log(` Primary UTXO (contract auth): ${Tt.txid}:${Tt.vout} (${Tt.satoshis.toString()} sats)`)),console.log(` \u2705 Selected UTXO: ${Tt.txid}:${Tt.vout}`),console.log(` \u2705 UTXO value: ${Tt.satoshis.toString()} sats`),console.log(` \u2705 UTXO confirmations: ${Tt.confirmations}`);const Pt=N.availableBTCSats;Tt.satoshis<Pt&&console.warn(` \u26a0\ufe0f Selected UTXO value (${Tt.satoshis.toString()}) < calculated balance (${Pt.toString()}). This is expected for multi-UTXO vaults where we select one UTXO.`),console.log(" \u2705 UTXO validation passed"),console.log(" \ud83d\udd0d Verifying UTXO vout against Bitcoin transaction...");const At=$t(ht).toLowerCase(),St=await D.getTransactionOutputs(Tt.txid);if(!St)throw new Error(`Could not fetch transaction outputs for ${Tt.txid} \u2014 cannot canonicalize vout. Refusing to authorize potentially incorrect UTXO. Retry the withdrawal once the Bitcoin data provider is reachable.`);const Et=Tt.vout;Tt=function(t,e,r,o){const i=r.toLowerCase(),n=e=>{if(!Number.isSafeInteger(e.value)||e.value<0)throw new Error(`Vault output ${t.txid}:${e.index} has a non-sane value (${String(e.value)}) \u2014 corrupt provider response, refusing to canonicalize against it.`);return BigInt(e.value)===t.satoshis},a=e.filter((t=>{const e=(t.scriptpubkey??"").toLowerCase();return e.length>0&&e===i||t.scriptpubkey_address===o}));if(0===a.length)throw new Error(`Vault output not found in tx ${t.txid}. Expected scriptPubKey ${i} or address ${o}, but no output in the transaction matches. Refusing to authorize wrong UTXO.`);const s=a.find((e=>e.index===t.vout));if(s&&n(s))return t;const c=a.filter(n);if(0===c.length)throw new Error(`No vault output in tx ${t.txid} carries the selected value ${t.satoshis.toString()} sats (scriptPubKey ${i} / address ${o}). Refusing to authorize a corrupted (vout, value) pair.`);if(c.length>1)throw new Error(`Ambiguous vout correction in tx ${t.txid}: reported vout ${t.vout} is not a vault output carrying the selected value, and ${c.length} vault outputs (vouts ${c.map((t=>t.index)).join(", ")}) all carry ${t.satoshis.toString()} sats. Refusing to guess \u2014 an index-order pick could authorize an outpoint that collides with authorized-spend bookkeeping.`);return{...t,vout:c[0].index}}(Tt,St,At,ht),Tt.vout!==Et?console.log(` \u26a0\ufe0f Esplora API reported vout=${Et} but the vault output carrying ${Tt.satoshis.toString()} sats is at vout=${Tt.vout} (matched on scriptPubKey + value). Correcting.`):console.log(` \u2705 UTXO vout=${Tt.vout} confirmed correct`),e.stepEnd("4.5"),k="5",console.log("[Step 5] Building authorization message..."),e.stepStart("5","Build authorization message");const Ct=e.getElapsed();console.log(`[TIMING] Step 5 started at ${Ct}ms`);const It=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(T.action)),xt=N.authorizedSpendsHash,Bt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[N.ucdDebt])),kt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[c,h,p,g])),Ut=BigInt(T.timestamp),Dt=nt,Mt=N.btcPriceUsd;if(Mt<l||Mt>u)throw new Error(`BTC price ${Mt.toString()} (8 decimals) is outside acceptable range (${l.toString()} - ${u.toString()})`);console.log("[Step 5] DEBUG: Message Hash Parameters:"),console.log(" positionId:",T.positionId),console.log(" action:",T.action),console.log(" actionHash:",It),console.log(" authorizedSpendsHash:",xt),console.log(" ucdDebtHash:",Bt),console.log(" withdrawalAddress:",I),console.log(" totalDeduction:",rt.toString()),console.log(" newCollateral:",Dt.toString()),console.log(" quantumTimestamp:",Ut.toString()),console.log(" btcPrice:",Mt.toString()),console.log(" utxoTxid:",Tt.txid),console.log(" utxoVout:",Tt.vout);const Ot=ct(T.positionId),Rt=A(i),Nt={name:w,version:y,chainId:Rt,verifyingContract:ethers.utils.getAddress(h)},Ft={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"}]},Lt=ethers.utils._TypedDataEncoder.hash(Nt,Ft,{positionId:Ot,actionHash:It,authorizedSpendsHash:xt,ucdDebtHash:Bt,contractBundleHash:kt,withdrawalAddress:I,totalDeduction:rt.toString(),newCollateral:Dt.toString(),quantumTimestamp:Ut.toString(),btcPrice:Mt.toString(),utxoTxid:Tt.txid,utxoVout:Tt.vout,caller:ethers.utils.getAddress(z)});console.log("[Step 5] Contract message hash for signing:",Lt),console.log("[Step 5] Message hash bytes length:",ethers.utils.arrayify(Lt).length),e.stepEnd("5"),k="6",console.log("[Step 6] Signing contract message hash..."),e.stepStart("6","Sign message");const qt=e.getElapsed();console.log(`[TIMING] Step 6 started at ${qt}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: ${T.positionId}`),e.log("6",`Action Hash: ${It}`),e.log("6",`Authorized Spends Hash: ${xt}`),e.log("6",`UCD Debt Hash: ${Bt}`),e.log("6",`Contract Bundle Hash: ${kt}`),e.log("6",`Destination Address: ${I}`),e.log("6",`Total Deduction: ${rt.toString()}`),e.log("6",`New Collateral: ${Dt.toString()}`),e.log("6",`Quantum Timestamp: ${Ut.toString()}`),e.log("6",`BTC Price: ${Mt.toString()}`),e.log("6",`Selected UTXO Txid: ${Tt.txid}`),e.log("6",`Selected UTXO Vout: ${Tt.vout}`),e.log("6",`Selected UTXO Satoshis: ${Tt.satoshis.toString()}`),e.log("6",`Selected UTXO Confirmations: ${Tt.confirmations}`),e.log("6","---"),e.log("6",`\ud83d\udcdd FINAL CONTRACT MESSAGE HASH: ${Lt}`),e.log("6","========================================"),e.log("6","Preparing signEcdsa call"),e.log("6",`contractMessageHash: ${Lt}`),e.log("6",`publicKey: ${B}`),e.log("6","publicKey with 0x prefix: "+("0x"+B));const _t=ethers.utils.arrayify(Lt);e.log("6",`messageBytes length: ${_t.length}`),e.log("6",`messageBytes: ${JSON.stringify(Array.from(_t))}`),e.log("6","About to sign with wallet-derived key (Chipotle)...");const zt=Date.now(),Xt=globalThis.validatorWalletAddress;if(!Xt||!Xt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Ht=await Lit.Actions.getPrivateKey({pkpId:Xt}),Vt="string"==typeof Ht?Ht.startsWith("0x")?Ht:`0x${Ht}`:String(Ht),Wt=new ethers.Wallet(Vt),jt=new ethers.utils.SigningKey(Vt);e.log("6",`Wallet-derived signer address: ${Wt.address}`),e.log("6",`validatorWalletAddress: ${Xt}`);const Kt=jt.signDigest(Lt),Gt=ethers.utils.joinSignature(Kt),Jt=Date.now()-zt;e.log("6",`Chipotle signature created in ${Jt}ms`),e.log("6",`signature: ${Gt}`);const Qt=b?.trim()||"";let Zt=null;if(Qt){const t=ct(T.positionId),r=A(i),o=Dt+rt,n={name:w,version:y,chainId:r,verifyingContract:ethers.utils.getAddress(Qt)},a={BtcSpendAuth:[{name:"positionId",type:"bytes32"},{name:"txid",type:"string"},{name:"vout",type:"uint32"},{name:"satoshis",type:"uint256"},{name:"targetAddress",type:"string"},{name:"targetAmount",type:"uint256"}]},s=ethers.utils._TypedDataEncoder.hash(n,a,{positionId:t,txid:Tt.txid,vout:Tt.vout,satoshis:o.toString(),targetAddress:I,targetAmount:rt.toString()});e.log("6",`EIP-712 BtcSpendAuth digest: ${s}`),Zt=await Wt._signTypedData(n,a,{positionId:t,txid:Tt.txid,vout:Tt.vout,satoshis:o.toString(),targetAddress:I,targetAmount:rt.toString()}),e.log("6",`btcSpendAuth signature: ${Zt}`)}e.stepEnd("6"),console.log("[BTC Withdrawal] \u2705 Complete"),e.summary();const Yt=ft.map((t=>({txid:t.txid,vout:t.txid===Tt.txid&&t.vout===wt.vout?Tt.vout:t.vout,value:t.satoshis.toString()}))),te=new Set;for(const t of Yt){const e=`${t.txid.toLowerCase()}:${t.vout}`;if(te.has(e))throw new Error(`confirmedUtxos: duplicate outpoint ${e} after representative vout remap \u2014 refusing to emit a spend set the SDK would silently dedupe.`);te.add(e)}const ee=St.find((t=>t.index===Tt.vout));if(!ee||BigInt(ee.value)!==Tt.satoshis)throw new Error(`Representative UTXO ${Tt.txid}:${Tt.vout} declares ${Tt.satoshis.toString()} sats but the funding tx output at that vout is ${ee?ee.value:"absent"} \u2014 (vout, value) decoupled; refusing to authorize.`);const re={approved:!0,positionId:T.positionId,actionHash:It,authorizedSpendsHash:xt,ucdDebtHash:Bt,contractBundleHash:kt,totalDeduction:rt.toString(),remainingCollateral:nt.toString(),newCollateralRatioBps:at>0n&&void 0!==ut?Number(ut):void 0,destinationAddress:I,signature:Gt,btcSpendAuthSignature:Zt,timestamp:Ut.toString(),btcPrice:Mt.toString(),utxoTxid:Tt.txid,utxoVout:Tt.vout,utxoSatoshis:Tt.satoshis.toString(),confirmedUtxos:Yt};return console.log("[BTC Withdrawal] \ud83d\udd0d Response data before JSON.stringify:"),console.log(" totalDeduction:",rt,"type:",typeof rt,"toString():",rt.toString()),console.log(" remainingCollateral:",nt,"type:",typeof nt,"toString():",nt.toString()),console.log(" btcPrice:",Mt,"type:",typeof Mt,"toString():",Mt.toString()),console.log(" timestamp:",Ut,"type:",typeof Ut,"toString():",Ut.toString()),console.log(" Full response object:",JSON.stringify(re,null,2)),re}catch(t){throw console.error("[BTC Withdrawal] \u274c Failed:",t.message),console.error(`[BTC Withdrawal] Failed at step: ${k}`),e.error("error",`Failed: ${t.message}`),t}var M}return Tt=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}),Tt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -1 +1 @@
1
- ce12f11e3b5469953bc919586e4f3b8b5d594224b58b799dd9a3b60e3749559c
1
+ 3cae8250861832f91ee3c573abeb50ff27b9acd34148176071cbfbabb359fc91
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-withdrawal",
3
- "originalSize": 225106,
4
- "minifiedSize": 95313,
5
- "compressionRatio": 0.5765861416399385,
6
- "hash": "ce12f11e3b5469953bc919586e4f3b8b5d594224b58b799dd9a3b60e3749559c",
7
- "buildTime": 1786125235768,
3
+ "originalSize": 229307,
4
+ "minifiedSize": 97456,
5
+ "compressionRatio": 0.57499771049292,
6
+ "hash": "3cae8250861832f91ee3c573abeb50ff27b9acd34148176071cbfbabb359fc91",
7
+ "buildTime": 1787171881993,
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": 1786125235773,
7
+ "buildTime": 1787171882008,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 76515,
5
5
  "compressionRatio": 0.604461216366409,
6
6
  "hash": "1d4e085335af80f194a663a577876902c83015177e95906a0b461fa93bd5da08",
7
- "buildTime": 1786125235943,
7
+ "buildTime": 1787171882273,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 66846,
5
5
  "compressionRatio": 0.5735230317723619,
6
6
  "hash": "b35ee7706d733d625faa4dbe37f73c8e20f0c1befa897cd7875e827de52003de",
7
- "buildTime": 1786125236081,
7
+ "buildTime": 1787171882404,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 56800,
5
5
  "compressionRatio": 0.5843152178685909,
6
6
  "hash": "a059133214e6ba0a73d655a15600c4b33e361fb340c98f8eecaf8ab7b95aaf83",
7
- "buildTime": 1786125236204,
7
+ "buildTime": 1787171882510,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 4140,
5
5
  "compressionRatio": 0.5104647037956722,
6
6
  "hash": "4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b",
7
- "buildTime": 1786125236225,
7
+ "buildTime": 1787171882522,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 8695,
5
5
  "compressionRatio": 0.5565811617114591,
6
6
  "hash": "ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74",
7
- "buildTime": 1786125236256,
7
+ "buildTime": 1787171882541,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 78736,
5
5
  "compressionRatio": 0.5951730910624033,
6
6
  "hash": "17191ecc9c009e0fa5ab52c876330beb2a9a75d30cccb92e7c0c04f169df088b",
7
- "buildTime": 1786125236433,
7
+ "buildTime": 1787171882713,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 37108,
5
5
  "compressionRatio": 0.49506055245611646,
6
6
  "hash": "04de5fc5b6f5131dc1544e3d3d187a1f9ef9616ffd12483d119f9102b3671791",
7
- "buildTime": 1786125236506,
7
+ "buildTime": 1787171882849,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 82739,
5
5
  "compressionRatio": 0.5933901761800624,
6
6
  "hash": "2bdd9aebdaad58a43a4731d5b7284f2531b7a9caaf8caf5719d891c4ed33cb2e",
7
- "buildTime": 1786125236667,
7
+ "buildTime": 1787171883046,
8
8
  "version": "0.1.0"
9
9
  }