@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,l=100000000000000n,d=60,h=86400,p=30,m=12,g=365,f=8e3;function w(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var y="DiamondHands.Protocol",v="1",b="mint-ucd",$=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))($||{}),P={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},T=["infura.io","drpc.org"],S={ethereum:1,sepolia:11155111,hardhat:1337};function A(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values($).join(", ")}`)}function E(t){return S[t]}function C(t){return Math.floor(t/d)*d}async function I(){const t=Math.floor(Date.now()/1e3),e=t%d;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%d;return e<8||e>=52}(t))return;let r;r=e>=52?d-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: ${C(Math.floor(Date.now()/1e3))}`)}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 l=new ethers.Contract(i.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],n),[d,,h]=await l.canWithdraw(t,u);return!0===d&&(i.outcome={effectiveFloorBps:Number(h)},!0)}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await I();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=C(i),o=C(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-d,s=n+d;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e();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 t.action===b&&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 M=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},U=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,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 U(t):new M}};function O(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function R(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function N(t){return t instanceof Error&&"AbortError"===t.name}function _(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&&_(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&&_(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 _(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`");_(n,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&_(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 F=new Map;async function L(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,n=F.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((()=>F.delete(i))),F.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function z(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 V=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await L(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),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"),N(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${R(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${R(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${R(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return z(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");z(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: ${R(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"),N(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(R(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${R(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const 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}`);z(s,`getBalance ${e} funded_txo_sum`),z(c,`getBalance ${e} spent_txo_sum`);const u=s-c;z(u,`getBalance ${e} confirmed balance`);const l=BigInt(u);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(n),N(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=R(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=R(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),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),N(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(R(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,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 z(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),N(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 H(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 G=j;async function K(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 W=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 V({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 l=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of a){const e=`${t.txid}:${t.vout}`;let i=t.confirmations,n=t.confirmations;for(let r=0;r<l.length;r++){const o=l[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),d.push(e))}d.length>0&&B(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<l.length;t++){const e=s(t+1);for(const[i,n]of l[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),l=[...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})),d=l.slice(0,5),h=l.length-d.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}(d,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)),l=u.map((t=>t.selfSpend)),d=l.map(((t,e)=>({vote:t,name:a(e)}))).filter((t=>t.vote!==l[0])).map((t=>`${a(0)}=${l[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!l[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 L(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(N(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(n)}}},J=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 W(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))),l=u.reduce(((t,e)=>t+e.satoshis),0n),d=this.computeAuthorizedSpendsHash(t,n);return{totalUTXOs:i.utxos,totalBalance:i.totalBalance,authorizedUTXOs:n,authorizedBalance:o,authorizedSpendsHash:d,availableUTXOs:u,availableBalance:l,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:f},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],i);return(await n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var Q=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:f},{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:f},{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:f},{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:f},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),n=await i.maxEscalatedThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function Y(t,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 Z=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),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 Q(u));var u;const l=this.config.termOverride??e.selectedTerm,[d,m,g]=await Promise.all([c.getLiquidationThreshold(),c.getMaxEscalatedThreshold(),c.getTermFees(l)]),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*p,n=r-t,o=Math.floor(n/h);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,d,m),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:d,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:f},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],i),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const u=Number(s.expiryAt),l=Number(s.selectedTerm),d=Number(s.totalTerm),m=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),w=(v=l,0===(y=u)?0:y-v*p*h);var y,v;const b=Y(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:w,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:d,lastRenewedAt:g}}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const i=await this.getVaultSnapshot(t);return function(t,e,r,i){const n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var tt="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",et={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function rt(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var it=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),nt=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),ot=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),at=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function st(t,e,r){return t.call({to:e,data:r})}async function ct(t,e){const r=new ethers.utils.Interface([tt]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([tt]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?rt({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):rt(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await st(t,e,it.encodeFunctionData("views",[])),[i]=it.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([st(t,e,it.encodeFunctionData("paused",[])),st(t,e,it.encodeFunctionData("liquidationPaused",[])),st(t,e,it.encodeFunctionData("simplePsm",[])),st(t,i,nt.encodeFunctionData("core",[])),st(t,i,nt.encodeFunctionData("loanOps",[])),st(t,i,nt.encodeFunctionData("collateralManager",[])),st(t,i,nt.encodeFunctionData("liquidationManager",[])),st(t,i,nt.encodeFunctionData("circuitBreaker",[]))]),h=it.decodeFunctionResult("paused",n)[0],p=it.decodeFunctionResult("liquidationPaused",o)[0],m=it.decodeFunctionResult("simplePsm",a)[0],g=nt.decodeFunctionResult("core",s)[0],f=nt.decodeFunctionResult("loanOps",c)[0],w=nt.decodeFunctionResult("collateralManager",u)[0],y=nt.decodeFunctionResult("liquidationManager",l)[0],v=nt.decodeFunctionResult("circuitBreaker",d)[0],b=await st(t,f,ot.encodeFunctionData("getUcdController",[])),$=await st(t,f,ot.encodeFunctionData("ucdToken",[])),P=ot.decodeFunctionResult("getUcdController",b)[0],T=ot.decodeFunctionResult("ucdToken",$)[0],S=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await st(t,e,at.encodeFunctionData("paused",[]));return at.decodeFunctionResult("paused",r)[0]}catch{return!1}},[A,E,C,I,x,k,B,M]=await Promise.all([S(g),S(f),S(w),S(y),S(v),S(P),S(T),S(m)]);return rt({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:A,loanOperationsPaused:E,collateralManagerPaused:C,liquidationManagerPaused:I,circuitBreakerPaused:x,ucdControllerPaused:k,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var ut={hardhat:{chain:"hardhat",chainId:S.hardhat,bitcoinNetwork:P.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:S.sepolia,bitcoinNetwork:P.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:S.ethereum,bitcoinNetwork:P.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var lt,dt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],ht=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function pt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function mt(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,minConfirmations:e.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,dt,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(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,ht,r);let s;try{s=await a.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await pt(e.ciphertext,e.pkpId),{url:i,auth:o}=q(r,{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)}async function gt(t,e,r,i,n){if(e.length<r)throw new Error(`Bitcoin balance consensus requires at least ${r} provider(s) on this chain; ${e.length} configured. Refusing to sign a balance without cross-check.`);return e.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null):async function(t,e,r,i,n){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const o=n??(t=>new V({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),a=await Promise.allSettled(e.map((e=>o(e).getBalance(t)))),s=a.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(s.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${s.length}/${e.length} provider(s): ${s.join("; ")}`);const c=a.map((t=>t.value)),u=c[0],l=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==u)).map((t=>`${e[0].name}=${u.toString()} vs ${t.name}=${t.bal.toString()}`));if(l.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${l.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${u.toString()} sats)`);return u}(t,e,r,i,n)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=D.create("UCD Mint Validator");let r,i="init";try{const t=[{inputs:[],name:"getRemainingMintCapacity",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=[{inputs:[],name:"maxSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],s=[{inputs:[],name:"getCurrentSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],c=[{inputs:[],name:"getProtocolConfig",outputs:[{internalType:"uint256",name:"_liquidationThreshold",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueUcd",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueWei",type:"uint256"},{internalType:"uint256",name:"_maximumLoanValueUcd",type:"uint256"}],stateMutability:"view",type:"function"}];e.stepStart("0","Validating configuration");const d=O(),$=d.chain;if(!$)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');r=x.verifyAmountPositionActionAuthorizationStructure(d.auth);const P=function(t){const e=A(t),r=ut[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}($),S=P.chain,C=P.bitcoinNetwork;let I,k;if(B(` \u2705 Chain: ${$} (${S})`),B(` \u2705 Bitcoin Network: ${C}`),e.log("0","Validating contract addresses..."),e.log("0",`contractAddresses exists: ${!!d.contractAddresses}`),e.log("0","contractAddresses type: "+typeof d.contractAddresses),!d.contractAddresses||"object"!=typeof d.contractAddresses)throw e.error("0",`\u274c ERROR: No valid contractAddresses object found: ${JSON.stringify(d.contractAddresses)}`),new Error("contractAddresses is required and must include: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController");e.log("0","\u2705 Found valid contractAddresses object"),e.log("0",`Available keys: ${Object.keys(d.contractAddresses)}`);const M=d.contractAddresses.PositionManager,U=d.contractAddresses.LoanOperationsManagerModule,D=d.contractAddresses.TermManagerModule,R=d.contractAddresses.UCDController,N=d.contractAddresses.LiquidationManagerModule??d.contractAddresses.LiquidationManager??"",_=d.contractAddresses.BTCSpendAuthorizer??"",q=d.contractAddresses.BitcoinProviderRegistry;if(e.log("0","Extracted addresses:"),e.log("0",`POSITION_MANAGER_ADDRESS: ${M||"MISSING"}`),e.log("0",`LOAN_OPS_MANAGER_ADDRESS: ${U||"MISSING"}`),e.log("0",`TERM_MANAGER_ADDRESS: ${D||"MISSING"}`),e.log("0",`UCD_CONTROLLER_ADDRESS: ${R||"MISSING"}`),!(M&&U&&D&&R&&N))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");B(" \u2705 Contract addresses loaded and validated"),B(` PositionManager: ${M}`),B(` LoanOpsManager: ${U}`),e.stepEnd("0"),B("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const F=BigInt(r.amount);if(F<=0n)throw new Error(`Amount must be positive, got: ${F.toString()} wei`);B(" Fetching protocol mint limits..."),e.log("0","Fetching protocol mint limits...");const L=d.rpcUrl;let z;L&&"string"==typeof L?(!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!T.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${T.join(", ")}`)}(P,L),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}(L)}`),z=L):(z=await Lit.Actions.getRpcUrl({chain:$}),B(` Using LIT-provided RPC URL for chain: ${$}`));const j=new ethers.providers.JsonRpcProvider({url:z,timeout:f});k=await mt({policy:P,ethersProvider:j,registryAddress:q,devBitcoinProviderUrl:d.devBitcoinProviderUrl}),I=k[0],B(` \u2705 Bitcoin Provider: ${I.name} (min confs ${I.minConfirmations})`);!function(t,e){const r=et[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("mintUcd",await ct(j,M));const W=new ethers.Contract(U,c,j);let Q,Y;try{const t=await W.getProtocolConfig();Q=BigInt(t[2].toString());Y=1000000000000000000n*BigInt(t[3].toString()),B(" \u2705 Protocol limits loaded from LoanOperationsManager (consolidated call)"),B(` - Minimum: ${Q.toString()} wei`),B(` - Maximum: ${Y.toString()} wei`),e.log("0","\u2705 Protocol limits loaded from LoanOperationsManager")}catch(t){const r=t?.message||String(t);throw B(` \u274c Failed to get protocol config (${r}); refusing to sign`),e.log("0","\u274c Protocol config unavailable \u2014 refusing to mint"),new Error(`getProtocolConfig failed; cannot validate mint limits: ${r}`)}if(F<Q)throw new Error(`Amount too small: ${F.toString()} wei. Minimum: ${Q.toString()} wei`);if(F>Y)throw new Error(`Amount too large: ${F.toString()} wei. Maximum: ${Y.toString()} wei`);const tt=d.publicKey;if(!tt)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof tt||0===tt.length)throw new Error("Invalid publicKey: must be non-empty string");i="0.5",B("[UCD Mint Validator] Started"),B(` Position: ${r.positionId}`),B(` Amount: ${F.toString()} wei`),e.log("0","Validator Started");const rt=new V({providerUrl:I.url,auth:I.auth,timeout:8e3}),it=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await K(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await K(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}(d.priceProviders),nt=!0===globalThis.devPriceMode;if(nt&&!P.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${P.chain}`);const ot=new G(it,void 0,void 0,{devSingleProvider:nt&&P.allowDevSinglePriceProvider}),at=(n={contractAddress:_||U,chain:$,chainId:E(S),rpcUrl:L,bitcoinProvider:rt,minConfirmations:I.minConfirmations,bitcoinProviderConfigs:k.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth,timeout:8e3}))),minConsensusProviders:P.minConsensusProviders},new J(n));if(i="1",B("[Step 1] Getting vault snapshot..."),e.stepStart("1","Getting vault snapshot"),d.debugOverrides?.useStubbedBtcData&&31337!==E(S))throw new Error("debugOverrides.useStubbedBtcData is not permitted on live networks");const st=function(t){return new Z(t)}({contractAddress:M,termManagerAddress:D,loanOpsManagerAddress:U,liquidationManagerAddress:N,chain:$,chainId:E(S),rpcUrl:L,vaultBalance:at,priceOracle:ot,debugOverrides:d.debugOverrides}),lt=await st.getVaultSnapshot(r.positionId);if(await gt(lt.vaultAddress,k,P.minConsensusProviders,8e3),lt.btcPriceUsd<u||lt.btcPriceUsd>l)throw new Error(`Bitcoin price ${lt.btcPriceUsd} is outside acceptable range (${u} - ${l}). This may indicate oracle manipulation or stale price data. Please try again later.`);B(` \u2705 BTC price validation passed: $${(Number(lt.btcPriceUsd)/1e8).toFixed(2)}`),e.stepEnd("1"),i="2",B("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticating caller");const dt=d.contractAddresses?.AgentDelegationRegistry,ht=dt?{registry:dt,op:"mint",outcome:void 0}:void 0;if(!await x.verifyMintAuthorization(r,lt.borrower,E(S),j,void 0,ht))throw new Error("Caller not authorized");const pt=ht?.outcome?.effectiveFloorBps??0;B(" \u2705 Caller authorized"),e.stepEnd("2"),i="3",B("[Step 3] Validating position state..."),e.stepStart("3","Validating position state");if(![0,1,2].includes(lt.status))throw new Error(`Invalid position status for minting: ${w(lt.status)}. Must be PENDING_DEPOSIT, PENDING_MINT, or ACTIVE. Current status prevents minting operations.`);if(B(` \u2705 Position status valid for minting: ${w(lt.status)}`),lt.isExpired)throw new Error(`Loan term expired ${lt.daysIntoGracePeriod} days ago - minting rejected. Must repay or extend term first.`);if(lt.isLiquidatable)throw new Error(`Position is liquidatable (${H(lt.collateralRatioBps)}% < ${H(lt.currentLiquidationThreshold)}%) - minting rejected. Add collateral first.`);B(" \u2705 Position is healthy"),B(` - Term: ${lt.daysUntilExpiry} days remaining`),B(` - Current ratio: ${H(lt.collateralRatioBps)}%`),B(` - Liquidation threshold: ${H(lt.currentLiquidationThreshold)}%`),e.stepEnd("3"),i="4",B("[Step 4] Calculating fees..."),e.stepStart("4","Calculating fees");let ft=function(t,e){if(t<0n)throw new Error("Amount cannot be negative");if(e<0||e>1e4)throw new Error("Fee basis points must be between 0 and 10000 (0% to 100%)");return t*BigInt(e)/10000n}(F,lt.originationFeeBps);const wt=Number(r.timestamp),yt=lt.previousExpiryAt??0,vt=lt.totalTerm??0;if(yt>0&&wt<yt){const t=BigInt(yt)-BigInt(wt),e=vt-(lt.selectedTerm??0),r=BigInt(e===m?g*h:e*p*h);if(0n===r)throw new Error(`Scenario B tail fee: original term length is zero (totalTerm=${vt}, selectedTerm=${lt.selectedTerm??0}). Cannot compute tail fee.`);const i=t*BigInt(lt.originationFeeBps)*F/(10000n*r);ft+=i,B(` Scenario B tail fee: ${i.toString()} wei (${e}mo original term, ${t}s remaining)`)}B(` Mint fee: ${ft.toString()} wei (${H(lt.originationFeeBps)}% base${yt>0&&wt<yt?" + tail":""})`),e.stepEnd("4"),i="4a",B("[Step 4a & 4b] Validating capacity limits..."),e.stepStart("4ab","Validating capacity limits");const bt=F+ft,$t=new ethers.Contract(R,[...t,...o,...s],j),[Pt,Tt,St]=await Promise.all([$t.getRemainingMintCapacity(),$t.maxSupply(),$t.getCurrentSupply()]),At=BigInt(Pt.toString()),Et=BigInt(Tt.toString()),Ct=BigInt(St.toString());if(bt>At)throw new Error(`Daily mint limit would be exceeded: attempting to mint ${bt.toString()} wei (${F.toString()} + ${ft.toString()} fee), but only ${At.toString()} wei remaining in daily capacity`);if(B(" \u2705 Daily mint limit check passed"),B(` - Mint amount (with fee): ${bt.toString()} wei`),B(` - Remaining capacity: ${At.toString()} wei`),Et>0n){const t=Ct+bt;if(t>Et)throw new Error(`Max supply would be exceeded: minting ${bt.toString()} wei (${F.toString()} + ${ft.toString()} fee) would result in total supply of ${t.toString()} wei, exceeding max supply of ${Et.toString()} wei`);B(" \u2705 Max supply check passed"),B(` - Current supply: ${Ct.toString()} wei`),B(` - After mint: ${t.toString()} wei`),B(` - Max supply: ${Et.toString()} wei`),B(` - Remaining capacity: ${(Et-Ct).toString()} wei`)}else B(" \u2705 Max supply unlimited (not enforced)");e.stepEnd("4ab"),i="5",B("[Step 5] Calculating new state..."),e.stepStart("5","Calculating new state");const It=lt.ucdDebt+F+ft,xt=lt.availableBTCSats;B(` Current debt: ${lt.ucdDebt.toString()} wei`),B(` New debt: ${It.toString()} wei`),B(` Available collateral: ${xt.toString()} sats`),e.stepEnd("5"),i="6",B("[Step 6] Validating collateral ratio after mint..."),e.stepStart("6","Validating collateral ratio after mint");const kt=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}(xt,lt.btcPriceUsd),Bt=X(kt,It);if(B(` New collateral ratio: ${H(Bt)}%`),B(` Minimum required: ${H(lt.liquidationThresholdBps)}%`),!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return X(t,e)>=r}(kt,It,lt.liquidationThresholdBps))throw new Error(`Insufficient collateral: ${H(Bt)}% < ${H(lt.liquidationThresholdBps)}%`);if(B(" \u2705 Sufficient collateral"),pt>0&&Bt<pt)throw new Error(`Agent mint refused: post-mint collateral ratio ${H(Bt)}% is below the delegation floor ${H(pt)}%`);const Mt=BigInt("340282366920938463463374607431768211455");if(It>Mt)throw new Error(`New debt exceeds maximum allowed value: ${It.toString()} > ${Mt.toString()} (type(uint128).max). The contract will revert with DebtOverflow error.`);B(` \u2705 New debt within bounds: ${It.toString()} <= ${Mt.toString()}`),e.stepEnd("6"),i="7",B("[Step 7] Building authorization message..."),e.stepStart("7","Building authorization message");const Ut=lt.authorizedSpendsHash,Dt=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[lt.ucdDebt])),Ot={authorizedSpendsHash:Ut,ucdDebtHash:Dt,contractBundleHash:ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[M,U,D,R])),btcPrice:lt.btcPriceUsd.toString(),mintAmount:F.toString(),mintFee:ft.toString(),newCollateral:xt.toString(),newDebt:It.toString()};if(r.action!==b)throw new Error(`Invalid mint authorization action: expected "${b}", got "${r.action}"`);const Rt=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(r.positionId),Nt=E(S),_t={name:y,version:v,chainId:Nt,verifyingContract:ethers.utils.getAddress(U)},qt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Ft={MintUcd:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"mintFee",type:"uint256"},{name:"newDebt",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractHash",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},Lt={actionTag:qt,positionId:Rt,mintAmount:Ot.mintAmount,mintFee:Ot.mintFee,newDebt:Ot.newDebt,newCollateral:Ot.newCollateral,btcPrice:Ot.btcPrice,authorizedSpendsHash:Ot.authorizedSpendsHash,ucdDebtHash:Ot.ucdDebtHash,contractHash:Ot.contractBundleHash,quantumTimestamp:r.timestamp,borrower:ethers.utils.getAddress(lt.borrower)};e.stepEnd("7"),i="8",e.stepStart("8","Signing authorization");const zt=globalThis.validatorWalletAddress;if(!zt||!zt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Vt=await Lit.Actions.getPrivateKey({pkpId:zt}),Xt="string"==typeof Vt?Vt.startsWith("0x")?Vt:`0x${Vt}`:String(Vt),Ht=new ethers.Wallet(Xt),jt=await Ht._signTypedData(_t,Ft,Lt);return e.stepEnd("8"),e.summary(),B("[UCD Mint Validator] \u2705 Complete"),{approved:!0,positionId:r.positionId,mintAmount:F.toString(),mintFee:ft.toString(),newDebt:It.toString(),newCollateral:xt.toString(),newCollateralRatioBps:Bt,btcPrice:lt.btcPriceUsd.toString(),authorizedSpendsHash:Ut,signature:jt,timestamp:r.timestamp,validatorPkp:Ht.address}}catch(t){throw console.error("[UCD Mint Validator] \u274c Failed:",t.message),console.error(`[UCD Mint Validator] Failed at step: ${i}`),t}var n}return lt=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),lt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ 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=86400,p=30,m=12,g=365,f=8e3,w={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};function y(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}var v="DiamondHands.Protocol",b="1",$="mint-ucd",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(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 A(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 w[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 S=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(S||{}),E={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},C=["infura.io","drpc.org"],I={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(S).join(", ")}`)}function k(t){return I[t]}function B(t){return Math.floor(t/l)*l}async function M(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=52}(t))return;let r;r=e>=52?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${B(Math.floor(Date.now()/1e3))}`)}var D="0x0000000000000000000000000000000000000000",U=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 M();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+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s="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:A(i,s.verifyingContract),types:T(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 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:A(i,a),types:T("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:A(i,s.verifyingContract),types:T(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}},N=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}},q=class{static create(t="LIT Action",e){return R(e)?new N(t):new F}};function _(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function L(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function z(t){return t instanceof Error&&"AbortError"===t.name}function V(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&&V(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&&V(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 V(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`");V(n,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&V(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 H=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=H.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((()=>H.delete(i))),H.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function G(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 K=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=q.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"),z(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: ${L(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: ${L(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${L(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 G(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");G(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: ${L(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"),z(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(L(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${L(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}`);G(s,`getBalance ${e} funded_txo_sum`),G(c,`getBalance ${e} spent_txo_sum`);const u=s-c;G(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),z(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=L(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=L(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),z(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(L(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 G(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),z(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 J(t){return t/100}var Q=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}};Q.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],Q.REQUIRED_PROVIDER_COUNT=3;var Y=Q;async function Z(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 tt=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 K({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(z(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(n)}}},et=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 tt(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:f},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 rt=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:f},{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:f},{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:f},{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:f},{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 it(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 E[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var nt=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 rt(u));var u;const d=this.config.termOverride??e.selectedTerm,[l,m,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*p,n=r-t,o=Math.floor(n/h);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,m),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:f},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),m=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),w=(v=d,0===(y=u)?0:y-v*p*h);var y,v;const b=it(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:w,selectedTerm:d,status:c,expiryAt:u,previousExpiryAt:m,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 ot="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))",at={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 st(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 ct=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),ut=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)"]),dt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),lt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function ht(t,e,r){return t.call({to:e,data:r})}async function pt(t,e){const r=new ethers.utils.Interface([ot]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([ot]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?st({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]}):st(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await ht(t,e,ct.encodeFunctionData("views",[])),[i]=ct.decodeFunctionResult("views",r),[n,o,a,s,c,u,d,l]=await Promise.all([ht(t,e,ct.encodeFunctionData("paused",[])),ht(t,e,ct.encodeFunctionData("liquidationPaused",[])),ht(t,e,ct.encodeFunctionData("simplePsm",[])),ht(t,i,ut.encodeFunctionData("core",[])),ht(t,i,ut.encodeFunctionData("loanOps",[])),ht(t,i,ut.encodeFunctionData("collateralManager",[])),ht(t,i,ut.encodeFunctionData("liquidationManager",[])),ht(t,i,ut.encodeFunctionData("circuitBreaker",[]))]),h=ct.decodeFunctionResult("paused",n)[0],p=ct.decodeFunctionResult("liquidationPaused",o)[0],m=ct.decodeFunctionResult("simplePsm",a)[0],g=ut.decodeFunctionResult("core",s)[0],f=ut.decodeFunctionResult("loanOps",c)[0],w=ut.decodeFunctionResult("collateralManager",u)[0],y=ut.decodeFunctionResult("liquidationManager",d)[0],v=ut.decodeFunctionResult("circuitBreaker",l)[0],b=await ht(t,f,dt.encodeFunctionData("getUcdController",[])),$=await ht(t,f,dt.encodeFunctionData("ucdToken",[])),P=dt.decodeFunctionResult("getUcdController",b)[0],T=dt.decodeFunctionResult("ucdToken",$)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await ht(t,e,lt.encodeFunctionData("paused",[]));return lt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[S,E,C,I,x,k,B,M]=await Promise.all([A(g),A(f),A(w),A(y),A(v),A(P),A(T),A(m)]);return st({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:S,loanOperationsPaused:E,collateralManagerPaused:C,liquidationManagerPaused:I,circuitBreakerPaused:x,ucdControllerPaused:k,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var mt={hardhat:{chain:"hardhat",chainId:I.hardhat,bitcoinNetwork:E.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:I.sepolia,bitcoinNetwork:E.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:I.ethereum,bitcoinNetwork:E.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var gt,ft=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],wt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function yt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),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 vt(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,ft,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,wt,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 yt(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)}async function bt(t,e,r,i,n){if(e.length<r)throw new Error(`Bitcoin balance consensus requires at least ${r} provider(s) on this chain; ${e.length} configured. Refusing to sign a balance without cross-check.`);return e.length<=1?(console.log(` \u24d8 Bitcoin balance consensus skipped \u2014 only ${e.length} provider(s) registered`),null):async function(t,e,r,i,n){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const o=n??(t=>new K({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),a=await Promise.allSettled(e.map((e=>o(e).getBalance(t)))),s=a.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(s.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${s.length}/${e.length} provider(s): ${s.join("; ")}`);const c=a.map((t=>t.value)),u=c[0],d=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==u)).map((t=>`${e[0].name}=${u.toString()} vs ${t.name}=${t.bal.toString()}`));if(d.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${d.join("; ")}`);e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${u.toString()} sats)`);return u}(t,e,r,i,n)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=q.create("UCD Mint Validator");let r,i="init";try{const t=[{inputs:[],name:"getRemainingMintCapacity",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],o=[{inputs:[],name:"maxSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],s=[{inputs:[],name:"getCurrentSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],c=[{inputs:[],name:"getProtocolConfig",outputs:[{internalType:"uint256",name:"_liquidationThreshold",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueUcd",type:"uint256"},{internalType:"uint256",name:"_minimumLoanValueWei",type:"uint256"},{internalType:"uint256",name:"_maximumLoanValueUcd",type:"uint256"}],stateMutability:"view",type:"function"}];e.stepStart("0","Validating configuration");const l=_(),w=l.chain;if(!w)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');r=U.verifyAmountPositionActionAuthorizationStructure(l.auth);const P=function(t){const e=x(t),r=mt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(w),T=P.chain,A=P.bitcoinNetwork;let S,E;if(O(` \u2705 Chain: ${w} (${T})`),O(` \u2705 Bitcoin Network: ${A}`),e.log("0","Validating contract addresses..."),e.log("0",`contractAddresses exists: ${!!l.contractAddresses}`),e.log("0","contractAddresses type: "+typeof l.contractAddresses),!l.contractAddresses||"object"!=typeof l.contractAddresses)throw e.error("0",`\u274c ERROR: No valid contractAddresses object found: ${JSON.stringify(l.contractAddresses)}`),new Error("contractAddresses is required and must include: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController");e.log("0","\u2705 Found valid contractAddresses object"),e.log("0",`Available keys: ${Object.keys(l.contractAddresses)}`);const I=l.contractAddresses.PositionManager,B=l.contractAddresses.LoanOperationsManagerModule,M=l.contractAddresses.TermManagerModule,D=l.contractAddresses.UCDController,R=l.contractAddresses.LiquidationManagerModule??l.contractAddresses.LiquidationManager??"",F=l.contractAddresses.BTCSpendAuthorizer??"",N=l.contractAddresses.BitcoinProviderRegistry;if(e.log("0","Extracted addresses:"),e.log("0",`POSITION_MANAGER_ADDRESS: ${I||"MISSING"}`),e.log("0",`LOAN_OPS_MANAGER_ADDRESS: ${B||"MISSING"}`),e.log("0",`TERM_MANAGER_ADDRESS: ${M||"MISSING"}`),e.log("0",`UCD_CONTROLLER_ADDRESS: ${D||"MISSING"}`),!(I&&B&&M&&D&&R))throw new Error("All contract addresses are required: PositionManager, LoanOperationsManagerModule, TermManagerModule, UCDController, and LiquidationManager or LiquidationManagerModule");O(" \u2705 Contract addresses loaded and validated"),O(` PositionManager: ${I}`),O(` LoanOpsManager: ${B}`),e.stepEnd("0"),O("[Step 0.5] Critical system health checks..."),e.stepStart("0.5","Critical system health checks"),e.warn("0.5","System health checks temporarily disabled (SystemHealthModule not available)"),e.log("0.5","\u2705 System health checks complete (skipped)"),e.stepEnd("0.5");const q=BigInt(r.amount);if(q<=0n)throw new Error(`Amount must be positive, got: ${q.toString()} wei`);O(" Fetching protocol mint limits..."),e.log("0","Fetching protocol mint limits...");const L=l.rpcUrl;let z;L&&"string"==typeof L?(!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(", ")}`)}(P,L),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}(L)}`),z=L):(z=await Lit.Actions.getRpcUrl({chain:w}),O(` Using LIT-provided RPC URL for chain: ${w}`));const V=new ethers.providers.JsonRpcProvider({url:z,timeout:f});E=await vt({policy:P,ethersProvider:V,registryAddress:N,devBitcoinProviderUrl:l.devBitcoinProviderUrl}),S=E[0],O(` \u2705 Bitcoin Provider: ${S.name} (min confs ${S.minConfirmations})`);!function(t,e){const r=at[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("mintUcd",await pt(V,I));const X=new ethers.Contract(B,c,V);let H,j;try{const t=await X.getProtocolConfig();H=BigInt(t[2].toString());j=1000000000000000000n*BigInt(t[3].toString()),O(" \u2705 Protocol limits loaded from LoanOperationsManager (consolidated call)"),O(` - Minimum: ${H.toString()} wei`),O(` - Maximum: ${j.toString()} wei`),e.log("0","\u2705 Protocol limits loaded from LoanOperationsManager")}catch(t){const r=t?.message||String(t);throw O(` \u274c Failed to get protocol config (${r}); refusing to sign`),e.log("0","\u274c Protocol config unavailable \u2014 refusing to mint"),new Error(`getProtocolConfig failed; cannot validate mint limits: ${r}`)}if(q<H)throw new Error(`Amount too small: ${q.toString()} wei. Minimum: ${H.toString()} wei`);if(q>j)throw new Error(`Amount too large: ${q.toString()} wei. Maximum: ${j.toString()} wei`);const G=l.publicKey;if(!G)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof G||0===G.length)throw new Error("Invalid publicKey: must be non-empty string");i="0.5",O("[UCD Mint Validator] Started"),O(` Position: ${r.positionId}`),O(` Amount: ${q.toString()} wei`),e.log("0","Validator Started");const Q=new K({providerUrl:S.url,auth:S.auth,timeout:8e3}),tt=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 Z(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await Z(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}(l.priceProviders),rt=!0===globalThis.devPriceMode;if(rt&&!P.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${P.chain}`);const it=new Y(tt,void 0,void 0,{devSingleProvider:rt&&P.allowDevSinglePriceProvider}),ot=(n={contractAddress:F||B,chain:w,chainId:k(T),rpcUrl:L,bitcoinProvider:Q,minConfirmations:S.minConfirmations,bitcoinProviderConfigs:E.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth,timeout:8e3}))),minConsensusProviders:P.minConsensusProviders},new et(n));if(i="1",O("[Step 1] Getting vault snapshot..."),e.stepStart("1","Getting vault snapshot"),l.debugOverrides?.useStubbedBtcData&&31337!==k(T))throw new Error("debugOverrides.useStubbedBtcData is not permitted on live networks");const st=function(t){return new nt(t)}({contractAddress:I,termManagerAddress:M,loanOpsManagerAddress:B,liquidationManagerAddress:R,chain:w,chainId:k(T),rpcUrl:L,vaultBalance:ot,priceOracle:it,debugOverrides:l.debugOverrides}),ct=await st.getVaultSnapshot(r.positionId);if(await bt(ct.vaultAddress,E,P.minConsensusProviders,8e3),ct.btcPriceUsd<u||ct.btcPriceUsd>d)throw new Error(`Bitcoin price ${ct.btcPriceUsd} is outside acceptable range (${u} - ${d}). This may indicate oracle manipulation or stale price data. Please try again later.`);O(` \u2705 BTC price validation passed: $${(Number(ct.btcPriceUsd)/1e8).toFixed(2)}`),e.stepEnd("1"),i="2",O("[Step 2] Authenticating caller..."),e.stepStart("2","Authenticating caller");const ut=l.contractAddresses?.AgentDelegationRegistry,dt=ut?{registry:ut,op:"mint",outcome:void 0}:void 0;if(!await U.verifyMintAuthorization(r,ct.borrower,k(T),V,void 0,dt,B))throw new Error("Caller not authorized");const lt=dt?.outcome?.effectiveFloorBps??0;O(" \u2705 Caller authorized"),e.stepEnd("2"),i="3",O("[Step 3] Validating position state..."),e.stepStart("3","Validating position state");if(![0,1,2].includes(ct.status))throw new Error(`Invalid position status for minting: ${y(ct.status)}. Must be PENDING_DEPOSIT, PENDING_MINT, or ACTIVE. Current status prevents minting operations.`);if(O(` \u2705 Position status valid for minting: ${y(ct.status)}`),ct.isExpired)throw new Error(`Loan term expired ${ct.daysIntoGracePeriod} days ago - minting rejected. Must repay or extend term first.`);if(ct.isLiquidatable)throw new Error(`Position is liquidatable (${J(ct.collateralRatioBps)}% < ${J(ct.currentLiquidationThreshold)}%) - minting rejected. Add collateral first.`);O(" \u2705 Position is healthy"),O(` - Term: ${ct.daysUntilExpiry} days remaining`),O(` - Current ratio: ${J(ct.collateralRatioBps)}%`),O(` - Liquidation threshold: ${J(ct.currentLiquidationThreshold)}%`),e.stepEnd("3"),i="4",O("[Step 4] Calculating fees..."),e.stepStart("4","Calculating fees");let ht=function(t,e){if(t<0n)throw new Error("Amount cannot be negative");if(e<0||e>1e4)throw new Error("Fee basis points must be between 0 and 10000 (0% to 100%)");return t*BigInt(e)/10000n}(q,ct.originationFeeBps);const gt=Number(r.timestamp),ft=ct.previousExpiryAt??0,wt=ct.totalTerm??0;if(ft>0&&gt<ft){const t=BigInt(ft)-BigInt(gt),e=wt-(ct.selectedTerm??0),r=BigInt(e===m?g*h:e*p*h);if(0n===r)throw new Error(`Scenario B tail fee: original term length is zero (totalTerm=${wt}, selectedTerm=${ct.selectedTerm??0}). Cannot compute tail fee.`);const i=t*BigInt(ct.originationFeeBps)*q/(10000n*r);ht+=i,O(` Scenario B tail fee: ${i.toString()} wei (${e}mo original term, ${t}s remaining)`)}O(` Mint fee: ${ht.toString()} wei (${J(ct.originationFeeBps)}% base${ft>0&&gt<ft?" + tail":""})`),e.stepEnd("4"),i="4a",O("[Step 4a & 4b] Validating capacity limits..."),e.stepStart("4ab","Validating capacity limits");const yt=q+ht,$t=new ethers.Contract(D,[...t,...o,...s],V),[Pt,Tt,At]=await Promise.all([$t.getRemainingMintCapacity(),$t.maxSupply(),$t.getCurrentSupply()]),St=BigInt(Pt.toString()),Et=BigInt(Tt.toString()),Ct=BigInt(At.toString());if(yt>St)throw new Error(`Daily mint limit would be exceeded: attempting to mint ${yt.toString()} wei (${q.toString()} + ${ht.toString()} fee), but only ${St.toString()} wei remaining in daily capacity`);if(O(" \u2705 Daily mint limit check passed"),O(` - Mint amount (with fee): ${yt.toString()} wei`),O(` - Remaining capacity: ${St.toString()} wei`),Et>0n){const t=Ct+yt;if(t>Et)throw new Error(`Max supply would be exceeded: minting ${yt.toString()} wei (${q.toString()} + ${ht.toString()} fee) would result in total supply of ${t.toString()} wei, exceeding max supply of ${Et.toString()} wei`);O(" \u2705 Max supply check passed"),O(` - Current supply: ${Ct.toString()} wei`),O(` - After mint: ${t.toString()} wei`),O(` - Max supply: ${Et.toString()} wei`),O(` - Remaining capacity: ${(Et-Ct).toString()} wei`)}else O(" \u2705 Max supply unlimited (not enforced)");e.stepEnd("4ab"),i="5",O("[Step 5] Calculating new state..."),e.stepStart("5","Calculating new state");const It=ct.ucdDebt+q+ht,xt=ct.availableBTCSats;O(` Current debt: ${ct.ucdDebt.toString()} wei`),O(` New debt: ${It.toString()} wei`),O(` Available collateral: ${xt.toString()} sats`),e.stepEnd("5"),i="6",O("[Step 6] Validating collateral ratio after mint..."),e.stepStart("6","Validating collateral ratio after mint");const kt=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}(xt,ct.btcPriceUsd),Bt=W(kt,It);if(O(` New collateral ratio: ${J(Bt)}%`),O(` Minimum required: ${J(ct.liquidationThresholdBps)}%`),!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return W(t,e)>=r}(kt,It,ct.liquidationThresholdBps))throw new Error(`Insufficient collateral: ${J(Bt)}% < ${J(ct.liquidationThresholdBps)}%`);if(O(" \u2705 Sufficient collateral"),lt>0&&Bt<lt)throw new Error(`Agent mint refused: post-mint collateral ratio ${J(Bt)}% is below the delegation floor ${J(lt)}%`);const Mt=BigInt("340282366920938463463374607431768211455");if(It>Mt)throw new Error(`New debt exceeds maximum allowed value: ${It.toString()} > ${Mt.toString()} (type(uint128).max). The contract will revert with DebtOverflow error.`);O(` \u2705 New debt within bounds: ${It.toString()} <= ${Mt.toString()}`),e.stepEnd("6"),i="7",O("[Step 7] Building authorization message..."),e.stepStart("7","Building authorization message");const Dt=ct.authorizedSpendsHash,Ut=ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["uint256"],[ct.ucdDebt])),Rt={authorizedSpendsHash:Dt,ucdDebtHash:Ut,contractBundleHash:ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["address","address","address","address"],[I,B,M,D])),btcPrice:ct.btcPriceUsd.toString(),mintAmount:q.toString(),mintFee:ht.toString(),newCollateral:xt.toString(),newDebt:It.toString()};if(r.action!==$)throw new Error(`Invalid mint authorization action: expected "${$}", got "${r.action}"`);const Ot=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(r.positionId),Ft=k(T),Nt={name:v,version:b,chainId:Ft,verifyingContract:ethers.utils.getAddress(B)},qt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes($)),_t={MintUcd:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"mintFee",type:"uint256"},{name:"newDebt",type:"uint256"},{name:"newCollateral",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"authorizedSpendsHash",type:"bytes32"},{name:"ucdDebtHash",type:"bytes32"},{name:"contractHash",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},Lt={actionTag:qt,positionId:Ot,mintAmount:Rt.mintAmount,mintFee:Rt.mintFee,newDebt:Rt.newDebt,newCollateral:Rt.newCollateral,btcPrice:Rt.btcPrice,authorizedSpendsHash:Rt.authorizedSpendsHash,ucdDebtHash:Rt.ucdDebtHash,contractHash:Rt.contractBundleHash,quantumTimestamp:r.timestamp,borrower:ethers.utils.getAddress(ct.borrower)};e.stepEnd("7"),i="8",e.stepStart("8","Signing authorization");const zt=globalThis.validatorWalletAddress;if(!zt||!zt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Vt=await Lit.Actions.getPrivateKey({pkpId:zt}),Xt="string"==typeof Vt?Vt.startsWith("0x")?Vt:`0x${Vt}`:String(Vt),Ht=new ethers.Wallet(Xt),jt=await Ht._signTypedData(Nt,_t,Lt);return e.stepEnd("8"),e.summary(),O("[UCD Mint Validator] \u2705 Complete"),{approved:!0,positionId:r.positionId,mintAmount:q.toString(),mintFee:ht.toString(),newDebt:It.toString(),newCollateral:xt.toString(),newCollateralRatioBps:Bt,btcPrice:ct.btcPriceUsd.toString(),authorizedSpendsHash:Dt,signature:jt,timestamp:r.timestamp,validatorPkp:Ht.address}}catch(t){throw console.error("[UCD Mint Validator] \u274c Failed:",t.message),console.error(`[UCD Mint Validator] Failed at step: ${i}`),t}var n}return gt=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}),gt)})();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
- 2bdd9aebdaad58a43a4731d5b7284f2531b7a9caaf8caf5719d891c4ed33cb2e
1
+ c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "ucd-mint-validator",
3
- "originalSize": 203485,
4
- "minifiedSize": 82739,
5
- "compressionRatio": 0.5933901761800624,
6
- "hash": "2bdd9aebdaad58a43a4731d5b7284f2531b7a9caaf8caf5719d891c4ed33cb2e",
7
- "buildTime": 1787171883046,
3
+ "originalSize": 210417,
4
+ "minifiedSize": 86197,
5
+ "compressionRatio": 0.5903515400371643,
6
+ "hash": "c2d80939746cc37f65ef2f63c6a3215b929214a63f10c78144e1f5c98320dabf",
7
+ "buildTime": 1788340137507,
8
8
  "version": "0.1.0"
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gvnrdao/dh-lit-actions",
3
- "version": "0.0.321",
3
+ "version": "0.0.322",
4
4
  "type": "commonjs",
