@gvnrdao/dh-lit-actions 0.0.321 → 0.0.322

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 (52) 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.action.js +1 -1
  13. package/dist/btc-transaction-signer.hash +1 -1
  14. package/dist/btc-transaction-signer.meta.json +5 -5
  15. package/dist/btc-utxo-invalidator.action.js +1 -1
  16. package/dist/btc-utxo-invalidator.hash +1 -1
  17. package/dist/btc-utxo-invalidator.meta.json +5 -5
  18. package/dist/btc-withdrawal.action.js +1 -1
  19. package/dist/btc-withdrawal.hash +1 -1
  20. package/dist/btc-withdrawal.meta.json +5 -5
  21. package/dist/encrypt-parameter.meta.json +1 -1
  22. package/dist/extend-position-validator.action.js +1 -1
  23. package/dist/extend-position-validator.hash +1 -1
  24. package/dist/extend-position-validator.meta.json +5 -5
  25. package/dist/liquidation-validator.meta.json +1 -1
  26. package/dist/loan-vault-btc-balance.meta.json +1 -1
  27. package/dist/pkp-validator.meta.json +1 -1
  28. package/dist/price-oracle.meta.json +1 -1
  29. package/dist/process-payment-validator.action.js +1 -1
  30. package/dist/process-payment-validator.hash +1 -1
  31. package/dist/process-payment-validator.meta.json +5 -5
  32. package/dist/stale-spend-recovery-validator.action.js +1 -1
  33. package/dist/stale-spend-recovery-validator.hash +1 -1
  34. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  35. package/dist/ucd-mint-validator.action.js +1 -1
  36. package/dist/ucd-mint-validator.hash +1 -1
  37. package/dist/ucd-mint-validator.meta.json +5 -5
  38. package/package.json +1 -1
  39. package/pkg-dist/pkg-src/index.d.ts +15 -0
  40. package/pkg-dist/pkg-src/index.d.ts.map +1 -1
  41. package/pkg-dist/pkg-src/index.js +151 -40
  42. package/pkg-dist/pkg-src/index.js.map +3 -3
  43. package/pkg-dist/src/constants/borrower-authorization-types.d.ts +126 -0
  44. package/pkg-dist/src/constants/borrower-authorization-types.d.ts.map +1 -0
  45. package/pkg-dist/src/constants/index.d.ts +1 -0
  46. package/pkg-dist/src/constants/index.d.ts.map +1 -1
  47. package/pkg-dist/src/modules/authorization.module.d.ts +67 -7
  48. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  49. package/pkg-dist/src/modules/bitcoin/dust.d.ts +24 -0
  50. package/pkg-dist/src/modules/bitcoin/dust.d.ts.map +1 -0
  51. package/pkg-dist/src/modules/bitcoin/invalidator-classification.d.ts +53 -6
  52. package/pkg-dist/src/modules/bitcoin/invalidator-classification.d.ts.map +1 -1
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=25e14,u=1000000000000n,d=100000000000000n,l=60,h=10,p=86400,m=30,g=12,f=365,w=8e3;var y="DiamondHands.Protocol",v="1",b="extend-position",T=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(T||{}),P={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},$=["infura.io","drpc.org"],E={ethereum:1,sepolia:11155111,hardhat:1337};function A(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(T).join(", ")}`)}function I(t){return Math.floor(t/l)*l}function S(){return I(Math.floor(Date.now()/1e3))}async function C(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${S()}`)}var x=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,i,n){try{const o=new ethers.Contract(i,["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)"],n);if("renew"===r){const[r]=await o.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await o.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[a,,s]=await o.canMint(t,e);return{ok:!0===a,effectiveFloorBps:Number(s)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,i,n){if(!i.module||!i.factory||!i.registry)return!1;const o=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],n);if(!0!==await o.isModuleEnabled(i.module))return!1;const a=new ethers.Contract(i.factory,["function isFromFactory(address) view returns (bool)"],n);if(!0!==await a.isFromFactory(i.module))return!1;const s=new ethers.Contract(i.module,["function safe() view returns (address)","function agent() view returns (address)"],n),c=await s.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const u=await s.agent();if(!u||u.toLowerCase()!==e.toLowerCase())return!1;const d=new ethers.Contract(i.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],n),[l,,h]=await d.canWithdraw(t,u);return!0===l&&(i.outcome={effectiveFloorBps:Number(h)},!0)}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await C();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=I(i),o=I(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.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,i,n,o,a){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,s,c)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,c,n))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,i,a.op,a.registry,n);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n,o)}static async verifyPaymentAuthorization(t,e,r,i,n,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n,o)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,i,r,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,i,o)=>e.toLowerCase()===r.toLowerCase()||!(!n||!await t.checkEIP1271(r,i,o,n))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o,a){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,s,c)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,c,n))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,i,a.op,a.registry,n);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n,o)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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),i=[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"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,i,r,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function k(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function B(...t){k()&&console.log(...t)}var U=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}},M=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},D=class{static create(t="LIT Action",e){return k(e)?new M(t):new U}};function O(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function R(t){return t instanceof Error&&"AbortError"===t.name}function F(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function q(t,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&&F(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const n=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&F(n,"esplora provider url"),{url:n,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return F(n,"maestro provider url"),{url:n,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");F(n,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&F(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:n,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var N=new Map;async function _(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,n=N.get(i);if(n)return n;const o=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,n=new AbortController,o=setTimeout((()=>n.abort()),e&&e>0?e:1e4);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:n.signal})}finally{clearTimeout(o)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return o.catch((()=>N.delete(i))),N.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function L(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 z=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await _(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),B(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${O(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${O(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${O(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return L(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,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");L(a,`parseBlockstreamUTXOs ${n}:${o}`),i.push({txid:n,vout:o,satoshis:BigInt(a),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(n),B(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${O(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(O(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${O(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),o=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(n),B(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`);const a=await o.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}`);L(s,`getBalance ${e} funded_txo_sum`),L(c,`getBalance ${e} spent_txo_sum`);const u=s-c;L(u,`getBalance ${e} confirmed balance`);const d=BigInt(u);return this.logger.log("3",`Balance: ${d.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),d}catch(t){if(clearTimeout(n),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=O(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=O(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),B(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(O(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((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 L(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),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function X(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function V(t){return t/100}var H=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"cryptocompare":if(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(o.apiKey,n++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),i=e?t.slice(4):t,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};H.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],H.REQUIRED_PROVIDER_COUNT=3;var j=H;async function G(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}var K=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 z({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const i=this.providerConfigs,n=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const o=new Set,a=t.filter((t=>t.confirmations>=r));for(const t of a)o.add(`${t.txid}:${t.vout}`);if(!i||i.length<=1||!n)return o;const s=t=>i[t].name||i[t].providerUrl,c=await Promise.allSettled(n.slice(1).map((t=>t.getUTXOSet(e,r)))),u=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(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${i.length-1} secondary provider(s): ${u.join("; ")}`);const d=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})),l=[];for(const t of a){const e=`${t.txid}:${t.vout}`;let i=t.confirmations,n=t.confirmations;for(let r=0;r<d.length;r++){const o=d[r].get(e),a=s(r+1);if(!o)throw new Error(`Confirmed UTXO ${e} present on ${s(0)} but absent on ${a}; refusing to sign (possible fabricated UTXO).`);if(o.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${a}=${o.value.toString()}; refusing to sign.`);o.confirmations<i&&(i=o.confirmations),o.confirmations>n&&(n=o.confirmations)}if(n-i>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${n-i} exceeds tolerance 3 (min ${i}, max ${n}); providers disagree on depth, refusing to sign.`);i<r&&(o.delete(e),l.push(e))}l.length>0&&B(`[VaultBalance] confirmed-consensus: ${l.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${l.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<d.length;t++){const e=s(t+1);for(const[i,n]of d[t]){if(n.confirmations<r)continue;const t=h.get(i);if(!t)throw new Error(`Confirmed UTXO ${i} present on ${e} (${n.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!==n.value)throw new Error(`Confirmed UTXO ${i} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${e}=${n.value.toString()}; refusing to sign.`);if(n.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${i} depth disagreement: ${s(0)}=${t.confirmations} vs ${e}=${n.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return o}async classifySelfChange(t,e,r){const i=this.providerConfigs,n=this.readers,o=new Set,a=t.filter((t=>t.confirmations<r));if(0===a.length)return o;if(this.assertProviderFloor("classifySelfChange"),!i||0===i.length||!n)return B(`[VaultBalance] ${a.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),o;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 u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),d=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),l=d.slice(0,5),h=d.length-l.length;h>0&&B(`[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 i=new Array(t.length);let n=0;const o=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=n++;if(e>=t.length)return;i[e]=await r(t[e])}}));return await Promise.all(o),i}(l,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),s,r,i,n)}))),m=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of a)m.has(t.txid)&&o.add(`${t.txid}:${t.vout}`);return m.size>0&&B(`[VaultBalance] self-change: ${o.size}/${a.length} unconfirmed UTXO(s) verified as protocol change by ${i.length} provider(s)`),o}async verifyParentIsSelfSpendConsensus(t,e,r,i,n,o){const a=t=>n[t].name||n[t].providerUrl,s=await Promise.allSettled(n.map(((n,a)=>this.evaluateParentForProvider(t,e,r,i,o[a],n)))),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}/${n.length} provider(s): ${c.join("; ")}`);const u=s.map((t=>t.value)),d=u.map((t=>t.selfSpend)),l=d.map(((t,e)=>({vote:t,name:a(e)}))).filter((t=>t.vote!==d[0])).map((t=>`${a(0)}=${d[0]} vs ${t.name}=${t.vote}`));if(l.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${l.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!d[0])return!1;const h=u.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,i,n,o){const a=await this.fetchParentTransaction(t,o);if(!a||0===a.inputs.length)return{selfSpend:!1,outputMismatch:null};const s=await this.verifyInputsAreSelfSpend(a.inputs,r,i,n),c=s?function(t,e,r){for(const i of t){const t=e.find((t=>t.index===i.vout));if(!t)return`claimed output ${i.txid}:${i.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${i.txid}:${i.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==i.satoshis)return`claimed output ${i.txid}:${i.vout} value ${t.value?.toString()??"<missing>"} != reported ${i.satoshis.toString()}`}return null}(e,a.outputs,r):null;return{selfSpend:s,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,i){const n=[...new Set(t.map((t=>t.txid)))],o=new Map,a=n.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(a.map((async t=>{o.set(t,await i.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=o.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const s=await Promise.all(n.map((t=>i.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,i=new AbortController,n=setTimeout((()=>i.abort()),r);try{const n=await fetch(`${e.providerUrl}/tx/${t}`,{signal:i.signal,headers:await _(e.auth,r)});if(!n.ok){if(404===n.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: ${n.status} ${n.statusText}`)}const o=await n.json();if(!o.vin||!Array.isArray(o.vin)||0===o.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const a=[];for(const e of o.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(o.vout)?o.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(R(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(n)}}},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),i=await this.getAuthorizedSpendsFromContract(t),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e){const r=this.config.minConfirmations,i=await this.bitcoinProvider.getUTXOSet(e,r),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const o=n.reduce(((t,e)=>t+e.satoshis),0n),a=new K(this.bitcoinProvider,this.config.bitcoinProviderConfigs,this.config.minConsensusProviders??1),s=await a.confirmedUtxoConsensus(i.utxos,e,r),c=await a.classifySelfChange(i.utxos,e,r),u=i.utxos.filter((t=>(s.has(`${t.txid}:${t.vout}`)||c.has(`${t.txid}:${t.vout}`))&&!this.isUTXOAuthorized(t,n))),d=u.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:o,authorizedSpendsHash:l,availableUTXOs:u,availableBalance:d,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],i);return(await n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var 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:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),n=await i.liquidationThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(i)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),n=await i.maxEscalatedThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function 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 P[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var Y=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),c=(u={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(u));var u;const d=this.config.termOverride??e.selectedTerm,[l,h,g]=await Promise.all([c.getLiquidationThreshold(),c.getMaxEscalatedThreshold(),c.getTermFees(d)]),f=function(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=Math.floor(Date.now()/1e3),i=e*m,n=r-t,o=Math.floor(n/p);return{termDurationDays:o,termLengthDays:i,isExpired:o>i,daysUntilExpiry:Math.max(0,i-o),daysIntoGracePeriod:Math.max(0,o-i)}}(e.termStartTimestamp,e.selectedTerm),w=function(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}(f.isExpired,f.daysIntoGracePeriod,l,h),y=function(t,e,r){const i=t*e/(100000000n*a);return 0n===r?{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}(i.availableBalance,n,e.ucdDebt),v=y.collateralRatioBps<w,b=y.collateralRatioBps-w;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:y.collateralValueUsd,collateralRatioBps:y.collateralRatioBps,termDurationDays:f.termDurationDays,termLengthDays:f.termLengthDays,isExpired:f.isExpired,daysUntilExpiry:f.daysUntilExpiry,daysIntoGracePeriod:f.daysIntoGracePeriod,currentLiquidationThreshold:w,isLiquidatable:v,marginToLiquidationBps:b,liquidationThresholdBps:l,originationFeeBps:g.originationFeeBps,extensionFeeBps:g.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],i),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const u=Number(s.expiryAt),d=Number(s.selectedTerm),l=Number(s.totalTerm),h=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),f=(v=d,0===(y=u)?0:y-v*m*p);var y,v;const b=Q(s.vaultAddress,A(this.config.chain));if("string"!=typeof b||0===b.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:b,ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:f,selectedTerm:d,status:c,expiryAt:u,previousExpiryAt:h,totalTerm:l,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 i=await this.getVaultSnapshot(t);return function(t,e,r,i){const n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var 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))",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)"]),it=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)"]),nt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),ot=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([Z]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([Z]).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){i=t}try{return await async function(t,e){const r=await at(t,e,rt.encodeFunctionData("views",[])),[i]=rt.decodeFunctionResult("views",r),[n,o,a,s,c,u,d,l]=await Promise.all([at(t,e,rt.encodeFunctionData("paused",[])),at(t,e,rt.encodeFunctionData("liquidationPaused",[])),at(t,e,rt.encodeFunctionData("simplePsm",[])),at(t,i,it.encodeFunctionData("core",[])),at(t,i,it.encodeFunctionData("loanOps",[])),at(t,i,it.encodeFunctionData("collateralManager",[])),at(t,i,it.encodeFunctionData("liquidationManager",[])),at(t,i,it.encodeFunctionData("circuitBreaker",[]))]),h=rt.decodeFunctionResult("paused",n)[0],p=rt.decodeFunctionResult("liquidationPaused",o)[0],m=rt.decodeFunctionResult("simplePsm",a)[0],g=it.decodeFunctionResult("core",s)[0],f=it.decodeFunctionResult("loanOps",c)[0],w=it.decodeFunctionResult("collateralManager",u)[0],y=it.decodeFunctionResult("liquidationManager",d)[0],v=it.decodeFunctionResult("circuitBreaker",l)[0],b=await at(t,f,nt.encodeFunctionData("getUcdController",[])),T=await at(t,f,nt.encodeFunctionData("ucdToken",[])),P=nt.decodeFunctionResult("getUcdController",b)[0],$=nt.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await at(t,e,ot.encodeFunctionData("paused",[]));return ot.decodeFunctionResult("paused",r)[0]}catch{return!1}},[A,I,S,C,x,k,B,U]=await Promise.all([E(g),E(f),E(w),E(y),E(v),E(P),E($),E(m)]);return et({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:A,loanOperationsPaused:I,collateralManagerPaused:S,liquidationManagerPaused:C,circuitBreakerPaused:x,ucdControllerPaused:k,ucdTokenPaused:B,simplePsmPaused:U})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var ct={hardhat:{chain:"hardhat",chainId:E.hardhat,bitcoinNetwork:P.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:E.sepolia,bitcoinNetwork:P.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:E.ethereum,bitcoinNetwork:P.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var ut=[{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"}],dt=[{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 lt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ht(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!i)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,ut,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.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:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,dt,r);let s;try{s=await a.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await lt(e.ciphertext,e.pkpId),{url:i,auth:o}=q(r,{requireHttps:!0});n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:o,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i)}var pt,mt=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],gt="UCDMintedWithAuthorization(bytes32,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes32)";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;let e="0";try{B("[Extend Position Validator] Starting..."),B("[Extend Position Validator] DEBUG: globalThis.priceProviders:",globalThis.priceProviders),B("[Extend Position Validator] DEBUG: priceProviders type:",typeof globalThis.priceProviders),globalThis.priceProviders&&(B("[Extend Position Validator] DEBUG: priceProviders isArray:",Array.isArray(globalThis.priceProviders)),B("[Extend Position Validator] DEBUG: priceProviders length:",globalThis.priceProviders.length),globalThis.priceProviders.length>0&&B("[Extend Position Validator] DEBUG: First provider:",globalThis.priceProviders[0])),e="0";const t=globalThis.chain,i=globalThis.selectedTerm;if(!t)throw new Error('Missing required parameter: "chain"');if(!i||"number"!=typeof i)throw new Error('Missing required parameter: "selectedTerm"');const n=x.verifyTermPositionActionAuthorizationStructure(globalThis.auth),o=function(t){const e=A(t),r=ct[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),s=o.chainId,c=globalThis.rpcUrl;let l;c&&"string"==typeof c?(!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,c),B(` Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(c)}`),l=c):(l=await Lit.Actions.getRpcUrl({chain:t}),B(` Using LIT-provided RPC URL for chain: ${t}`));const w=new ethers.providers.JsonRpcProvider(l),T=await ht({policy:o,ethersProvider:w,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),P=T[0];B(` \u2705 Bitcoin Providers: ${T.length} (${T.map((t=>t.name)).join(", ")})`);const E=P.minConfirmations;let I,C,k,U,M,D;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error("Contract addresses not provided. Required for both dev and service modes.");if(I=globalThis.contractAddresses.PositionManager,C=globalThis.contractAddresses.LoanOperationsManagerModule,k=globalThis.contractAddresses.TermManagerModule,U=globalThis.contractAddresses.UCDController,M=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",D=globalThis.contractAddresses.BTCSpendAuthorizer||C,!(I&&C&&k&&U&&M))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");B("\ud83d\udd0d LIT Action Contract Addresses:"),B(" PositionManager:",I),B(" LoanOpsManager:",C),B(" TermManager:",k),B(" UCDController:",U);const O=s,R=new ethers.providers.JsonRpcProvider(l);!function(t,e){const r=tt[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await st(R,I));const F=new z({providerUrl:P.url,auth:P.auth}),q=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await G(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await G(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(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 _=new j(q,void 0,void 0,{devSingleProvider:N&&o.allowDevSinglePriceProvider}),L=(r={contractAddress:D,chain:t,chainId:O,rpcUrl:c,bitcoinProvider:F,minConfirmations:E,bitcoinProviderConfigs:T.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),minConsensusProviders:o.minConsensusProviders},new W(r));e="1";const H=function(t){return new Y(t)}({contractAddress:I,termManagerAddress:k,loanOpsManagerAddress:C,liquidationManagerAddress:M,chain:t,chainId:O,rpcUrl:c,vaultBalance:L,priceOracle:_,termOverride:i}),K=await H.getVaultSnapshot(n.positionId),J=K.btcPriceUsd,Q=BigInt(J.toString());if(Q<u||Q>d)throw new Error(`Bitcoin price ${Q} is outside acceptable range (${u} - ${d})`);e="2";const Z=globalThis.contractAddresses?.AgentDelegationRegistry;if(!await x.verifyExtendAuthorization(n,K.borrower,O,R,void 0,Z?{registry:Z,op:"renew"}:void 0))throw B(`[DEBUG] Authorization failed - signer: ${n.signature?"present":"missing"}, borrower: ${K.borrower}`),B(`[DEBUG] Position ID: ${n.positionId}`),B(`[DEBUG] Auth timestamp: ${n.timestamp}, chainId: ${n.chainId}, newTerm: ${n.newTerm}`),B(`[DEBUG] Auth action: ${n.action}`),B(`[DEBUG] Auth signature: ${n.signature}`),new Error("Caller not authorized");x.assertSelectedTermMatchesAuth(i,n.newTerm),e="3";if(![2,3].includes(K.status))throw new Error(`Invalid position status for extension: ${function(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})`}}(K.status)}. Must be ACTIVE or EXPIRED.`);const et=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(n.positionId);new ethers.Contract(k,[...mt],R);if(K.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const rt=K.selectedTerm,it=rt+i,nt=65535;if(it>nt)throw new Error(`Extension would cause term overflow: ${rt} + ${i} = ${it} months, exceeds max ${nt} months`);let ot;try{const t=await R.getBlock("latest");ot=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const at=i===g?f*p:i*m*p,ut=K.expiryAt+at,dt=3===K.status;if(ut-ot>2*at)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(dt&&ut<=ot)throw new Error("Invalid requested expiry date: extension must extend into the future for expired loans");e="4",B("\ud83d\udd0d Using extensionFeeBps from vault snapshot:",K.extensionFeeBps);const lt=BigInt(K.extensionFeeBps);let pt=[];try{const t=await async function(t,e,r,i){const n="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(gt)),a=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]),s=await t.getBlock("latest"),c=Math.max(0,s.timestamp-i),u=Math.ceil(c/12),d=[];let l=Math.max(0,s.number-u-200);for(;l<=s.number;){const r=Math.min(l+900-1,s.number),i=await t.getLogs({address:e,topics:[o,n],fromBlock:l,toBlock:r});if(d.push(...i),r>=s.number)break;l=r+1}return d.map((t=>{const e=a.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(R,C,n.positionId,K.termStartTimestamp),e=BigInt(K.termStartTimestamp);pt=t.filter((t=>t.quantumTimestamp>=e)),B(`[Pro-Rata] Found ${t.length} total mints, ${pt.length} in current term`)}catch(t){throw new Error(`EXTEND_M7_MINT_LOG_FETCH_FAILED: Pro-rata mint-log fetch failed: ${t?.message??String(t)}. Retry with a healthy RPC so the pro-rata renewal credit can be computed; do not silently overcharge.`)}e="5";const ft=BigInt(S()),wt=function(t){const{mints:e,termStart:r,termExpiry:i,renewalNow:n,ucdDebt:o,extensionFeeRateBps:a}=t,s=o*a/10000n;if(0===e.length)return s;const c=(i-r)/BigInt(p);if(0n===c)return s;let u=0n,d=0n;for(const t of e){if(t.quantumTimestamp<r)continue;const e=(n-t.quantumTimestamp)/BigInt(p),i=(e>c?c:e)*t.mintFee/c;u+=t.mintFee,d+=i}const l=u>d?u-d:0n;return s>l?s-l:0n}({mints:pt,termStart:BigInt(K.termStartTimestamp),termExpiry:BigInt(K.expiryAt),renewalNow:ft,ucdDebt:BigInt(K.ucdDebt.toString()),extensionFeeRateBps:lt}),yt=BigInt(K.ucdDebt.toString())+wt;e="6";const vt=function(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}(K.availableBTCSats,Q),bt=X(vt,yt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return X(t,e)>=r}(vt,yt,K.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${V(bt)}% < ${V(K.liquidationThresholdBps)}%`);e="7";const Tt=S()+h,Pt={name:y,version:v,chainId:s,verifyingContract:ethers.utils.getAddress(C)},$t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Et={ExtendPosition:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"availableBTCBalance",type:"uint256"},{name:"proRataRenewalFee",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},At={actionTag:$t,positionId:et,selectedTerm:i,btcPrice:Q.toString(),availableBTCBalance:K.availableBTCSats.toString(),proRataRenewalFee:wt.toString(),quantumTimestamp:Tt,borrower:ethers.utils.getAddress(K.borrower)};e="8";const It=globalThis.validatorWalletAddress;if(!It||!It.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const St=await Lit.Actions.getPrivateKey({pkpId:It}),Ct="string"==typeof St?St.startsWith("0x")?St:`0x${St}`:String(St),xt=new ethers.Wallet(Ct),kt=await xt._signTypedData(Pt,Et,At);return{approved:!0,positionId:n.positionId,selectedTerm:i,btcPrice:Q.toString(),availableBTCBalance:K.availableBTCSats.toString(),proRataRenewalFee:wt.toString(),newTotalDebt:yt.toString(),newCollateralRatioBps:bt.toString(),signature:kt,timestamp:n.timestamp,quantumTimestamp:Tt,validatorPkp:xt.address}}catch(t){throw console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),t}var r}return pt=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),pt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=25e14,u=1000000000000n,d=100000000000000n,l=60,h=10,p=86400,m=30,g=12,f=365,w=8e3,y={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 v="DiamondHands.Protocol",b="1",T="extend-position",P={MintRequest:[{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RepayRequest:[{name:"positionId",type:"bytes32"},{name:"paymentAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RenewRequest:[{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],WithdrawRequest:[{name:"positionId",type:"bytes32"},{name:"totalDeduction",type:"uint256"},{name:"withdrawalAddress",type:"string"},{name:"quantumTimestamp",type:"uint256"}]};function $(t){const e=P[t];if(!e)throw new Error(`Unknown borrower authorization primary type "${t}"; expected one of ${Object.keys(P).join(", ")}`);return{[t]:e.map((t=>({...t})))}}function E(t,e){if(!Number.isInteger(t)||t<=0)throw new Error(`Borrower authorization domain requires a positive integer chainId, got ${String(t)}`);const r=function(t){return y[t]??null}(t),i=r?.LoanOperationsManagerModule;if(i&&e&&i.toLowerCase()!==e.toLowerCase())throw new Error(`Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${t}: caller ${e}, pinned ${i}`);const n=i??e;if(!n)throw new Error(`No pinned LoanOperationsManagerModule for chainId ${t} and no verifyingContract supplied; refusing to build a borrower authorization domain without one`);return{name:v,version:b,chainId:t,verifyingContract:n}}var A=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(A||{}),I={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},C=["infura.io","drpc.org"],S={ethereum:1,sepolia:11155111,hardhat:1337};function x(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(A).join(", ")}`)}function B(t){return Math.floor(t/l)*l}function k(){return B(Math.floor(Date.now()/1e3))}async function U(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${k()}`)}var D="0x0000000000000000000000000000000000000000",M=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,i,n){try{const o=new ethers.Contract(i,["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)"],n);if("renew"===r){const[r]=await o.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await o.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[a,,s]=await o.canMint(t,e);return{ok:!0===a,effectiveFloorBps:Number(s)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,i,n){if(!i.module||!i.factory||!i.registry)return!1;const o=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],n);if(!0!==await o.isModuleEnabled(i.module))return!1;const a=new ethers.Contract(i.factory,["function isFromFactory(address) view returns (bool)"],n);if(!0!==await a.isFromFactory(i.module))return!1;const s=new ethers.Contract(i.module,["function safe() view returns (address)","function agent() view returns (address)"],n),c=await s.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const u=await s.agent();if(!u||u.toLowerCase()!==e.toLowerCase())return!1;const d=new ethers.Contract(i.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],n),[l,,h]=await d.canWithdraw(t,u);return!0===l&&(i.outcome={effectiveFloorBps:Number(h)},!0)}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await U();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=B(i),o=B(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s="string"==typeof a?{legacy:a}:a;{const e=s.legacy;let i=D;try{i=await this.recoverSigner(e,t.signature)}catch{}if(await r(i,e,t.signature))return!0}if(s.typed){const{domain:e,types:i,message:n}=s.typed;let o;try{o=ethers.utils._TypedDataEncoder.hash(e,i,n)}catch(t){throw new Error(`Failed to compute EIP-712 digest for ${s.typed.primaryType}: ${t instanceof Error?t.message:String(t)}`)}let a=D;try{a=ethers.utils.recoverAddress(o,t.signature)}catch{}if(await r(a,o,t.signature))return!0}return!1}static async verifyAmountPositionActionAuthorization(e,r,i,n,o,a,s){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),t],o=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n);if(!s)return o;const a="MintRequest"===s.primaryType?"mintAmount":"paymentAmount";return{legacy:o,typed:{domain:E(i,s.verifyingContract),types:$(s.primaryType),primaryType:s.primaryType,message:{positionId:e.positionId,[a]:r.toString(),quantumTimestamp:e.timestamp}}}}),(async(i,s,c)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,c,n))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,i,a.op,a.registry,n);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n,o,a){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n,o,{primaryType:"MintRequest",verifyingContract:a})}static async verifyPaymentAuthorization(t,e,r,i,n,o,a){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n,o,{primaryType:"RepayRequest",verifyingContract:a})}static async verifyWithdrawAuthorization(e,r,i,n,o,a){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return{legacy:ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n),typed:{domain:E(i,a),types:$("WithdrawRequest"),primaryType:"WithdrawRequest",message:{positionId:e.positionId,totalDeduction:r.toString(),withdrawalAddress:e.destinationAddress,quantumTimestamp:e.timestamp}}}}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,i,r,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,i,o)=>e.toLowerCase()===r.toLowerCase()||!(!n||!await t.checkEIP1271(r,i,o,n))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o,a,s){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t],n=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r);return s?{legacy:n,typed:{domain:E(i,s.verifyingContract),types:$(s.primaryType),primaryType:s.primaryType,message:{positionId:e.positionId,selectedTerm:e.newTerm,quantumTimestamp:e.timestamp}}}:n}),(async(i,s,c)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,c,n))return!0;if(a){const r=await t.checkAgentDelegationGrant(e.positionId,i,a.op,a.registry,n);return r.ok&&(a.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n,o,a){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n,o,{primaryType:"RenewRequest",verifyingContract:a})}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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),i=[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"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,i,r,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function R(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 O(...t){R()&&console.log(...t)}var F=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}},q=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},N=class{static create(t="LIT Action",e){return R(e)?new q(t):new F}};function _(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function L(t){return t instanceof Error&&"AbortError"===t.name}function z(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function X(t,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&&z(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const n=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&z(n,"esplora provider url"),{url:n,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return z(n,"maestro provider url"),{url:n,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");z(n,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&z(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:n,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var V=new Map;async function j(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,n=V.get(i);if(n)return n;const o=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,n=new AbortController,o=setTimeout((()=>n.abort()),e&&e>0?e:1e4);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:n.signal})}finally{clearTimeout(o)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return o.catch((()=>V.delete(i))),V.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function H(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 G=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=N.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await j(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),O(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${_(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${_(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${_(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return H(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,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");H(a,`parseBlockstreamUTXOs ${n}:${o}`),i.push({txid:n,vout:o,satoshis:BigInt(a),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(n),O(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${_(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(_(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${_(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),o=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(n),O(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`);const a=await o.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}`);H(s,`getBalance ${e} funded_txo_sum`),H(c,`getBalance ${e} spent_txo_sum`);const u=s-c;H(u,`getBalance ${e} confirmed balance`);const d=BigInt(u);return this.logger.log("3",`Balance: ${d.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),d}catch(t){if(clearTimeout(n),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=_(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=_(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),O(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(_(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.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 H(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),L(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};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 J=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"cryptocompare":if(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(o.apiKey,n++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),i=e?t.slice(4):t,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};J.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],J.REQUIRED_PROVIDER_COUNT=3;var Q=J;async function Y(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}var Z=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 G({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const i=this.providerConfigs,n=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const o=new Set,a=t.filter((t=>t.confirmations>=r));for(const t of a)o.add(`${t.txid}:${t.vout}`);if(!i||i.length<=1||!n)return o;const s=t=>i[t].name||i[t].providerUrl,c=await Promise.allSettled(n.slice(1).map((t=>t.getUTXOSet(e,r)))),u=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(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${i.length-1} secondary provider(s): ${u.join("; ")}`);const d=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})),l=[];for(const t of a){const e=`${t.txid}:${t.vout}`;let i=t.confirmations,n=t.confirmations;for(let r=0;r<d.length;r++){const o=d[r].get(e),a=s(r+1);if(!o)throw new Error(`Confirmed UTXO ${e} present on ${s(0)} but absent on ${a}; refusing to sign (possible fabricated UTXO).`);if(o.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${a}=${o.value.toString()}; refusing to sign.`);o.confirmations<i&&(i=o.confirmations),o.confirmations>n&&(n=o.confirmations)}if(n-i>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${n-i} exceeds tolerance 3 (min ${i}, max ${n}); providers disagree on depth, refusing to sign.`);i<r&&(o.delete(e),l.push(e))}l.length>0&&O(`[VaultBalance] confirmed-consensus: ${l.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${l.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<d.length;t++){const e=s(t+1);for(const[i,n]of d[t]){if(n.confirmations<r)continue;const t=h.get(i);if(!t)throw new Error(`Confirmed UTXO ${i} present on ${e} (${n.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!==n.value)throw new Error(`Confirmed UTXO ${i} value mismatch: ${s(0)}=${t.satoshis.toString()} vs ${e}=${n.value.toString()}; refusing to sign.`);if(n.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${i} depth disagreement: ${s(0)}=${t.confirmations} vs ${e}=${n.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return o}async classifySelfChange(t,e,r){const i=this.providerConfigs,n=this.readers,o=new Set,a=t.filter((t=>t.confirmations<r));if(0===a.length)return o;if(this.assertProviderFloor("classifySelfChange"),!i||0===i.length||!n)return O(`[VaultBalance] ${a.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),o;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 u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),d=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),l=d.slice(0,5),h=d.length-l.length;h>0&&O(`[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 i=new Array(t.length);let n=0;const o=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=n++;if(e>=t.length)return;i[e]=await r(t[e])}}));return await Promise.all(o),i}(l,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),s,r,i,n)}))),m=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of a)m.has(t.txid)&&o.add(`${t.txid}:${t.vout}`);return m.size>0&&O(`[VaultBalance] self-change: ${o.size}/${a.length} unconfirmed UTXO(s) verified as protocol change by ${i.length} provider(s)`),o}async verifyParentIsSelfSpendConsensus(t,e,r,i,n,o){const a=t=>n[t].name||n[t].providerUrl,s=await Promise.allSettled(n.map(((n,a)=>this.evaluateParentForProvider(t,e,r,i,o[a],n)))),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}/${n.length} provider(s): ${c.join("; ")}`);const u=s.map((t=>t.value)),d=u.map((t=>t.selfSpend)),l=d.map(((t,e)=>({vote:t,name:a(e)}))).filter((t=>t.vote!==d[0])).map((t=>`${a(0)}=${d[0]} vs ${t.name}=${t.vote}`));if(l.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${l.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!d[0])return!1;const h=u.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,i,n,o){const a=await this.fetchParentTransaction(t,o);if(!a||0===a.inputs.length)return{selfSpend:!1,outputMismatch:null};const s=await this.verifyInputsAreSelfSpend(a.inputs,r,i,n),c=s?function(t,e,r){for(const i of t){const t=e.find((t=>t.index===i.vout));if(!t)return`claimed output ${i.txid}:${i.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${i.txid}:${i.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==i.satoshis)return`claimed output ${i.txid}:${i.vout} value ${t.value?.toString()??"<missing>"} != reported ${i.satoshis.toString()}`}return null}(e,a.outputs,r):null;return{selfSpend:s,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,i){const n=[...new Set(t.map((t=>t.txid)))],o=new Map,a=n.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(a.map((async t=>{o.set(t,await i.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=o.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const s=await Promise.all(n.map((t=>i.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,i=new AbortController,n=setTimeout((()=>i.abort()),r);try{const n=await fetch(`${e.providerUrl}/tx/${t}`,{signal:i.signal,headers:await j(e.auth,r)});if(!n.ok){if(404===n.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: ${n.status} ${n.statusText}`)}const o=await n.json();if(!o.vin||!Array.isArray(o.vin)||0===o.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const a=[];for(const e of o.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(o.vout)?o.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(L(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(n)}}},tt=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),i=await this.getAuthorizedSpendsFromContract(t),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e){const r=this.config.minConfirmations,i=await this.bitcoinProvider.getUTXOSet(e,r),n=await this.getAuthorizedSpendsFromContract(t);for(const t of n){if(i.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const o=n.reduce(((t,e)=>t+e.satoshis),0n),a=new Z(this.bitcoinProvider,this.config.bitcoinProviderConfigs,this.config.minConsensusProviders??1),s=await a.confirmedUtxoConsensus(i.utxos,e,r),c=await a.classifySelfChange(i.utxos,e,r),u=i.utxos.filter((t=>(s.has(`${t.txid}:${t.vout}`)||c.has(`${t.txid}:${t.vout}`))&&!this.isUTXOAuthorized(t,n))),d=u.reduce(((t,e)=>t+e.satoshis),0n),l=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:o,authorizedSpendsHash:l,availableUTXOs:u,availableBalance:d,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],i);return(await n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var et=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:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),n=await i.liquidationThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(i)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),n=await i.maxEscalatedThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function rt(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 I[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var it=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),c=(u={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 et(u));var u;const d=this.config.termOverride??e.selectedTerm,[l,h,g]=await Promise.all([c.getLiquidationThreshold(),c.getMaxEscalatedThreshold(),c.getTermFees(d)]),f=function(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=Math.floor(Date.now()/1e3),i=e*m,n=r-t,o=Math.floor(n/p);return{termDurationDays:o,termLengthDays:i,isExpired:o>i,daysUntilExpiry:Math.max(0,i-o),daysIntoGracePeriod:Math.max(0,o-i)}}(e.termStartTimestamp,e.selectedTerm),w=function(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}(f.isExpired,f.daysIntoGracePeriod,l,h),y=function(t,e,r){const i=t*e/(100000000n*a);return 0n===r?{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}(i.availableBalance,n,e.ucdDebt),v=y.collateralRatioBps<w,b=y.collateralRatioBps-w;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:y.collateralValueUsd,collateralRatioBps:y.collateralRatioBps,termDurationDays:f.termDurationDays,termLengthDays:f.termLengthDays,isExpired:f.isExpired,daysUntilExpiry:f.daysUntilExpiry,daysIntoGracePeriod:f.daysIntoGracePeriod,currentLiquidationThreshold:w,isLiquidatable:v,marginToLiquidationBps:b,liquidationThresholdBps:l,originationFeeBps:g.originationFeeBps,extensionFeeBps:g.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],i),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const u=Number(s.expiryAt),d=Number(s.selectedTerm),l=Number(s.totalTerm),h=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),f=(v=d,0===(y=u)?0:y-v*m*p);var y,v;const b=rt(s.vaultAddress,x(this.config.chain));if("string"!=typeof b||0===b.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:b,ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:f,selectedTerm:d,status:c,expiryAt:u,previousExpiryAt:h,totalTerm:l,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 i=await this.getVaultSnapshot(t);return function(t,e,r,i){const n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var nt="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))",ot={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 at(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 st=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),ct=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)"]),ut=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),dt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function lt(t,e,r){return t.call({to:e,data:r})}async function ht(t,e){const r=new ethers.utils.Interface([nt]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([nt]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?at({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]}):at(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await lt(t,e,st.encodeFunctionData("views",[])),[i]=st.decodeFunctionResult("views",r),[n,o,a,s,c,u,d,l]=await Promise.all([lt(t,e,st.encodeFunctionData("paused",[])),lt(t,e,st.encodeFunctionData("liquidationPaused",[])),lt(t,e,st.encodeFunctionData("simplePsm",[])),lt(t,i,ct.encodeFunctionData("core",[])),lt(t,i,ct.encodeFunctionData("loanOps",[])),lt(t,i,ct.encodeFunctionData("collateralManager",[])),lt(t,i,ct.encodeFunctionData("liquidationManager",[])),lt(t,i,ct.encodeFunctionData("circuitBreaker",[]))]),h=st.decodeFunctionResult("paused",n)[0],p=st.decodeFunctionResult("liquidationPaused",o)[0],m=st.decodeFunctionResult("simplePsm",a)[0],g=ct.decodeFunctionResult("core",s)[0],f=ct.decodeFunctionResult("loanOps",c)[0],w=ct.decodeFunctionResult("collateralManager",u)[0],y=ct.decodeFunctionResult("liquidationManager",d)[0],v=ct.decodeFunctionResult("circuitBreaker",l)[0],b=await lt(t,f,ut.encodeFunctionData("getUcdController",[])),T=await lt(t,f,ut.encodeFunctionData("ucdToken",[])),P=ut.decodeFunctionResult("getUcdController",b)[0],$=ut.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await lt(t,e,dt.encodeFunctionData("paused",[]));return dt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[A,I,C,S,x,B,k,U]=await Promise.all([E(g),E(f),E(w),E(y),E(v),E(P),E($),E(m)]);return at({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:A,loanOperationsPaused:I,collateralManagerPaused:C,liquidationManagerPaused:S,circuitBreakerPaused:x,ucdControllerPaused:B,ucdTokenPaused:k,simplePsmPaused:U})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var pt={hardhat:{chain:"hardhat",chainId:S.hardhat,bitcoinNetwork:I.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:S.sepolia,bitcoinNetwork:I.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:S.ethereum,bitcoinNetwork:I.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var mt=[{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"}],gt=[{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 ft(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function wt(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!i)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,mt,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.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:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,gt,r);let s;try{s=await a.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await ft(e.ciphertext,e.pkpId),{url:i,auth:o}=X(r,{requireHttps:!0});n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:o,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i)}var yt,vt=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],bt="UCDMintedWithAuthorization(bytes32,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes32)";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;let e="0";try{O("[Extend Position Validator] Starting..."),O("[Extend Position Validator] DEBUG: globalThis.priceProviders:",globalThis.priceProviders),O("[Extend Position Validator] DEBUG: priceProviders type:",typeof globalThis.priceProviders),globalThis.priceProviders&&(O("[Extend Position Validator] DEBUG: priceProviders isArray:",Array.isArray(globalThis.priceProviders)),O("[Extend Position Validator] DEBUG: priceProviders length:",globalThis.priceProviders.length),globalThis.priceProviders.length>0&&O("[Extend Position Validator] DEBUG: First provider:",globalThis.priceProviders[0])),e="0";const t=globalThis.chain,i=globalThis.selectedTerm;if(!t)throw new Error('Missing required parameter: "chain"');if(!i||"number"!=typeof i)throw new Error('Missing required parameter: "selectedTerm"');const n=M.verifyTermPositionActionAuthorizationStructure(globalThis.auth),o=function(t){const e=x(t),r=pt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),s=o.chainId,c=globalThis.rpcUrl;let l;c&&"string"==typeof c?(!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(!C.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${C.join(", ")}`)}(o,c),O(` Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(c)}`),l=c):(l=await Lit.Actions.getRpcUrl({chain:t}),O(` Using LIT-provided RPC URL for chain: ${t}`));const w=new ethers.providers.JsonRpcProvider(l),y=await wt({policy:o,ethersProvider:w,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl}),P=y[0];O(` \u2705 Bitcoin Providers: ${y.length} (${y.map((t=>t.name)).join(", ")})`);const $=P.minConfirmations;let E,A,I,S,B,U;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error("Contract addresses not provided. Required for both dev and service modes.");if(E=globalThis.contractAddresses.PositionManager,A=globalThis.contractAddresses.LoanOperationsManagerModule,I=globalThis.contractAddresses.TermManagerModule,S=globalThis.contractAddresses.UCDController,B=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",U=globalThis.contractAddresses.BTCSpendAuthorizer||A,!(E&&A&&I&&S&&B))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");O("\ud83d\udd0d LIT Action Contract Addresses:"),O(" PositionManager:",E),O(" LoanOpsManager:",A),O(" TermManager:",I),O(" UCDController:",S);const D=s,R=new ethers.providers.JsonRpcProvider(l);!function(t,e){const r=ot[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await ht(R,E));const F=new G({providerUrl:P.url,auth:P.auth}),q=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await Y(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await Y(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(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 _=new Q(q,void 0,void 0,{devSingleProvider:N&&o.allowDevSinglePriceProvider}),L=(r={contractAddress:U,chain:t,chainId:D,rpcUrl:c,bitcoinProvider:F,minConfirmations:$,bitcoinProviderConfigs:y.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),minConsensusProviders:o.minConsensusProviders},new tt(r));e="1";const z=function(t){return new it(t)}({contractAddress:E,termManagerAddress:I,loanOpsManagerAddress:A,liquidationManagerAddress:B,chain:t,chainId:D,rpcUrl:c,vaultBalance:L,priceOracle:_,termOverride:i}),X=await z.getVaultSnapshot(n.positionId),V=X.btcPriceUsd,j=BigInt(V.toString());if(j<u||j>d)throw new Error(`Bitcoin price ${j} is outside acceptable range (${u} - ${d})`);e="2";const H=globalThis.contractAddresses?.AgentDelegationRegistry;if(!await M.verifyExtendAuthorization(n,X.borrower,D,R,void 0,H?{registry:H,op:"renew"}:void 0,A))throw O(`[DEBUG] Authorization failed - signer: ${n.signature?"present":"missing"}, borrower: ${X.borrower}`),O(`[DEBUG] Position ID: ${n.positionId}`),O(`[DEBUG] Auth timestamp: ${n.timestamp}, chainId: ${n.chainId}, newTerm: ${n.newTerm}`),O(`[DEBUG] Auth action: ${n.action}`),O(`[DEBUG] Auth signature: ${n.signature}`),new Error("Caller not authorized");M.assertSelectedTermMatchesAuth(i,n.newTerm),e="3";if(![2,3].includes(X.status))throw new Error(`Invalid position status for extension: ${function(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})`}}(X.status)}. Must be ACTIVE or EXPIRED.`);const J=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(n.positionId);new ethers.Contract(I,[...vt],R);if(X.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const Z=X.selectedTerm,et=Z+i,rt=65535;if(et>rt)throw new Error(`Extension would cause term overflow: ${Z} + ${i} = ${et} months, exceeds max ${rt} months`);let nt;try{const t=await R.getBlock("latest");nt=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const at=i===g?f*p:i*m*p,st=X.expiryAt+at,ct=3===X.status;if(st-nt>2*at)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(ct&&st<=nt)throw new Error("Invalid requested expiry date: extension must extend into the future for expired loans");e="4",O("\ud83d\udd0d Using extensionFeeBps from vault snapshot:",X.extensionFeeBps);const ut=BigInt(X.extensionFeeBps);let dt=[];try{const t=await async function(t,e,r,i){const n="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(bt)),a=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]),s=await t.getBlock("latest"),c=Math.max(0,s.timestamp-i),u=Math.ceil(c/12),d=[];let l=Math.max(0,s.number-u-200);for(;l<=s.number;){const r=Math.min(l+900-1,s.number),i=await t.getLogs({address:e,topics:[o,n],fromBlock:l,toBlock:r});if(d.push(...i),r>=s.number)break;l=r+1}return d.map((t=>{const e=a.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(R,A,n.positionId,X.termStartTimestamp),e=BigInt(X.termStartTimestamp);dt=t.filter((t=>t.quantumTimestamp>=e)),O(`[Pro-Rata] Found ${t.length} total mints, ${dt.length} in current term`)}catch(t){throw new Error(`EXTEND_M7_MINT_LOG_FETCH_FAILED: Pro-rata mint-log fetch failed: ${t?.message??String(t)}. Retry with a healthy RPC so the pro-rata renewal credit can be computed; do not silently overcharge.`)}e="5";const lt=BigInt(k()),mt=function(t){const{mints:e,termStart:r,termExpiry:i,renewalNow:n,ucdDebt:o,extensionFeeRateBps:a}=t,s=o*a/10000n;if(0===e.length)return s;const c=(i-r)/BigInt(p);if(0n===c)return s;let u=0n,d=0n;for(const t of e){if(t.quantumTimestamp<r)continue;const e=(n-t.quantumTimestamp)/BigInt(p),i=(e>c?c:e)*t.mintFee/c;u+=t.mintFee,d+=i}const l=u>d?u-d:0n;return s>l?s-l:0n}({mints:dt,termStart:BigInt(X.termStartTimestamp),termExpiry:BigInt(X.expiryAt),renewalNow:lt,ucdDebt:BigInt(X.ucdDebt.toString()),extensionFeeRateBps:ut}),gt=BigInt(X.ucdDebt.toString())+mt;e="6";const ft=function(t,e){if(t<0n)throw new Error("BTC amount cannot be negative");if(e<=0n)throw new Error("BTC price must be positive");return t*e/a}(X.availableBTCSats,j),yt=W(ft,gt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return W(t,e)>=r}(ft,gt,X.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${K(yt)}% < ${K(X.liquidationThresholdBps)}%`);e="7";const Tt=k()+h,Pt={name:v,version:b,chainId:s,verifyingContract:ethers.utils.getAddress(A)},$t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(T)),Et={ExtendPosition:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"availableBTCBalance",type:"uint256"},{name:"proRataRenewalFee",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},At={actionTag:$t,positionId:J,selectedTerm:i,btcPrice:j.toString(),availableBTCBalance:X.availableBTCSats.toString(),proRataRenewalFee:mt.toString(),quantumTimestamp:Tt,borrower:ethers.utils.getAddress(X.borrower)};e="8";const It=globalThis.validatorWalletAddress;if(!It||!It.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Ct=await Lit.Actions.getPrivateKey({pkpId:It}),St="string"==typeof Ct?Ct.startsWith("0x")?Ct:`0x${Ct}`:String(Ct),xt=new ethers.Wallet(St),Bt=await xt._signTypedData(Pt,Et,At);return{approved:!0,positionId:n.positionId,selectedTerm:i,btcPrice:j.toString(),availableBTCBalance:X.availableBTCSats.toString(),proRataRenewalFee:mt.toString(),newTotalDebt:gt.toString(),newCollateralRatioBps:yt.toString(),signature:Bt,timestamp:n.timestamp,quantumTimestamp:Tt,validatorPkp:xt.address}}catch(t){throw console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),t}var r}return yt=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),yt)})();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
- 1d4e085335af80f194a663a577876902c83015177e95906a0b461fa93bd5da08
1
+ 31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "extend-position-validator",
3
- "originalSize": 193445,
4
- "minifiedSize": 76515,
5
- "compressionRatio": 0.604461216366409,
6
- "hash": "1d4e085335af80f194a663a577876902c83015177e95906a0b461fa93bd5da08",
7
- "buildTime": 1787171882273,
3
+ "originalSize": 200318,
4
+ "minifiedSize": 79975,
5
+ "compressionRatio": 0.60075979193083,
6
+ "hash": "31c1aaf883ef22f37681ddb0a4a949be5c05304b6aef178989475a2da935ef9a",
7
+ "buildTime": 1788340136053,
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": 1787171882404,
7
+ "buildTime": 1788340136489,
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": 1787171882510,
7
+ "buildTime": 1788340136641,
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": 1787171882522,
7
+ "buildTime": 1788340136665,
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": 1787171882541,
7
+ "buildTime": 1788340136689,
8
8
  "version": "0.1.0"
9
9
  }