@gvnrdao/dh-lit-actions 0.0.300 → 0.0.302

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 (44) hide show
  1. package/dist/address-probe-signer.meta.json +1 -1
  2. package/dist/address-probe.meta.json +1 -1
  3. package/dist/always-signer.meta.json +1 -1
  4. package/dist/authorization-dummy-b.meta.json +1 -1
  5. package/dist/authorization-dummy.meta.json +1 -1
  6. package/dist/btc-transaction-signer.action.js +1 -1
  7. package/dist/btc-transaction-signer.hash +1 -1
  8. package/dist/btc-transaction-signer.meta.json +5 -5
  9. package/dist/btc-utxo-invalidator.action.js +1 -1
  10. package/dist/btc-utxo-invalidator.hash +1 -1
  11. package/dist/btc-utxo-invalidator.meta.json +5 -5
  12. package/dist/btc-withdrawal.action.js +1 -1
  13. package/dist/btc-withdrawal.hash +1 -1
  14. package/dist/btc-withdrawal.meta.json +5 -5
  15. package/dist/encrypt-parameter.meta.json +1 -1
  16. package/dist/ethers-version-probe.meta.json +1 -1
  17. package/dist/extend-position-validator.action.js +1 -1
  18. package/dist/extend-position-validator.hash +1 -1
  19. package/dist/extend-position-validator.meta.json +5 -5
  20. package/dist/liquidation-validator.action.js +1 -1
  21. package/dist/liquidation-validator.hash +1 -1
  22. package/dist/liquidation-validator.meta.json +5 -5
  23. package/dist/loan-vault-btc-balance.action.js +1 -1
  24. package/dist/loan-vault-btc-balance.hash +1 -1
  25. package/dist/loan-vault-btc-balance.meta.json +5 -5
  26. package/dist/pkp-validator.meta.json +1 -1
  27. package/dist/price-oracle.meta.json +1 -1
  28. package/dist/process-payment-sign-only.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.js +41 -41
  40. package/pkg-dist/pkg-src/index.js.map +1 -1
  41. package/pkg-dist/src/modules/authorization.module.d.ts +25 -0
  42. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
  43. package/pkg-dist/src/modules/bitcoin-provider-registry.d.ts +28 -0
  44. package/pkg-dist/src/modules/bitcoin-provider-registry.d.ts.map +1 -1
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1418,
5
5
  "compressionRatio": 0.4642992066490367,
6
6
  "hash": "b66a469b07b3ba5d753ff8726775188d32450b3e6a77b91404c8d5e8114be9e8",
7
- "buildTime": 1779831976224,
7
+ "buildTime": 1779878463634,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 856,
5
5
  "compressionRatio": 0.4751686082158185,
6
6
  "hash": "bc0bcb38452275c93fa74c5240ae496d7a3eef9d38e7fb0dd99c5202c554d5e3",
7
- "buildTime": 1779831976231,
7
+ "buildTime": 1779878463643,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 4143,
5
5
  "compressionRatio": 0.5279170464904284,
6
6
  "hash": "25007f80b4ed3169470bf617d403971136be431eb29dfb09f78afe2494bf0138",
7
- "buildTime": 1779831976257,
7
+ "buildTime": 1779878463668,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1695,
5
5
  "compressionRatio": 0.46292775665399244,
6
6
  "hash": "def4576ba6c382d145f996c4f950b5e39e58792415ee7fdd749e0d2bc61e8f0b",
7
- "buildTime": 1779831976264,
7
+ "buildTime": 1779878463676,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 2026,
5
5
  "compressionRatio": 0.48197391971362824,
6
6
  "hash": "349d51aa096d56b394f82de75ed34cd4eef72719969f7e5fe584f4582b2745fa",
7
- "buildTime": 1779831976273,
7
+ "buildTime": 1779878463684,
8
8
  "version": "0.1.0"
