@gvnrdao/dh-lit-actions 0.0.296 → 0.0.297
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.
- package/dist/address-probe-signer.meta.json +1 -1
- package/dist/address-probe.meta.json +1 -1
- package/dist/admin-liquidation-validator.meta.json +1 -1
- package/dist/always-signer.meta.json +1 -1
- package/dist/authorization-dummy-b.meta.json +1 -1
- package/dist/authorization-dummy.meta.json +1 -1
- package/dist/btc-transaction-signer.meta.json +1 -1
- package/dist/btc-utxo-invalidator.meta.json +1 -1
- package/dist/btc-withdrawal.meta.json +1 -1
- package/dist/encrypt-parameter.meta.json +1 -1
- package/dist/ethers-version-probe.meta.json +1 -1
- package/dist/extend-position-validator.action.js +1 -1
- package/dist/extend-position-validator.hash +1 -1
- package/dist/extend-position-validator.meta.json +5 -5
- package/dist/liquidation-validator.meta.json +1 -1
- package/dist/loan-vault-btc-balance.meta.json +1 -1
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-sign-only.meta.json +1 -1
- package/dist/process-payment-validator.meta.json +1 -1
- package/dist/stale-spend-recovery-validator.action.js +1 -1
- package/dist/stale-spend-recovery-validator.hash +1 -1
- package/dist/stale-spend-recovery-validator.meta.json +5 -5
- package/dist/ucd-mint-validator.meta.json +1 -1
- package/package.json +1 -1
- package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
- package/pkg-dist/pkg-src/index.js +18 -5
- package/pkg-dist/pkg-src/index.js.map +2 -2
- package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts +2 -0
- package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,u=100000000000000n,l=60,d=10,h=86400,p=30,m=12,g=365,f=8e3;var w="DiamondHands.Protocol",y="1",b="extend-position",T=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(T||{}),v={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},P=["infura.io","drpc.org"],E={ethereum:1,sepolia:11155111,hardhat:1337};function A(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(T).join(", ")}`)}function I(t){return Math.floor(t/l)*l}function S(){return I(Math.floor(Date.now()/1e3))}async function B(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${S()}`)}var $=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await B();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=I(i),o=I(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyPaymentAuthorization(t,e,r,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyWithdrawAuthorization(e,r,i,n){if("withdraw-btc"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n){if("btc-utxo-invalidator"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i)}static async verifyBtcExecutionAuthorization(e,r,i,n){if("execute-btc-withdrawal"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}),{strictCurrentQuantum:!0})}};function C(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function x(...t){C()&&console.log(...t)}var D=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},k=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},M=class{static create(t="LIT Action",e){return C(e)?new k(t):new D}};function U(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function O(t){return t instanceof Error&&"AbortError"===t.name}var R=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=M.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),x(`[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"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${U(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: ${U(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${U(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(a),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),x(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${U(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"),O(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(U(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${U(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(n),x(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=o.chain_stats.funded_txo_sum,s=o.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(n),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=U(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=U(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),x(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();return o.status?{txid:o.txid??t,confirmations:o.status.confirmed&&o.status.block_height?1:0}:null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(U(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function N(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)}}function q(t,e,r,i){if(!t)return r??13e3;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function F(t,e,r){const i=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}function L(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 _(t){return t/100}var z=class t{constructor(e,r,i){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error("Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass 3 distinct {name, apiKey} entries from the supported set: "+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Price oracle requires at least ${t.MIN_DISTINCT_PROVIDERS} eligible providers for consensus. Currently configured: ${this.sources.length} provider(s). Supported active providers: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(0===e.length)throw new Error("priceProviders must be a non-empty array of 3 distinct providers, each with an apiKey.");const r=[],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}". Supported: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires 3 DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use 3 different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"binance":if(!o.apiKey)throw new Error("Binance provider requires an apiKey");r.push(this.createBinanceSource(o.apiKey,n++));break;case"coinbase":if(!o.apiKey)throw new Error("Coinbase provider requires an apiKey");r.push(this.createCoinbaseSource(o.apiKey,n++));break;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}`)}}if(r.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Insufficient price providers: need at least ${t.MIN_DISTINCT_PROVIDERS} distinct entries, got ${r.length}.`);return this.selectSampledSources(r)}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`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(){return async(t,e)=>{const r=new AbortController,i=setTimeout((()=>r.abort()),5e3);try{const i=await fetch(t,{headers:{Accept:"application/json",...e||{}},signal:r.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}getSelectionSeed(){const t="undefined"!=typeof process?process.env.PRICE_PROVIDER_SELECTION_SEED:void 0,e=t?Number(t):NaN;return Number.isFinite(e)?e:("undefined"!=typeof process,0,Math.floor(Date.now()+1e6*Math.random()))}selectSampledSources(t){const e=[...t];let r=this.getSelectionSeed()>>>0;for(let t=e.length-1;t>0;t--){const i=Math.floor((r=1664525*r+1013904223>>>0,r/4294967296*(t+1)));[e[t],e[i]]=[e[i],e[t]]}return e.slice(0,3).map(((t,e)=>({...t,priority:e+1})))}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson();return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),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}}createBinanceSource(t,e){if(!t)throw new Error("createBinanceSource requires an apiKey");const r=this.createFetchJson();return{name:"Binance",fetchPrice:async()=>{const e=new URL("https://api.binance.com/api/v3/ticker/price");e.searchParams.set("symbol","BTCUSDT");const i=await r(e.toString(),{"X-MBX-APIKEY":t}),n=Number(i?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid Binance price payload");return n},priority:e}}createCoinbaseSource(t,e){if(!t)throw new Error("createCoinbaseSource requires an apiKey");const r=this.createFetchJson();return{name:"Coinbase",fetchPrice:async()=>{const e=await r("https://api.coinbase.com/v2/prices/BTC-USDT/spot",{"CB-ACCESS-KEY":t}),i=Number(e?.data?.amount);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid Coinbase price payload");return i},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson();return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const 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(3!==this.sources.length)throw new Error(`Price oracle requires exactly 3 providers. Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now(),r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e)),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}async getBTCPriceConsensus(){console.log("[Price Oracle] Fetching BTC price with consensus...");const t=(await Promise.allSettled(this.sources.map((async t=>{const e=await t.fetchPrice();return{source:t.name,price:e}})))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===t.length)throw new Error("No price sources returned data");console.log(`[Price Oracle] Got prices from ${t.length}/${this.sources.length} sources:`),t.forEach((t=>{console.log(` ${t.source}: $${t.price.toLocaleString()}`)}));const e=t.map((t=>t.price));e.sort(((t,e)=>t-e));const r=e[Math.floor(e.length/2)],i=e[0],n=e[e.length-1]/i,o=t.filter((t=>Math.abs(t.price-r)/r<=.02));if(n>1.05&&o.length===t.length)throw new Error(`Price consensus failed: sources too dispersed (${(100*(n-1)).toFixed(1)}% spread)`);if(o.length<t.length){const e=t.filter((t=>!o.find((e=>e.source===t.source))));if(console.log(`[Price Oracle] \u26a0\ufe0f Detected ${e.length} outlier(s):`),e.forEach((t=>{const e=Math.abs(t.price-r)/r;console.log(` ${t.source}: $${t.price.toLocaleString()} (${(100*e).toFixed(1)}% deviation)`)})),o.length<2)throw new Error("Price consensus failed: insufficient valid sources after outlier removal");console.log(`[Price Oracle] \u2705 Outliers filtered, continuing with ${o.length} valid sources`);const i=o.map((t=>t.price));i.sort(((t,e)=>t-e));const n=i[Math.floor(i.length/2)];console.log(`[Price Oracle] \u2705 Consensus price (median): $${n.toLocaleString()}`);const a=Math.round(100*n);return 1000000n*BigInt(a)}console.log(`[Price Oracle] \u2705 Consensus price (median): $${r.toLocaleString()}`);const a=Math.round(100*r);return 1000000n*BigInt(a)}};z.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinbase","binance","coinmarketcap","coingecko"],z.MIN_DISTINCT_PROVIDERS=3;var V=z,X=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),i=await this.getAuthorizedSpendsFromContract(t),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const i=this.config.minConfirmations||6,n=await this.bitcoinProvider.getUTXOSet(e,i),o=await this.getAuthorizedSpendsFromContract(t);for(const t of o){if(n.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=o.reduce(((t,e)=>t+e.satoshis),0n),s=n.utxos.filter((t=>!this.isUTXOAuthorized(t,o))),c=s.reduce(((t,e)=>t+e.satoshis),0n),u=this.computeAuthorizedSpendsHash(t,o);return{totalUTXOs:n.utxos,totalBalance:n.totalBalance,authorizedUTXOs:o,authorizedBalance:a,authorizedSpendsHash:u,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout: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 G=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout: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 H(t){return new G(t)}var j=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPriceConsensus()]),o=H({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=N(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=F(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPriceConsensus()]),o=H({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=N(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=F(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout: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=(b=l,0===(y=u)?0:y-b*p*h);var y,b;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,A(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:w,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:d,lastRenewedAt:g}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return v[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const i=await this.getVaultSnapshot(t);return function(t,e,r,i){const n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var K="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))",W={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],adminLiquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function J(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var Q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),Z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),tt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function et(t,e,r){return t.call({to:e,data:r})}async function rt(t,e){const r=new ethers.utils.Interface([K]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([K]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):J(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await et(t,e,Q.encodeFunctionData("views",[])),[i]=Q.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([et(t,e,Q.encodeFunctionData("paused",[])),et(t,e,Q.encodeFunctionData("liquidationPaused",[])),et(t,e,Q.encodeFunctionData("simplePsm",[])),et(t,i,Y.encodeFunctionData("core",[])),et(t,i,Y.encodeFunctionData("loanOps",[])),et(t,i,Y.encodeFunctionData("collateralManager",[])),et(t,i,Y.encodeFunctionData("liquidationManager",[])),et(t,i,Y.encodeFunctionData("circuitBreaker",[]))]),h=Q.decodeFunctionResult("paused",n)[0],p=Q.decodeFunctionResult("liquidationPaused",o)[0],m=Q.decodeFunctionResult("simplePsm",a)[0],g=Y.decodeFunctionResult("core",s)[0],f=Y.decodeFunctionResult("loanOps",c)[0],w=Y.decodeFunctionResult("collateralManager",u)[0],y=Y.decodeFunctionResult("liquidationManager",l)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await et(t,f,Z.encodeFunctionData("getUcdController",[])),v=await et(t,f,Z.encodeFunctionData("ucdToken",[])),P=Z.decodeFunctionResult("getUcdController",T)[0],E=Z.decodeFunctionResult("ucdToken",v)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await et(t,e,tt.encodeFunctionData("paused",[]));return tt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,S,B,$,C,x,D,k]=await Promise.all([A(g),A(f),A(w),A(y),A(b),A(P),A(E),A(m)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:S,collateralManagerPaused:B,liquidationManagerPaused:$,circuitBreakerPaused:C,ucdControllerPaused:x,ucdTokenPaused:D,simplePsmPaused:k})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var it={hardhat:{chain:"hardhat",chainId:E.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:E.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:E.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var nt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}];async function ot(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 at(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!i)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const o=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,nt,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const n=[];for(const e of i){const r=await ot(e.ciphertext,e.pkpId);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i);return o[0]}var st,ct=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],ut="UCDMintedWithAuthorization(bytes32,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes32)";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;let e="0";try{x("[Extend Position Validator] Starting..."),x("[Extend Position Validator] DEBUG: globalThis.priceProviders:",globalThis.priceProviders),x("[Extend Position Validator] DEBUG: priceProviders type:",typeof globalThis.priceProviders),globalThis.priceProviders&&(x("[Extend Position Validator] DEBUG: priceProviders isArray:",Array.isArray(globalThis.priceProviders)),x("[Extend Position Validator] DEBUG: priceProviders length:",globalThis.priceProviders.length),globalThis.priceProviders.length>0&&x("[Extend Position Validator] DEBUG: First provider:",globalThis.priceProviders[0])),e="0";const t=globalThis.chain,r=globalThis.selectedTerm;if(!t)throw new Error('Missing required parameter: "chain"');if(!r||"number"!=typeof r)throw new Error('Missing required parameter: "selectedTerm"');const i=$.verifyTermPositionActionAuthorizationStructure(globalThis.auth),n=function(t){const e=A(t),r=it[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),o=n.chain,s=(n.bitcoinNetwork,n.chainId),l=globalThis.rpcUrl;let f;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(!P.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${P.join(", ")}`)}(n,l),x(` 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)}`),f=l):(f=await Lit.Actions.getRpcUrl({chain:t}),x(` Using LIT-provided RPC URL for chain: ${t}`));const T=new ethers.providers.JsonRpcProvider(f),v=await at({policy:n,ethersProvider:T,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});x(` \u2705 Bitcoin Provider: ${v.name} (min confs ${v.minConfirmations})`);const I=v.minConfirmations;let B,C,D,k,M,U;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses){(function(t){E[t]})(o);throw new Error("Contract addresses not provided. Required for both dev and service modes.")}if(B=globalThis.contractAddresses.PositionManager,C=globalThis.contractAddresses.LoanOperationsManagerModule,D=globalThis.contractAddresses.TermManagerModule,k=globalThis.contractAddresses.UCDController,M=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",U=globalThis.contractAddresses.BTCSpendAuthorizer||C,!(B&&C&&D&&k&&M))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");x("\ud83d\udd0d LIT Action Contract Addresses:"),x(" PositionManager:",B),x(" LoanOpsManager:",C),x(" TermManager:",D),x(" UCDController:",k);const O=s,N=new ethers.providers.JsonRpcProvider(f);!function(t,e){const r=W[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await rt(N,B));const q=new R({providerUrl:v.url}),F=new V(globalThis.priceProviders,void 0),z=new X({contractAddress:U,chain:t,chainId:O,rpcUrl:l,bitcoinProvider:q,minConfirmations:I});e="1";const G=function(t){return new j(t)}({contractAddress:B,termManagerAddress:D,loanOpsManagerAddress:C,liquidationManagerAddress:M,chain:t,chainId:O,rpcUrl:l,vaultBalance:z,priceOracle:F,termOverride:r});x("[Extend Position Validator] Using fast balance path (skipUTXOValidation: true)");const H=await G.getVaultSnapshot(i.positionId),K=H.btcPriceUsd,J=BigInt(K.toString());if(J<c||J>u)throw new Error(`Bitcoin price ${J} is outside acceptable range (${c} - ${u})`);e="2";if(!await $.verifyExtendAuthorization(i,H.borrower,N,globalThis.contractAddresses?.PositionDelegateRegistry))throw x(`[DEBUG] Authorization failed - signer: ${i.signature?"present":"missing"}, borrower: ${H.borrower}`),x(`[DEBUG] Position ID: ${i.positionId}`),x(`[DEBUG] Auth timestamp: ${i.timestamp}, chainId: ${i.chainId}, newTerm: ${i.newTerm}`),x(`[DEBUG] Auth action: ${i.action}`),x(`[DEBUG] Auth signature: ${i.signature}`),new Error("Caller not authorized");e="3";if(![2,3].includes(H.status))throw new Error(`Invalid position status for extension: ${function(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}(H.status)}. Must be ACTIVE or EXPIRED.`);const Q=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()}(i.positionId);new ethers.Contract(D,[...ct],N);if(H.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const Y=H.selectedTerm,Z=Y+r,tt=65535;if(Z>tt)throw new Error(`Extension would cause term overflow: ${Y} + ${r} = ${Z} months, exceeds max ${tt} months`);let et;try{const t=await N.getBlock("latest");et=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const nt=r===m?g*h:r*p*h,ot=H.expiryAt+nt,st=3===H.status;if(ot-et>2*nt)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(st&&ot<=et)throw new Error("Invalid requested expiry date: extension must extend into the future for expired loans");e="4",x("\ud83d\udd0d Using extensionFeeBps from vault snapshot:",H.extensionFeeBps);const lt=BigInt(H.extensionFeeBps);let dt=[];try{const t=await async function(t,e,r){const i="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(ut)),o=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]);return(await t.getLogs({address:e,topics:[n,i],fromBlock:0,toBlock:"latest"})).map((t=>{const e=o.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(N,C,i.positionId),e=BigInt(H.termStartTimestamp);dt=t.filter((t=>t.quantumTimestamp>=e)),x(`[Pro-Rata] Found ${t.length} total mints, ${dt.length} in current term`)}catch(t){x(`[Pro-Rata] Warning: could not fetch mint logs (${t.message}), using baseline fee`)}e="5";const ht=BigInt(S()),pt=function(t){const{mints:e,termStart:r,termExpiry:i,renewalNow:n,ucdDebt:o,extensionFeeRateBps:a}=t,s=o*a/10000n;if(0===e.length)return s;const c=(i-r)/BigInt(h);if(0n===c)return s;let u=0n,l=0n;for(const t of e){if(t.quantumTimestamp<r)continue;const e=(n-t.quantumTimestamp)/BigInt(h),i=(e>c?c:e)*t.mintFee/c;u+=t.mintFee,l+=i}const d=u>l?u-l:0n;return s>d?s-d:0n}({mints:dt,termStart:BigInt(H.termStartTimestamp),termExpiry:BigInt(H.expiryAt),renewalNow:ht,ucdDebt:BigInt(H.ucdDebt.toString()),extensionFeeRateBps:lt}),mt=BigInt(H.ucdDebt.toString())+pt;e="6";const gt=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}(H.availableBTCSats,J),ft=L(gt,mt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return L(t,e)>=r}(gt,mt,H.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${_(ft)}% < ${_(H.liquidationThresholdBps)}%`);e="7";const wt=S()+d,yt={name:w,version:y,chainId:s,verifyingContract:ethers.utils.getAddress(C)},bt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Tt={ExtendPosition:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"availableBTCBalance",type:"uint256"},{name:"proRataRenewalFee",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},vt={actionTag:bt,positionId:Q,selectedTerm:r,btcPrice:J.toString(),availableBTCBalance:H.availableBTCSats.toString(),proRataRenewalFee:pt.toString(),quantumTimestamp:wt,borrower:ethers.utils.getAddress(H.borrower)};e="8";const Pt=globalThis.validatorWalletAddress;if(!Pt||!Pt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Et=await Lit.Actions.getPrivateKey({pkpId:Pt}),At="string"==typeof Et?Et.startsWith("0x")?Et:`0x${Et}`:String(Et),It=new ethers.Wallet(At),St=await It._signTypedData(yt,Tt,vt);return{approved:!0,positionId:i.positionId,selectedTerm:r,btcPrice:J.toString(),availableBTCBalance:H.availableBTCSats.toString(),proRataRenewalFee:pt.toString(),newTotalDebt:mt.toString(),newCollateralRatioBps:ft.toString(),signature:St,timestamp:i.timestamp,quantumTimestamp:wt,validatorPkp:It.address}}catch(t){return console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),{approved:!1,reason:t.message||t.toString(),positionId:globalThis.auth?.positionId,timestamp:Date.now()}}}return st=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}),st)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
1
|
+
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=11e3,a=100000000n,s=1000000000000000000n,c=1000000000000n,u=100000000000000n,l=60,d=10,h=86400,p=30,m=12,g=365,f=8e3;var w="DiamondHands.Protocol",y="1",b="extend-position",T=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(T||{}),v={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},P=["infura.io","drpc.org"],E={ethereum:1,sepolia:11155111,hardhat:1337};function A(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(T).join(", ")}`)}function I(t){return Math.floor(t/l)*l}function S(){return I(Math.floor(Date.now()/1e3))}async function B(){const t=Math.floor(Date.now()/1e3),e=t%l;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%l;return e<8||e>=l-8}(t))return;let r;r=e>=l-8?l-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${S()}`)}var $=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await B();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=I(i),o=I(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const a=n-l,s=n+l;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+(l-8))throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await r(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyMintAuthorization(t,e,r,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyPaymentAuthorization(t,e,r,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i)}static async verifyWithdrawAuthorization(e,r,i,n){if("withdraw-btc"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n){if("btc-utxo-invalidator"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n){return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i)}static async verifyBtcExecutionAuthorization(e,r,i,n){if("execute-btc-withdrawal"!==e.action)return!1;return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(o,a,s)=>{if(o.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,s,i))return!0;if(n)return t.checkPositionDelegate(e.positionId,o,n,i)}return!1}),{strictCurrentQuantum:!0})}};function C(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function x(...t){C()&&console.log(...t)}var D=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},k=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},M=class{static create(t="LIT Action",e){return C(e)?new k(t):new D}};function U(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function O(t){return t instanceof Error&&"AbortError"===t.name}var R=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=M.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),x(`[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"),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${U(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: ${U(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${U(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,a=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===a)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(a),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),x(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const s=await a.text();if(s.trim().startsWith("<!DOCTYPE")||s.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(s)}catch(t){const e=s.length>200?s.substring(0,200)+"... (truncated)":s;throw new Error(`Failed to parse JSON response: ${U(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"),O(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(U(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${U(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),a=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:a}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(n),x(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=o.chain_stats.funded_txo_sum,s=o.chain_stats.spent_txo_sum;if(void 0===a||void 0===s)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${s}`);const c=BigInt(a-s);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${s} sats`),c}catch(t){if(clearTimeout(n),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=U(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=U(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),x(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();return o.status?{txid:o.txid??t,confirmations:o.status.confirmed&&o.status.block_height?1:0}:null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(U(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),O(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function N(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)}}function q(t,e,r,i){if(!t)return r??13e3;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function F(t,e,r){const i=t*e/(100000000n*a);if(0n===r)return{collateralValueUsd:i,collateralRatioBps:Number.MAX_SAFE_INTEGER};return{collateralValueUsd:i,collateralRatioBps:Number(i*s*10000n/r)}}function L(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 _(t){return t/100}var z=class t{constructor(e,r,i){if(r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error("Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass 3 distinct {name, apiKey} entries from the supported set: "+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Price oracle requires at least ${t.MIN_DISTINCT_PROVIDERS} eligible providers for consensus. Currently configured: ${this.sources.length} provider(s). Supported active providers: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`)}buildSources(e){if(0===e.length)throw new Error("priceProviders must be a non-empty array of 3 distinct providers, each with an apiKey.");const r=[],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}". Supported: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires 3 DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use 3 different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"binance":if(!o.apiKey)throw new Error("Binance provider requires an apiKey");r.push(this.createBinanceSource(o.apiKey,n++));break;case"coinbase":if(!o.apiKey)throw new Error("Coinbase provider requires an apiKey");r.push(this.createCoinbaseSource(o.apiKey,n++));break;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}`)}}if(r.length<t.MIN_DISTINCT_PROVIDERS)throw new Error(`Insufficient price providers: need at least ${t.MIN_DISTINCT_PROVIDERS} distinct entries, got ${r.length}.`);return this.selectSampledSources(r)}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`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(){return async(t,e)=>{const r=new AbortController,i=setTimeout((()=>r.abort()),5e3);try{const i=await fetch(t,{headers:{Accept:"application/json",...e||{}},signal:r.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}getSelectionSeed(){const t="undefined"!=typeof process?process.env.PRICE_PROVIDER_SELECTION_SEED:void 0,e=t?Number(t):NaN;return Number.isFinite(e)?e:("undefined"!=typeof process,0,Math.floor(Date.now()+1e6*Math.random()))}selectSampledSources(t){const e=[...t];let r=this.getSelectionSeed()>>>0;for(let t=e.length-1;t>0;t--){const i=Math.floor((r=1664525*r+1013904223>>>0,r/4294967296*(t+1)));[e[t],e[i]]=[e[i],e[t]]}return e.slice(0,3).map(((t,e)=>({...t,priority:e+1})))}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson();return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),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}}createBinanceSource(t,e){if(!t)throw new Error("createBinanceSource requires an apiKey");const r=this.createFetchJson();return{name:"Binance",fetchPrice:async()=>{const e=new URL("https://api.binance.com/api/v3/ticker/price");e.searchParams.set("symbol","BTCUSDT");const i=await r(e.toString(),{"X-MBX-APIKEY":t}),n=Number(i?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid Binance price payload");return n},priority:e}}createCoinbaseSource(t,e){if(!t)throw new Error("createCoinbaseSource requires an apiKey");const r=this.createFetchJson();return{name:"Coinbase",fetchPrice:async()=>{const e=await r("https://api.coinbase.com/v2/prices/BTC-USDT/spot",{"CB-ACCESS-KEY":t}),i=Number(e?.data?.amount);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid Coinbase price payload");return i},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson();return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const 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(3!==this.sources.length)throw new Error(`Price oracle requires exactly 3 providers. Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now(),r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e)),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}async getBTCPriceConsensus(){console.log("[Price Oracle] Fetching BTC price with consensus...");const t=(await Promise.allSettled(this.sources.map((async t=>{const e=await t.fetchPrice();return{source:t.name,price:e}})))).filter((t=>"fulfilled"===t.status)).map((t=>t.value));if(0===t.length)throw new Error("No price sources returned data");console.log(`[Price Oracle] Got prices from ${t.length}/${this.sources.length} sources:`),t.forEach((t=>{console.log(` ${t.source}: $${t.price.toLocaleString()}`)}));const e=t.map((t=>t.price));e.sort(((t,e)=>t-e));const r=e[Math.floor(e.length/2)],i=e[0],n=e[e.length-1]/i,o=t.filter((t=>Math.abs(t.price-r)/r<=.02));if(n>1.05&&o.length===t.length)throw new Error(`Price consensus failed: sources too dispersed (${(100*(n-1)).toFixed(1)}% spread)`);if(o.length<t.length){const e=t.filter((t=>!o.find((e=>e.source===t.source))));if(console.log(`[Price Oracle] \u26a0\ufe0f Detected ${e.length} outlier(s):`),e.forEach((t=>{const e=Math.abs(t.price-r)/r;console.log(` ${t.source}: $${t.price.toLocaleString()} (${(100*e).toFixed(1)}% deviation)`)})),o.length<2)throw new Error("Price consensus failed: insufficient valid sources after outlier removal");console.log(`[Price Oracle] \u2705 Outliers filtered, continuing with ${o.length} valid sources`);const i=o.map((t=>t.price));i.sort(((t,e)=>t-e));const n=i[Math.floor(i.length/2)];console.log(`[Price Oracle] \u2705 Consensus price (median): $${n.toLocaleString()}`);const a=Math.round(100*n);return 1000000n*BigInt(a)}console.log(`[Price Oracle] \u2705 Consensus price (median): $${r.toLocaleString()}`);const a=Math.round(100*r);return 1000000n*BigInt(a)}};z.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinbase","binance","coinmarketcap","coingecko"],z.MIN_DISTINCT_PROVIDERS=3;var V=z,X=class{constructor(t){this.config=t,this.bitcoinProvider=t.bitcoinProvider}async calculateBalance(t,e){const r=await this.bitcoinProvider.getBalance(e),i=await this.getAuthorizedSpendsFromContract(t),n=i.reduce(((t,e)=>t+e.satoshis),0n),o=r>n?r-n:0n;return{totalUTXOs:[],totalBalance:r,authorizedUTXOs:i,authorizedBalance:n,authorizedSpendsHash:this.computeAuthorizedSpendsHash(t,i),availableUTXOs:[],availableBalance:o,vaultAddress:e,positionId:t,timestamp:Date.now()}}async calculateTrustedBalance(t,e,r){if(r)return await this.calculateBalance(t,e);const i=this.config.minConfirmations||6,n=await this.bitcoinProvider.getUTXOSet(e,i),o=await this.getAuthorizedSpendsFromContract(t);for(const t of o){if(n.utxos.some((e=>e.txid===t.txid&&e.vout===t.vout)))throw new Error(`Authorized UTXO ${t.txid}:${t.vout} not yet spent. Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. Complete the transaction by signing and broadcasting it.`)}const a=o.reduce(((t,e)=>t+e.satoshis),0n),s=n.utxos.filter((t=>!this.isUTXOAuthorized(t,o))),c=s.reduce(((t,e)=>t+e.satoshis),0n),u=this.computeAuthorizedSpendsHash(t,o);return{totalUTXOs:n.utxos,totalBalance:n.totalBalance,authorizedUTXOs:o,authorizedBalance:a,authorizedSpendsHash:u,availableUTXOs:s,availableBalance:c,vaultAddress:e,positionId:t,timestamp:Date.now()}}async getTrustedBalance(t,e){return(await this.calculateTrustedBalance(t,e)).availableBalance}async getAvailableUTXOs(t,e){return(await this.calculateTrustedBalance(t,e)).availableUTXOs}async isUTXOAvailable(t,e,r,i){return(await this.getAvailableUTXOs(t,e)).some((t=>t.txid===r&&t.vout===i))}isUTXOAuthorized(t,e){return e.some((e=>e.txid===t.txid&&e.vout===t.vout))}async getAuthorizedSpendsFromContract(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout: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 G=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout: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 H(t){return new G(t)}var j=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPriceConsensus()]),o=H({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=N(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=F(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.extensionFeeBps,timestamp:Date.now()}}async getVaultSnapshotFast(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress,!0),this.config.priceOracle.getBTCPriceConsensus()]),o=H({termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId||1,rpcUrl:this.config.rpcUrl}),a=this.config.termOverride??e.selectedTerm,[s,c,u]=await Promise.all([o.getLiquidationThreshold(),o.getMaxEscalatedThreshold(),o.getTermFees(a)]),l=N(e.termStartTimestamp,e.selectedTerm),d=q(l.isExpired,l.daysIntoGracePeriod,s,c),h=F(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<d,m=h.collateralRatioBps-d;return{positionId:e.positionId,pkpId:e.pkpId,borrower:e.borrower,vaultAddress:e.vaultAddress,ucdDebt:e.ucdDebt,termStartTimestamp:e.termStartTimestamp,selectedTerm:e.selectedTerm,status:e.status,expiryAt:e.expiryAt,previousExpiryAt:e.previousExpiryAt,totalTerm:e.totalTerm,lastRenewedAt:e.lastRenewedAt,totalBTCSats:i.totalBalance,totalUTXOs:i.totalUTXOs,authorizedSpendsSats:i.authorizedBalance,authorizedSpendsHash:i.authorizedSpendsHash,availableBTCSats:i.availableBalance,availableUTXOs:i.availableUTXOs,btcPriceUsd:n,collateralValueUsd:h.collateralValueUsd,collateralRatioBps:h.collateralRatioBps,termDurationDays:l.termDurationDays,termLengthDays:l.termLengthDays,isExpired:l.isExpired,daysUntilExpiry:l.daysUntilExpiry,daysIntoGracePeriod:l.daysIntoGracePeriod,currentLiquidationThreshold:d,isLiquidatable:p,marginToLiquidationBps:m,liquidationThresholdBps:s,originationFeeBps:u.originationFeeBps,extensionFeeBps:u.extensionFeeBps,timestamp:Date.now()}}buildStubbedBtcSnapshotInputs(t){const e=BigInt(this.config.debugOverrides?.stubbedAvailableBtcSats??"10000000"),r=BigInt(this.config.debugOverrides?.stubbedBtcPriceUsd??"5000000000000");return[{totalUTXOs:[],totalBalance:e,authorizedUTXOs:[],authorizedBalance:0n,authorizedSpendsHash:this.config.debugOverrides?.stubbedAuthorizedSpendsHash??ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[t.positionId,[]])),availableUTXOs:[],availableBalance:e,vaultAddress:t.vaultAddress,positionId:t.positionId,timestamp:Date.now()},r]}async queryPositionState(t){const e=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.config.chain});const i=new ethers.providers.StaticJsonRpcProvider({url:r,timeout: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=(b=l,0===(y=u)?0:y-b*p*h);var y,b;return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:this.parseVaultAddress(s.vaultAddress,A(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:w,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:d,lastRenewedAt:g}}parseVaultAddress(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return v[t]}(e);return"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}async isLiquidatable(t){return(await this.getVaultSnapshot(t)).isLiquidatable}async getCollateralRatio(t){return(await this.getVaultSnapshot(t)).collateralRatioBps}async getAvailableBalance(t){return(await this.getVaultSnapshot(t)).availableBTCSats}async hasSufficientCollateral(t,e,r){const i=await this.getVaultSnapshot(t);return function(t,e,r,i){const n=e+r;return 0n===n||Number(t*s*10000n/n)>=i}(i.collateralValueUsd,i.ucdDebt,e,r)}};var K="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))",W={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],adminLiquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function J(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var Q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Y=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),Z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),tt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function et(t,e,r){return t.call({to:e,data:r})}async function rt(t,e){const r=new ethers.utils.Interface([K]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([K]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?J({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):J(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await et(t,e,Q.encodeFunctionData("views",[])),[i]=Q.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([et(t,e,Q.encodeFunctionData("paused",[])),et(t,e,Q.encodeFunctionData("liquidationPaused",[])),et(t,e,Q.encodeFunctionData("simplePsm",[])),et(t,i,Y.encodeFunctionData("core",[])),et(t,i,Y.encodeFunctionData("loanOps",[])),et(t,i,Y.encodeFunctionData("collateralManager",[])),et(t,i,Y.encodeFunctionData("liquidationManager",[])),et(t,i,Y.encodeFunctionData("circuitBreaker",[]))]),h=Q.decodeFunctionResult("paused",n)[0],p=Q.decodeFunctionResult("liquidationPaused",o)[0],m=Q.decodeFunctionResult("simplePsm",a)[0],g=Y.decodeFunctionResult("core",s)[0],f=Y.decodeFunctionResult("loanOps",c)[0],w=Y.decodeFunctionResult("collateralManager",u)[0],y=Y.decodeFunctionResult("liquidationManager",l)[0],b=Y.decodeFunctionResult("circuitBreaker",d)[0],T=await et(t,f,Z.encodeFunctionData("getUcdController",[])),v=await et(t,f,Z.encodeFunctionData("ucdToken",[])),P=Z.decodeFunctionResult("getUcdController",T)[0],E=Z.decodeFunctionResult("ucdToken",v)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await et(t,e,tt.encodeFunctionData("paused",[]));return tt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,S,B,$,C,x,D,k]=await Promise.all([A(g),A(f),A(w),A(y),A(b),A(P),A(E),A(m)]);return J({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:S,collateralManagerPaused:B,liquidationManagerPaused:$,circuitBreakerPaused:C,ucdControllerPaused:x,ucdTokenPaused:D,simplePsmPaused:k})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var it={hardhat:{chain:"hardhat",chainId:E.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:E.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:E.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};var nt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}];async function ot(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 at(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!i)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const o=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,nt,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const n=[];for(const e of i){const r=await ot(e.ciphertext,e.pkpId);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i);return o[0]}var st,ct=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],ut="UCDMintedWithAuthorization(bytes32,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes32)";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;let e="0";try{x("[Extend Position Validator] Starting..."),x("[Extend Position Validator] DEBUG: globalThis.priceProviders:",globalThis.priceProviders),x("[Extend Position Validator] DEBUG: priceProviders type:",typeof globalThis.priceProviders),globalThis.priceProviders&&(x("[Extend Position Validator] DEBUG: priceProviders isArray:",Array.isArray(globalThis.priceProviders)),x("[Extend Position Validator] DEBUG: priceProviders length:",globalThis.priceProviders.length),globalThis.priceProviders.length>0&&x("[Extend Position Validator] DEBUG: First provider:",globalThis.priceProviders[0])),e="0";const t=globalThis.chain,r=globalThis.selectedTerm;if(!t)throw new Error('Missing required parameter: "chain"');if(!r||"number"!=typeof r)throw new Error('Missing required parameter: "selectedTerm"');const i=$.verifyTermPositionActionAuthorizationStructure(globalThis.auth),n=function(t){const e=A(t),r=it[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),o=n.chain,s=(n.bitcoinNetwork,n.chainId),l=globalThis.rpcUrl;let f;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(!P.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${P.join(", ")}`)}(n,l),x(` 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)}`),f=l):(f=await Lit.Actions.getRpcUrl({chain:t}),x(` Using LIT-provided RPC URL for chain: ${t}`));const T=new ethers.providers.JsonRpcProvider(f),v=await at({policy:n,ethersProvider:T,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});x(` \u2705 Bitcoin Provider: ${v.name} (min confs ${v.minConfirmations})`);const I=v.minConfirmations;let B,C,D,k,M,U;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses){(function(t){E[t]})(o);throw new Error("Contract addresses not provided. Required for both dev and service modes.")}if(B=globalThis.contractAddresses.PositionManager,C=globalThis.contractAddresses.LoanOperationsManagerModule,D=globalThis.contractAddresses.TermManagerModule,k=globalThis.contractAddresses.UCDController,M=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",U=globalThis.contractAddresses.BTCSpendAuthorizer||C,!(B&&C&&D&&k&&M))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");x("\ud83d\udd0d LIT Action Contract Addresses:"),x(" PositionManager:",B),x(" LoanOpsManager:",C),x(" TermManager:",D),x(" UCDController:",k);const O=s,N=new ethers.providers.JsonRpcProvider(f);!function(t,e){const r=W[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await rt(N,B));const q=new R({providerUrl:v.url}),F=new V(globalThis.priceProviders,void 0),z=new X({contractAddress:U,chain:t,chainId:O,rpcUrl:l,bitcoinProvider:q,minConfirmations:I});e="1";const G=function(t){return new j(t)}({contractAddress:B,termManagerAddress:D,loanOpsManagerAddress:C,liquidationManagerAddress:M,chain:t,chainId:O,rpcUrl:l,vaultBalance:z,priceOracle:F,termOverride:r});x("[Extend Position Validator] Using fast balance path (skipUTXOValidation: true)");const H=await G.getVaultSnapshot(i.positionId),K=H.btcPriceUsd,J=BigInt(K.toString());if(J<c||J>u)throw new Error(`Bitcoin price ${J} is outside acceptable range (${c} - ${u})`);e="2";if(!await $.verifyExtendAuthorization(i,H.borrower,N,globalThis.contractAddresses?.PositionDelegateRegistry))throw x(`[DEBUG] Authorization failed - signer: ${i.signature?"present":"missing"}, borrower: ${H.borrower}`),x(`[DEBUG] Position ID: ${i.positionId}`),x(`[DEBUG] Auth timestamp: ${i.timestamp}, chainId: ${i.chainId}, newTerm: ${i.newTerm}`),x(`[DEBUG] Auth action: ${i.action}`),x(`[DEBUG] Auth signature: ${i.signature}`),new Error("Caller not authorized");e="3";if(![2,3].includes(H.status))throw new Error(`Invalid position status for extension: ${function(t){switch(t){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${t})`}}(H.status)}. Must be ACTIVE or EXPIRED.`);const Q=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()}(i.positionId);new ethers.Contract(D,[...ct],N);if(H.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const Y=H.selectedTerm,Z=Y+r,tt=65535;if(Z>tt)throw new Error(`Extension would cause term overflow: ${Y} + ${r} = ${Z} months, exceeds max ${tt} months`);let et;try{const t=await N.getBlock("latest");et=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const nt=r===m?g*h:r*p*h,ot=H.expiryAt+nt,st=3===H.status;if(ot-et>2*nt)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(st&&ot<=et)throw new Error("Invalid requested expiry date: extension must extend into the future for expired loans");e="4",x("\ud83d\udd0d Using extensionFeeBps from vault snapshot:",H.extensionFeeBps);const lt=BigInt(H.extensionFeeBps);let dt=[];try{const t=await async function(t,e,r){const i="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(ut)),o=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]);return(await t.getLogs({address:e,topics:[n,i],fromBlock:0,toBlock:"latest"})).map((t=>{const e=o.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(N,C,i.positionId),e=BigInt(H.termStartTimestamp);dt=t.filter((t=>t.quantumTimestamp>=e)),x(`[Pro-Rata] Found ${t.length} total mints, ${dt.length} in current term`)}catch(t){throw new Error(`Pro-rata mint-log fetch failed: ${t?.message??String(t)}. Retry with a healthy RPC so the pro-rata renewal credit can be computed; do not silently overcharge.`)}e="5";const ht=BigInt(S()),pt=function(t){const{mints:e,termStart:r,termExpiry:i,renewalNow:n,ucdDebt:o,extensionFeeRateBps:a}=t,s=o*a/10000n;if(0===e.length)return s;const c=(i-r)/BigInt(h);if(0n===c)return s;let u=0n,l=0n;for(const t of e){if(t.quantumTimestamp<r)continue;const e=(n-t.quantumTimestamp)/BigInt(h),i=(e>c?c:e)*t.mintFee/c;u+=t.mintFee,l+=i}const d=u>l?u-l:0n;return s>d?s-d:0n}({mints:dt,termStart:BigInt(H.termStartTimestamp),termExpiry:BigInt(H.expiryAt),renewalNow:ht,ucdDebt:BigInt(H.ucdDebt.toString()),extensionFeeRateBps:lt}),mt=BigInt(H.ucdDebt.toString())+pt;e="6";const gt=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}(H.availableBTCSats,J),ft=L(gt,mt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return L(t,e)>=r}(gt,mt,H.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${_(ft)}% < ${_(H.liquidationThresholdBps)}%`);e="7";const wt=S()+d,yt={name:w,version:y,chainId:s,verifyingContract:ethers.utils.getAddress(C)},bt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),Tt={ExtendPosition:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"availableBTCBalance",type:"uint256"},{name:"proRataRenewalFee",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},vt={actionTag:bt,positionId:Q,selectedTerm:r,btcPrice:J.toString(),availableBTCBalance:H.availableBTCSats.toString(),proRataRenewalFee:pt.toString(),quantumTimestamp:wt,borrower:ethers.utils.getAddress(H.borrower)};e="8";const Pt=globalThis.validatorWalletAddress;if(!Pt||!Pt.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Et=await Lit.Actions.getPrivateKey({pkpId:Pt}),At="string"==typeof Et?Et.startsWith("0x")?Et:`0x${Et}`:String(Et),It=new ethers.Wallet(At),St=await It._signTypedData(yt,Tt,vt);return{approved:!0,positionId:i.positionId,selectedTerm:r,btcPrice:J.toString(),availableBTCBalance:H.availableBTCSats.toString(),proRataRenewalFee:pt.toString(),newTotalDebt:mt.toString(),newCollateralRatioBps:ft.toString(),signature:St,timestamp:i.timestamp,quantumTimestamp:wt,validatorPkp:It.address}}catch(t){return console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),{approved:!1,reason:t.message||t.toString(),positionId:globalThis.auth?.positionId,timestamp:Date.now()}}}return st=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}),st)})();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
|
-
|
|
1
|
+
77c7fecdd58aa34d4c4b16023edbed65c8c03cced9659fa6809ba6eab2dec0b8
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "extend-position-validator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 153151,
|
|
4
|
+
"minifiedSize": 62264,
|
|
5
|
+
"compressionRatio": 0.5934469902253332,
|
|
6
|
+
"hash": "77c7fecdd58aa34d4c4b16023edbed65c8c03cced9659fa6809ba6eab2dec0b8",
|
|
7
|
+
"buildTime": 1779050481468,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|