@gvnrdao/dh-lit-actions 0.0.321 → 0.0.322

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/agent-module-executor.action.js +1 -1
  9. package/dist/agent-module-executor.hash +1 -1
  10. package/dist/agent-module-executor.meta.json +5 -5
  11. package/dist/btc-address-balance.meta.json +1 -1
  12. package/dist/btc-transaction-signer.action.js +1 -1
  13. package/dist/btc-transaction-signer.hash +1 -1
  14. package/dist/btc-transaction-signer.meta.json +5 -5
  15. package/dist/btc-utxo-invalidator.action.js +1 -1
  16. package/dist/btc-utxo-invalidator.hash +1 -1
  17. package/dist/btc-utxo-invalidator.meta.json +5 -5
  18. package/dist/btc-withdrawal.action.js +1 -1
  19. package/dist/btc-withdrawal.hash +1 -1
  20. package/dist/btc-withdrawal.meta.json +5 -5
  21. package/dist/encrypt-parameter.meta.json +1 -1
  22. package/dist/extend-position-validator.action.js +1 -1
  23. package/dist/extend-position-validator.hash +1 -1
  24. package/dist/extend-position-validator.meta.json +5 -5
  25. package/dist/liquidation-validator.meta.json +1 -1
  26. package/dist/loan-vault-btc-balance.meta.json +1 -1
  27. package/dist/pkp-validator.meta.json +1 -1
  28. package/dist/price-oracle.meta.json +1 -1
  29. package/dist/process-payment-validator.action.js +1 -1
  30. package/dist/process-payment-validator.hash +1 -1
  31. package/dist/process-payment-validator.meta.json +5 -5
  32. package/dist/stale-spend-recovery-validator.action.js +1 -1
  33. package/dist/stale-spend-recovery-validator.hash +1 -1
  34. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  35. package/dist/ucd-mint-validator.action.js +1 -1
  36. package/dist/ucd-mint-validator.hash +1 -1
  37. package/dist/ucd-mint-validator.meta.json +5 -5
  38. package/package.json +1 -1
  39. package/pkg-dist/pkg-src/index.d.ts +15 -0
  40. package/pkg-dist/pkg-src/index.d.ts.map +1 -1
  41. package/pkg-dist/pkg-src/index.js +151 -40
  42. package/pkg-dist/pkg-src/index.js.map +3 -3
  43. package/pkg-dist/src/constants/borrower-authorization-types.d.ts +126 -0
  44. package/pkg-dist/src/constants/borrower-authorization-types.d.ts.map +1 -0
  45. package/pkg-dist/src/constants/index.d.ts +1 -0
  46. package/pkg-dist/src/constants/index.d.ts.map +1 -1
  47. package/pkg-dist/src/modules/authorization.module.d.ts +67 -7
  48. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  49. package/pkg-dist/src/modules/bitcoin/dust.d.ts +24 -0
  50. package/pkg-dist/src/modules/bitcoin/dust.d.ts.map +1 -0
  51. package/pkg-dist/src/modules/bitcoin/invalidator-classification.d.ts +53 -6
  52. package/pkg-dist/src/modules/bitcoin/invalidator-classification.d.ts.map +1 -1
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{main:()=>main});var o=25e14,s=546n,a=100,c=1e5,u=60,l="btc-utxo-invalidator",d=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(d||{}),h={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},p={ethereum:1,sepolia:11155111,hardhat:1337};function f(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(", ")}`)}function g(t){return Math.floor(t/u)*u}async function m(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=52}(t))return;let r;r=e>=52?u-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: ${g(Math.floor(Date.now()/1e3))}`)}var w=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),n=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,n){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,n){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],n),o=await i.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,n,i){try{const o=new ethers.Contract(n,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],i);if("renew"===r){const[r]=await o.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await o.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[s,,a]=await o.canMint(t,e);return{ok:!0===s,effectiveFloorBps:Number(a)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,n,i){if(!n.module||!n.factory||!n.registry)return!1;const o=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],i);if(!0!==await o.isModuleEnabled(n.module))return!1;const s=new ethers.Contract(n.factory,["function isFromFactory(address) view returns (bool)"],i);if(!0!==await s.isFromFactory(n.module))return!1;const a=new ethers.Contract(n.module,["function safe() view returns (address)","function agent() view returns (address)"],i),c=await a.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const u=await a.agent();if(!u||u.toLowerCase()!==e.toLowerCase())return!1;const l=new ethers.Contract(n.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],i),[d,,h]=await l.canWithdraw(t,u);return!0===d&&(n.outcome={effectiveFloorBps:Number(h)},!0)}static async verifyActionAuthorization(t,e,r,n){const i=Math.floor(Date.now()/1e3);await m();const o=n?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const n=e??Math.floor(Date.now()/1e3),i=g(n),o=g(t);if(r?.strictCurrentQuantum){if(o!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${i}`);return}const s=i-u,a=i+u;if(o!==s&&o!==i&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${i} (current), ${a} (next)]`);if(o===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===n?.strictCurrentQuantum})}catch{return!1}const s=e();let a="0x0000000000000000000000000000000000000000";try{a=await this.recoverSigner(s,t.signature)}catch{}return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,n,i,o,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,n,o,i)}return!1}))}static async verifyMintAuthorization(t,e,r,n,i,o){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,i,o)}static async verifyPaymentAuthorization(t,e,r,n,i,o){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,i,o)}static async verifyWithdrawAuthorization(e,r,n,i,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,n,r,o,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,n,i){if(e.action!==l)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,n,o)=>e.toLowerCase()===r.toLowerCase()||!(!i||!await t.checkEIP1271(r,n,o,i))))}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,n,i,o,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,n,o,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,n,i,o){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,n,i,o)}static async verifyBtcExecutionAuthorization(e,r,n,i,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,n,r,o,i)}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 y(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 v(...t){y()&&console.log(...t)}var $=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,n=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${n}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 n=Date.now()-r;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-i;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 n=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${n}%)`)}}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}},P=class{static create(t="LIT Action",e){return y(e)?new b(t):new $}};function T(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function E(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function x(t){return t instanceof Error&&"AbortError"===t.name}var I="https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token";function A(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function S(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&A(r,"provider url"),{url:r,auth:{provider:"esplora"}};let n;try{n=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof n.url||0===n.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=n.url.trim();switch(n.provider){case void 0:case"esplora":return e?.requireHttps&&A(i,"esplora provider url"),{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof n.apiKey||0===n.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return A(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:n.apiKey}};case"blockstream-enterprise":{if("string"!=typeof n.clientId||0===n.clientId.length||"string"!=typeof n.clientSecret||0===n.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");A(i,"blockstream-enterprise provider url");const t="string"==typeof n.tokenUrl&&n.tokenUrl.length>0;return t&&A(n.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:n.clientId,clientSecret:n.clientSecret,...t?{tokenUrl:n.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(n.provider)}"`)}}var k=new Map,C=1e4;async function B(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||I,n=`${r}\n${t.clientId}`,i=k.get(n);if(i)return i;const o=(async()=>{const n=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,i=new AbortController,o=setTimeout((()=>i.abort()),e&&e>0?e:C);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,signal:i.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(n))),k.set(n,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function M(t,e){if(!Number.isSafeInteger(t)||t<0||t>o)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var U=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=P.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await B(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(),n=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),v(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const i=await n.text();if(i.trim().startsWith("<!DOCTYPE")||i.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(i.trim(),10);if(isNaN(o)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),x(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: ${E(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: ${E(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${E(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return M(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,n=[];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 i=t.txid,o=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");M(s,`parseBlockstreamUTXOs ${i}:${o}`),n.push({txid:i,vout:o,satoshis:BigInt(s),confirmations:r})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const n=new AbortController,i=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[o,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:n.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(i),v(`[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: ${E(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(i),this.logger.stepEnd("1"),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],n=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}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(E(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${E(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=i-o;return{utxos:r,totalBalance:i,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 n=new AbortController,i=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),o=await fetch(r,{signal:n.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(i),v(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`);const s=await o.json();if(!s.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=s.chain_stats.funded_txo_sum,c=s.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);M(a,`getBalance ${e} funded_txo_sum`),M(c,`getBalance ${e} spent_txo_sum`);const u=a-c;M(u,`getBalance ${e} confirmed balance`);const l=BigInt(u);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(i),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=E(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=E(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const n=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),v(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.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 n=(await r.text()).trim(),i=Number.parseInt(n,10);if(!Number.isFinite(i)||i<=0)return{txid:o.txid??t,confirmations:1};const s=i-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),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(E(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 n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const i=await n.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return M(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),x(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function O(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),n=e.slice(66,130),i=(BigInt("0x"+n)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+i);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",i=[];for(let t=0;t<r.length;t+=2)i.push(parseInt(r.substr(t,2),16));const o=q(i,8,5,!0),s=[e,...o],a=function(t,e){const r=N(t).concat(e).concat([0,0,0,0,0,0]),n=1^_(r),i=[];for(let t=0;t<6;t++)i.push(n>>5*(5-t)&31);return i}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=n[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function D(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const i=r;if(i.length>90)throw new Error(`Bech32 address too long (${i.length} > 90): ${t}`);const o=i.lastIndexOf("1");if(o<1||o+7>i.length)throw new Error(`Invalid bech32 separator position in ${t}`);const s=i.slice(0,o),a=i.slice(o+1),c=[];for(let r=0;r<a.length;r++){const n=e.indexOf(a[r]);if(-1===n)throw new Error(`Invalid bech32 character '${a[r]}' in ${t}`);c.push(n)}const u=c[0];if(void 0===u||u<0||u>16)throw new Error(`Invalid witness version ${u} in ${t}`);const l=0===u?F:R;if(_(N(s).concat(c))!==l)throw new Error(`Invalid bech32${0===u?"":"m"} checksum for ${t}`);const d=q(c.slice(1,c.length-6),5,8,!1);if(d.length<2||d.length>40)throw new Error(`Invalid witness program length ${d.length} in ${t}`);if(0===u&&20!==d.length&&32!==d.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${d.length} in ${t}`);const h=d.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:u,program:h}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let n=0;n<t.length;n++){const i=e.indexOf(t[n]);if(i<0)throw new Error(`Invalid Base58 character: ${t[n]}`);r=58n*r+BigInt(i)}let n=r.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),n=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==n)throw new Error(`Invalid Base58Check checksum for ${t}`);const i=parseInt(r.slice(0,2),16),o=r.slice(2);return{version:i,hash:o}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}function N(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}function _(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let n=0;n<t.length;n++){const i=r>>25;r=(33554431&r)<<5^t[n];for(let t=0;t<5;t++)i>>t&1&&(r^=e[t])}return r}var F=1,R=734539939;function q(t,e,r,n){let i=0,o=0;const s=[],a=(1<<r)-1;for(let n=0;n<t.length;n++){const c=t[n];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,o+=e;o>=r;)o-=r,s.push(i>>o&a)}if(n)o>0&&s.push(i<<r-o&a);else if(o>=e||i<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function L(t){const{utxos:e,destination:r,amount:n,changeAddress:i,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",c="ffffffff",u="00000000",l=j(e.length),d=e.map((t=>z(t.txid)+X(t.vout,4)+"00"+c)).join(""),h=[],p=D(r);if(h.push(X(n,8)+j(p.length/2)+p),o>0){const t=D(i),e=function(t){const e=t.toLowerCase();return e.startsWith("0014")?294:e.startsWith("0020")||e.startsWith("5120")?330:Number(s)}(t);o<e?console.log(`[bitcoin/transaction] Sub-dust change of ${o} sats folded into the miner fee (dust limit ${e} sats for this script type \u2014 an output would be non-standard)`):h.push(X(o,8)+j(t.length/2)+t)}const f=j(h.length),g=h.join(""),m=a+l+d+f+g+u,w=e.map((t=>z(t.txid)+X(t.vout,4))).join(""),y=ethers.utils.sha256(ethers.utils.sha256("0x"+w)),v=e.map((()=>c)).join(""),$=ethers.utils.sha256(ethers.utils.sha256("0x"+v)),b=ethers.utils.sha256(ethers.utils.sha256("0x"+g));return{txHex:m,sigHashes:e.map((t=>{const e=z(t.txid)+X(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+y.slice(2)+$.slice(2)+e+r+X(t.value,8)+c+b.slice(2)+u+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}function z(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 X(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`numToLittleEndianHex: value must be a non-negative safe integer (got ${t})`);let r=t.toString(16).padStart(2*e,"0");if(r.length>2*e)throw new Error(`numToLittleEndianHex: value ${t} does not fit in ${e} byte(s)`);const n=r.match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function j(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+X(t,2):t<=4294967295?"fe"+X(t,4):"ff"+X(t,8)}var H=[{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"}],K=[{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 W(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),n="string"==typeof e?e:String(e??"");if(!n)throw new Error("Decrypt returned empty plaintext");return n}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function V(t){const{policy:e,ethersProvider:r,registryAddress:n,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!n)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 n=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 n=new ethers.Contract(r,H,e),[i,o]=await n.getProviders(t),s=[];for(let t=0;t<i.length;t++)s.push({providerId:i[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(t.chainId,e,r);if(n.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${n.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:n}=t;if(!n||"string"!=typeof n)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),s=new ethers.Contract(n,K,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 i=[];for(const e of n){const r=await W(e.ciphertext,e.pkpId),{url:n,auth:o}=S(r,{requireHttps:!0});i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:n,auth:o,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return i}(e,r,n)}var G=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new U({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const n=this.providerConfigs,i=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const o=new Set,s=t.filter((t=>t.confirmations>=r));for(const t of s)o.add(`${t.txid}:${t.vout}`);if(!n||n.length<=1||!i)return o;const a=t=>n[t].name||n[t].providerUrl,c=await Promise.allSettled(i.slice(1).map((t=>t.getUTXOSet(e,r)))),u=c.map(((t,e)=>({r:t,name:a(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${n.length-1} secondary provider(s): ${u.join("; ")}`);const l=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of s){const e=`${t.txid}:${t.vout}`;let n=t.confirmations,i=t.confirmations;for(let r=0;r<l.length;r++){const o=l[r].get(e),s=a(r+1);if(!o)throw new Error(`Confirmed UTXO ${e} present on ${a(0)} but absent on ${s}; refusing to sign (possible fabricated UTXO).`);if(o.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${s}=${o.value.toString()}; refusing to sign.`);o.confirmations<n&&(n=o.confirmations),o.confirmations>i&&(i=o.confirmations)}if(i-n>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${i-n} exceeds tolerance 3 (min ${n}, max ${i}); providers disagree on depth, refusing to sign.`);n<r&&(o.delete(e),d.push(e))}d.length>0&&v(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<l.length;t++){const e=a(t+1);for(const[n,i]of l[t]){if(i.confirmations<r)continue;const t=h.get(n);if(!t)throw new Error(`Confirmed UTXO ${n} present on ${e} (${i.confirmations} confs) but absent on ${a(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==i.value)throw new Error(`Confirmed UTXO ${n} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${e}=${i.value.toString()}; refusing to sign.`);if(i.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${n} depth disagreement: ${a(0)}=${t.confirmations} vs ${e}=${i.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return o}async classifySelfChange(t,e,r){const n=this.providerConfigs,i=this.readers,o=new Set,s=t.filter((t=>t.confirmations<r));if(0===s.length)return o;if(this.assertProviderFloor("classifySelfChange"),!n||0===n.length||!i)return v(`[VaultBalance] ${s.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),o;const a=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of s){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),l=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),d=l.slice(0,5),h=l.length-d.length;h>0&&v(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const n=new Array(t.length);let i=0;const o=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=i++;if(e>=t.length)return;n[e]=await r(t[e])}}));return await Promise.all(o),n}(d,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),a,r,n,i)}))),f=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of s)f.has(t.txid)&&o.add(`${t.txid}:${t.vout}`);return f.size>0&&v(`[VaultBalance] self-change: ${o.size}/${s.length} unconfirmed UTXO(s) verified as protocol change by ${n.length} provider(s)`),o}async verifyParentIsSelfSpendConsensus(t,e,r,n,i,o){const s=t=>i[t].name||i[t].providerUrl,a=await Promise.allSettled(i.map(((i,s)=>this.evaluateParentForProvider(t,e,r,n,o[s],i)))),c=a.map(((t,e)=>({r:t,name:s(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${i.length} provider(s): ${c.join("; ")}`);const u=a.map((t=>t.value)),l=u.map((t=>t.selfSpend)),d=l.map(((t,e)=>({vote:t,name:s(e)}))).filter((t=>t.vote!==l[0])).map((t=>`${s(0)}=${l[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!l[0])return!1;const h=u.map(((t,e)=>t.outputMismatch?`${s(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,n,i,o){const s=await this.fetchParentTransaction(t,o);if(!s||0===s.inputs.length)return{selfSpend:!1,outputMismatch:null};const a=await this.verifyInputsAreSelfSpend(s.inputs,r,n,i),c=a?function(t,e,r){for(const n of t){const t=e.find((t=>t.index===n.vout));if(!t)return`claimed output ${n.txid}:${n.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${n.txid}:${n.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==n.satoshis)return`claimed output ${n.txid}:${n.vout} value ${t.value?.toString()??"<missing>"} != reported ${n.satoshis.toString()}`}return null}(e,s.outputs,r):null;return{selfSpend:a,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,n){const i=[...new Set(t.map((t=>t.txid)))],o=new Map,s=i.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(s.map((async t=>{o.set(t,await n.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=o.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const a=await Promise.all(i.map((t=>n.getTransaction(t))));for(const t of a)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,n=new AbortController,i=setTimeout((()=>n.abort()),r);try{const i=await fetch(`${e.providerUrl}/tx/${t}`,{signal:n.signal,headers:await B(e.auth,r)});if(!i.ok){if(404===i.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();if(!o.vin||!Array.isArray(o.vin)||0===o.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const s=[];for(const e of o.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);s.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:s,outputs:Array.isArray(o.vout)?o.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(x(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(i)}}};var J=11,Q=68,Z=34;function Y(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return h[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var tt={hardhat:{chain:"hardhat",chainId:p.hardhat,bitcoinNetwork:h.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:p.sepolia,bitcoinNetwork:h.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:p.ethereum,bitcoinNetwork:h.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var et={hardhat:30,sepolia:30,ethereum:3600};var rt="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))",nt={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 it(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 ot=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),st=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)"]),at=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),ct=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function ut(t,e,r){return t.call({to:e,data:r})}async function lt(t,e){const r=new ethers.utils.Interface([rt]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([rt]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?it({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]}):it(e)}(await t.call({to:e,data:r}))}catch(t){n=t}try{return await async function(t,e){const r=await ut(t,e,ot.encodeFunctionData("views",[])),[n]=ot.decodeFunctionResult("views",r),[i,o,s,a,c,u,l,d]=await Promise.all([ut(t,e,ot.encodeFunctionData("paused",[])),ut(t,e,ot.encodeFunctionData("liquidationPaused",[])),ut(t,e,ot.encodeFunctionData("simplePsm",[])),ut(t,n,st.encodeFunctionData("core",[])),ut(t,n,st.encodeFunctionData("loanOps",[])),ut(t,n,st.encodeFunctionData("collateralManager",[])),ut(t,n,st.encodeFunctionData("liquidationManager",[])),ut(t,n,st.encodeFunctionData("circuitBreaker",[]))]),h=ot.decodeFunctionResult("paused",i)[0],p=ot.decodeFunctionResult("liquidationPaused",o)[0],f=ot.decodeFunctionResult("simplePsm",s)[0],g=st.decodeFunctionResult("core",a)[0],m=st.decodeFunctionResult("loanOps",c)[0],w=st.decodeFunctionResult("collateralManager",u)[0],y=st.decodeFunctionResult("liquidationManager",l)[0],v=st.decodeFunctionResult("circuitBreaker",d)[0],$=await ut(t,m,at.encodeFunctionData("getUcdController",[])),b=await ut(t,m,at.encodeFunctionData("ucdToken",[])),P=at.decodeFunctionResult("getUcdController",$)[0],T=at.decodeFunctionResult("ucdToken",b)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await ut(t,e,ct.encodeFunctionData("paused",[]));return ct.decodeFunctionResult("paused",r)[0]}catch{return!1}},[x,I,A,S,k,C,B,M]=await Promise.all([E(g),E(m),E(w),E(y),E(v),E(P),E(T),E(f)]);return it({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:x,loanOperationsPaused:I,collateralManagerPaused:A,liquidationManagerPaused:S,circuitBreakerPaused:k,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var dt,ht={ethereum:20,sepolia:2,hardhat:2},pt=[{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"}],ft=[{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:"uint8",name:"status",type:"uint8"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],gt=[{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=P.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 n=function(t){const e=f(t),r=tt[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),i=T(),o=i.publicKey;if(!o||"string"!=typeof o)throw new Error('Missing required parameter "publicKey"');const u=globalThis.contractAddresses;if(!u)throw new Error('Missing "contractAddresses"');const d=u.PositionManager,h=u.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:m,utxoVout:y,timestamp:v,signature:$,chainId:b,action:P}=p;if(!g||!m||"number"!=typeof y)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof v||!$||"number"!=typeof b)throw new Error("auth requires { timestamp, signature, chainId }");if(P!==l)throw new Error(`auth.action must be "${l}" (got "${P}")`);const E=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);e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider");const x=globalThis.rpcUrl;if(!x)throw new Error('Missing required parameter "rpcUrl" \u2014 Chipotle actions cannot resolve an RPC endpoint themselves');console.log(` RPC: ${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)}`);const I=new ethers.providers.JsonRpcProvider(x);if(!n.allowArbitraryBitcoinProvider&&!u.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 btc-utxo-invalidator resolves providers from the on-chain registry (no single-provider fallback)");const A=await V({policy:n,ethersProvider:I,registryAddress:u.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});if(A.length<n.minConsensusProviders)throw new Error(`btc-utxo-invalidator requires at least ${n.minConsensusProviders} Bitcoin provider(s) on ${n.chain}; ${A.length} registered. Refusing to sign without cross-provider consensus.`);const S=A[0];console.log(` \u2705 Bitcoin providers: ${A.length} (${A.map((t=>t.name)).join(", ")})`);!function(t,e){const r=nt[t],n=[];for(const t of r)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await lt(I,d)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const k=new ethers.Contract(h,pt,I),C=await k.getAuthorizedSpends(E);let M=null;for(const t of C)if(t.txid.toLowerCase()===m.toLowerCase()&&Number(t.vout)===y){M=t;break}if(!M)throw new Error(`No AuthorizedSpend on-chain for ${m}:${y} under position ${E}`);const N=BigInt(M.authorizedAt.toString()),_=BigInt(M.satoshis.toString()),F=BigInt(Math.floor(Date.now()/1e3)),R=function(t){return et[f(t)]}(t);if(F-N<BigInt(R))throw new Error(`AuthorizedSpend not yet stale: age=${(F-N).toString()}s, required=${R}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const q=new ethers.Contract(d,gt,I),z=await q.core(),X=new ethers.Contract(z,ft,I),j=await X.getPositionDetails(E),H=j.borrower??j[4],K=j.vaultAddress??j[3];if(!H||H===ethers.constants.AddressZero)throw new Error(`Position ${E} not found or no borrower set`);if(!K)throw new Error(`Position ${E} missing vaultAddress`);const W=i.pkpId;if(!W)throw new Error('Missing required parameter "pkpId"');const rt=j.pkpId??j[1],it=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");if(!rt||it(W)!==it(rt))throw new Error(`Supplied pkpId ${W} does not match position ${E}'s on-chain pkpId ${rt??"<unset>"} \u2014 refusing to sign with a key the position does not own.`);if(b!==n.chainId)throw new Error(`auth.chainId (${b}) \u2260 policy.chainId (${n.chainId})`);if(!await w.verifyRecoveryAuthorization({positionId:E,timestamp:v,chainId:b,utxoTxid:m,utxoVout:y,action:P,signature:$},H,n.chainId,I))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const ot=15e3,st="regtest"!==n.bitcoinNetwork||!!S.auth&&"esplora"!==S.auth.provider,at=await(async()=>{try{const t=await async function(t,e,r){const n=Date.now()+r,i=await B(e,r),o=Math.max(1,n-Date.now()),s=new AbortController,a=setTimeout((()=>s.abort()),o);try{return await fetch(t,{headers:i,signal:s.signal})}finally{clearTimeout(a)}}(`${S.url}/tx/${m}/outspends`,S.auth,ot);if(!t.ok){if(st)throw new Error(`Cannot verify UTXO spend status: ${S.name} GET /tx/${m}/outspends \u2192 ${t.status} ${t.statusText}`);return null}return await t.json()}catch(t){if(st)throw t;return null}})();if(at&&at[y]&&at[y].spent){const t=at[y].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:E,utxoTxid:m,utxoVout:y,authorizedAt:N.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const ct=await O(o,n.bitcoinNetwork),ut=Y(String(K),t);if("string"!=typeof ut||0===ut.length)throw new Error(`Position ${E} has no on-chain vaultAddress for chain "${t}" \u2014 cannot bind PKP address`);const dt=ut.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");if(dt.toLowerCase()!==ct.toLowerCase())throw new Error(`Derived PKP BTC address ${ct} does not match position ${E}'s on-chain vault address ${dt} \u2014 the supplied publicKey is not this position's PKP`);e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx");const mt=t=>String(t).toLowerCase().replace(/^0x/,""),wt=new U({providerUrl:S.url,auth:S.auth}),yt=await wt.getUTXOs(ct),vt=new Map(yt.map((t=>[`${mt(t.txid)}:${Number(t.vout)}`,t]))),$t=vt.get(`${mt(m)}:${Number(y)}`);if(!$t)throw new Error(`Authorized UTXO ${m}:${y} is not an unspent output of the vault \u2014 refusing to sign`);const bt=Number($t.satoshis),Pt=BigInt(bt)!==_;Pt&&console.log(` \u26a0\ufe0f Authorization declares ${_.toString()} sats but the REAL output is ${bt} sats \u2014 building the invalidator on the real value (corrupt-record recovery)`);const Tt=n.minBitcoinSpendConfirmations,Et=new G(wt,A.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),n.minConsensusProviders),xt=function(t,e,r){const n=new Set;for(const i of t)e.has(`${i.txid}:${i.vout}`)&&n.add(`${r(i.txid)}:${Number(i.vout)}`);return n}(yt,await Et.confirmedUtxoConsensus(yt,ct,Tt),mt);!function(t,e,r,n,i){for(const o of t){const t=`${n(o.txid)}:${Number(o.vout)}`,s=e.get(t);if(!s)throw new Error(`Input ${o.txid}:${o.vout} is not an unspent output of the vault \u2014 refusing to sign`);if(s.satoshis!==BigInt(o.value))throw new Error(`Input ${o.txid}:${o.vout} declared value ${o.value} sats does not match the on-chain output value ${s.satoshis.toString()} sats \u2014 refusing to sign a corrupted sighash`);if(!r.has(t))throw new Error(`Input ${o.txid}:${o.vout} is not confirmed at the spend depth (${i}) \u2014 refusing to sign (reorg-vulnerable, or providers disagree on its depth)`)}}([{txid:m,vout:y,value:bt}],vt,xt,mt,Tt),console.log(` \u2705 Input consensus-confirmed at >=${Tt} conf across ${A.length} provider(s), value ${bt} sats`);const It=ht[t];if(!It)throw new Error(`No invalidator fee rate configured for chain "${t}"`);const At=It*function(t,e){if(!Number.isInteger(t)||t<1)throw new Error(`estimateP2WPKHVBytes: numInputs must be a positive integer (got ${t})`);if(!Number.isInteger(e)||e<1)throw new Error(`estimateP2WPKHVBytes: numOutputs must be a positive integer (got ${e})`);return J+Q*t+Z*e}(1,1);if(At<a)throw new Error(`Invalidator fee (${At}) < MIN_BTC_FEE_SATS (${a})`);if(At>c)throw new Error(`Invalidator fee (${At}) > MAX_BTC_FEE_SATS (${c})`);const St=bt-At;if(St<Number(s))throw new Error(`Invalidator output (${St} sats) below dust limit \u2014 UTXO too small to self-recover; admin path required`);const kt={txid:m,vout:y,value:bt,scriptPubKey:D(ct)},{txHex:Ct,sigHashes:Bt}=L({utxos:[kt],destination:ct,amount:St,changeAddress:ct,changeAmount:0,network:n.bitcoinNetwork,pkpPublicKey:o});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const Mt=await Lit.Actions.getPrivateKey({pkpId:W}),Ut="string"==typeof Mt?Mt.startsWith("0x")?Mt:`0x${Mt}`:String(Mt),Ot=new ethers.utils.SigningKey(Ut),Dt=[];for(let t=0;t<Bt.length;t++){const e=Ot.signDigest(Bt[t]);Dt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:Ct,sigHashes:Bt,signatures:Dt,pkpPublicKey:o,pkpBtcAddress:ct,invalidatorAmount:St,networkFee:At,utxo:{txid:m,vout:y,value:bt,scriptPubKey:kt.scriptPubKey},onchainDeclaredSatoshis:_.toString(),valueMismatch:Pt,authorization:{authorizedAt:N.toString(),positionId:E},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 dt=i,((i,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))n.call(i,c)||c===s||t(i,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return i})(t({},"__esModule",{value:!0}),dt)})();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,n=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{main:()=>main});var o=25e14,s=546n,a=100,c=1e5,u=60,d={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};var l="btc-utxo-invalidator",h={MintRequest:[{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RepayRequest:[{name:"positionId",type:"bytes32"},{name:"paymentAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RenewRequest:[{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],WithdrawRequest:[{name:"positionId",type:"bytes32"},{name:"totalDeduction",type:"uint256"},{name:"withdrawalAddress",type:"string"},{name:"quantumTimestamp",type:"uint256"}]};function p(t){const e=h[t];if(!e)throw new Error(`Unknown borrower authorization primary type "${t}"; expected one of ${Object.keys(h).join(", ")}`);return{[t]:e.map((t=>({...t})))}}function f(t,e){if(!Number.isInteger(t)||t<=0)throw new Error(`Borrower authorization domain requires a positive integer chainId, got ${String(t)}`);const r=function(t){return d[t]??null}(t),n=r?.LoanOperationsManagerModule;if(n&&e&&n.toLowerCase()!==e.toLowerCase())throw new Error(`Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${t}: caller ${e}, pinned ${n}`);const i=n??e;if(!i)throw new Error(`No pinned LoanOperationsManagerModule for chainId ${t} and no verifyingContract supplied; refusing to build a borrower authorization domain without one`);return{name:"DiamondHands.Protocol",version:"1",chainId:t,verifyingContract:i}}var m=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(m||{}),g={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},w={ethereum:1,sepolia:11155111,hardhat:1337};function y(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(m).join(", ")}`)}function v(t){return Math.floor(t/u)*u}async function $(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=52}(t))return;let r;r=e>=52?u-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: ${v(Math.floor(Date.now()/1e3))}`)}var b="0x0000000000000000000000000000000000000000",P=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),n=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,n){try{const i=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await i.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,n){try{const i=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],n),o=await i.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,n,i){try{const o=new ethers.Contract(n,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],i);if("renew"===r){const[r]=await o.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await o.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[s,,a]=await o.canMint(t,e);return{ok:!0===s,effectiveFloorBps:Number(a)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async checkSafeAgentWithdrawAuthorization(t,e,r,n,i){if(!n.module||!n.factory||!n.registry)return!1;const o=new ethers.Contract(r,["function isModuleEnabled(address) view returns (bool)"],i);if(!0!==await o.isModuleEnabled(n.module))return!1;const s=new ethers.Contract(n.factory,["function isFromFactory(address) view returns (bool)"],i);if(!0!==await s.isFromFactory(n.module))return!1;const a=new ethers.Contract(n.module,["function safe() view returns (address)","function agent() view returns (address)"],i),c=await a.safe();if(!c||c.toLowerCase()!==r.toLowerCase())return!1;const u=await a.agent();if(!u||u.toLowerCase()!==e.toLowerCase())return!1;const d=new ethers.Contract(n.registry,["function canWithdraw(bytes32,address) view returns (bool,uint8,uint32)"],i),[l,,h]=await d.canWithdraw(t,u);return!0===l&&(n.outcome={effectiveFloorBps:Number(h)},!0)}static async verifyActionAuthorization(t,e,r,n){const i=Math.floor(Date.now()/1e3);await $();const o=n?.strictCurrentQuantum?i:void 0;try{!function(t,e,r){const n=e??Math.floor(Date.now()/1e3),i=v(n),o=v(t);if(r?.strictCurrentQuantum){if(o!==i)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${i}`);return}const s=i-u,a=i+u;if(o!==s&&o!==i&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${i} (current), ${a} (next)]`);if(o===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===n?.strictCurrentQuantum})}catch{return!1}const s=e(),a="string"==typeof s?{legacy:s}:s;{const e=a.legacy;let n=b;try{n=await this.recoverSigner(e,t.signature)}catch{}if(await r(n,e,t.signature))return!0}if(a.typed){const{domain:e,types:n,message:i}=a.typed;let o;try{o=ethers.utils._TypedDataEncoder.hash(e,n,i)}catch(t){throw new Error(`Failed to compute EIP-712 digest for ${a.typed.primaryType}: ${t instanceof Error?t.message:String(t)}`)}let s=b;try{s=ethers.utils.recoverAddress(o,t.signature)}catch{}if(await r(s,o,t.signature))return!0}return!1}static async verifyAmountPositionActionAuthorization(e,r,n,i,o,s,a){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t],o=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i);if(!a)return o;const s="MintRequest"===a.primaryType?"mintAmount":"paymentAmount";return{legacy:o,typed:{domain:f(n,a.verifyingContract),types:p(a.primaryType),primaryType:a.primaryType,message:{positionId:e.positionId,[s]:r.toString(),quantumTimestamp:e.timestamp}}}}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,n,o,i)}return!1}))}static async verifyMintAuthorization(t,e,r,n,i,o,s){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,i,o,{primaryType:"MintRequest",verifyingContract:s})}static async verifyPaymentAuthorization(t,e,r,n,i,o,s){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,i,o,{primaryType:"RepayRequest",verifyingContract:s})}static async verifyWithdrawAuthorization(e,r,n,i,o,s){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return{legacy:ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i),typed:{domain:f(n,s),types:p("WithdrawRequest"),primaryType:"WithdrawRequest",message:{positionId:e.positionId,totalDeduction:r.toString(),withdrawalAddress:e.destinationAddress,quantumTimestamp:e.timestamp}}}}),(async(n,s,a)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,n,r,o,i)}return!1}))}static async verifyRecoveryAuthorization(e,r,n,i){if(e.action!==l)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,n,o)=>e.toLowerCase()===r.toLowerCase()||!(!i||!await t.checkEIP1271(r,n,o,i))))}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,n,i,o,s,a){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t],i=ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r);return a?{legacy:i,typed:{domain:f(n,a.verifyingContract),types:p(a.primaryType),primaryType:a.primaryType,message:{positionId:e.positionId,selectedTerm:e.newTerm,quantumTimestamp:e.timestamp}}}:i}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,a,c,i))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,i);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(o)return t.checkPositionDelegate(e.positionId,n,o,i)}return!1}))}static async verifyExtendAuthorization(t,e,r,n,i,o,s){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,n,i,o,{primaryType:"RenewRequest",verifyingContract:s})}static async verifyBtcExecutionAuthorization(e,r,n,i,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],n)}),(async(n,s,a)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(i){if(await t.checkEIP1271(r,s,a,i))return!0;if(o)return t.checkSafeAgentWithdrawAuthorization(e.positionId,n,r,o,i)}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 T(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 E(...t){T()&&console.log(...t)}var x=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}},A=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,n=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${n}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 n=Date.now()-r;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const i=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-i;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 n=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${n}%)`)}}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}},I=class{static create(t="LIT Action",e){return T(e)?new A(t):new x}};function C(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function S(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function k(t){return t instanceof Error&&"AbortError"===t.name}var B="https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token";function M(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function D(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&M(r,"provider url"),{url:r,auth:{provider:"esplora"}};let n;try{n=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof n.url||0===n.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const i=n.url.trim();switch(n.provider){case void 0:case"esplora":return e?.requireHttps&&M(i,"esplora provider url"),{url:i,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof n.apiKey||0===n.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return M(i,"maestro provider url"),{url:i,auth:{provider:"maestro",apiKey:n.apiKey}};case"blockstream-enterprise":{if("string"!=typeof n.clientId||0===n.clientId.length||"string"!=typeof n.clientSecret||0===n.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");M(i,"blockstream-enterprise provider url");const t="string"==typeof n.tokenUrl&&n.tokenUrl.length>0;return t&&M(n.tokenUrl,"blockstream-enterprise tokenUrl"),{url:i,auth:{provider:"blockstream-enterprise",clientId:n.clientId,clientSecret:n.clientSecret,...t?{tokenUrl:n.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(n.provider)}"`)}}var O=new Map,U=1e4;async function F(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||B,n=`${r}\n${t.clientId}`,i=O.get(n);if(i)return i;const o=(async()=>{const n=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,i=new AbortController,o=setTimeout((()=>i.abort()),e&&e>0?e:U);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,signal:i.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((()=>O.delete(n))),O.set(n,o),o}(t,e);return{Authorization:`Bearer ${r}`}}}}function R(t,e){if(!Number.isSafeInteger(t)||t<0||t>o)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var q=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=I.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await F(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(),n=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),E(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const i=await n.text();if(i.trim().startsWith("<!DOCTYPE")||i.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(i.trim(),10);if(isNaN(o)){const t=i.length>200?i.substring(0,200)+"... (truncated)":i;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),k(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: ${S(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: ${S(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${S(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return R(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,n=[];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 i=t.txid,o=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===i||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");R(s,`parseBlockstreamUTXOs ${i}:${o}`),n.push({txid:i,vout:o,satoshis:BigInt(s),confirmations:r})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const n=new AbortController,i=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[o,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:n.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(i),E(`[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: ${S(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(i),this.logger.stepEnd("1"),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],n=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}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(S(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${S(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const i=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=i-o;return{utxos:r,totalBalance:i,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 n=new AbortController,i=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),o=await fetch(r,{signal:n.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(i),E(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!o.ok)throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`);const s=await o.json();if(!s.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=s.chain_stats.funded_txo_sum,c=s.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);R(a,`getBalance ${e} funded_txo_sum`),R(c,`getBalance ${e} spent_txo_sum`);const u=a-c;R(u,`getBalance ${e} confirmed balance`);const d=BigInt(u);return this.logger.log("3",`Balance: ${d.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),d}catch(t){if(clearTimeout(i),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=S(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=S(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 n=Date.now(),i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),E(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.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 n=(await r.text()).trim(),i=Number.parseInt(n,10);if(!Number.isFinite(i)||i<=0)return{txid:o.txid??t,confirmations:1};const s=i-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),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(S(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 n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const i=await n.json();return i.vout&&Array.isArray(i.vout)?i.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return R(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),k(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function N(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),n=e.slice(66,130),i=(BigInt("0x"+n)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+i);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",i=[];for(let t=0;t<r.length;t+=2)i.push(parseInt(r.substr(t,2),16));const o=H(i,8,5,!0),s=[e,...o],a=function(t,e){const r=L(t).concat(e).concat([0,0,0,0,0,0]),n=1^z(r),i=[];for(let t=0;t<6;t++)i.push(n>>5*(5-t)&31);return i}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=n[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function _(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const i=r;if(i.length>90)throw new Error(`Bech32 address too long (${i.length} > 90): ${t}`);const o=i.lastIndexOf("1");if(o<1||o+7>i.length)throw new Error(`Invalid bech32 separator position in ${t}`);const s=i.slice(0,o),a=i.slice(o+1),c=[];for(let r=0;r<a.length;r++){const n=e.indexOf(a[r]);if(-1===n)throw new Error(`Invalid bech32 character '${a[r]}' in ${t}`);c.push(n)}const u=c[0];if(void 0===u||u<0||u>16)throw new Error(`Invalid witness version ${u} in ${t}`);const d=0===u?j:X;if(z(L(s).concat(c))!==d)throw new Error(`Invalid bech32${0===u?"":"m"} checksum for ${t}`);const l=H(c.slice(1,c.length-6),5,8,!1);if(l.length<2||l.length>40)throw new Error(`Invalid witness program length ${l.length} in ${t}`);if(0===u&&20!==l.length&&32!==l.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${l.length} in ${t}`);const h=l.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:u,program:h}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let n=0;n<t.length;n++){const i=e.indexOf(t[n]);if(i<0)throw new Error(`Invalid Base58 character: ${t[n]}`);r=58n*r+BigInt(i)}let n=r.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),n=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==n)throw new Error(`Invalid Base58Check checksum for ${t}`);const i=parseInt(r.slice(0,2),16),o=r.slice(2);return{version:i,hash:o}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}function L(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}function z(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let n=0;n<t.length;n++){const i=r>>25;r=(33554431&r)<<5^t[n];for(let t=0;t<5;t++)i>>t&1&&(r^=e[t])}return r}var j=1,X=734539939;function H(t,e,r,n){let i=0,o=0;const s=[],a=(1<<r)-1;for(let n=0;n<t.length;n++){const c=t[n];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(i=i<<e|c,o+=e;o>=r;)o-=r,s.push(i>>o&a)}if(n)o>0&&s.push(i<<r-o&a);else if(o>=e||i<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function K(t){const{utxos:e,destination:r,amount:n,changeAddress:i,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",c="ffffffff",u="00000000",d=G(e.length),l=e.map((t=>W(t.txid)+V(t.vout,4)+"00"+c)).join(""),h=[],p=_(r);if(h.push(V(n,8)+G(p.length/2)+p),o>0){const t=_(i),e=function(t){const e=t.toLowerCase();return e.startsWith("0014")?294:e.startsWith("0020")||e.startsWith("5120")?330:Number(s)}(t);o<e?console.log(`[bitcoin/transaction] Sub-dust change of ${o} sats folded into the miner fee (dust limit ${e} sats for this script type \u2014 an output would be non-standard)`):h.push(V(o,8)+G(t.length/2)+t)}const f=G(h.length),m=h.join(""),g=a+d+l+f+m+u,w=e.map((t=>W(t.txid)+V(t.vout,4))).join(""),y=ethers.utils.sha256(ethers.utils.sha256("0x"+w)),v=e.map((()=>c)).join(""),$=ethers.utils.sha256(ethers.utils.sha256("0x"+v)),b=ethers.utils.sha256(ethers.utils.sha256("0x"+m));return{txHex:g,sigHashes:e.map((t=>{const e=W(t.txid)+V(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+y.slice(2)+$.slice(2)+e+r+V(t.value,8)+c+b.slice(2)+u+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}function W(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 V(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`numToLittleEndianHex: value must be a non-negative safe integer (got ${t})`);let r=t.toString(16).padStart(2*e,"0");if(r.length>2*e)throw new Error(`numToLittleEndianHex: value ${t} does not fit in ${e} byte(s)`);const n=r.match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function G(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+V(t,2):t<=4294967295?"fe"+V(t,4):"ff"+V(t,8)}var J=[{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 Z(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),n="string"==typeof e?e:String(e??"");if(!n)throw new Error("Decrypt returned empty plaintext");return n}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function Y(t){const{policy:e,ethersProvider:r,registryAddress:n,devBitcoinProviderUrl:i}=t;if(e.allowArbitraryBitcoinProvider){if(!i)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:i,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!n)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 n=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 n=new ethers.Contract(r,J,e),[i,o]=await n.getProviders(t),s=[];for(let t=0;t<i.length;t++)s.push({providerId:i[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(t.chainId,e,r);if(n.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${n.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:n}=t;if(!n||"string"!=typeof n)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const i=globalThis.ipfsId;if("string"!=typeof i||0===i.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(i)),s=new ethers.Contract(n,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 i=[];for(const e of n){const r=await Z(e.ciphertext,e.pkpId),{url:n,auth:o}=D(r,{requireHttps:!0});i.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:n,auth:o,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return i}(e,r,n)}var tt=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new q({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const n=this.providerConfigs,i=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const o=new Set,s=t.filter((t=>t.confirmations>=r));for(const t of s)o.add(`${t.txid}:${t.vout}`);if(!n||n.length<=1||!i)return o;const a=t=>n[t].name||n[t].providerUrl,c=await Promise.allSettled(i.slice(1).map((t=>t.getUTXOSet(e,r)))),u=c.map(((t,e)=>({r:t,name:a(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${n.length-1} secondary provider(s): ${u.join("; ")}`);const d=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),l=[];for(const t of s){const e=`${t.txid}:${t.vout}`;let n=t.confirmations,i=t.confirmations;for(let r=0;r<d.length;r++){const o=d[r].get(e),s=a(r+1);if(!o)throw new Error(`Confirmed UTXO ${e} present on ${a(0)} but absent on ${s}; refusing to sign (possible fabricated UTXO).`);if(o.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${s}=${o.value.toString()}; refusing to sign.`);o.confirmations<n&&(n=o.confirmations),o.confirmations>i&&(i=o.confirmations)}if(i-n>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${i-n} exceeds tolerance 3 (min ${n}, max ${i}); providers disagree on depth, refusing to sign.`);n<r&&(o.delete(e),l.push(e))}l.length>0&&E(`[VaultBalance] confirmed-consensus: ${l.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${l.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<d.length;t++){const e=a(t+1);for(const[n,i]of d[t]){if(i.confirmations<r)continue;const t=h.get(n);if(!t)throw new Error(`Confirmed UTXO ${n} present on ${e} (${i.confirmations} confs) but absent on ${a(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==i.value)throw new Error(`Confirmed UTXO ${n} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${e}=${i.value.toString()}; refusing to sign.`);if(i.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${n} depth disagreement: ${a(0)}=${t.confirmations} vs ${e}=${i.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return o}async classifySelfChange(t,e,r){const n=this.providerConfigs,i=this.readers,o=new Set,s=t.filter((t=>t.confirmations<r));if(0===s.length)return o;if(this.assertProviderFloor("classifySelfChange"),!n||0===n.length||!i)return E(`[VaultBalance] ${s.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),o;const a=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of s){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),d=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),l=d.slice(0,5),h=d.length-l.length;h>0&&E(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const n=new Array(t.length);let i=0;const o=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=i++;if(e>=t.length)return;n[e]=await r(t[e])}}));return await Promise.all(o),n}(l,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),a,r,n,i)}))),f=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of s)f.has(t.txid)&&o.add(`${t.txid}:${t.vout}`);return f.size>0&&E(`[VaultBalance] self-change: ${o.size}/${s.length} unconfirmed UTXO(s) verified as protocol change by ${n.length} provider(s)`),o}async verifyParentIsSelfSpendConsensus(t,e,r,n,i,o){const s=t=>i[t].name||i[t].providerUrl,a=await Promise.allSettled(i.map(((i,s)=>this.evaluateParentForProvider(t,e,r,n,o[s],i)))),c=a.map(((t,e)=>({r:t,name:s(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${i.length} provider(s): ${c.join("; ")}`);const u=a.map((t=>t.value)),d=u.map((t=>t.selfSpend)),l=d.map(((t,e)=>({vote:t,name:s(e)}))).filter((t=>t.vote!==d[0])).map((t=>`${s(0)}=${d[0]} vs ${t.name}=${t.vote}`));if(l.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${l.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!d[0])return!1;const h=u.map(((t,e)=>t.outputMismatch?`${s(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,n,i,o){const s=await this.fetchParentTransaction(t,o);if(!s||0===s.inputs.length)return{selfSpend:!1,outputMismatch:null};const a=await this.verifyInputsAreSelfSpend(s.inputs,r,n,i),c=a?function(t,e,r){for(const n of t){const t=e.find((t=>t.index===n.vout));if(!t)return`claimed output ${n.txid}:${n.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${n.txid}:${n.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==n.satoshis)return`claimed output ${n.txid}:${n.vout} value ${t.value?.toString()??"<missing>"} != reported ${n.satoshis.toString()}`}return null}(e,s.outputs,r):null;return{selfSpend:a,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,n){const i=[...new Set(t.map((t=>t.txid)))],o=new Map,s=i.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(s.map((async t=>{o.set(t,await n.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=o.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const a=await Promise.all(i.map((t=>n.getTransaction(t))));for(const t of a)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,n=new AbortController,i=setTimeout((()=>n.abort()),r);try{const i=await fetch(`${e.providerUrl}/tx/${t}`,{signal:n.signal,headers:await F(e.auth,r)});if(!i.ok){if(404===i.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.json();if(!o.vin||!Array.isArray(o.vin)||0===o.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const s=[];for(const e of o.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);s.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:s,outputs:Array.isArray(o.vout)?o.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(k(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(i)}}};var et=11,rt=68,nt=34;function it(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return g[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var ot={hardhat:{chain:"hardhat",chainId:w.hardhat,bitcoinNetwork:g.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:w.sepolia,bitcoinNetwork:g.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:w.ethereum,bitcoinNetwork:g.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var st={hardhat:30,sepolia:30,ethereum:3600};var at="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))",ct={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 ut(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 dt=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),lt=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)"]),ht=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),pt=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function ft(t,e,r){return t.call({to:e,data:r})}async function mt(t,e){const r=new ethers.utils.Interface([at]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([at]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?ut({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]}):ut(e)}(await t.call({to:e,data:r}))}catch(t){n=t}try{return await async function(t,e){const r=await ft(t,e,dt.encodeFunctionData("views",[])),[n]=dt.decodeFunctionResult("views",r),[i,o,s,a,c,u,d,l]=await Promise.all([ft(t,e,dt.encodeFunctionData("paused",[])),ft(t,e,dt.encodeFunctionData("liquidationPaused",[])),ft(t,e,dt.encodeFunctionData("simplePsm",[])),ft(t,n,lt.encodeFunctionData("core",[])),ft(t,n,lt.encodeFunctionData("loanOps",[])),ft(t,n,lt.encodeFunctionData("collateralManager",[])),ft(t,n,lt.encodeFunctionData("liquidationManager",[])),ft(t,n,lt.encodeFunctionData("circuitBreaker",[]))]),h=dt.decodeFunctionResult("paused",i)[0],p=dt.decodeFunctionResult("liquidationPaused",o)[0],f=dt.decodeFunctionResult("simplePsm",s)[0],m=lt.decodeFunctionResult("core",a)[0],g=lt.decodeFunctionResult("loanOps",c)[0],w=lt.decodeFunctionResult("collateralManager",u)[0],y=lt.decodeFunctionResult("liquidationManager",d)[0],v=lt.decodeFunctionResult("circuitBreaker",l)[0],$=await ft(t,g,ht.encodeFunctionData("getUcdController",[])),b=await ft(t,g,ht.encodeFunctionData("ucdToken",[])),P=ht.decodeFunctionResult("getUcdController",$)[0],T=ht.decodeFunctionResult("ucdToken",b)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await ft(t,e,pt.encodeFunctionData("paused",[]));return pt.decodeFunctionResult("paused",r)[0]}catch{return!1}},[x,A,I,C,S,k,B,M]=await Promise.all([E(m),E(g),E(w),E(y),E(v),E(P),E(T),E(f)]);return ut({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:x,loanOperationsPaused:A,collateralManagerPaused:I,liquidationManagerPaused:C,circuitBreakerPaused:S,ucdControllerPaused:k,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var gt,wt={ethereum:20,sepolia:2,hardhat:2},yt=[{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"}],vt=[{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:"uint8",name:"status",type:"uint8"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],$t=[{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=I.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 n=function(t){const e=y(t),r=ot[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}(t),i=C(),o=i.publicKey;if(!o||"string"!=typeof o)throw new Error('Missing required parameter "publicKey"');const u=globalThis.contractAddresses;if(!u)throw new Error('Missing "contractAddresses"');const d=u.PositionManager,h=u.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:f,utxoTxid:m,utxoVout:g,timestamp:w,signature:v,chainId:$,action:b}=p;if(!f||!m||"number"!=typeof g)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof w||!v||"number"!=typeof $)throw new Error("auth requires { timestamp, signature, chainId }");if(b!==l)throw new Error(`auth.action must be "${l}" (got "${b}")`);const T=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()}(f);e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider");const E=globalThis.rpcUrl;if(!E)throw new Error('Missing required parameter "rpcUrl" \u2014 Chipotle actions cannot resolve an RPC endpoint themselves');console.log(` RPC: ${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)}`);const x=new ethers.providers.JsonRpcProvider(E);if(!n.allowArbitraryBitcoinProvider&&!u.BitcoinProviderRegistry)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 btc-utxo-invalidator resolves providers from the on-chain registry (no single-provider fallback)");const A=await Y({policy:n,ethersProvider:x,registryAddress:u.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});if(A.length<n.minConsensusProviders)throw new Error(`btc-utxo-invalidator requires at least ${n.minConsensusProviders} Bitcoin provider(s) on ${n.chain}; ${A.length} registered. Refusing to sign without cross-provider consensus.`);const I=A[0];console.log(` \u2705 Bitcoin providers: ${A.length} (${A.map((t=>t.name)).join(", ")})`);!function(t,e){const r=ct[t],n=[];for(const t of r)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await mt(x,d)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const S=new ethers.Contract(h,yt,x),k=await S.getAuthorizedSpends(T);let B=null;for(const t of k)if(t.txid.toLowerCase()===m.toLowerCase()&&Number(t.vout)===g){B=t;break}if(!B)throw new Error(`No AuthorizedSpend on-chain for ${m}:${g} under position ${T}`);const M=BigInt(B.authorizedAt.toString()),D=BigInt(B.satoshis.toString()),O=BigInt(Math.floor(Date.now()/1e3)),U=function(t){return st[y(t)]}(t);if(O-M<BigInt(U))throw new Error(`AuthorizedSpend not yet stale: age=${(O-M).toString()}s, required=${U}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const R=new ethers.Contract(d,$t,x),L=await R.core(),z=new ethers.Contract(L,vt,x),j=await z.getPositionDetails(T),X=j.borrower??j[4],H=j.vaultAddress??j[3];if(!X||X===ethers.constants.AddressZero)throw new Error(`Position ${T} not found or no borrower set`);if(!H)throw new Error(`Position ${T} missing vaultAddress`);const W=i.pkpId;if(!W)throw new Error('Missing required parameter "pkpId"');const V=j.pkpId??j[1],G=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");if(!V||G(W)!==G(V))throw new Error(`Supplied pkpId ${W} does not match position ${T}'s on-chain pkpId ${V??"<unset>"} \u2014 refusing to sign with a key the position does not own.`);if($!==n.chainId)throw new Error(`auth.chainId (${$}) \u2260 policy.chainId (${n.chainId})`);if(!await P.verifyRecoveryAuthorization({positionId:T,timestamp:w,chainId:$,utxoTxid:m,utxoVout:g,action:b,signature:v},X,n.chainId,x))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const J=15e3,Q="regtest"!==n.bitcoinNetwork||!!I.auth&&"esplora"!==I.auth.provider,Z=await(async()=>{try{const t=await async function(t,e,r){const n=Date.now()+r,i=await F(e,r),o=Math.max(1,n-Date.now()),s=new AbortController,a=setTimeout((()=>s.abort()),o);try{return await fetch(t,{headers:i,signal:s.signal})}finally{clearTimeout(a)}}(`${I.url}/tx/${m}/outspends`,I.auth,J);if(!t.ok){if(Q)throw new Error(`Cannot verify UTXO spend status: ${I.name} GET /tx/${m}/outspends \u2192 ${t.status} ${t.statusText}`);return null}return await t.json()}catch(t){if(Q)throw t;return null}})();if(Z&&Z[g]&&Z[g].spent){const t=Z[g].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:T,utxoTxid:m,utxoVout:g,authorizedAt:M.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const at=await N(o,n.bitcoinNetwork),ut=it(String(H),t);if("string"!=typeof ut||0===ut.length)throw new Error(`Position ${T} has no on-chain vaultAddress for chain "${t}" \u2014 cannot bind PKP address`);const dt=ut.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");if(dt.toLowerCase()!==at.toLowerCase())throw new Error(`Derived PKP BTC address ${at} does not match position ${T}'s on-chain vault address ${dt} \u2014 the supplied publicKey is not this position's PKP`);e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx");const lt=t=>String(t).toLowerCase().replace(/^0x/,""),ht=new q({providerUrl:I.url,auth:I.auth}),pt=await ht.getUTXOs(at),ft=new Map(pt.map((t=>[`${lt(t.txid)}:${Number(t.vout)}`,t]))),gt=ft.get(`${lt(m)}:${Number(g)}`);if(!gt)throw new Error(`Authorized UTXO ${m}:${g} is not an unspent output of the vault \u2014 refusing to sign`);const bt=Number(gt.satoshis),Pt=BigInt(bt)!==D;Pt&&console.log(` \u26a0\ufe0f Authorization declares ${D.toString()} sats but the REAL output is ${bt} sats \u2014 building the invalidator on the real value (corrupt-record recovery)`);const Tt=n.minBitcoinSpendConfirmations,Et=new tt(ht,A.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),n.minConsensusProviders),xt=function(t,e,r){const n=new Set;for(const i of t)e.has(`${i.txid}:${i.vout}`)&&n.add(`${r(i.txid)}:${Number(i.vout)}`);return n}(pt,await Et.confirmedUtxoConsensus(pt,at,Tt),lt);!function(t,e,r,n,i){for(const o of t){const t=`${n(o.txid)}:${Number(o.vout)}`,s=e.get(t);if(!s)throw new Error(`Input ${o.txid}:${o.vout} is not an unspent output of the vault \u2014 refusing to sign`);if(s.satoshis!==BigInt(o.value))throw new Error(`Input ${o.txid}:${o.vout} declared value ${o.value} sats does not match the on-chain output value ${s.satoshis.toString()} sats \u2014 refusing to sign a corrupted sighash`);if(!r.has(t))throw new Error(`Input ${o.txid}:${o.vout} is not confirmed at the spend depth (${i}) \u2014 refusing to sign (reorg-vulnerable, or providers disagree on its depth)`)}}([{txid:m,vout:g,value:bt}],ft,xt,lt,Tt),console.log(` \u2705 Input consensus-confirmed at >=${Tt} conf across ${A.length} provider(s), value ${bt} sats`);const At=wt[t];if(!At)throw new Error(`No invalidator fee rate configured for chain "${t}"`);const It=At*function(t,e){if(!Number.isInteger(t)||t<1)throw new Error(`estimateP2WPKHVBytes: numInputs must be a positive integer (got ${t})`);if(!Number.isInteger(e)||e<1)throw new Error(`estimateP2WPKHVBytes: numOutputs must be a positive integer (got ${e})`);return et+rt*t+nt*e}(1,1);if(It<a)throw new Error(`Invalidator fee (${It}) < MIN_BTC_FEE_SATS (${a})`);if(It>c)throw new Error(`Invalidator fee (${It}) > MAX_BTC_FEE_SATS (${c})`);const Ct=bt-It;if(Ct<Number(s))throw new Error(`Invalidator output (${Ct} sats) below dust limit \u2014 UTXO too small to self-recover; admin path required`);const St={txid:m,vout:g,value:bt,scriptPubKey:_(at)},{txHex:kt,sigHashes:Bt}=K({utxos:[St],destination:at,amount:Ct,changeAddress:at,changeAmount:0,network:n.bitcoinNetwork,pkpPublicKey:o});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const Mt=await Lit.Actions.getPrivateKey({pkpId:W}),Dt="string"==typeof Mt?Mt.startsWith("0x")?Mt:`0x${Mt}`:String(Mt),Ot=new ethers.utils.SigningKey(Dt),Ut=[];for(let t=0;t<Bt.length;t++){const e=Ot.signDigest(Bt[t]);Ut.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:kt,sigHashes:Bt,signatures:Ut,pkpPublicKey:o,pkpBtcAddress:at,invalidatorAmount:Ct,networkFee:It,utxo:{txid:m,vout:g,value:bt,scriptPubKey:St.scriptPubKey},onchainDeclaredSatoshis:D.toString(),valueMismatch:Pt,authorization:{authorizedAt:M.toString(),positionId:T},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 gt=i,((i,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))n.call(i,c)||c===s||t(i,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return i})(t({},"__esModule",{value:!0}),gt)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -1 +1 @@
1
- 1dcea2b49e545c423195be22e072dc5e3039ed1c95a8490b23505956029f5b33
1
+ 603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-utxo-invalidator",
3
- "originalSize": 152174,
4
- "minifiedSize": 62553,
5
- "compressionRatio": 0.5889376634641923,
6
- "hash": "1dcea2b49e545c423195be22e072dc5e3039ed1c95a8490b23505956029f5b33",
7
- "buildTime": 1787171881633,
3
+ "originalSize": 159006,
4
+ "minifiedSize": 66026,
5
+ "compressionRatio": 0.5847578078814636,
6
+ "hash": "603bc50920d7f1dee77086f2c518d9e2922ab3858a419d3fbea8221ea3a6d9e9",
7
+ "buildTime": 1788340135302,
8
8
  "version": "0.1.0"
9
9
  }