@gvnrdao/dh-lit-actions 0.0.309 → 0.0.310
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/a_dev_address-probe-signer.meta.json +1 -1
- package/dist/a_dev_address-probe.meta.json +1 -1
- package/dist/a_dev_always-signer.meta.json +1 -1
- package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
- package/dist/a_dev_authorization-dummy.meta.json +1 -1
- package/dist/a_dev_ethers-version-probe.meta.json +1 -1
- package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
- package/dist/btc-address-balance.action.js +1 -1
- package/dist/btc-address-balance.hash +1 -1
- package/dist/btc-address-balance.meta.json +5 -5
- package/dist/btc-transaction-signer.action.js +1 -1
- package/dist/btc-transaction-signer.hash +1 -1
- package/dist/btc-transaction-signer.meta.json +5 -5
- package/dist/btc-utxo-invalidator.action.js +1 -1
- package/dist/btc-utxo-invalidator.hash +1 -1
- package/dist/btc-utxo-invalidator.meta.json +5 -5
- package/dist/btc-withdrawal.action.js +1 -1
- package/dist/btc-withdrawal.hash +1 -1
- package/dist/btc-withdrawal.meta.json +5 -5
- package/dist/encrypt-parameter.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.action.js +1 -1
- package/dist/liquidation-validator.hash +1 -1
- package/dist/liquidation-validator.meta.json +5 -5
- package/dist/loan-vault-btc-balance.action.js +1 -1
- package/dist/loan-vault-btc-balance.hash +1 -1
- package/dist/loan-vault-btc-balance.meta.json +5 -5
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-validator.action.js +1 -1
- package/dist/process-payment-validator.hash +1 -1
- package/dist/process-payment-validator.meta.json +5 -5
- 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.action.js +1 -1
- package/dist/ucd-mint-validator.hash +1 -1
- package/dist/ucd-mint-validator.meta.json +5 -5
- package/package.json +1 -1
- package/pkg-dist/pkg-src/index.js +138 -65
- package/pkg-dist/pkg-src/index.js.map +4 -4
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +7 -0
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +5 -0
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts +23 -2
- package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts +8 -1
- package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts +70 -0
- package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts.map +1 -0
- package/pkg-dist/src/modules/bitcoin-provider-registry.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,d=60,l=10,h=86400,p=30,m=12,g=365,w=8e3;var f="DiamondHands.Protocol",y="1",b="extend-position",T=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(T||{}),v={sepolia:"regtest",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/d)*d}function S(){return I(Math.floor(Date.now()/1e3))}async function $(){const t=Math.floor(Date.now()/1e3),e=t%d;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%d;return e<8||e>=d-8}(t))return;let r;r=e>=d-8?d-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${S()}`)}var C=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),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 $();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-d,s=n+d;if(o!==a&&o!==n&&o!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${a} (past), ${n} (current), ${s} (next)]`);if(o===a){if(i<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(o===s&&i>=s+(d-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,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}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,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function B(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){B()&&console.log(...t)}var k=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}},D=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}},U=class{static create(t="LIT Action",e){return B(e)?new D(t):new k}};function M(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function R(t){return t instanceof Error&&"AbortError"===t.name}var O=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=U.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"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${M(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${M(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${M(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,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: ${M(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(M(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${M(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(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),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=M(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=M(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const 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();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(M(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const 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),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function q(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 N(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function L(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 F(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{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"cryptocompare":if(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(o.apiKey,n++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),i=e?t.slice(4):t,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};z.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],z.REQUIRED_PROVIDER_COUNT=3;var V=z;async function X(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}var H=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:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],i);return(await n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var 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:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),n=await i.liquidationThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(i)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),n=await i.maxEscalatedThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function j(t){return new G(t)}var K=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),o=j({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)]),d=q(e.termStartTimestamp,e.selectedTerm),l=N(d.isExpired,d.daysIntoGracePeriod,s,c),h=L(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<l,m=h.collateralRatioBps-l;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:l,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.getBTCPrice()]),o=j({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)]),d=q(e.termStartTimestamp,e.selectedTerm),l=N(d.isExpired,d.daysIntoGracePeriod,s,c),h=L(i.availableBalance,n,e.ucdDebt),p=h.collateralRatioBps<l,m=h.collateralRatioBps-l;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:d.termDurationDays,termLengthDays:d.termLengthDays,isExpired:d.isExpired,daysUntilExpiry:d.daysUntilExpiry,daysIntoGracePeriod:d.daysIntoGracePeriod,currentLiquidationThreshold:l,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:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],i),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const u=Number(s.expiryAt),d=Number(s.selectedTerm),l=Number(s.totalTerm),m=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),f=(b=d,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:f,selectedTerm:d,status:c,expiryAt:u,previousExpiryAt:m,totalTerm:l,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 W="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",J={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function Q(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 Y=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),Z=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)"]),tt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),et=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function rt(t,e,r){return t.call({to:e,data:r})}async function it(t,e){const r=new ethers.utils.Interface([W]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([W]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?Q({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]}):Q(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await rt(t,e,Y.encodeFunctionData("views",[])),[i]=Y.decodeFunctionResult("views",r),[n,o,a,s,c,u,d,l]=await Promise.all([rt(t,e,Y.encodeFunctionData("paused",[])),rt(t,e,Y.encodeFunctionData("liquidationPaused",[])),rt(t,e,Y.encodeFunctionData("simplePsm",[])),rt(t,i,Z.encodeFunctionData("core",[])),rt(t,i,Z.encodeFunctionData("loanOps",[])),rt(t,i,Z.encodeFunctionData("collateralManager",[])),rt(t,i,Z.encodeFunctionData("liquidationManager",[])),rt(t,i,Z.encodeFunctionData("circuitBreaker",[]))]),h=Y.decodeFunctionResult("paused",n)[0],p=Y.decodeFunctionResult("liquidationPaused",o)[0],m=Y.decodeFunctionResult("simplePsm",a)[0],g=Z.decodeFunctionResult("core",s)[0],w=Z.decodeFunctionResult("loanOps",c)[0],f=Z.decodeFunctionResult("collateralManager",u)[0],y=Z.decodeFunctionResult("liquidationManager",d)[0],b=Z.decodeFunctionResult("circuitBreaker",l)[0],T=await rt(t,w,tt.encodeFunctionData("getUcdController",[])),v=await rt(t,w,tt.encodeFunctionData("ucdToken",[])),P=tt.decodeFunctionResult("getUcdController",T)[0],E=tt.decodeFunctionResult("ucdToken",v)[0],A=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await rt(t,e,et.encodeFunctionData("paused",[]));return et.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,S,$,C,B,x,k,D]=await Promise.all([A(g),A(w),A(f),A(y),A(b),A(P),A(E),A(m)]);return Q({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:S,collateralManagerPaused:$,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:x,ucdTokenPaused:k,simplePsmPaused:D})}(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 nt={hardhat:{chain:"hardhat",chainId:E.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:E.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:E.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var ot=[{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"}],at=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function st(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 ct(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}]}if(!i)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,ot,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.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,at,r);let s;try{s=await a.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await st(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)}var ut,dt=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],lt="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=C.verifyTermPositionActionAuthorizationStructure(globalThis.auth),n=function(t){const e=A(t),r=nt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),o=n.chainId,s=globalThis.rpcUrl;let d;s&&"string"==typeof s?(!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,s),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}(s)}`),d=s):(d=await Lit.Actions.getRpcUrl({chain:t}),x(` Using LIT-provided RPC URL for chain: ${t}`));const w=new ethers.providers.JsonRpcProvider(d),T=await async function(t){return(await ct(t))[0]}({policy:n,ethersProvider:w,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});x(` \u2705 Bitcoin Provider: ${T.name} (min confs ${T.minConfirmations})`);const v=T.minConfirmations;let E,I,$,B,k,D;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error("Contract addresses not provided. Required for both dev and service modes.");if(E=globalThis.contractAddresses.PositionManager,I=globalThis.contractAddresses.LoanOperationsManagerModule,$=globalThis.contractAddresses.TermManagerModule,B=globalThis.contractAddresses.UCDController,k=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",D=globalThis.contractAddresses.BTCSpendAuthorizer||I,!(E&&I&&$&&B&&k))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");x("\ud83d\udd0d LIT Action Contract Addresses:"),x(" PositionManager:",E),x(" LoanOpsManager:",I),x(" TermManager:",$),x(" UCDController:",B);const U=o,M=new ethers.providers.JsonRpcProvider(d);!function(t,e){const r=J[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await it(M,E));const R=new O({providerUrl:T.url}),q=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await X(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await X(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(globalThis.priceProviders),N=!0===globalThis.devPriceMode;if(N&&!n.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${n.chain}`);const L=new V(q,void 0,void 0,{devSingleProvider:N&&n.allowDevSinglePriceProvider}),z=new H({contractAddress:D,chain:t,chainId:U,rpcUrl:s,bitcoinProvider:R,minConfirmations:v});e="1";const G=function(t){return new K(t)}({contractAddress:E,termManagerAddress:$,loanOpsManagerAddress:I,liquidationManagerAddress:k,chain:t,chainId:U,rpcUrl:s,vaultBalance:z,priceOracle:L,termOverride:r});x("[Extend Position Validator] Using fast balance path (skipUTXOValidation: true)");const j=await G.getVaultSnapshot(i.positionId),W=j.btcPriceUsd,Q=BigInt(W.toString());if(Q<c||Q>u)throw new Error(`Bitcoin price ${Q} is outside acceptable range (${c} - ${u})`);e="2";if(!await C.verifyExtendAuthorization(i,j.borrower,U,M,globalThis.contractAddresses?.PositionDelegateRegistry))throw x(`[DEBUG] Authorization failed - signer: ${i.signature?"present":"missing"}, borrower: ${j.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");C.assertSelectedTermMatchesAuth(r,i.newTerm),e="3";if(![2,3].includes(j.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})`}}(j.status)}. Must be ACTIVE or EXPIRED.`);const Y=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($,[...dt],M);if(j.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const Z=j.selectedTerm,tt=Z+r,et=65535;if(tt>et)throw new Error(`Extension would cause term overflow: ${Z} + ${r} = ${tt} months, exceeds max ${et} months`);let rt;try{const t=await M.getBlock("latest");rt=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const ot=r===m?g*h:r*p*h,at=j.expiryAt+ot,st=3===j.status;if(at-rt>2*ot)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(st&&at<=rt)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:",j.extensionFeeBps);const ut=BigInt(j.extensionFeeBps);let ht=[];try{const t=await async function(t,e,r,i){const n="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(lt)),a=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]),s=await t.getBlock("latest"),c=Math.max(0,s.timestamp-i),u=Math.ceil(c/12),d=[];let l=Math.max(0,s.number-u-200);for(;l<=s.number;){const r=Math.min(l+900-1,s.number),i=await t.getLogs({address:e,topics:[o,n],fromBlock:l,toBlock:r});if(d.push(...i),r>=s.number)break;l=r+1}return d.map((t=>{const e=a.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(M,I,i.positionId,j.termStartTimestamp),e=BigInt(j.termStartTimestamp);ht=t.filter((t=>t.quantumTimestamp>=e)),x(`[Pro-Rata] Found ${t.length} total mints, ${ht.length} in current term`)}catch(t){throw new Error(`EXTEND_M7_MINT_LOG_FETCH_FAILED: Pro-rata mint-log fetch failed: ${t?.message??String(t)}. Retry with a healthy RPC so the pro-rata renewal credit can be computed; do not silently overcharge.`)}e="5";const pt=BigInt(S()),mt=function(t){const{mints:e,termStart:r,termExpiry:i,renewalNow:n,ucdDebt:o,extensionFeeRateBps:a}=t,s=o*a/10000n;if(0===e.length)return s;const c=(i-r)/BigInt(h);if(0n===c)return s;let u=0n,d=0n;for(const t of e){if(t.quantumTimestamp<r)continue;const e=(n-t.quantumTimestamp)/BigInt(h),i=(e>c?c:e)*t.mintFee/c;u+=t.mintFee,d+=i}const l=u>d?u-d:0n;return s>l?s-l:0n}({mints:ht,termStart:BigInt(j.termStartTimestamp),termExpiry:BigInt(j.expiryAt),renewalNow:pt,ucdDebt:BigInt(j.ucdDebt.toString()),extensionFeeRateBps:ut}),gt=BigInt(j.ucdDebt.toString())+mt;e="6";const wt=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}(j.availableBTCSats,Q),ft=F(wt,gt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return F(t,e)>=r}(wt,gt,j.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${_(ft)}% < ${_(j.liquidationThresholdBps)}%`);e="7";const yt=S()+l,bt={name:f,version:y,chainId:o,verifyingContract:ethers.utils.getAddress(I)},Tt=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(b)),vt={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"}]},Pt={actionTag:Tt,positionId:Y,selectedTerm:r,btcPrice:Q.toString(),availableBTCBalance:j.availableBTCSats.toString(),proRataRenewalFee:mt.toString(),quantumTimestamp:yt,borrower:ethers.utils.getAddress(j.borrower)};e="8";const Et=globalThis.validatorWalletAddress;if(!Et||!Et.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const At=await Lit.Actions.getPrivateKey({pkpId:Et}),It="string"==typeof At?At.startsWith("0x")?At:`0x${At}`:String(At),St=new ethers.Wallet(It),$t=await St._signTypedData(bt,vt,Pt);return{approved:!0,positionId:i.positionId,selectedTerm:r,btcPrice:Q.toString(),availableBTCBalance:j.availableBTCSats.toString(),proRataRenewalFee:mt.toString(),newTotalDebt:gt.toString(),newCollateralRatioBps:ft.toString(),signature:$t,timestamp:i.timestamp,quantumTimestamp:yt,validatorPkp:St.address}}catch(t){throw console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),t}}return ut=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}),ut)})();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,w=8e3;var f="DiamondHands.Protocol",y="1",b="extend-position",v=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(v||{}),T={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},P=["infura.io","drpc.org"],A={ethereum:1,sepolia:11155111,hardhat:1337};function E(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(v).join(", ")}`)}function I(t){return Math.floor(t/l)*l}function S(){return I(Math.floor(Date.now()/1e3))}async function $(){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 C=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),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 $();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,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}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,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);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(i,a,s)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,a,s,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function B(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){B()&&console.log(...t)}var k=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},U=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},D=class{static create(t="LIT Action",e){return B(e)?new U(t):new k}};function M(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function R(t){return t instanceof Error&&"AbortError"===t.name}function O(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function q(t){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const e=t.trim();if(!e.startsWith("{"))return{url:e,auth:{provider:"esplora"}};let r;try{r=JSON.parse(e)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof r.url||0===r.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=r.url.trim();switch(r.provider){case void 0:case"esplora":return{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof r.apiKey||0===r.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return O(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:r.apiKey}};case"blockstream-enterprise":{if("string"!=typeof r.clientId||0===r.clientId.length||"string"!=typeof r.clientSecret||0===r.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");O(i,"blockstream-enterprise provider url");const t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&O(r.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:r.clientId,clientSecret:r.clientSecret,...t?{tokenUrl:r.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(r.provider)}"`)}}var N=new Map;async function L(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,n=N.get(i);if(n)return n;const o=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,n=new AbortController,o=setTimeout((()=>n.abort()),e&&e>0?e:1e4);let a;try{a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:n.signal})}finally{clearTimeout(o)}if(!a.ok)throw new Error(`Blockstream OAuth token exchange failed: ${a.status} ${a.statusText}`);const s=await a.json(),c=s?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return o.catch((()=>N.delete(i))),N.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}var F=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=D.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await L(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),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"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${M(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${M(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${M(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,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}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(n),x(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${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: ${M(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(M(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${M(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(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:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(n),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),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=M(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=M(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),x(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const a=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:a>0?a:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(M(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),R(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};function _(t,e){if(0===t)return{termDurationDays:0,termLengthDays:30*e,isExpired:!1,daysUntilExpiry:30*e,daysIntoGracePeriod:0};const r=Math.floor(Date.now()/1e3),i=e*p,n=r-t,o=Math.floor(n/h);return{termDurationDays:o,termLengthDays:i,isExpired:o>i,daysUntilExpiry:Math.max(0,i-o),daysIntoGracePeriod:Math.max(0,o-i)}}function z(t,e,r,i){if(!t)return r;const n=i??o,a=Math.min(e,30);return o+a*a*(n-o)/900}function V(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 X(t,e){if(t<0n)throw new Error("Collateral value cannot be negative");if(e<=0n)throw new Error("Debt must be positive to calculate ratio");const r=Number(10000n*(10000000000n*t)/e);if(r<0)throw new Error(`Collateral ratio out of bounds: ${r} bps (${r/100}%)`);return!isFinite(r)||r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}function H(t){return t/100}var G=class t{requiredCount(){return this.devSingleProvider?1:t.REQUIRED_PROVIDER_COUNT}constructor(e,r,i,n){if(this.devSingleProvider=!0===n?.devSingleProvider,r&&Array.isArray(r))this.sources=r;else{if(!Array.isArray(e))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${t.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+t.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(e)}this.sources.sort(((t,e)=>t.priority-e.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(e){if(e.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${e.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`));const r=[],i=new Set;let n=1;for(const o of e){if(!o||"string"!=typeof o.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const e=o.name.toLowerCase();if(!t.ACTIVE_PROVIDER_NAMES.includes(e))throw new Error(`Unsupported price provider "${o.name}". Locked production set: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(i.has(e))throw new Error(`Duplicate price provider "${e}" \u2014 the oracle requires ${t.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${t.REQUIRED_PROVIDER_COUNT} different provider names from: ${t.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(i.add(e),e){case"cryptocompare":if(!o.apiKey)throw new Error("CryptoCompare provider requires an apiKey");r.push(this.createCryptoCompareSource(o.apiKey,n++));break;case"coinmarketcap":if(!o.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");r.push(this.createCoinMarketCapSource(o.apiKey,n++));break;case"coingecko":if(!o.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");r.push(this.createCoinGeckoSource(o.apiKey,n++));break;default:throw new Error(`Unhandled provider: ${e}`)}}return r}createCryptoCompareSource(t,e){return{name:"CryptoCompare",fetchPrice:async()=>{const e=new URL("https://min-api.cryptocompare.com/data/price");e.searchParams.set("fsym","BTC"),e.searchParams.set("tsyms","USDT"),e.searchParams.set("api_key",t);const r=await(async t=>{const e=new AbortController,r=setTimeout((()=>e.abort()),5e3);try{const i=await fetch(t,{signal:e.signal,headers:{Accept:"application/json"}});if(clearTimeout(r),!i.ok)throw new Error(`CryptoCompare HTTP ${i.status} ${i.statusText}`);return await i.json()}catch(t){if(clearTimeout(r),"AbortError"===t.name)throw new Error("Request timeout after 5000ms");throw t}})(e.toString()),i=Number(r?.USDT);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CryptoCompare price payload");return i},priority:e}}createFetchJson(t){return async(e,r)=>{const i=new AbortController,n=setTimeout((()=>i.abort()),5e3);try{const n=await fetch(e,{headers:{Accept:"application/json",...r||{}},signal:i.signal});if(!n.ok)throw new Error(`${t} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}createCoinGeckoSource(t,e){if(!t)throw new Error("createCoinGeckoSource requires an apiKey");const r=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const e=t.startsWith("pro:"),i=e?t.slice(4):t,n=e?{"x-cg-pro-api-key":i}:{"x-cg-demo-api-key":i},o=new URL("https://api.coingecko.com/api/v3/simple/price");o.searchParams.set("ids","bitcoin"),o.searchParams.set("vs_currencies","usd");const a=await r(o.toString(),n),s=Number(a?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:e}}createCoinMarketCapSource(t,e){const r=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const e=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");e.searchParams.set("symbol","BTC"),e.searchParams.set("convert","USDT");const i=await r(e.toString(),{"X-CMC_PRO_API_KEY":t}),n=Number(i?.data?.BTC?.[0]?.quote?.USDT?.price??i?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},priority:e}}async getBTCPrice(){const t=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const e=new Promise(((t,e)=>{setTimeout((()=>{e(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),r=Promise.all(this.sources.map((async t=>{const e=Date.now();try{const r=await t.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-e}ms] ${t.name}: $${r.toLocaleString()}`),r}catch(e){const r=e instanceof Error?e.message:String(e);throw console.log(`[Price Oracle] \u274c ${t.name}: ${r}`),new Error(`${t.name} price fetch failed: ${r}`)}}))),i=[...await Promise.race([r,e])].sort(((t,e)=>t-e));let n;if(this.devSingleProvider)n=i[0];else{n=i[1];if((i[2]-i[0])/i[0]>.01){const t=this.sources.map((t=>t.name)).join(", "),e=i.map((t=>`$${t.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${t}]. Prices: [${e}]`)}}const o=Math.round(100*n),a=1000000n*BigInt(o),s=Date.now()-t;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${a}`),a}};G.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],G.REQUIRED_PROVIDER_COUNT=3;var j=G;async function K(t,e,r,i){try{const t=await Lit.Actions.Decrypt({pkpId:r,ciphertext:i});return"string"==typeof t?t:String(t??"")}catch(r){const i=r instanceof Error?r.message:String(r);throw new Error(`Failed to decrypt ${e} for provider ${t}: ${i}`)}}var W=class{constructor(t){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:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],i);return(await n.getAuthorizedSpends(e)).map((e=>({txid:e.txid,vout:Number(e.vout),satoshis:BigInt(e.satoshis.toString()),positionId:t,targetAddress:e.targetAddress,targetAmount:BigInt(e.targetAmount.toString()),timestamp:Number(e.authorizedAt)})))}computeAuthorizedSpendsHash(t,e){const r=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`;if(0===e.length)return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,[]]));const i=e.map((t=>{const e=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.txid)),r=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(t.targetAddress));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","uint32","uint256","bytes32","uint256","uint256"],[e,t.vout,t.satoshis.toString(),r,t.targetAmount.toString(),t.timestamp]))}));return ethers.utils.keccak256(ethers.utils.defaultAbiCoder.encode(["bytes32","bytes32[]"],[r,i]))}};var J=class{constructor(t){this.termManagerAddress=t.termManagerAddress,this.loanOpsManagerAddress=t.loanOpsManagerAddress,this.liquidationManagerAddress=t.liquidationManagerAddress,this.chain=t.chain,this.chainId=t.chainId,this.rpcUrl=t.rpcUrl}async getLiquidationThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.loanOpsManagerAddress,r,e),n=await i.liquidationThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",t.message),new Error(`Failed to fetch liquidation threshold: ${t.message}`)}}async getTermFees(t){try{let e;e=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,i,r),o=await n.getTermFees(t);return{originationFeeBps:Number(o.originationFee?.toString?.()??o[0]?.toString?.()??o[0]),extensionFeeBps:Number(o.extensionFee?.toString?.()??o[1]?.toString?.()??o[1])}}catch(t){throw console.error("[ProtocolParameters] Error fetching term fees:",t.message),new Error(`Failed to fetch term fees: ${t.message}`)}}async getAuthorizedSpendsHash(t){try{const e=this.rpcUrl||await Lit.Actions.getRpcUrl({chain:this.chain}),r=new ethers.providers.StaticJsonRpcProvider({url:e,timeout:w},{name:"any",chainId:this.chainId}),i=t.startsWith("0x")?t:`0x${t.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(i)}catch(t){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",t.message),new Error(`Failed to fetch authorized spends hash: ${t.message}`)}}async getMaxEscalatedThreshold(){try{let t;t=this.rpcUrl?this.rpcUrl:await Lit.Actions.getRpcUrl({chain:this.chain});const e=new ethers.providers.StaticJsonRpcProvider({url:t,timeout:w},{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"maxEscalatedThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,r,e),n=await i.maxEscalatedThreshold();return Number(n.toString())}catch(t){throw console.error("[ProtocolParameters] Error fetching max escalated threshold:",t.message),new Error(`Failed to fetch max escalated threshold: ${t.message}`)}}};function Q(t){return new J(t)}var Y=class{constructor(t){this.config=t}async getVaultSnapshot(t){const e=await this.queryPositionState(t);console.log(`[Vault Snapshot] Raw vault address from contract: "${e.vaultAddress}"`);const r=!0===this.config.debugOverrides?.useStubbedBtcData,[i,n]=r?this.buildStubbedBtcSnapshotInputs(e):await Promise.all([this.config.vaultBalance.calculateTrustedBalance(t,e.vaultAddress),this.config.priceOracle.getBTCPrice()]),o=Q({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=_(e.termStartTimestamp,e.selectedTerm),d=z(l.isExpired,l.daysIntoGracePeriod,s,c),h=V(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.getBTCPrice()]),o=Q({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=_(e.termStartTimestamp,e.selectedTerm),d=z(l.isExpired,l.daysIntoGracePeriod,s,c),h=V(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:w},this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],i),o=await n.core(),a=new ethers.Contract(o,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],i),s=await a.getPositionDetails(e),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",e),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${e}`);const u=Number(s.expiryAt),l=Number(s.selectedTerm),d=Number(s.totalTerm),m=Number(s.previousExpiryAt),g=Number(s.lastRenewedAt),f=(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,E(this.config.chain)),ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:f,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 T[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 Z="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",tt={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function et(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var rt=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),it=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),nt=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),ot=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function at(t,e,r){return t.call({to:e,data:r})}async function st(t,e){const r=new ethers.utils.Interface([Z]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([Z]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?et({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):et(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await at(t,e,rt.encodeFunctionData("views",[])),[i]=rt.decodeFunctionResult("views",r),[n,o,a,s,c,u,l,d]=await Promise.all([at(t,e,rt.encodeFunctionData("paused",[])),at(t,e,rt.encodeFunctionData("liquidationPaused",[])),at(t,e,rt.encodeFunctionData("simplePsm",[])),at(t,i,it.encodeFunctionData("core",[])),at(t,i,it.encodeFunctionData("loanOps",[])),at(t,i,it.encodeFunctionData("collateralManager",[])),at(t,i,it.encodeFunctionData("liquidationManager",[])),at(t,i,it.encodeFunctionData("circuitBreaker",[]))]),h=rt.decodeFunctionResult("paused",n)[0],p=rt.decodeFunctionResult("liquidationPaused",o)[0],m=rt.decodeFunctionResult("simplePsm",a)[0],g=it.decodeFunctionResult("core",s)[0],w=it.decodeFunctionResult("loanOps",c)[0],f=it.decodeFunctionResult("collateralManager",u)[0],y=it.decodeFunctionResult("liquidationManager",l)[0],b=it.decodeFunctionResult("circuitBreaker",d)[0],v=await at(t,w,nt.encodeFunctionData("getUcdController",[])),T=await at(t,w,nt.encodeFunctionData("ucdToken",[])),P=nt.decodeFunctionResult("getUcdController",v)[0],A=nt.decodeFunctionResult("ucdToken",T)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await at(t,e,ot.encodeFunctionData("paused",[]));return ot.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,S,$,C,B,x,k,U]=await Promise.all([E(g),E(w),E(f),E(y),E(b),E(P),E(A),E(m)]);return et({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:S,collateralManagerPaused:$,liquidationManagerPaused:C,circuitBreakerPaused:B,ucdControllerPaused:x,ucdTokenPaused:k,simplePsmPaused:U})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var ct={hardhat:{chain:"hardhat",chainId:A.hardhat,bitcoinNetwork:T.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:A.sepolia,bitcoinNetwork:T.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:A.ethereum,bitcoinNetwork:T.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};var ut=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],lt=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function dt(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function ht(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}]}if(!i)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,ut,e),[n,o]=await i.getProviders(t),a=[];for(let t=0;t<n.length;t++)a.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return a}(t.chainId,e,r);if(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.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),a=new ethers.Contract(i,lt,r);let s;try{s=await a.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!s)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await dt(e.ciphertext,e.pkpId),{url:i,auth:o}=q(r);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:o,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i)}var pt,mt=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"isValidTerm",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],gt="UCDMintedWithAuthorization(bytes32,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes32)";async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;let e="0";try{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=C.verifyTermPositionActionAuthorizationStructure(globalThis.auth),n=function(t){const e=E(t),r=ct[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),o=n.chainId,s=globalThis.rpcUrl;let l;s&&"string"==typeof s?(!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,s),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}(s)}`),l=s):(l=await Lit.Actions.getRpcUrl({chain:t}),x(` Using LIT-provided RPC URL for chain: ${t}`));const w=new ethers.providers.JsonRpcProvider(l),v=await async function(t){return(await ht(t))[0]}({policy:n,ethersProvider:w,registryAddress:globalThis.contractAddresses?.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});x(` \u2705 Bitcoin Provider: ${v.name} (min confs ${v.minConfirmations})`);const T=v.minConfirmations;let A,I,$,B,k,U;if(!globalThis.contractAddresses||"object"!=typeof globalThis.contractAddresses)throw new Error("Contract addresses not provided. Required for both dev and service modes.");if(A=globalThis.contractAddresses.PositionManager,I=globalThis.contractAddresses.LoanOperationsManagerModule,$=globalThis.contractAddresses.TermManagerModule,B=globalThis.contractAddresses.UCDController,k=globalThis.contractAddresses.LiquidationManagerModule??globalThis.contractAddresses.LiquidationManager??"",U=globalThis.contractAddresses.BTCSpendAuthorizer||I,!(A&&I&&$&&B&&k))throw new Error("Missing required contract addresses (including LiquidationManager or LiquidationManagerModule)");x("\ud83d\udd0d LIT Action Contract Addresses:"),x(" PositionManager:",A),x(" LoanOpsManager:",I),x(" TermManager:",$),x(" UCDController:",B);const D=o,M=new ethers.providers.JsonRpcProvider(l);!function(t,e){const r=tt[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("extendPosition",await st(M,A));const R=new F({providerUrl:v.url,auth:v.auth}),O=await async function(t){if(!t)return t;const e=[];for(const i of t){if(!i?.name||"string"!=typeof i.name)throw new Error("Each price provider must include a valid name");let t,n;if(i.pkpId&&"string"==typeof i.pkpId){const e=(r=i.pkpId).startsWith("0x")||r.startsWith("0X")?r:`0x${r}`;i.apiKey&&(t=await K(i.name,"apiKey",e,i.apiKey)),i.apiSecret&&(n=await K(i.name,"apiSecret",e,i.apiSecret))}else t=i.apiKey,n=i.apiSecret;e.push({name:i.name,apiKey:t,apiSecret:n})}var r;return e}(globalThis.priceProviders),q=!0===globalThis.devPriceMode;if(q&&!n.allowDevSinglePriceProvider)throw new Error(`devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${n.chain}`);const N=new j(O,void 0,void 0,{devSingleProvider:q&&n.allowDevSinglePriceProvider}),L=new W({contractAddress:U,chain:t,chainId:D,rpcUrl:s,bitcoinProvider:R,minConfirmations:T});e="1";const _=function(t){return new Y(t)}({contractAddress:A,termManagerAddress:$,loanOpsManagerAddress:I,liquidationManagerAddress:k,chain:t,chainId:D,rpcUrl:s,vaultBalance:L,priceOracle:N,termOverride:r});x("[Extend Position Validator] Using fast balance path (skipUTXOValidation: true)");const z=await _.getVaultSnapshot(i.positionId),V=z.btcPriceUsd,G=BigInt(V.toString());if(G<c||G>u)throw new Error(`Bitcoin price ${G} is outside acceptable range (${c} - ${u})`);e="2";if(!await C.verifyExtendAuthorization(i,z.borrower,D,M,globalThis.contractAddresses?.PositionDelegateRegistry))throw x(`[DEBUG] Authorization failed - signer: ${i.signature?"present":"missing"}, borrower: ${z.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");C.assertSelectedTermMatchesAuth(r,i.newTerm),e="3";if(![2,3].includes(z.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})`}}(z.status)}. Must be ACTIVE or EXPIRED.`);const J=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(i.positionId);new ethers.Contract($,[...mt],M);if(z.isLiquidatable)throw new Error("Position is liquidatable - extension rejected. Add collateral first.");const Q=z.selectedTerm,Z=Q+r,et=65535;if(Z>et)throw new Error(`Extension would cause term overflow: ${Q} + ${r} = ${Z} months, exceeds max ${et} months`);let rt;try{const t=await M.getBlock("latest");rt=Number(t.timestamp)}catch(t){throw new Error(`Failed to read latest block.timestamp: ${t?.message??String(t)}`)}const it=r===m?g*h:r*p*h,nt=z.expiryAt+it,ot=3===z.status;if(nt-rt>2*it)throw new Error("Invalid requested expiry date: cannot extend beyond double term period from now");if(ot&&nt<=rt)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:",z.extensionFeeBps);const at=BigInt(z.extensionFeeBps);let ut=[];try{const t=await async function(t,e,r,i){const n="0x"+(r.startsWith("0x")?r.slice(2):r).padStart(64,"0"),o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(gt)),a=new ethers.utils.Interface(["event UCDMintedWithAuthorization(bytes32 indexed positionId, address indexed borrower, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, uint256 quantumTimestamp, bytes32 authorizedSpendsHash)"]),s=await t.getBlock("latest"),c=Math.max(0,s.timestamp-i),u=Math.ceil(c/12),l=[];let d=Math.max(0,s.number-u-200);for(;d<=s.number;){const r=Math.min(d+900-1,s.number),i=await t.getLogs({address:e,topics:[o,n],fromBlock:d,toBlock:r});if(l.push(...i),r>=s.number)break;d=r+1}return l.map((t=>{const e=a.parseLog(t);return{mintFee:BigInt(e.args.mintFee.toString()),quantumTimestamp:BigInt(e.args.quantumTimestamp.toString())}}))}(M,I,i.positionId,z.termStartTimestamp),e=BigInt(z.termStartTimestamp);ut=t.filter((t=>t.quantumTimestamp>=e)),x(`[Pro-Rata] Found ${t.length} total mints, ${ut.length} in current term`)}catch(t){throw new Error(`EXTEND_M7_MINT_LOG_FETCH_FAILED: Pro-rata mint-log fetch failed: ${t?.message??String(t)}. Retry with a healthy RPC so the pro-rata renewal credit can be computed; do not silently overcharge.`)}e="5";const lt=BigInt(S()),dt=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:ut,termStart:BigInt(z.termStartTimestamp),termExpiry:BigInt(z.expiryAt),renewalNow:lt,ucdDebt:BigInt(z.ucdDebt.toString()),extensionFeeRateBps:at}),pt=BigInt(z.ucdDebt.toString())+dt;e="6";const wt=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}(z.availableBTCSats,G),ft=X(wt,pt);if(!function(t,e,r){if(r<0||r>1e6)throw new Error("Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)");return X(t,e)>=r}(wt,pt,z.liquidationThresholdBps))throw new Error(`Insufficient collateral after extension: ${H(ft)}% < ${H(z.liquidationThresholdBps)}%`);e="7";const yt=S()+d,bt={name:f,version:y,chainId:o,verifyingContract:ethers.utils.getAddress(I)},vt=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"}]},Pt={actionTag:vt,positionId:J,selectedTerm:r,btcPrice:G.toString(),availableBTCBalance:z.availableBTCSats.toString(),proRataRenewalFee:dt.toString(),quantumTimestamp:yt,borrower:ethers.utils.getAddress(z.borrower)};e="8";const At=globalThis.validatorWalletAddress;if(!At||!At.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const Et=await Lit.Actions.getPrivateKey({pkpId:At}),It="string"==typeof Et?Et.startsWith("0x")?Et:`0x${Et}`:String(Et),St=new ethers.Wallet(It),$t=await St._signTypedData(bt,Tt,Pt);return{approved:!0,positionId:i.positionId,selectedTerm:r,btcPrice:G.toString(),availableBTCBalance:z.availableBTCSats.toString(),proRataRenewalFee:dt.toString(),newTotalDebt:pt.toString(),newCollateralRatioBps:ft.toString(),signature:$t,timestamp:i.timestamp,quantumTimestamp:yt,validatorPkp:St.address}}catch(t){throw console.error(`[Extend Position Validator] Failed at step ${e}:`,t.message),t}}return pt=n,((n,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===a||t(n,c,{get:()=>o[c],enumerable:!(s=e(o,c))||s.enumerable});return n})(t({},"__esModule",{value:!0}),pt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
0db666fa2888e9acea13d8e4d79edd4ca252f5a4bb06d97e53aa14a9a34b7143
|
|
@@ -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": 160477,
|
|
4
|
+
"minifiedSize": 66543,
|
|
5
|
+
"compressionRatio": 0.5853424478274145,
|
|
6
|
+
"hash": "0db666fa2888e9acea13d8e4d79edd4ca252f5a4bb06d97e53aa14a9a34b7143",
|
|
7
|
+
"buildTime": 1781559387841,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|