9
9
  }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,r={};async function i(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const n=e.slice(2,66),o=e.slice(66,130),r=(BigInt("0x"+o)%2n===0n?"02":"03")+n,i=ethers.utils.sha256("0x"+r);let a;a="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const u=function(t,e,n){const o="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=[];for(let t=0;t<n.length;t+=2)r.push(parseInt(n.substr(t,2),16));const i=s(r,8,5,!0),a=[e,...i],u=function(t,e){const n=function(t){const e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n)>>5);e.push(0);for(let n=0;n<t.length;n++)e.push(31&t.charCodeAt(n));return e}(t).concat(e).concat([0,0,0,0,0,0]),o=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let n=1;for(let o=0;o<t.length;o++){const r=n>>25;n=(33554431&n)<<5^t[o];for(let t=0;t<5;t++)r>>t&1&&(n^=e[t])}return n}(n),r=[];for(let t=0;t<6;t++)r.push(o>>5*(5-t)&31);return r}(t,a),c=[...a,...u];let d=t+"1";for(let t=0;t<c.length;t++)d+=o[c[t]];return d}(a,0,ethers.utils.ripemd160(i).slice(2));return u}function a(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=t.lastIndexOf("1");if(n<1)throw new Error("No separator character for bech32");t.substring(0,n).toLowerCase();const o=t.substring(n+1).toLowerCase(),r=[];for(let t=0;t<o.length;t++){const n=e.indexOf(o[t]);if(-1===n)throw new Error(`Invalid bech32 character: ${o[t]}`);r.push(n)}const i=r.slice(0,-6),a=(i[0],s(i.slice(1),5,8,!1));return{witnessProgram:a.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let n=0n;for(let o=0;o<t.length;o++){const r=e.indexOf(t[o]);if(r<0)throw new Error(`Invalid Base58 character: ${t[o]}`);n=58n*n+BigInt(r)}let o=n.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function s(t,e,n,o){let r=0,i=0;const a=[],s=(1<<n)-1;for(let o=0;o<t.length;o++){const u=t[o];if(u<0||u>>e)throw new Error("Invalid data for bit conversion");for(r=r<<e|u,i+=e;i>=n;)i-=n,a.push(r>>i&s)}if(o)i>0&&a.push(r<<n-i&s);else if(i>=e||r<<n-i&s)throw new Error("Invalid padding in bit conversion");return a}function u(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 c(t,e){const n=t.toString(16).padStart(2*e,"0").match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function d(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+c(t,2):t<=4294967295?"fe"+c(t,4):"ff"+c(t,8)}((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(r,{main:()=>main});var l=100,g=1e5,h=60,p={ethereum:1,sepolia:11155111,hardhat:1337};function f(t){return Math.floor(t/h)*h}async function w(){const t=Math.floor(Date.now()/1e3),e=t%h;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%h;return e<8||e>=52}(t))return;let n;n=e>=52?h-e+8:8-e,console.log(`[Quantum] Waiting ${n}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*n))),console.log(`[Quantum] Safe quantum ready: ${f(Math.floor(Date.now()/1e3))}`)}var m=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const n=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(n);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,n,o){try{const r=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await r.isValidSignature(e,n)}catch{return!1}}static async checkPositionDelegate(t,e,n,o){try{const r=new ethers.Contract(n,["function positionDelegate(bytes32) view returns (address)"],o),i=await r.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,n,o){const r=Math.floor(Date.now()/1e3);await w();const i=o?.strictCurrentQuantum?r:void 0;try{!function(t,e,n){const o=e??Math.floor(Date.now()/1e3),r=f(o),i=f(t);if(n?.strictCurrentQuantum){if(i!==r)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${r}`);return}const a=r-h,s=r+h;if(i!==a&&i!==r&&i!==s)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${a} (past), ${r} (current), ${s} (next)]`);if(i===a){if(o<a+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${a}). This is unsafe due to boundary instability.`)}else if(i===s&&o>=s+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${s}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const a=e(),s=await this.recoverSigner(a,t.signature);return await n(s,a,t.signature)}static async verifyAmountPositionActionAuthorization(e,n,o,r,i){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,n.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,a,s,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyMintAuthorization(t,e,n,o,r){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,n,o,r)}static async verifyPaymentAuthorization(t,e,n,o,r){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,n,o,r)}static async verifyWithdrawAuthorization(e,n,o,r,i){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,n.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,a,s,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyRecoveryAuthorization(e,n,o,r,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],n)}),(async(o,a,s)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,a,s,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,n,o,r,i){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(o,a,s)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,a,s,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyExtendAuthorization(t,e,n,o,r){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,n,o,r)}static async verifyBtcExecutionAuthorization(e,n,o,r,i){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,n.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(o,a,s)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,a,s,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}),{strictCurrentQuantum:!0})}};function y(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}var P="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))",b={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 v(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 A,I=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),T=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)"]),k=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),$=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function x(t,e,n){return t.call({to:e,data:n})}async function C(t,e){const n=new ethers.utils.Interface([P]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([P]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?v({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]}):v(e)}(await t.call({to:e,data:n}))}catch(t){o=t}try{return await async function(t,e){const n=await x(t,e,I.encodeFunctionData("views",[])),[o]=I.decodeFunctionResult("views",n),[r,i,a,s,u,c,d,l]=await Promise.all([x(t,e,I.encodeFunctionData("paused",[])),x(t,e,I.encodeFunctionData("liquidationPaused",[])),x(t,e,I.encodeFunctionData("simplePsm",[])),x(t,o,T.encodeFunctionData("core",[])),x(t,o,T.encodeFunctionData("loanOps",[])),x(t,o,T.encodeFunctionData("collateralManager",[])),x(t,o,T.encodeFunctionData("liquidationManager",[])),x(t,o,T.encodeFunctionData("circuitBreaker",[]))]),g=I.decodeFunctionResult("paused",r)[0],h=I.decodeFunctionResult("liquidationPaused",i)[0],p=I.decodeFunctionResult("simplePsm",a)[0],f=T.decodeFunctionResult("core",s)[0],w=T.decodeFunctionResult("loanOps",u)[0],m=T.decodeFunctionResult("collateralManager",c)[0],y=T.decodeFunctionResult("liquidationManager",d)[0],P=T.decodeFunctionResult("circuitBreaker",l)[0],b=await x(t,w,k.encodeFunctionData("getUcdController",[])),A=await x(t,w,k.encodeFunctionData("ucdToken",[])),C=k.decodeFunctionResult("getUcdController",b)[0],E=k.decodeFunctionResult("ucdToken",A)[0],M=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const n=await x(t,e,$.encodeFunctionData("paused",[]));return $.decodeFunctionResult("paused",n)[0]}catch{return!1}},[S,q,O,L,B,D,z,F]=await Promise.all([M(f),M(w),M(m),M(y),M(P),M(C),M(E),M(p)]);return v({positionManagerPaused:g,positionManagerLiquidationsPaused:h,positionManagerCorePaused:S,loanOperationsPaused:q,collateralManagerPaused:O,liquidationManagerPaused:L,circuitBreakerPaused:B,ucdControllerPaused:D,ucdTokenPaused:z,simplePsmPaused:F})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),n=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${n})`)}}async function main(t){for(const[e,n]of Object.entries(t))globalThis[e]=n;const e=y();console.log("[Step 0] Validating configuration...");const n=e.chain,o=e.bitcoinNetwork;if(!n)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!o)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(o))throw new Error(`Invalid bitcoinNetwork: "${o}". Must be "mainnet", "testnet", or "regtest"`);const r=e.auth;if(!r||"object"!=typeof r)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!r.positionId)throw new Error("auth.positionId is required");if(!r.utxo||"object"!=typeof r.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===r.networkFee||r.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!r.targetAddress||"string"!=typeof r.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===r.targetAmount||null===r.targetAmount)throw new Error("auth.targetAmount is required");if(!r.utxo.txid||void 0===r.utxo.vout||!r.utxo.value||!r.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const s=r.positionId,h=r.utxo,f=r.utxos&&r.utxos.length>0?r.utxos:[h],w=r.networkFee;console.log(" \u2705 Parameters validated"),console.log(` Position: ${s}`),console.log(` UTXOs to spend: ${f.length}`),console.log(` Network fee: ${w} sats`),console.log(` Bitcoin network: ${o}`);const P=e.publicKey;if(!P)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof P||0===P.length)throw new Error("Invalid publicKey: must be non-empty string");const v=P;if(!e.contractAddresses||!e.contractAddresses.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!e.contractAddresses.PositionManager)throw new Error("contractAddresses.PositionManager is required");const A=e.contractAddresses.LoanOperationsManagerModule,I=e.contractAddresses.PositionManager,T=e.contractAddresses.BTCSpendAuthorizer??A;console.log(" \u2705 Contract addresses loaded from parameters");let k="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${s}`),console.log(` UTXO: ${h.txid}:${h.vout} (${h.value} sats)`),k="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;let y;t&&"string"==typeof t?(console.log(` \u2705 Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(t)}`),y=t):(console.log(" \u26a0\ufe0f No custom RPC URL provided, falling back to Lit.Actions.getRpcUrl()"),console.log(" \u26a0\ufe0f This may timeout or fail if Lit RPC service is slow/unavailable"),y=await Lit.Actions.getRpcUrl({chain:n}),console.log(` Using LIT-provided RPC URL for chain: ${n}`));const P=new ethers.providers.JsonRpcProvider(y);!function(t,e){const n=b[t],o=[];for(const t of n)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("btcTransactionSign",await C(P,I)),k="2",console.log("[Step 2] UTXO existence check..."),console.log(` UTXO: ${h.txid}:${h.vout}`),console.log(" \u26a0\ufe0f UTXO existence check deferred to Bitcoin consensus"),console.log(" \u2705 Proceeding (Bitcoin will reject if spent)"),k="3",console.log("[Step 3] Querying authorization from contract...");const A=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],$=new ethers.Contract(T,A,P),x=await $.getAuthorizedSpends(s);let E=null;for(const t of x){const e=t.txid.toLowerCase(),n=h.txid.toLowerCase(),o=Number(t.vout),r=Number(h.vout);if(e===n&&o===r){E=t;break}}if(!E)throw new Error(`No authorization found for UTXO ${h.txid}:${h.vout}`);const M=BigInt(E.targetAmount.toString()),S=E.targetAddress,q=BigInt(E.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${S}`),console.log(` Authorized at: ${q.toString()}`),k="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const O=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],L=new ethers.Contract(I,O,P),B=await L.core();console.log(` Core facet address: ${B}`);const D=[{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"}],z=new ethers.Contract(B,D,P),F=await z.getPositionDetails(s);let U;if(5===F.status){if(!e.contractAddresses?.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(e.contractAddresses.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],P),n=await t.pkpOwners(F.pkpId);if(!n||n===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");U=n,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${U}`)}else U=F.borrower;console.log(` Position owner: ${U}`);const R=`${h.txid}:${h.vout}`,j=await m.verifyBtcExecutionAuthorization({positionId:r.positionId,timestamp:r.timestamp,chainId:r.chainId,utxoIdentifier:R,networkFee:r.networkFee,targetAddress:r.targetAddress,targetAmount:r.targetAmount,action:"execute-btc-withdrawal",signature:r.signature},U,function(t){return p[t]}(n),P,globalThis.contractAddresses?.PositionDelegateRegistry);if(!j)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const K=String(S);if(r.targetAddress.toLowerCase()!==K.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${r.targetAddress}" but on-chain authorizer records "${K}"`);const N=BigInt(r.targetAmount.toString());if(N!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${N.toString()} but on-chain authorizer records ${M.toString()}`);if(k="4",console.log("[Step 4] Validating network fee..."),w>g)throw new Error(`Network fee ${w} sats exceeds maximum ${g} sats`);if(w<l)throw new Error(`Network fee ${w} sats below minimum ${l} sats`);if(BigInt(w)>=M)throw new Error(`Network fee ${w} sats cannot exceed target amount ${M.toString()} sats`);const _=Number(M)-w;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${_} sats`),k="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const X=await i(v,o);console.log(` \u2705 PKP BTC address: ${X}`),k="6",console.log("[Step 6] Validating UTXO ownership...");const Q=a(X);for(const t of f){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==Q)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${Q}, got ${e}`)}console.log(` \u2705 All ${f.length} UTXO(s) belong to vault (PKP address)`),k="7",console.log("[Step 7] Validating UTXO value...");const V=Number(M),W=f.reduce(((t,e)=>t+e.value),0);if(W<V)throw new Error(`Insufficient UTXO value: total ${W} sats across ${f.length} input(s), need ${V} sats`);const H=W-V;console.log(` \u2705 Total UTXO value sufficient (${f.length} input(s))`),console.log(` Total value: ${W} sats`),console.log(` Total required: ${V} sats`),console.log(` Change: ${H} sats`),k="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:Z,sigHashes:J}=function(t){const{utxos:e,destination:n,amount:o,changeAddress:r,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",l="ffffffff",g="00000000",h=d(e.length),p=e.map((t=>u(t.txid)+c(t.vout,4)+"00"+l)).join(""),f=[],w=a(n);if(f.push(c(o,8)+d(w.length/2)+w),i>0){const t=a(r);f.push(c(i,8)+d(t.length/2)+t)}const m=d(f.length),y=f.join(""),P=s+h+p+m+y+g,b=e.map((t=>u(t.txid)+c(t.vout,4))).join(""),v=ethers.utils.sha256(ethers.utils.sha256("0x"+b)),A=e.map((()=>l)).join(""),I=ethers.utils.sha256(ethers.utils.sha256("0x"+A)),T=ethers.utils.sha256(ethers.utils.sha256("0x"+y));return{txHex:P,sigHashes:e.map((t=>{const e=u(t.txid)+c(t.vout,4),n="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",o=s+v.slice(2)+I.slice(2)+e+n+c(t.value,8)+l+T.slice(2)+g+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+o))}))}}({utxos:f,destination:S,amount:_,changeAddress:X,changeAmount:H,network:o,pkpPublicKey:v});console.log(` \u2705 Transaction built (${f.length} input(s))`),console.log(` Signature hashes: ${J.length}`),k="9",console.log(`[Step 9] Signing ${J.length} input(s)...`);const G=globalThis.pkpId;if(!G)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const Y=await Lit.Actions.getPrivateKey({pkpId:G}),tt="string"==typeof Y?Y.startsWith("0x")?Y:`0x${Y}`:String(Y),et=new ethers.utils.SigningKey(tt),nt=[];for(let t=0;t<J.length;t++){const e=et.signDigest(J[t]);nt.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${J[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:Z,sigHashes:J,sigHash:J[0],signatures:nt,signature:nt[0],pkpPublicKey:v,pkpBtcAddress:X,destination:S,userReceivesAmount:_,networkFee:w,changeAmount:H,utxos:f.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:h.txid,vout:h.vout,value:h.value},authorization:{targetAmount:M.toString(),authorizedAt:q.toString()},timestamp:Date.now(),action:"btc-transaction-signer"}}catch(t){return console.error("[BTC Transaction Signer] \u274c Failed:",t.message),console.error(`[BTC Transaction Signer] Failed at step: ${k}`),{success:!1,error:t.message||t.toString(),positionId:r?.positionId,timestamp:Date.now()}}}return A=r,((r,i,a,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let u of n(i))o.call(r,u)||u===a||t(r,u,{get:()=>i[u],enumerable:!(s=e(i,u))||s.enumerable});return r})(t({},"__esModule",{value:!0}),A)})();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,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,r={};async function i(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const n=e.slice(2,66),o=e.slice(66,130),r=(BigInt("0x"+o)%2n===0n?"02":"03")+n,i=ethers.utils.sha256("0x"+r);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const u=function(t,e,n){const o="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=[];for(let t=0;t<n.length;t+=2)r.push(parseInt(n.substr(t,2),16));const i=a(r,8,5,!0),s=[e,...i],u=function(t,e){const n=function(t){const e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n)>>5);e.push(0);for(let n=0;n<t.length;n++)e.push(31&t.charCodeAt(n));return e}(t).concat(e).concat([0,0,0,0,0,0]),o=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let n=1;for(let o=0;o<t.length;o++){const r=n>>25;n=(33554431&n)<<5^t[o];for(let t=0;t<5;t++)r>>t&1&&(n^=e[t])}return n}(n),r=[];for(let t=0;t<6;t++)r.push(o>>5*(5-t)&31);return r}(t,s),c=[...s,...u];let d=t+"1";for(let t=0;t<c.length;t++)d+=o[c[t]];return d}(s,0,ethers.utils.ripemd160(i).slice(2));return u}function s(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=t.lastIndexOf("1");if(n<1)throw new Error("No separator character for bech32");t.substring(0,n).toLowerCase();const o=t.substring(n+1).toLowerCase(),r=[];for(let t=0;t<o.length;t++){const n=e.indexOf(o[t]);if(-1===n)throw new Error(`Invalid bech32 character: ${o[t]}`);r.push(n)}const i=r.slice(0,-6),s=(i[0],a(i.slice(1),5,8,!1));return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let n=0n;for(let o=0;o<t.length;o++){const r=e.indexOf(t[o]);if(r<0)throw new Error(`Invalid Base58 character: ${t[o]}`);n=58n*n+BigInt(r)}let o=n.toString(16);o.length%2&&(o="0"+o);for(let e=0;e<t.length&&"1"===t[e];e++)o="00"+o;return o}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function a(t,e,n,o){let r=0,i=0;const s=[],a=(1<<n)-1;for(let o=0;o<t.length;o++){const u=t[o];if(u<0||u>>e)throw new Error("Invalid data for bit conversion");for(r=r<<e|u,i+=e;i>=n;)i-=n,s.push(r>>i&a)}if(o)i>0&&s.push(r<<n-i&a);else if(i>=e||r<<n-i&a)throw new Error("Invalid padding in bit conversion");return s}function u(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 c(t,e){const n=t.toString(16).padStart(2*e,"0").match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function d(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+c(t,2):t<=4294967295?"fe"+c(t,4):"ff"+c(t,8)}((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(r,{main:()=>main});var l=100,h=1e5,g=60,p={ethereum:1,sepolia:11155111,hardhat:1337};function f(t){return Math.floor(t/g)*g}async function w(){const t=Math.floor(Date.now()/1e3),e=t%g;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%g;return e<8||e>=52}(t))return;let n;n=e>=52?g-e+8:8-e,console.log(`[Quantum] Waiting ${n}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*n))),console.log(`[Quantum] Safe quantum ready: ${f(Math.floor(Date.now()/1e3))}`)}var m=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const n=ethers.utils.arrayify(t),o=ethers.utils.hashMessage(n);return ethers.utils.recoverAddress(o,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,n,o){try{const r=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],o);return"0x1626ba7e"===await r.isValidSignature(e,n)}catch{return!1}}static async checkPositionDelegate(t,e,n,o){try{const r=new ethers.Contract(n,["function positionDelegate(bytes32) view returns (address)"],o),i=await r.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,n,o){const r=Math.floor(Date.now()/1e3);await w();const i=o?.strictCurrentQuantum?r:void 0;try{!function(t,e,n){const o=e??Math.floor(Date.now()/1e3),r=f(o),i=f(t);if(n?.strictCurrentQuantum){if(i!==r)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${r}`);return}const s=r-g,a=r+g;if(i!==s&&i!==r&&i!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${s} (past), ${r} (current), ${a} (next)]`);if(i===s){if(o<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(i===a&&o>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${o}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===o?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await n(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,n,o,r,i){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,n.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],o)}),(async(o,s,a)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyMintAuthorization(t,e,n,o,r){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,n,o,r)}static async verifyPaymentAuthorization(t,e,n,o,r){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,n,o,r)}static async verifyWithdrawAuthorization(e,n,o,r,i){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="string"==typeof e.amount?BigInt(e.amount):e.amount,o=[e.positionId,e.timestamp,e.chainId,n.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],o)}),(async(o,s,a)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyRecoveryAuthorization(e,n,o,r,i){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],n)}),(async(o,s,a)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,n,o,r,i){if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(o,s,a)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}))}static async verifyExtendAuthorization(t,e,n,o,r){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,n,o,r)}static async verifyBtcExecutionAuthorization(e,n,o,r,i){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==o)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${o})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),n="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),o=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,n.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],o)}),(async(o,s,a)=>{if(o.toLowerCase()===n.toLowerCase())return!0;if(r){if(await t.checkEIP1271(n,s,a,r))return!0;if(i)return t.checkPositionDelegate(e.positionId,o,i,r)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const n=BigInt(e);if(n!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${n.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const n=Number(e);if(!Number.isFinite(n)||n!==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(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}var P="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))",b={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 v(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 A,T=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),I=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)"]),k=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),$=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function x(t,e,n){return t.call({to:e,data:n})}async function C(t,e){const n=new ethers.utils.Interface([P]).encodeFunctionData("getProtocolPauseStatus",[]);let o;try{return function(t){const e=new ethers.utils.Interface([P]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?v({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]}):v(e)}(await t.call({to:e,data:n}))}catch(t){o=t}try{return await async function(t,e){const n=await x(t,e,T.encodeFunctionData("views",[])),[o]=T.decodeFunctionResult("views",n),[r,i,s,a,u,c,d,l]=await Promise.all([x(t,e,T.encodeFunctionData("paused",[])),x(t,e,T.encodeFunctionData("liquidationPaused",[])),x(t,e,T.encodeFunctionData("simplePsm",[])),x(t,o,I.encodeFunctionData("core",[])),x(t,o,I.encodeFunctionData("loanOps",[])),x(t,o,I.encodeFunctionData("collateralManager",[])),x(t,o,I.encodeFunctionData("liquidationManager",[])),x(t,o,I.encodeFunctionData("circuitBreaker",[]))]),h=T.decodeFunctionResult("paused",r)[0],g=T.decodeFunctionResult("liquidationPaused",i)[0],p=T.decodeFunctionResult("simplePsm",s)[0],f=I.decodeFunctionResult("core",a)[0],w=I.decodeFunctionResult("loanOps",u)[0],m=I.decodeFunctionResult("collateralManager",c)[0],y=I.decodeFunctionResult("liquidationManager",d)[0],P=I.decodeFunctionResult("circuitBreaker",l)[0],b=await x(t,w,k.encodeFunctionData("getUcdController",[])),A=await x(t,w,k.encodeFunctionData("ucdToken",[])),C=k.decodeFunctionResult("getUcdController",b)[0],E=k.decodeFunctionResult("ucdToken",A)[0],M=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const n=await x(t,e,$.encodeFunctionData("paused",[]));return $.decodeFunctionResult("paused",n)[0]}catch{return!1}},[S,q,O,L,B,D,z,F]=await Promise.all([M(f),M(w),M(m),M(y),M(P),M(C),M(E),M(p)]);return v({positionManagerPaused:h,positionManagerLiquidationsPaused:g,positionManagerCorePaused:S,loanOperationsPaused:q,collateralManagerPaused:O,liquidationManagerPaused:L,circuitBreakerPaused:B,ucdControllerPaused:D,ucdTokenPaused:z,simplePsmPaused:F})}(t,e)}catch(t){const e=o instanceof Error?o.message:String(o),n=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${n})`)}}async function main(t){for(const[e,n]of Object.entries(t))globalThis[e]=n;const e=y();console.log("[Step 0] Validating configuration...");const n=e.chain,o=e.bitcoinNetwork;if(!n)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!o)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(o))throw new Error(`Invalid bitcoinNetwork: "${o}". Must be "mainnet", "testnet", or "regtest"`);const r=e.auth;if(!r||"object"!=typeof r)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!r.positionId)throw new Error("auth.positionId is required");if(!r.utxo||"object"!=typeof r.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===r.networkFee||r.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!r.targetAddress||"string"!=typeof r.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===r.targetAmount||null===r.targetAmount)throw new Error("auth.targetAmount is required");if(!r.utxo.txid||void 0===r.utxo.vout||!r.utxo.value||!r.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const a=r.positionId,g=r.utxo,f=r.utxos&&r.utxos.length>0?r.utxos:[g],w=r.networkFee;console.log(" \u2705 Parameters validated"),console.log(` Position: ${a}`),console.log(` UTXOs to spend: ${f.length}`),console.log(` Network fee: ${w} sats`),console.log(` Bitcoin network: ${o}`);const P=e.publicKey;if(!P)throw new Error('Missing required parameter: "publicKey"');if("string"!=typeof P||0===P.length)throw new Error("Invalid publicKey: must be non-empty string");const v=P;if(!e.contractAddresses||!e.contractAddresses.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!e.contractAddresses.PositionManager)throw new Error("contractAddresses.PositionManager is required");const A=e.contractAddresses.LoanOperationsManagerModule,T=e.contractAddresses.PositionManager,I=e.contractAddresses.BTCSpendAuthorizer??A;console.log(" \u2705 Contract addresses loaded from parameters");let k="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${a}`),console.log(` UTXO: ${g.txid}:${g.vout} (${g.value} sats)`),k="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;let y;t&&"string"==typeof t?(console.log(` \u2705 Using RPC URL override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(t)}`),y=t):(console.log(" \u26a0\ufe0f No custom RPC URL provided, falling back to Lit.Actions.getRpcUrl()"),console.log(" \u26a0\ufe0f This may timeout or fail if Lit RPC service is slow/unavailable"),y=await Lit.Actions.getRpcUrl({chain:n}),console.log(` Using LIT-provided RPC URL for chain: ${n}`));const P=new ethers.providers.JsonRpcProvider(y);!function(t,e){const n=b[t],o=[];for(const t of n)e[t]&&o.push(t);if(o.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:o,status:e}))}("btcTransactionSign",await C(P,T)),k="2",console.log("[Step 2] UTXO existence check..."),console.log(` UTXO: ${g.txid}:${g.vout}`),console.log(" \u26a0\ufe0f UTXO existence check deferred to Bitcoin consensus"),console.log(" \u2705 Proceeding (Bitcoin will reject if spent)"),k="3",console.log("[Step 3] Querying authorization from contract...");const A=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct LoanOperationsManager.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],$=new ethers.Contract(I,A,P),x=await $.getAuthorizedSpends(a);let E=null;for(const t of x){const e=t.txid.toLowerCase(),n=g.txid.toLowerCase(),o=Number(t.vout),r=Number(g.vout);if(e===n&&o===r){E=t;break}}if(!E)throw new Error(`No authorization found for UTXO ${g.txid}:${g.vout}`);const M=BigInt(E.targetAmount.toString()),S=E.targetAddress,q=BigInt(E.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${S}`),console.log(` Authorized at: ${q.toString()}`),k="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const O=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],L=new ethers.Contract(T,O,P),B=await L.core();console.log(` Core facet address: ${B}`);const D=[{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"}],z=new ethers.Contract(B,D,P),F=await z.getPositionDetails(a);let U;if(5===F.status){if(!e.contractAddresses?.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(e.contractAddresses.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],P),n=await t.pkpOwners(F.pkpId);if(!n||n===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");U=n,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${U}`)}else U=F.borrower;console.log(` Position owner: ${U}`);const R=`${g.txid}:${g.vout}`,K=await m.verifyBtcExecutionAuthorization({positionId:r.positionId,timestamp:r.timestamp,chainId:r.chainId,utxoIdentifier:R,networkFee:r.networkFee,targetAddress:r.targetAddress,targetAmount:r.targetAmount,action:"execute-btc-withdrawal",signature:r.signature},U,function(t){return p[t]}(n),P,globalThis.contractAddresses?.PositionDelegateRegistry);if(!K)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const j=String(S);if(r.targetAddress.toLowerCase()!==j.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${r.targetAddress}" but on-chain authorizer records "${j}"`);const N=BigInt(r.targetAmount.toString());if(N!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${N.toString()} but on-chain authorizer records ${M.toString()}`);if(k="4",console.log("[Step 4] Validating network fee..."),w>h)throw new Error(`Network fee ${w} sats exceeds maximum ${h} sats`);if(w<l)throw new Error(`Network fee ${w} sats below minimum ${l} sats`);if(BigInt(w)>=M)throw new Error(`Network fee ${w} sats cannot exceed target amount ${M.toString()} sats`);const _=Number(M)-w;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${_} sats`),k="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const X=await i(v,o);console.log(` \u2705 PKP BTC address: ${X}`),k="6",console.log("[Step 6] Validating UTXO ownership...");const Q=s(X);for(const t of f){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==Q)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${Q}, got ${e}`)}console.log(` \u2705 All ${f.length} UTXO(s) belong to vault (PKP address)`),k="7",console.log("[Step 7] Validating UTXO value...");const V=Number(M),W=f.reduce(((t,e)=>t+e.value),0);if(W<V)throw new Error(`Insufficient UTXO value: total ${W} sats across ${f.length} input(s), need ${V} sats`);const H=W-V;console.log(` \u2705 Total UTXO value sufficient (${f.length} input(s))`),console.log(` Total value: ${W} sats`),console.log(` Total required: ${V} sats`),console.log(` Change: ${H} sats`),k="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:Z,sigHashes:J}=function(t){const{utxos:e,destination:n,amount:o,changeAddress:r,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",l="ffffffff",h="00000000",g=d(e.length),p=e.map((t=>u(t.txid)+c(t.vout,4)+"00"+l)).join(""),f=[],w=s(n);if(f.push(c(o,8)+d(w.length/2)+w),i>0){const t=s(r);f.push(c(i,8)+d(t.length/2)+t)}const m=d(f.length),y=f.join(""),P=a+g+p+m+y+h,b=e.map((t=>u(t.txid)+c(t.vout,4))).join(""),v=ethers.utils.sha256(ethers.utils.sha256("0x"+b)),A=e.map((()=>l)).join(""),T=ethers.utils.sha256(ethers.utils.sha256("0x"+A)),I=ethers.utils.sha256(ethers.utils.sha256("0x"+y));return{txHex:P,sigHashes:e.map((t=>{const e=u(t.txid)+c(t.vout,4),n="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",o=a+v.slice(2)+T.slice(2)+e+n+c(t.value,8)+l+I.slice(2)+h+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+o))}))}}({utxos:f,destination:S,amount:_,changeAddress:X,changeAmount:H,network:o,pkpPublicKey:v});console.log(` \u2705 Transaction built (${f.length} input(s))`),console.log(` Signature hashes: ${J.length}`),k="9",console.log(`[Step 9] Signing ${J.length} input(s)...`);const G=globalThis.pkpId;if(!G)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const Y=await Lit.Actions.getPrivateKey({pkpId:G}),tt="string"==typeof Y?Y.startsWith("0x")?Y:`0x${Y}`:String(Y),et=new ethers.utils.SigningKey(tt),nt=[];for(let t=0;t<J.length;t++){const e=et.signDigest(J[t]);nt.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${J[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:Z,sigHashes:J,sigHash:J[0],signatures:nt,signature:nt[0],pkpPublicKey:v,pkpBtcAddress:X,destination:S,userReceivesAmount:_,networkFee:w,changeAmount:H,utxos:f.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:g.txid,vout:g.vout,value:g.value},authorization:{targetAmount:M.toString(),authorizedAt:q.toString()},timestamp:Date.now(),action:"btc-transaction-signer"}}catch(t){return console.error("[BTC Transaction Signer] \u274c Failed:",t.message),console.error(`[BTC Transaction Signer] Failed at step: ${k}`),{success:!1,error:t.message||t.toString(),positionId:r?.positionId,timestamp:Date.now()}}}return A=r,((r,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let u of n(i))o.call(r,u)||u===s||t(r,u,{get:()=>i[u],enumerable:!(a=e(i,u))||a.enumerable});return r})(t({},"__esModule",{value:!0}),A)})();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