5
5
  "description": "Diamond Hands Protocol LIT Actions - Deterministic, Auditable Builds",
6
6
  "main": "pkg-dist/pkg-src/index.js",
@@ -9,5 +9,20 @@ export * from "./interfaces";
9
9
  export * from "./constants/chunks/lit-actions-registry";
10
10
  export * from "./utils";
11
11
  export * from "./executors";
12
+ /**
13
+ * Borrower authorization EIP-712 types — the ONE definition the SDK and the
14
+ * LIT Actions share.
15
+ *
16
+ * Exported from `src/` rather than re-declared here: the SDK signs these
17
+ * messages and `modules/authorization.module.ts` verifies them, so a second
18
+ * copy would be a second digest waiting to disagree. `tsconfig.pkg.json`
19
+ * already compiles `src/constants/**`, and the module is plain constants with
20
+ * no LIT-runtime dependency, so bundling it into the package costs nothing.
21
+ *
22
+ * Named exports, not `export *`: the sibling `message-hash-domains` module is
23
+ * NOT re-exported, because its action tags are LIT-internal and would widen
24
+ * this package's public surface for no consumer.
25
+ */
26
+ export { type BorrowerAuthorizationField, type BorrowerAuthorizationDomain, type BorrowerAuthorizationPrimaryType, BORROWER_AUTHORIZATION_PRIMARY_TYPES, BORROWER_AUTHORIZATION_FIELDS, BORROWER_AUTHORIZATION_ENCODE_TYPES, borrowerAuthorizationTypes, buildBorrowerAuthorizationDomain, } from "../src/constants/borrower-authorization-types";
12
27
  export { DH_LIT_ACTIONS_CHIPOTLE, CHIPOTLE_DEPLOYMENTS } from "./constants/chunks/lit-actions-registry";
13
28
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../pkg-src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,cAAc,cAAc,CAAC;AAG7B,cAAc,yCAAyC,CAAC;AAGxD,cAAc,SAAS,CAAC;AAGxB,cAAc,aAAa,CAAC;AAG5B,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../pkg-src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,cAAc,cAAc,CAAC;AAG7B,cAAc,yCAAyC,CAAC;AAGxD,cAAc,SAAS,CAAC;AAGxB,cAAc,aAAa,CAAC;AAE5B;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,2BAA2B,EAChC,KAAK,gCAAgC,EACrC,oCAAoC,EACpC,6BAA6B,EAC7B,mCAAmC,EACnC,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC"}