@gvnrdao/dh-lit-actions 0.0.308 → 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 +150 -77
- 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=546n,s=100,a=1e5,c=60,u="btc-utxo-invalidator",d=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(d||{}),l={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},h={ethereum:1,sepolia:11155111,hardhat:1337};function p(t){return Math.floor(t/c)*c}async function g(){const t=Math.floor(Date.now()/1e3),e=t%c;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%c;return e<8||e>=52}(t))return;let r;r=e>=52?c-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: ${p(Math.floor(Date.now()/1e3))}`)}var f=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 g();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=p(i),o=p(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 s=n-c,a=n+c;if(o!==s&&o!==n&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${n} (current), ${a} (next)]`);if(o===s){if(i<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&i>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await r(a,s,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if(e.action!==u)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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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 m(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 w(...t){m()&&console.log(...t)}var y=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},b=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,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}},v=class{static create(t="LIT Action",e){return m(e)?new b(t):new y}};function P(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}var E=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=v.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),w(`[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"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(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,s=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(s),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,s]=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),w(`[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}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${T(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"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(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),s=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const 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),w(`[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 s=o.chain_stats.funded_txo_sum,a=o.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const c=BigInt(s-a);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),c}catch(t){if(clearTimeout(n),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(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),w(`[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 s=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:s>0?s:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(T(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),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function I(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const i="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=[];for(let t=0;t<r.length;t+=2)n.push(parseInt(r.substr(t,2),16));const o=x(n,8,5,!0),s=[e,...o],a=function(t,e){const r=function(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}(t).concat(e).concat([0,0,0,0,0,0]),i=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let i=0;i<t.length;i++){const n=r>>25;r=(33554431&r)<<5^t[i];for(let t=0;t<5;t++)n>>t&1&&(r^=e[t])}return r}(r),n=[];for(let t=0;t<6;t++)n.push(i>>5*(5-t)&31);return n}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=i[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function A(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");const i=t.substring(r+1).toLowerCase(),n=[];for(let t=0;t<i.length;t++){const r=e.indexOf(i[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${i[t]}`);n.push(r)}const o=n.slice(0,-6),s=x(o.slice(1),5,8,!1);return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let i=0;i<t.length;i++){const n=e.indexOf(t[i]);if(n<0)throw new Error(`Invalid Base58 character: ${t[i]}`);r=58n*r+BigInt(n)}let i=r.toString(16);i.length%2&&(i="0"+i);for(let e=0;e<t.length&&"1"===t[e];e++)i="00"+i;return i}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function x(t,e,r,i){let n=0,o=0;const s=[],a=(1<<r)-1;for(let i=0;i<t.length;i++){const c=t[i];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(n=n<<e|c,o+=e;o>=r;)o-=r,s.push(n>>o&a)}if(i)o>0&&s.push(n<<r-o&a);else if(o>=e||n<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function k(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function S(t,e){const r=t.toString(16).padStart(2*e,"0").match(/../g);if(!r)throw new Error(`Invalid hex conversion: ${t}`);return r.reverse().join("")}function C(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+S(t,2):t<=4294967295?"fe"+S(t,4):"ff"+S(t,8)}var B=[{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"}],M=[{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 D(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 O(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,B,e),[n,o]=await i.getProviders(t),s=[];for(let t=0;t<n.length;t++)s.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(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)),s=new ethers.Contract(i,M,r);let a;try{a=await s.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${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 D(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 U={hardhat:{chain:"hardhat",chainId:h.hardhat,bitcoinNetwork:l.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:h.sepolia,bitcoinNetwork:l.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:h.ethereum,bitcoinNetwork:l.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function N(t){const e=function(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(d).join(", ")}`)}(t),r=U[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _="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))",q={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 R(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 L=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),F=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),j=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function H(t,e,r){return t.call({to:e,data:r})}async function X(t,e){const r=new ethers.utils.Interface([_]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([_]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?R({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]}):R(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await H(t,e,L.encodeFunctionData("views",[])),[i]=L.decodeFunctionResult("views",r),[n,o,s,a,c,u,d,l]=await Promise.all([H(t,e,L.encodeFunctionData("paused",[])),H(t,e,L.encodeFunctionData("liquidationPaused",[])),H(t,e,L.encodeFunctionData("simplePsm",[])),H(t,i,F.encodeFunctionData("core",[])),H(t,i,F.encodeFunctionData("loanOps",[])),H(t,i,F.encodeFunctionData("collateralManager",[])),H(t,i,F.encodeFunctionData("liquidationManager",[])),H(t,i,F.encodeFunctionData("circuitBreaker",[]))]),h=L.decodeFunctionResult("paused",n)[0],p=L.decodeFunctionResult("liquidationPaused",o)[0],g=L.decodeFunctionResult("simplePsm",s)[0],f=F.decodeFunctionResult("core",a)[0],m=F.decodeFunctionResult("loanOps",c)[0],w=F.decodeFunctionResult("collateralManager",u)[0],y=F.decodeFunctionResult("liquidationManager",d)[0],b=F.decodeFunctionResult("circuitBreaker",l)[0],v=await H(t,m,z.encodeFunctionData("getUcdController",[])),P=await H(t,m,z.encodeFunctionData("ucdToken",[])),T=z.decodeFunctionResult("getUcdController",v)[0],$=z.decodeFunctionResult("ucdToken",P)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await H(t,e,j.encodeFunctionData("paused",[]));return j.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,A,x,k,S,C,B,M]=await Promise.all([E(f),E(m),E(w),E(y),E(b),E(T),E($),E(g)]);return R({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:A,collateralManagerPaused:x,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var K,V=3600,W=1500,Q=[{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 BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],G=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],J=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=v.create("BTC UTXO Invalidator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing required parameter "chain"');const i=N(t),n=P(),c=n.publicKey;if(!c||"string"!=typeof c)throw new Error('Missing required parameter "publicKey"');const d=globalThis.contractAddresses;if(!d)throw new Error('Missing "contractAddresses"');const l=d.PositionManager,h=d.BTCSpendAuthorizer;if(!l||!h)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const p=globalThis.auth;if(!p||"object"!=typeof p)throw new Error('Missing or invalid "auth" parameter');const{positionId:g,utxoTxid:m,utxoVout:w,timestamp:y,signature:b,chainId:v,action:T}=p;if(!g||!m||"number"!=typeof w)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof y||!b||"number"!=typeof v)throw new Error("auth requires { timestamp, signature, chainId }");if(T!==u)throw new Error(`auth.action must be "${u}" (got "${T}")`);const $=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()}(g);let x;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(x=globalThis.rpcUrl,console.log(` RPC 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}(x)}`)):x=await Lit.Actions.getRpcUrl({chain:t});const B=new ethers.providers.JsonRpcProvider(x),M=await async function(t){return(await O(t))[0]}({policy:i,ethersProvider:B,registryAddress:d.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});new E({providerUrl:M.url});!function(t,e){const r=q[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}))}("btcTransactionSign",await X(B,l)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const D=new ethers.Contract(h,Q,B),U=await D.getAuthorizedSpends($);let _=null;for(const t of U)if(t.txid.toLowerCase()===m.toLowerCase()&&Number(t.vout)===w){_=t;break}if(!_)throw new Error(`No AuthorizedSpend on-chain for ${m}:${w} under position ${$}`);const R=BigInt(_.authorizedAt.toString()),L=BigInt(_.satoshis.toString()),F=BigInt(Math.floor(Date.now()/1e3));if(F-R<BigInt(V))throw new Error(`AuthorizedSpend not yet stale: age=${(F-R).toString()}s, required=${V}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const z=new ethers.Contract(l,J,B),j=await z.core(),H=new ethers.Contract(j,G,B),K=await H.getPositionDetails($),Z=K.borrower??K[1],Y=K.vaultAddress??K[3];if(!Z||Z===ethers.constants.AddressZero)throw new Error(`Position ${$} not found or no borrower set`);if(!Y)throw new Error(`Position ${$} missing vaultAddress`);if(v!==i.chainId)throw new Error(`auth.chainId (${v}) \u2260 policy.chainId (${i.chainId})`);if(!await f.verifyRecoveryAuthorization({positionId:$,timestamp:y,chainId:v,utxoTxid:m,utxoVout:w,action:T,signature:b},Z,i.chainId,B,d.PositionDelegateRegistry))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const tt=await(async()=>{try{const t=await fetch(`${M.url}/tx/${m}/outspends`);return t.ok?await t.json():null}catch{return null}})();if(tt&&tt[w]&&tt[w].spent){const t=tt[w].txid??"unknown";return console.log(` \u2139\ufe0f UTXO already spent by ${t}; short-circuiting to recovery-validator path`),e.stepEnd("4"),{success:!0,alreadySpent:{spendingTxid:t},positionId:$,utxoTxid:m,utxoVout:w,authorizedAt:R.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const et=await I(c,i.bitcoinNetwork);if(Y&&et.toLowerCase()!==Y.toLowerCase())throw new Error(`Derived PKP address ${et} \u2260 on-chain vaultAddress ${Y}`);if(e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx"),W<s)throw new Error(`INVALIDATOR_FEE_SATS (${W}) < MIN_BTC_FEE_SATS (${s})`);if(W>a)throw new Error(`INVALIDATOR_FEE_SATS (${W}) > MAX_BTC_FEE_SATS (${a})`);const rt=Number(L)-W;if(rt<Number(o))throw new Error(`Invalidator output (${rt} sats) below dust limit; UTXO too small to recover`);const it={txid:m,vout:w,value:Number(L),scriptPubKey:""};it.scriptPubKey=A(et);const{txHex:nt,sigHashes:ot}=function(t){const{utxos:e,destination:r,amount:i,changeAddress:n,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",a="ffffffff",c="00000000",u=C(e.length),d=e.map((t=>k(t.txid)+S(t.vout,4)+"00"+a)).join(""),l=[],h=A(r);if(l.push(S(i,8)+C(h.length/2)+h),o>0){const t=A(n);l.push(S(o,8)+C(t.length/2)+t)}const p=C(l.length),g=l.join(""),f=s+u+d+p+g+c,m=e.map((t=>k(t.txid)+S(t.vout,4))).join(""),w=ethers.utils.sha256(ethers.utils.sha256("0x"+m)),y=e.map((()=>a)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+y)),v=ethers.utils.sha256(ethers.utils.sha256("0x"+g));return{txHex:f,sigHashes:e.map((t=>{const e=k(t.txid)+S(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",i=s+w.slice(2)+b.slice(2)+e+r+S(t.value,8)+a+v.slice(2)+c+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+i))}))}}({utxos:[it],destination:et,amount:rt,changeAddress:et,changeAmount:0,network:i.bitcoinNetwork,pkpPublicKey:c});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const st=n.pkpId;if(!st)throw new Error('Missing required parameter "pkpId"');const at=await Lit.Actions.getPrivateKey({pkpId:st}),ct="string"==typeof at?at.startsWith("0x")?at:`0x${at}`:String(at),ut=new ethers.utils.SigningKey(ct),dt=[];for(let t=0;t<ot.length;t++){const e=ut.signDigest(ot[t]);dt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:nt,sigHashes:ot,signatures:dt,pkpPublicKey:c,pkpBtcAddress:et,invalidatorAmount:rt,networkFee:W,utxo:{txid:m,vout:w,value:Number(L)},authorization:{authorizedAt:R.toString(),positionId:$},timestamp:Date.now(),action:"btc-utxo-invalidator"}}catch(t){return console.error(`[BTC UTXO Invalidator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"btc-utxo-invalidator"}}}return K=n,((n,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===s||t(n,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return n})(t({},"__esModule",{value:!0}),K)})();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=546n,s=100,a=1e5,c=60,u="btc-utxo-invalidator",l=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(l||{}),d={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},h={ethereum:1,sepolia:11155111,hardhat:1337};function p(t){return Math.floor(t/c)*c}async function g(){const t=Math.floor(Date.now()/1e3),e=t%c;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%c;return e<8||e>=52}(t))return;let r;r=e>=52?c-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: ${p(Math.floor(Date.now()/1e3))}`)}var m=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await g();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=p(i),o=p(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 s=n-c,a=n+c;if(o!==s&&o!==n&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${n} (current), ${a} (next)]`);if(o===s){if(i<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&i>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await r(a,s,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if(e.action!==u)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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,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 f(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 w(...t){f()&&console.log(...t)}var y=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},b=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,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}},v=class{static create(t="LIT Action",e){return f(e)?new b(t):new y}};function P(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}var E="https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token";function I(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function A(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 I(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`");I(i,"blockstream-enterprise provider url");const t="string"==typeof r.tokenUrl&&r.tokenUrl.length>0;return t&&I(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 k=new Map,x=1e4;async function S(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||E,i=`${r}\n${t.clientId}`,n=k.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:x);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i,signal:n.signal})}finally{clearTimeout(o)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return o.catch((()=>k.delete(i))),k.set(i,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}var C=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=v.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await S(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),w(`[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"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(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,s=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(s),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,s]=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),w(`[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}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${T(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"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(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),s=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const 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),w(`[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 s=o.chain_stats.funded_txo_sum,a=o.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const c=BigInt(s-a);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),c}catch(t){if(clearTimeout(n),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(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),w(`[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 s=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:s>0?s:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(T(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),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function B(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const i="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=[];for(let t=0;t<r.length;t+=2)n.push(parseInt(r.substr(t,2),16));const o=D(n,8,5,!0),s=[e,...o],a=function(t,e){const r=function(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}(t).concat(e).concat([0,0,0,0,0,0]),i=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let i=0;i<t.length;i++){const n=r>>25;r=(33554431&r)<<5^t[i];for(let t=0;t<5;t++)n>>t&1&&(r^=e[t])}return r}(r),n=[];for(let t=0;t<6;t++)n.push(i>>5*(5-t)&31);return n}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=i[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function M(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");const i=t.substring(r+1).toLowerCase(),n=[];for(let t=0;t<i.length;t++){const r=e.indexOf(i[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${i[t]}`);n.push(r)}const o=n.slice(0,-6),s=D(o.slice(1),5,8,!1);return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let i=0;i<t.length;i++){const n=e.indexOf(t[i]);if(n<0)throw new Error(`Invalid Base58 character: ${t[i]}`);r=58n*r+BigInt(n)}let i=r.toString(16);i.length%2&&(i="0"+i);for(let e=0;e<t.length&&"1"===t[e];e++)i="00"+i;return i}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function D(t,e,r,i){let n=0,o=0;const s=[],a=(1<<r)-1;for(let i=0;i<t.length;i++){const c=t[i];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(n=n<<e|c,o+=e;o>=r;)o-=r,s.push(n>>o&a)}if(i)o>0&&s.push(n<<r-o&a);else if(o>=e||n<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function O(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function U(t,e){const r=t.toString(16).padStart(2*e,"0").match(/../g);if(!r)throw new Error(`Invalid hex conversion: ${t}`);return r.reverse().join("")}function N(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+U(t,2):t<=4294967295?"fe"+U(t,4):"ff"+U(t,8)}var _=[{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"}],q=[{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 R(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 L(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,_,e),[n,o]=await i.getProviders(t),s=[];for(let t=0;t<n.length;t++)s.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(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)),s=new ethers.Contract(i,q,r);let a;try{a=await s.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${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 R(e.ciphertext,e.pkpId),{url:i,auth:o}=A(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 F={hardhat:{chain:"hardhat",chainId:h.hardhat,bitcoinNetwork:d.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,allowDevSinglePriceProvider:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:h.sepolia,bitcoinNetwork:d.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:h.ethereum,bitcoinNetwork:d.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,allowDevSinglePriceProvider:!1,minBitcoinConfirmations:6}};function z(t){const e=function(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(l).join(", ")}`)}(t),r=F[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var j="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))",H={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 X(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 K=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),V=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)"]),W=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),G=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function J(t,e,r){return t.call({to:e,data:r})}async function Q(t,e){const r=new ethers.utils.Interface([j]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([j]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?X({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]}):X(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await J(t,e,K.encodeFunctionData("views",[])),[i]=K.decodeFunctionResult("views",r),[n,o,s,a,c,u,l,d]=await Promise.all([J(t,e,K.encodeFunctionData("paused",[])),J(t,e,K.encodeFunctionData("liquidationPaused",[])),J(t,e,K.encodeFunctionData("simplePsm",[])),J(t,i,V.encodeFunctionData("core",[])),J(t,i,V.encodeFunctionData("loanOps",[])),J(t,i,V.encodeFunctionData("collateralManager",[])),J(t,i,V.encodeFunctionData("liquidationManager",[])),J(t,i,V.encodeFunctionData("circuitBreaker",[]))]),h=K.decodeFunctionResult("paused",n)[0],p=K.decodeFunctionResult("liquidationPaused",o)[0],g=K.decodeFunctionResult("simplePsm",s)[0],m=V.decodeFunctionResult("core",a)[0],f=V.decodeFunctionResult("loanOps",c)[0],w=V.decodeFunctionResult("collateralManager",u)[0],y=V.decodeFunctionResult("liquidationManager",l)[0],b=V.decodeFunctionResult("circuitBreaker",d)[0],v=await J(t,f,W.encodeFunctionData("getUcdController",[])),P=await J(t,f,W.encodeFunctionData("ucdToken",[])),T=W.decodeFunctionResult("getUcdController",v)[0],$=W.decodeFunctionResult("ucdToken",P)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await J(t,e,G.encodeFunctionData("paused",[]));return G.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,A,k,x,S,C,B,M]=await Promise.all([E(m),E(f),E(w),E(y),E(b),E(T),E($),E(g)]);return X({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:A,collateralManagerPaused:k,liquidationManagerPaused:x,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var Z,Y=3600,tt=1500,et=[{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 BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],rt=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],it=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=v.create("BTC UTXO Invalidator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing required parameter "chain"');const i=z(t),n=P(),c=n.publicKey;if(!c||"string"!=typeof c)throw new Error('Missing required parameter "publicKey"');const l=globalThis.contractAddresses;if(!l)throw new Error('Missing "contractAddresses"');const d=l.PositionManager,h=l.BTCSpendAuthorizer;if(!d||!h)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const p=globalThis.auth;if(!p||"object"!=typeof p)throw new Error('Missing or invalid "auth" parameter');const{positionId:g,utxoTxid:f,utxoVout:w,timestamp:y,signature:b,chainId:v,action:T}=p;if(!g||!f||"number"!=typeof w)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof y||!b||"number"!=typeof v)throw new Error("auth requires { timestamp, signature, chainId }");if(T!==u)throw new Error(`auth.action must be "${u}" (got "${T}")`);const $=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()}(g);let E;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(E=globalThis.rpcUrl,console.log(` RPC 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}(E)}`)):E=await Lit.Actions.getRpcUrl({chain:t});const I=new ethers.providers.JsonRpcProvider(E),A=await async function(t){return(await L(t))[0]}({policy:i,ethersProvider:I,registryAddress:l.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});new C({providerUrl:A.url,auth:A.auth});!function(t,e){const r=H[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}))}("btcTransactionSign",await Q(I,d)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const k=new ethers.Contract(h,et,I),x=await k.getAuthorizedSpends($);let D=null;for(const t of x)if(t.txid.toLowerCase()===f.toLowerCase()&&Number(t.vout)===w){D=t;break}if(!D)throw new Error(`No AuthorizedSpend on-chain for ${f}:${w} under position ${$}`);const _=BigInt(D.authorizedAt.toString()),q=BigInt(D.satoshis.toString()),R=BigInt(Math.floor(Date.now()/1e3));if(R-_<BigInt(Y))throw new Error(`AuthorizedSpend not yet stale: age=${(R-_).toString()}s, required=${Y}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const F=new ethers.Contract(d,it,I),j=await F.core(),X=new ethers.Contract(j,rt,I),K=await X.getPositionDetails($),V=K.borrower??K[1],W=K.vaultAddress??K[3];if(!V||V===ethers.constants.AddressZero)throw new Error(`Position ${$} not found or no borrower set`);if(!W)throw new Error(`Position ${$} missing vaultAddress`);if(v!==i.chainId)throw new Error(`auth.chainId (${v}) \u2260 policy.chainId (${i.chainId})`);if(!await m.verifyRecoveryAuthorization({positionId:$,timestamp:y,chainId:v,utxoTxid:f,utxoVout:w,action:T,signature:b},V,i.chainId,I,l.PositionDelegateRegistry))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const G=15e3,J=!!A.auth&&"esplora"!==A.auth.provider,Z=await(async()=>{try{const t=await async function(t,e,r){const i=Date.now()+r,n=await S(e,r),o=Math.max(1,i-Date.now()),s=new AbortController,a=setTimeout((()=>s.abort()),o);try{return await fetch(t,{headers:n,signal:s.signal})}finally{clearTimeout(a)}}(`${A.url}/tx/${f}/outspends`,A.auth,G);if(!t.ok){if(J)throw new Error(`Cannot verify UTXO spend status: ${A.name} GET /tx/${f}/outspends \u2192 ${t.status} ${t.statusText}`);return null}return await t.json()}catch(t){if(J)throw t;return null}})();if(Z&&Z[w]&&Z[w].spent){const t=Z[w].txid??"unknown";return console.log(` \u2139\ufe0f UTXO already spent by ${t}; short-circuiting to recovery-validator path`),e.stepEnd("4"),{success:!0,alreadySpent:{spendingTxid:t},positionId:$,utxoTxid:f,utxoVout:w,authorizedAt:_.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const nt=await B(c,i.bitcoinNetwork);if(W&&nt.toLowerCase()!==W.toLowerCase())throw new Error(`Derived PKP address ${nt} \u2260 on-chain vaultAddress ${W}`);if(e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx"),tt<s)throw new Error(`INVALIDATOR_FEE_SATS (${tt}) < MIN_BTC_FEE_SATS (${s})`);if(tt>a)throw new Error(`INVALIDATOR_FEE_SATS (${tt}) > MAX_BTC_FEE_SATS (${a})`);const ot=Number(q)-tt;if(ot<Number(o))throw new Error(`Invalidator output (${ot} sats) below dust limit; UTXO too small to recover`);const st={txid:f,vout:w,value:Number(q),scriptPubKey:""};st.scriptPubKey=M(nt);const{txHex:at,sigHashes:ct}=function(t){const{utxos:e,destination:r,amount:i,changeAddress:n,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",a="ffffffff",c="00000000",u=N(e.length),l=e.map((t=>O(t.txid)+U(t.vout,4)+"00"+a)).join(""),d=[],h=M(r);if(d.push(U(i,8)+N(h.length/2)+h),o>0){const t=M(n);d.push(U(o,8)+N(t.length/2)+t)}const p=N(d.length),g=d.join(""),m=s+u+l+p+g+c,f=e.map((t=>O(t.txid)+U(t.vout,4))).join(""),w=ethers.utils.sha256(ethers.utils.sha256("0x"+f)),y=e.map((()=>a)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+y)),v=ethers.utils.sha256(ethers.utils.sha256("0x"+g));return{txHex:m,sigHashes:e.map((t=>{const e=O(t.txid)+U(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",i=s+w.slice(2)+b.slice(2)+e+r+U(t.value,8)+a+v.slice(2)+c+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+i))}))}}({utxos:[st],destination:nt,amount:ot,changeAddress:nt,changeAmount:0,network:i.bitcoinNetwork,pkpPublicKey:c});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const ut=n.pkpId;if(!ut)throw new Error('Missing required parameter "pkpId"');const lt=await Lit.Actions.getPrivateKey({pkpId:ut}),dt="string"==typeof lt?lt.startsWith("0x")?lt:`0x${lt}`:String(lt),ht=new ethers.utils.SigningKey(dt),pt=[];for(let t=0;t<ct.length;t++){const e=ht.signDigest(ct[t]);pt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:at,sigHashes:ct,signatures:pt,pkpPublicKey:c,pkpBtcAddress:nt,invalidatorAmount:ot,networkFee:tt,utxo:{txid:f,vout:w,value:Number(q)},authorization:{authorizedAt:_.toString(),positionId:$},timestamp:Date.now(),action:"btc-utxo-invalidator"}}catch(t){return console.error(`[BTC UTXO Invalidator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"btc-utxo-invalidator"}}}return Z=n,((n,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===s||t(n,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return n})(t({},"__esModule",{value:!0}),Z)})();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
|
+
4c75ae20614bad806cc045411344bf298568ad9c08e89db5c98b1d8a6360e410
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "btc-utxo-invalidator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 104646,
|
|
4
|
+
"minifiedSize": 45400,
|
|
5
|
+
"compressionRatio": 0.5661563748256024,
|
|
6
|
+
"hash": "4c75ae20614bad806cc045411344bf298568ad9c08e89db5c98b1d8a6360e410",
|
|
7
|
+
"buildTime": 1781559387243,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|