- fbfb8f39c6ccbd3bb2a429075ada0d2e22f6953c80ab73d8cfc716f54627a83d
1
+ a232ff448649b7eb8204e9edbdca3eb5b8f5afdbf592aebdbc8959b66481337a
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-transaction-signer",
3
- "originalSize": 64382,
4
- "minifiedSize": 27269,
5
- "compressionRatio": 0.5764499394240626,
6
- "hash": "fbfb8f39c6ccbd3bb2a429075ada0d2e22f6953c80ab73d8cfc716f54627a83d",
7
- "buildTime": 1779831976359,
3
+ "originalSize": 66407,
4
+ "minifiedSize": 27835,
5
+ "compressionRatio": 0.5808423810742843,
6
+ "hash": "a232ff448649b7eb8204e9edbdca3eb5b8f5afdbf592aebdbc8959b66481337a",
7
+ "buildTime": 1779878463766,
8
8
  "version": "0.1.0"
9
9
  }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=546n,s=100,a=1e5,c=60,u="btc-utxo-invalidator",l=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(l||{}),d={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},h={ethereum:1,sepolia:11155111,hardhat:1337};function p(t){return Math.floor(t/c)*c}async function g(){const t=Math.floor(Date.now()/1e3),e=t%c;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%c;return e<8||e>=52}(t))return;let r;r=e>=52?c-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${p(Math.floor(Date.now()/1e3))}`)}var f=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await g();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=p(i),o=p(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const s=n-c,a=n+c;if(o!==s&&o!==n&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${n} (current), ${a} (next)]`);if(o===s){if(i<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&i>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if(e.action!==u)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}};function m(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function w(...t){m()&&console.log(...t)}var y=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},b=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},v=class{static create(t="LIT Action",e){return m(e)?new b(t):new y}};function P(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}var E=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=v.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),w(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),w(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${T(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(n),w(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=o.chain_stats.funded_txo_sum,a=o.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const c=BigInt(s-a);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),c}catch(t){if(clearTimeout(n),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),w(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const s=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:s>0?s:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(T(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function I(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const i="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=[];for(let t=0;t<r.length;t+=2)n.push(parseInt(r.substr(t,2),16));const o=x(n,8,5,!0),s=[e,...o],a=function(t,e){const r=function(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}(t).concat(e).concat([0,0,0,0,0,0]),i=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let i=0;i<t.length;i++){const n=r>>25;r=(33554431&r)<<5^t[i];for(let t=0;t<5;t++)n>>t&1&&(r^=e[t])}return r}(r),n=[];for(let t=0;t<6;t++)n.push(i>>5*(5-t)&31);return n}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=i[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function A(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const i=t.substring(r+1).toLowerCase(),n=[];for(let t=0;t<i.length;t++){const r=e.indexOf(i[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${i[t]}`);n.push(r)}const o=n.slice(0,-6),s=(o[0],x(o.slice(1),5,8,!1));return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let i=0;i<t.length;i++){const n=e.indexOf(t[i]);if(n<0)throw new Error(`Invalid Base58 character: ${t[i]}`);r=58n*r+BigInt(n)}let i=r.toString(16);i.length%2&&(i="0"+i);for(let e=0;e<t.length&&"1"===t[e];e++)i="00"+i;return i}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function x(t,e,r,i){let n=0,o=0;const s=[],a=(1<<r)-1;for(let i=0;i<t.length;i++){const c=t[i];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(n=n<<e|c,o+=e;o>=r;)o-=r,s.push(n>>o&a)}if(i)o>0&&s.push(n<<r-o&a);else if(o>=e||n<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function k(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function S(t,e){const r=t.toString(16).padStart(2*e,"0").match(/../g);if(!r)throw new Error(`Invalid hex conversion: ${t}`);return r.reverse().join("")}function C(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+S(t,2):t<=4294967295?"fe"+S(t,4):"ff"+S(t,8)}var B=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}];async function M(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function D(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!i)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const o=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,B,e),[n,o]=await i.getProviders(t),s=[];for(let t=0;t<n.length;t++)s.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(t.chainId,e,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);const n=[];for(const e of i){const r=await M(e.ciphertext,e.pkpId);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i);return o[0]}var O={hardhat:{chain:"hardhat",chainId:h.hardhat,bitcoinNetwork:d.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:h.sepolia,bitcoinNetwork:d.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:h.ethereum,bitcoinNetwork:d.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};function U(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(l).join(", ")}`)}(t),r=O[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var N="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))",_={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 L(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var q=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),R=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)"]),F=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),z=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function j(t,e,r){return t.call({to:e,data:r})}async function H(t,e){const r=new ethers.utils.Interface([N]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([N]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?L({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]}):L(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await j(t,e,q.encodeFunctionData("views",[])),[i]=q.decodeFunctionResult("views",r),[n,o,s,a,c,u,l,d]=await Promise.all([j(t,e,q.encodeFunctionData("paused",[])),j(t,e,q.encodeFunctionData("liquidationPaused",[])),j(t,e,q.encodeFunctionData("simplePsm",[])),j(t,i,R.encodeFunctionData("core",[])),j(t,i,R.encodeFunctionData("loanOps",[])),j(t,i,R.encodeFunctionData("collateralManager",[])),j(t,i,R.encodeFunctionData("liquidationManager",[])),j(t,i,R.encodeFunctionData("circuitBreaker",[]))]),h=q.decodeFunctionResult("paused",n)[0],p=q.decodeFunctionResult("liquidationPaused",o)[0],g=q.decodeFunctionResult("simplePsm",s)[0],f=R.decodeFunctionResult("core",a)[0],m=R.decodeFunctionResult("loanOps",c)[0],w=R.decodeFunctionResult("collateralManager",u)[0],y=R.decodeFunctionResult("liquidationManager",l)[0],b=R.decodeFunctionResult("circuitBreaker",d)[0],v=await j(t,m,F.encodeFunctionData("getUcdController",[])),P=await j(t,m,F.encodeFunctionData("ucdToken",[])),T=F.decodeFunctionResult("getUcdController",v)[0],$=F.decodeFunctionResult("ucdToken",P)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await j(t,e,z.encodeFunctionData("paused",[]));return z.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,A,x,k,S,C,B,M]=await Promise.all([E(f),E(m),E(w),E(y),E(b),E(T),E($),E(g)]);return L({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:A,collateralManagerPaused:x,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var X,K=3600,V=1500,W=[{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"}],Q=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],G=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=v.create("BTC UTXO Invalidator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing required parameter "chain"');const i=U(t),n=P(),c=n.publicKey;if(!c||"string"!=typeof c)throw new Error('Missing required parameter "publicKey"');const l=globalThis.contractAddresses;if(!l)throw new Error('Missing "contractAddresses"');const d=l.PositionManager,h=l.BTCSpendAuthorizer;if(!d||!h)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const p=globalThis.auth;if(!p||"object"!=typeof p)throw new Error('Missing or invalid "auth" parameter');const{positionId:g,utxoTxid:m,utxoVout:w,timestamp:y,signature:b,chainId:v,action:T}=p;if(!g||!m||"number"!=typeof w)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof y||!b||"number"!=typeof v)throw new Error("auth requires { timestamp, signature, chainId }");if(T!==u)throw new Error(`auth.action must be "${u}" (got "${T}")`);const $=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(g);let x;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(x=globalThis.rpcUrl,console.log(` RPC override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(x)}`)):x=await Lit.Actions.getRpcUrl({chain:t});const B=new ethers.providers.JsonRpcProvider(x),M=await D({policy:i,ethersProvider:B,registryAddress:l.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});new E({providerUrl:M.url});!function(t,e){const r=_[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("btcTransactionSign",await H(B,d)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const O=new ethers.Contract(h,W,B),N=await O.getAuthorizedSpends($);let L=null;for(const t of N)if(t.txid.toLowerCase()===m.toLowerCase()&&Number(t.vout)===w){L=t;break}if(!L)throw new Error(`No AuthorizedSpend on-chain for ${m}:${w} under position ${$}`);const q=BigInt(L.authorizedAt.toString()),R=BigInt(L.satoshis.toString()),F=BigInt(Math.floor(Date.now()/1e3));if(F-q<BigInt(K))throw new Error(`AuthorizedSpend not yet stale: age=${(F-q).toString()}s, required=${K}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const z=new ethers.Contract(d,G,B),j=await z.core(),X=new ethers.Contract(j,Q,B),J=await X.getPositionDetails($),Z=J.borrower??J[1],Y=J.vaultAddress??J[3];if(!Z||Z===ethers.constants.AddressZero)throw new Error(`Position ${$} not found or no borrower set`);if(!Y)throw new Error(`Position ${$} missing vaultAddress`);if(v!==i.chainId)throw new Error(`auth.chainId (${v}) \u2260 policy.chainId (${i.chainId})`);if(!await f.verifyRecoveryAuthorization({positionId:$,timestamp:y,chainId:v,utxoTxid:m,utxoVout:w,action:T,signature:b},Z,i.chainId,B,l.PositionDelegateRegistry))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const tt=await(async()=>{try{const t=await fetch(`${M.url}/tx/${m}/outspends`);return t.ok?await t.json():null}catch{return null}})();if(tt&&tt[w]&&tt[w].spent){const t=tt[w].txid??"unknown";return console.log(` \u2139\ufe0f UTXO already spent by ${t}; short-circuiting to recovery-validator path`),e.stepEnd("4"),{success:!0,alreadySpent:{spendingTxid:t},positionId:$,utxoTxid:m,utxoVout:w,authorizedAt:q.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const et=await I(c,i.bitcoinNetwork);if(Y&&et.toLowerCase()!==Y.toLowerCase())throw new Error(`Derived PKP address ${et} \u2260 on-chain vaultAddress ${Y}`);if(e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx"),V<s)throw new Error(`INVALIDATOR_FEE_SATS (${V}) < MIN_BTC_FEE_SATS (${s})`);if(V>a)throw new Error(`INVALIDATOR_FEE_SATS (${V}) > MAX_BTC_FEE_SATS (${a})`);const rt=Number(R)-V;if(rt<Number(o))throw new Error(`Invalidator output (${rt} sats) below dust limit; UTXO too small to recover`);const it={txid:m,vout:w,value:Number(R),scriptPubKey:""};it.scriptPubKey=A(et);const{txHex:nt,sigHashes:ot}=function(t){const{utxos:e,destination:r,amount:i,changeAddress:n,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",a="ffffffff",c="00000000",u=C(e.length),l=e.map((t=>k(t.txid)+S(t.vout,4)+"00"+a)).join(""),d=[],h=A(r);if(d.push(S(i,8)+C(h.length/2)+h),o>0){const t=A(n);d.push(S(o,8)+C(t.length/2)+t)}const p=C(d.length),g=d.join(""),f=s+u+l+p+g+c,m=e.map((t=>k(t.txid)+S(t.vout,4))).join(""),w=ethers.utils.sha256(ethers.utils.sha256("0x"+m)),y=e.map((()=>a)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+y)),v=ethers.utils.sha256(ethers.utils.sha256("0x"+g));return{txHex:f,sigHashes:e.map((t=>{const e=k(t.txid)+S(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",i=s+w.slice(2)+b.slice(2)+e+r+S(t.value,8)+a+v.slice(2)+c+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+i))}))}}({utxos:[it],destination:et,amount:rt,changeAddress:et,changeAmount:0,network:i.bitcoinNetwork,pkpPublicKey:c});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const st=n.pkpId;if(!st)throw new Error('Missing required parameter "pkpId"');const at=await Lit.Actions.getPrivateKey({pkpId:st}),ct="string"==typeof at?at.startsWith("0x")?at:`0x${at}`:String(at),ut=new ethers.utils.SigningKey(ct),lt=[];for(let t=0;t<ot.length;t++){const e=ut.signDigest(ot[t]);lt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:nt,sigHashes:ot,signatures:lt,pkpPublicKey:c,pkpBtcAddress:et,invalidatorAmount:rt,networkFee:V,utxo:{txid:m,vout:w,value:Number(R)},authorization:{authorizedAt:q.toString(),positionId:$},timestamp:Date.now(),action:"btc-utxo-invalidator"}}catch(t){return console.error(`[BTC UTXO Invalidator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"btc-utxo-invalidator"}}}return X=n,((n,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===s||t(n,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return n})(t({},"__esModule",{value:!0}),X)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{main:()=>main});var o=546n,s=100,a=1e5,c=60,u="btc-utxo-invalidator",d=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(d||{}),l={sepolia:"testnet",ethereum:"mainnet",hardhat:"regtest"},h={ethereum:1,sepolia:11155111,hardhat:1337};function p(t){return Math.floor(t/c)*c}async function g(){const t=Math.floor(Date.now()/1e3),e=t%c;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%c;return e<8||e>=52}(t))return;let r;r=e>=52?c-e+8:8-e,console.log(`[Quantum] Waiting ${r}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*r))),console.log(`[Quantum] Safe quantum ready: ${p(Math.floor(Date.now()/1e3))}`)}var f=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),i=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(i,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,i){try{const n=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],i);return"0x1626ba7e"===await n.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,i){try{const n=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],i),o=await n.positionDelegate(t);return!(!o||o===ethers.constants.AddressZero)&&o.toLowerCase()===e.toLowerCase()}catch{return!1}}static async verifyActionAuthorization(t,e,r,i){const n=Math.floor(Date.now()/1e3);await g();const o=i?.strictCurrentQuantum?n:void 0;try{!function(t,e,r){const i=e??Math.floor(Date.now()/1e3),n=p(i),o=p(t);if(r?.strictCurrentQuantum){if(o!==n)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${o}, current quantum: ${n}`);return}const s=n-c,a=n+c;if(o!==s&&o!==n&&o!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${o}, Valid range: [${s} (past), ${n} (current), ${a} (next)]`);if(o===s){if(i<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(o===a&&i>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${i}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,o,{strictCurrentQuantum:!0===i?.strictCurrentQuantum})}catch{return!1}const s=e(),a=await this.recoverSigner(s,t.signature);return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyMintAuthorization(t,e,r,i,n){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyPaymentAuthorization(t,e,r,i,n){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,i,n)}static async verifyWithdrawAuthorization(e,r,i,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,i=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyRecoveryAuthorization(e,r,i,n,o){if(e.action!==u)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,i,n,o){if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}))}static async verifyExtendAuthorization(t,e,r,i,n){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,i,n)}static async verifyBtcExecutionAuthorization(e,r,i,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==i)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${i})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),i=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32"],i)}),(async(i,s,a)=>{if(i.toLowerCase()===r.toLowerCase())return!0;if(n){if(await t.checkEIP1271(r,s,a,n))return!0;if(o)return t.checkPositionDelegate(e.positionId,i,o,n)}return!1}),{strictCurrentQuantum:!0})}static assertPaymentAmountMatchesAuth(t,e){const r=BigInt(e);if(r!==t)throw new Error(`paymentAmount mismatch: globalThis.paymentAmount=${t.toString()} but authMessage.paymentAmount=${r.toString()}. These must be identical \u2014 the PKP refuses to sign for an amount the user did not sign.`)}static assertSelectedTermMatchesAuth(t,e){const r=Number(e);if(!Number.isFinite(r)||r!==t)throw new Error(`selectedTerm mismatch: globalThis.selectedTerm=${t} but auth.newTerm=${e}. These must be identical \u2014 the PKP refuses to sign for a term the user did not sign.`)}};function m(t){if(!0===t)return!0;if(!1===t)return!1;const e=globalThis;return!0===e.debugAction||(!0===e.LIT_ACTION_DEBUG||("true"===e.LIT_ACTION_DEBUG||function(){try{if("undefined"==typeof process||!process.env)return!1;const t=process.env.LIT_ACTION_DEBUG,e=process.env.DEBUG;return"1"===t||"true"===t||"1"===e||"true"===e}catch{return!1}}()))}function w(...t){m()&&console.log(...t)}var y=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},b=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const n=Date.now()-this.executionStartTime,o=this.TIMEOUT_MS-n;o<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${o}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},v=class{static create(t="LIT Action",e){return m(e)?new b(t):new y}};function P(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function $(t){return t instanceof Error&&"AbortError"===t.name}var E=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=v.create("BitcoinDataProvider")}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:{Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(e),w(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const n=await i.text();if(n.trim().startsWith("<!DOCTYPE")||n.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of block height. URL may be pointing to web interface instead of API endpoint. Expected: plain text number, Got: HTML document. Check that URL ends with /api/esplora (not root /)");const o=parseInt(n.trim(),10);if(isNaN(o)){const t=n.length>200?n.substring(0,200)+"... (truncated)":n;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),o}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>({txid:t.txid,vout:t.vout,satoshis:BigInt(Math.round(1e8*t.amount)),confirmations:t.confirmations})))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const n=t.txid,o=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===n||void 0===o||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");i.push({txid:n,vout:o,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxos`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[o,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}})]);if(clearTimeout(n),w(`[BitcoinDataProvider] parallel(tipHeight + GET utxos) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxos (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${o}`),!s.ok)throw new Error(`Bitcoin provider error: ${s.status} ${s.statusText}`);const a=await s.text();if(a.trim().startsWith("<!DOCTYPE")||a.trim().startsWith("<html"))throw new Error("Bitcoin RPC endpoint returned HTML instead of JSON. URL may be pointing to web interface instead of API endpoint. Expected: JSON array of UTXOs, Got: HTML document. Check that URL ends with /api/esplora (not root /)");let c;try{c=JSON.parse(a)}catch(t){const e=a.length>200?a.substring(0,200)+"... (truncated)":a;throw new Error(`Failed to parse JSON response: ${T(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,o);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(n),this.logger.stepEnd("1"),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const n=r.reduce(((t,e)=>t+e.satoshis),0n),o=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=n-o;return{utxos:r,totalBalance:n,totalUTXOs:r.length,confirmedBalance:o,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,n=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),e=await fetch(r,{signal:i.signal,headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"}});if(clearTimeout(n),w(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!e.ok)throw new Error(`Bitcoin provider error: ${e.status} ${e.statusText}`);const o=await e.json();if(!o.chain_stats)throw new Error("Invalid response: missing chain_stats");const s=o.chain_stats.funded_txo_sum,a=o.chain_stats.spent_txo_sum;if(void 0===s||void 0===a)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${s}, spent_txo_sum: ${a}`);const c=BigInt(s-a);return this.logger.log("3",`Balance: ${c.toString()} sats`),this.logger.log("3",` - Funded: ${s} sats, Spent: ${a} sats`),c}catch(t){if(clearTimeout(n),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),w(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-i}ms (timeout budget ${this.timeout}ms)`),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();if(o.status){if(!o.status.confirmed||!o.status.block_height)return{txid:o.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal});if(!r.ok)return{txid:o.txid??t,confirmations:1};const i=(await r.text()).trim(),n=Number.parseInt(i,10);if(!Number.isFinite(n)||n<=0)return{txid:o.txid??t,confirmations:1};const s=n-o.status.block_height+1;return{txid:o.txid??t,confirmations:s>0?s:0}}catch{return{txid:o.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(T(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const n=await i.json();return n.vout&&Array.isArray(n.vout)?n.vout.map(((t,e)=>({index:e,scriptpubkey:t.scriptpubkey,scriptpubkey_address:t.scriptpubkey_address,value:t.value??0}))):null}catch(t){if(clearTimeout(r),$(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};async function I(pkpPublicKey,t){const e=pkpPublicKey.startsWith("0x")?pkpPublicKey.slice(2):pkpPublicKey;if(130!==e.length)throw new Error(`Invalid public key length: ${e.length}, expected 130 (uncompressed format)`);if(!e.startsWith("04"))throw new Error(`Invalid public key prefix: expected 04 (uncompressed), got ${e.substring(0,2)}`);const r=e.slice(2,66),i=e.slice(66,130),n=(BigInt("0x"+i)%2n===0n?"02":"03")+r,o=ethers.utils.sha256("0x"+n);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const a=function(t,e,r){const i="qpzry9x8gf2tvdw0s3jn54khce6mua7l",n=[];for(let t=0;t<r.length;t+=2)n.push(parseInt(r.substr(t,2),16));const o=x(n,8,5,!0),s=[e,...o],a=function(t,e){const r=function(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}(t).concat(e).concat([0,0,0,0,0,0]),i=1^function(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let i=0;i<t.length;i++){const n=r>>25;r=(33554431&r)<<5^t[i];for(let t=0;t<5;t++)n>>t&1&&(r^=e[t])}return r}(r),n=[];for(let t=0;t<6;t++)n.push(i>>5*(5-t)&31);return n}(t,s),c=[...s,...a];let u=t+"1";for(let t=0;t<c.length;t++)u+=i[c[t]];return u}(s,0,ethers.utils.ripemd160(o).slice(2));return a}function A(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]{11,87}$/.test(t)){const e=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.lastIndexOf("1");if(r<1)throw new Error("No separator character for bech32");t.substring(0,r).toLowerCase();const i=t.substring(r+1).toLowerCase(),n=[];for(let t=0;t<i.length;t++){const r=e.indexOf(i[t]);if(-1===r)throw new Error(`Invalid bech32 character: ${i[t]}`);n.push(r)}const o=n.slice(0,-6),s=(o[0],x(o.slice(1),5,8,!1));return{witnessProgram:s.map((t=>t.toString(16).padStart(2,"0"))).join("")}}(t);return"0014"+e.witnessProgram}{const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let i=0;i<t.length;i++){const n=e.indexOf(t[i]);if(n<0)throw new Error(`Invalid Base58 character: ${t[i]}`);r=58n*r+BigInt(n)}let i=r.toString(16);i.length%2&&(i="0"+i);for(let e=0;e<t.length&&"1"===t[e];e++)i="00"+i;return i}(t);return"76a914"+e.slice(2,e.length-8)+"88ac"}}function x(t,e,r,i){let n=0,o=0;const s=[],a=(1<<r)-1;for(let i=0;i<t.length;i++){const c=t[i];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(n=n<<e|c,o+=e;o>=r;)o-=r,s.push(n>>o&a)}if(i)o>0&&s.push(n<<r-o&a);else if(o>=e||n<<r-o&a)throw new Error("Invalid padding in bit conversion");return s}function k(t){const e=(t.startsWith("0x")?t.slice(2):t).match(/../g);if(!e)throw new Error(`Invalid hex string: ${t}`);return e.reverse().join("")}function S(t,e){const r=t.toString(16).padStart(2*e,"0").match(/../g);if(!r)throw new Error(`Invalid hex conversion: ${t}`);return r.reverse().join("")}function C(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+S(t,2):t<=4294967295?"fe"+S(t,4):"ff"+S(t,8)}var B=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"}],name:"getProviders",outputs:[{internalType:"bytes32[]",name:"ids",type:"bytes32[]"},{components:[{internalType:"bytes",name:"ciphertext",type:"bytes"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint64",name:"addedAt",type:"uint64"}],internalType:"struct BitcoinProviderRegistry.ProviderEntry[]",name:"entries",type:"tuple[]"}],stateMutability:"view",type:"function"}],M=[{inputs:[{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"bytes32",name:"cidHash",type:"bytes32"}],name:"isAllowedCid",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];async function D(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function O(t){const{policy:e,ethersProvider:r,registryAddress:i,devBitcoinProviderUrl:n}=t;if(e.allowArbitraryBitcoinProvider){if(!n)throw new Error("resolveDefaultBitcoinProvider: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return{name:"Dev Provider",url:n,minConfirmations:e.minBitcoinConfirmations,network:e.bitcoinNetwork}}if(!i)throw new Error(`resolveDefaultBitcoinProvider: BitcoinProviderRegistry address required on chain "${e.chain}"`);const o=await async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,B,e),[n,o]=await i.getProviders(t),s=[];for(let t=0;t<n.length;t++)s.push({providerId:n[t],ciphertext:o[t].ciphertext,pkpId:o[t].pkpId,addedAt:Number(o[t].addedAt)});return s}(t.chainId,e,r);if(0===i.length)throw new Error(`No Bitcoin providers registered for chainId=${t.chainId} in ${r}. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const n=globalThis.ipfsId;if("string"!=typeof n||0===n.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const o=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n)),s=new ethers.Contract(i,M,r);let a;try{a=await s.isAllowedCid(e,o)}catch(t){throw new Error(`assertSelfCidAllowedForDecrypt: failed to query BitcoinProviderRegistry.isAllowedCid: ${t?.message??String(t)}`)}if(!a)throw new Error(`BitcoinProviderRegistry CID allowlist denied this bundle on chainId=${e} (cidHash=${o.slice(0,10)}\u2026). Admin must addAllowedCid(...) via AdminModule before this CID can decrypt encrypted Bitcoin provider URLs.`)}({chainId:t.chainId,ethersProvider:e,registryAddress:r});const n=[];for(const e of i){const r=await D(e.ciphertext,e.pkpId);n.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:r,minConfirmations:t.minBitcoinConfirmations,network:t.bitcoinNetwork})}return n}(e,r,i);return o[0]}var U={hardhat:{chain:"hardhat",chainId:h.hardhat,bitcoinNetwork:l.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,minBitcoinConfirmations:1},sepolia:{chain:"sepolia",chainId:h.sepolia,bitcoinNetwork:l.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:1},ethereum:{chain:"ethereum",chainId:h.ethereum,bitcoinNetwork:l.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,minBitcoinConfirmations:6}};function N(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(d).join(", ")}`)}(t),r=U[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",q={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]};function R(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var L=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),F=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),z=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),j=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function H(t,e,r){return t.call({to:e,data:r})}async function X(t,e){const r=new ethers.utils.Interface([_]).encodeFunctionData("getProtocolPauseStatus",[]);let i;try{return function(t){const e=new ethers.utils.Interface([_]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?R({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):R(e)}(await t.call({to:e,data:r}))}catch(t){i=t}try{return await async function(t,e){const r=await H(t,e,L.encodeFunctionData("views",[])),[i]=L.decodeFunctionResult("views",r),[n,o,s,a,c,u,d,l]=await Promise.all([H(t,e,L.encodeFunctionData("paused",[])),H(t,e,L.encodeFunctionData("liquidationPaused",[])),H(t,e,L.encodeFunctionData("simplePsm",[])),H(t,i,F.encodeFunctionData("core",[])),H(t,i,F.encodeFunctionData("loanOps",[])),H(t,i,F.encodeFunctionData("collateralManager",[])),H(t,i,F.encodeFunctionData("liquidationManager",[])),H(t,i,F.encodeFunctionData("circuitBreaker",[]))]),h=L.decodeFunctionResult("paused",n)[0],p=L.decodeFunctionResult("liquidationPaused",o)[0],g=L.decodeFunctionResult("simplePsm",s)[0],f=F.decodeFunctionResult("core",a)[0],m=F.decodeFunctionResult("loanOps",c)[0],w=F.decodeFunctionResult("collateralManager",u)[0],y=F.decodeFunctionResult("liquidationManager",d)[0],b=F.decodeFunctionResult("circuitBreaker",l)[0],v=await H(t,m,z.encodeFunctionData("getUcdController",[])),P=await H(t,m,z.encodeFunctionData("ucdToken",[])),T=z.decodeFunctionResult("getUcdController",v)[0],$=z.decodeFunctionResult("ucdToken",P)[0],E=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await H(t,e,j.encodeFunctionData("paused",[]));return j.decodeFunctionResult("paused",r)[0]}catch{return!1}},[I,A,x,k,S,C,B,M]=await Promise.all([E(f),E(m),E(w),E(y),E(b),E(T),E($),E(g)]);return R({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:I,loanOperationsPaused:A,collateralManagerPaused:x,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=i instanceof Error?i.message:String(i),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var K,V=3600,W=1500,Q=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getAuthorizedSpends",outputs:[{components:[{internalType:"string",name:"txid",type:"string"},{internalType:"uint32",name:"vout",type:"uint32"},{internalType:"uint256",name:"satoshis",type:"uint256"},{internalType:"string",name:"targetAddress",type:"string"},{internalType:"uint256",name:"targetAmount",type:"uint256"},{internalType:"uint256",name:"authorizedAt",type:"uint256"}],internalType:"struct BTCSpendAuthorizer.AuthorizedSpend[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"}],G=[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"address",name:"borrower",type:"address"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"string",name:"vaultAddress",type:"string"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],J=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=v.create("BTC UTXO Invalidator");let r="0";try{r="0",e.stepStart("0","Validate configuration");const t=globalThis.chain;if(!t)throw new Error('Missing required parameter "chain"');const i=N(t),n=P(),c=n.publicKey;if(!c||"string"!=typeof c)throw new Error('Missing required parameter "publicKey"');const d=globalThis.contractAddresses;if(!d)throw new Error('Missing "contractAddresses"');const l=d.PositionManager,h=d.BTCSpendAuthorizer;if(!l||!h)throw new Error("contractAddresses.PositionManager and BTCSpendAuthorizer are required");const p=globalThis.auth;if(!p||"object"!=typeof p)throw new Error('Missing or invalid "auth" parameter');const{positionId:g,utxoTxid:m,utxoVout:w,timestamp:y,signature:b,chainId:v,action:T}=p;if(!g||!m||"number"!=typeof w)throw new Error("auth requires { positionId, utxoTxid, utxoVout }");if("number"!=typeof y||!b||"number"!=typeof v)throw new Error("auth requires { timestamp, signature, chainId }");if(T!==u)throw new Error(`auth.action must be "${u}" (got "${T}")`);const $=function(t){if("string"!=typeof t)throw new Error("positionId must be a string");const e=t.trim(),r=/^0x/i.test(e)?e.slice(2):e;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(g);let x;e.stepEnd("0"),r="1",e.stepStart("1","Resolve RPC + Bitcoin provider"),globalThis.rpcUrl?(x=globalThis.rpcUrl,console.log(` RPC override: ${function(t){if(null==t||"string"!=typeof t)return"[missing]";let e=t.replace(/([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,"$1$2=[REDACTED]");try{const t=new URL(e);(t.username||t.password)&&(t.username="",t.password="",e=t.toString())}catch{}return e}(x)}`)):x=await Lit.Actions.getRpcUrl({chain:t});const B=new ethers.providers.JsonRpcProvider(x),M=await O({policy:i,ethersProvider:B,registryAddress:d.BitcoinProviderRegistry,devBitcoinProviderUrl:globalThis.devBitcoinProviderUrl});new E({providerUrl:M.url});!function(t,e){const r=q[t],i=[];for(const t of r)e[t]&&i.push(t);if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:i,status:e}))}("btcTransactionSign",await X(B,l)),e.stepEnd("1"),r="2",e.stepStart("2","Validate AuthorizedSpend + stale window");const D=new ethers.Contract(h,Q,B),U=await D.getAuthorizedSpends($);let _=null;for(const t of U)if(t.txid.toLowerCase()===m.toLowerCase()&&Number(t.vout)===w){_=t;break}if(!_)throw new Error(`No AuthorizedSpend on-chain for ${m}:${w} under position ${$}`);const R=BigInt(_.authorizedAt.toString()),L=BigInt(_.satoshis.toString()),F=BigInt(Math.floor(Date.now()/1e3));if(F-R<BigInt(V))throw new Error(`AuthorizedSpend not yet stale: age=${(F-R).toString()}s, required=${V}s. Wait before invalidating.`);e.stepEnd("2"),r="3",e.stepStart("3","Verify caller authorisation");const z=new ethers.Contract(l,J,B),j=await z.core(),H=new ethers.Contract(j,G,B),K=await H.getPositionDetails($),Z=K.borrower??K[1],Y=K.vaultAddress??K[3];if(!Z||Z===ethers.constants.AddressZero)throw new Error(`Position ${$} not found or no borrower set`);if(!Y)throw new Error(`Position ${$} missing vaultAddress`);if(v!==i.chainId)throw new Error(`auth.chainId (${v}) \u2260 policy.chainId (${i.chainId})`);if(!await f.verifyRecoveryAuthorization({positionId:$,timestamp:y,chainId:v,utxoTxid:m,utxoVout:w,action:T,signature:b},Z,i.chainId,B,d.PositionDelegateRegistry))throw new Error("Caller authorisation failed");e.stepEnd("3"),r="4",e.stepStart("4","Check UTXO is still unspent");const tt=await(async()=>{try{const t=await fetch(`${M.url}/tx/${m}/outspends`);return t.ok?await t.json():null}catch{return null}})();if(tt&&tt[w]&&tt[w].spent){const t=tt[w].txid??"unknown";return console.log(` \u2139\ufe0f UTXO already spent by ${t}; short-circuiting to recovery-validator path`),e.stepEnd("4"),{success:!0,alreadySpent:{spendingTxid:t},positionId:$,utxoTxid:m,utxoVout:w,authorizedAt:R.toString(),timestamp:Date.now(),action:"btc-utxo-invalidator"}}e.stepEnd("4"),r="5",e.stepStart("5","Derive PKP BTC address (vault)");const et=await I(c,i.bitcoinNetwork);if(Y&&et.toLowerCase()!==Y.toLowerCase())throw new Error(`Derived PKP address ${et} \u2260 on-chain vaultAddress ${Y}`);if(e.stepEnd("5"),r="6",e.stepStart("6","Build invalidator tx"),W<s)throw new Error(`INVALIDATOR_FEE_SATS (${W}) < MIN_BTC_FEE_SATS (${s})`);if(W>a)throw new Error(`INVALIDATOR_FEE_SATS (${W}) > MAX_BTC_FEE_SATS (${a})`);const rt=Number(L)-W;if(rt<Number(o))throw new Error(`Invalidator output (${rt} sats) below dust limit; UTXO too small to recover`);const it={txid:m,vout:w,value:Number(L),scriptPubKey:""};it.scriptPubKey=A(et);const{txHex:nt,sigHashes:ot}=function(t){const{utxos:e,destination:r,amount:i,changeAddress:n,changeAmount:o}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const s="02000000",a="ffffffff",c="00000000",u=C(e.length),d=e.map((t=>k(t.txid)+S(t.vout,4)+"00"+a)).join(""),l=[],h=A(r);if(l.push(S(i,8)+C(h.length/2)+h),o>0){const t=A(n);l.push(S(o,8)+C(t.length/2)+t)}const p=C(l.length),g=l.join(""),f=s+u+d+p+g+c,m=e.map((t=>k(t.txid)+S(t.vout,4))).join(""),w=ethers.utils.sha256(ethers.utils.sha256("0x"+m)),y=e.map((()=>a)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+y)),v=ethers.utils.sha256(ethers.utils.sha256("0x"+g));return{txHex:f,sigHashes:e.map((t=>{const e=k(t.txid)+S(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",i=s+w.slice(2)+b.slice(2)+e+r+S(t.value,8)+a+v.slice(2)+c+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+i))}))}}({utxos:[it],destination:et,amount:rt,changeAddress:et,changeAmount:0,network:i.bitcoinNetwork,pkpPublicKey:c});e.stepEnd("6"),r="7",e.stepStart("7","Sign tx hashes with PKP");const st=n.pkpId;if(!st)throw new Error('Missing required parameter "pkpId"');const at=await Lit.Actions.getPrivateKey({pkpId:st}),ct="string"==typeof at?at.startsWith("0x")?at:`0x${at}`:String(at),ut=new ethers.utils.SigningKey(ct),dt=[];for(let t=0;t<ot.length;t++){const e=ut.signDigest(ot[t]);dt.push(ethers.utils.joinSignature(e))}return e.stepEnd("7"),console.log("[BTC UTXO Invalidator] \u2705 Signed"),{success:!0,alreadySpent:!1,unsignedTxHex:nt,sigHashes:ot,signatures:dt,pkpPublicKey:c,pkpBtcAddress:et,invalidatorAmount:rt,networkFee:W,utxo:{txid:m,vout:w,value:Number(L)},authorization:{authorizedAt:R.toString(),positionId:$},timestamp:Date.now(),action:"btc-utxo-invalidator"}}catch(t){return console.error(`[BTC UTXO Invalidator] \u274c Failed at step ${r}: ${t?.message??t}`),{success:!1,step:r,error:t?.message??String(t),timestamp:Date.now(),action:"btc-utxo-invalidator"}}}return K=n,((n,o,s,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of r(o))i.call(n,c)||c===s||t(n,c,{get:()=>o[c],enumerable:!(a=e(o,c))||a.enumerable});return n})(t({},"__esModule",{value:!0}),K)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
@@ -1 +1 @@
1
- bb685436296e5661156d275fedecca123b7247b6be663e02f5fa9207f0294011
1
+ 5fa69eb88c01503c9b1caa51ab2fd418db7776de205f04d5d5758937b7798a9e
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-utxo-invalidator",
3
- "originalSize": 94099,
4
- "minifiedSize": 40048,
5
- "compressionRatio": 0.5744056791251766,
6
- "hash": "bb685436296e5661156d275fedecca123b7247b6be663e02f5fa9207f0294011",
7
- "buildTime": 1779831976472,
3
+ "originalSize": 98066,
4
+ "minifiedSize": 41875,
5
+ "compressionRatio": 0.5729916586788489,
6
+ "hash": "5fa69eb88c01503c9b1caa51ab2fd418db7776de205f04d5d5758937b7798a9e",
7
+ "buildTime": 1779878463869,
8
8
  "version": "0.1.0"
9
9
  }