@gvnrdao/dh-lit-actions 0.0.317 → 0.0.319

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 (37) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/btc-address-balance.meta.json +1 -1
  9. package/dist/btc-transaction-signer.action.js +1 -1
  10. package/dist/btc-transaction-signer.hash +1 -1
  11. package/dist/btc-transaction-signer.meta.json +5 -5
  12. package/dist/btc-utxo-invalidator.action.js +1 -1
  13. package/dist/btc-utxo-invalidator.hash +1 -1
  14. package/dist/btc-utxo-invalidator.meta.json +5 -5
  15. package/dist/btc-withdrawal.action.js +1 -1
  16. package/dist/btc-withdrawal.hash +1 -1
  17. package/dist/btc-withdrawal.meta.json +5 -5
  18. package/dist/encrypt-parameter.meta.json +1 -1
  19. package/dist/extend-position-validator.action.js +1 -1
  20. package/dist/extend-position-validator.hash +1 -1
  21. package/dist/extend-position-validator.meta.json +5 -5
  22. package/dist/liquidation-validator.meta.json +1 -1
  23. package/dist/loan-vault-btc-balance.meta.json +1 -1
  24. package/dist/pkp-validator.meta.json +1 -1
  25. package/dist/price-oracle.meta.json +1 -1
  26. package/dist/process-payment-validator.action.js +1 -1
  27. package/dist/process-payment-validator.hash +1 -1
  28. package/dist/process-payment-validator.meta.json +5 -5
  29. package/dist/stale-spend-recovery-validator.meta.json +1 -1
  30. package/dist/ucd-mint-validator.action.js +1 -1
  31. package/dist/ucd-mint-validator.hash +1 -1
  32. package/dist/ucd-mint-validator.meta.json +5 -5
  33. package/package.json +2 -1
  34. package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
  35. package/pkg-dist/pkg-src/index.js +35 -31
  36. package/pkg-dist/pkg-src/index.js.map +2 -2
  37. package/pkg-dist/src/modules/authorization.module.d.ts.map +1 -1
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1608,
5
5
  "compressionRatio": 0.45895020188425306,
6
6
  "hash": "c6042989c2e0ac53631e008a960aef78f977471b9a7a8fc05a1537b10f34c8a9",
7
- "buildTime": 1785191241080,
7
+ "buildTime": 1785704145963,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 856,
5
5
  "compressionRatio": 0.4827794561933535,
6
6
  "hash": "bc0bcb38452275c93fa74c5240ae496d7a3eef9d38e7fb0dd99c5202c554d5e3",
7
- "buildTime": 1785191241090,
7
+ "buildTime": 1785704145994,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 4307,
5
5
  "compressionRatio": 0.5257130271996476,
6
6
  "hash": "22aa318284a25e721d1c949c8b4e5dbbb21853d1a3f649a72fd85ae32467bb17",
7
- "buildTime": 1785191241127,
7
+ "buildTime": 1785704146134,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1889,
5
5
  "compressionRatio": 0.4549913444893249,
6
6
  "hash": "790a1c5326a623065ab3c295d2c50cc8838d643730e53cb993a303ab9d7e0d83",
7
- "buildTime": 1785191241137,
7
+ "buildTime": 1785704146247,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 2220,
5
5
  "compressionRatio": 0.4740582800284293,
6
6
  "hash": "828aea87c7a7652377e00cb7a97c18324f09b87d3fa6703487fa3034e204a82c",
7
- "buildTime": 1785191241149,
7
+ "buildTime": 1785704146320,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 1046,
5
5
  "compressionRatio": 0.47960199004975124,
6
6
  "hash": "03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72",
7
- "buildTime": 1785191241156,
7
+ "buildTime": 1785704146391,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 2329,
5
5
  "compressionRatio": 0.44875739644970414,
6
6
  "hash": "6d26460ed9170782834926bcc30669fb48a9a0346f555eb838c99f8d9e6e8796",
7
- "buildTime": 1785191241166,
7
+ "buildTime": 1785704146430,
8
8
  "version": "0.1.0"
9
9
  }
@@ -4,6 +4,6 @@
4
4
  "minifiedSize": 27309,
5
5
  "compressionRatio": 0.506986568457539,
6
6
  "hash": "f0d08938713d9d89a56a3a386cacbc2b57afd5ad367ea82d827d40e1bfc70989",
7
- "buildTime": 1785191241260,
7
+ "buildTime": 1785704147650,
8
8
  "version": "0.1.0"
9
9
  }
@@ -1 +1 @@
1
- var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};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),n=e.slice(66,130),o=(BigInt("0x"+n)%2n===0n?"02":"03")+r,i=ethers.utils.sha256("0x"+o);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const u=function(t,e,r){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",o=[];for(let t=0;t<r.length;t+=2)o.push(parseInt(r.substr(t,2),16));const i=d(o,8,5,!0),s=[e,...i],u=function(t,e){const r=a(t).concat(e).concat([0,0,0,0,0,0]),n=1^c(r),o=[];for(let t=0;t<6;t++)o.push(n>>5*(5-t)&31);return o}(t,s),l=[...s,...u];let h=t+"1";for(let t=0;t<l.length;t++)h+=n[l[t]];return h}(s,0,ethers.utils.ripemd160(i).slice(2));return u}function s(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const o=r;if(o.length>90)throw new Error(`Bech32 address too long (${o.length} > 90): ${t}`);const i=o.lastIndexOf("1");if(i<1||i+7>o.length)throw new Error(`Invalid bech32 separator position in ${t}`);const s=o.slice(0,i),h=o.slice(i+1),p=[];for(let r=0;r<h.length;r++){const n=e.indexOf(h[r]);if(-1===n)throw new Error(`Invalid bech32 character '${h[r]}' in ${t}`);p.push(n)}const g=p[0];if(void 0===g||g<0||g>16)throw new Error(`Invalid witness version ${g} in ${t}`);const f=0===g?u:l;if(c(a(s).concat(p))!==f)throw new Error(`Invalid bech32${0===g?"":"m"} checksum for ${t}`);const m=d(p.slice(1,p.length-6),5,8,!1);if(m.length<2||m.length>40)throw new Error(`Invalid witness program length ${m.length} in ${t}`);if(0===g&&20!==m.length&&32!==m.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${m.length} in ${t}`);const w=m.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:g,program:w}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let n=0;n<t.length;n++){const o=e.indexOf(t[n]);if(o<0)throw new Error(`Invalid Base58 character: ${t[n]}`);r=58n*r+BigInt(o)}let n=r.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),n=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==n)throw new Error(`Invalid Base58Check checksum for ${t}`);const o=parseInt(r.slice(0,2),16),i=r.slice(2);return{version:o,hash:i}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}function a(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}function c(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let n=0;n<t.length;n++){const o=r>>25;r=(33554431&r)<<5^t[n];for(let t=0;t<5;t++)o>>t&1&&(r^=e[t])}return r}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(o,{main:()=>main});var u=1,l=734539939;function d(t,e,r,n){let o=0,i=0;const s=[],a=(1<<r)-1;for(let n=0;n<t.length;n++){const c=t[n];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(o=o<<e|c,i+=e;i>=r;)i-=r,s.push(o>>i&a)}if(n)i>0&&s.push(o<<r-i&a);else if(i>=e||o<<r-i&a)throw new Error("Invalid padding in bit conversion");return s}var h=25e14,p=546n,g=100,f=60,m={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};var w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),v={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){const{utxos:e,destination:r,amount:n,changeAddress:o,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",c="ffffffff",u="00000000",l=x(e.length),d=e.map((t=>P(t.txid)+T(t.vout,4)+"00"+c)).join(""),h=[],g=s(r);if(h.push(T(n,8)+x(g.length/2)+g),i>0){const t=s(o),e=function(t){const e=t.toLowerCase();return e.startsWith("0014")?294:e.startsWith("0020")||e.startsWith("5120")?330:Number(p)}(t);i<e?console.log(`[bitcoin/transaction] Sub-dust change of ${i} sats folded into the miner fee (dust limit ${e} sats for this script type \u2014 an output would be non-standard)`):h.push(T(i,8)+x(t.length/2)+t)}const f=x(h.length),m=h.join(""),w=a+l+d+f+m+u,v=e.map((t=>P(t.txid)+T(t.vout,4))).join(""),y=ethers.utils.sha256(ethers.utils.sha256("0x"+v)),$=e.map((()=>c)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+$)),E=ethers.utils.sha256(ethers.utils.sha256("0x"+m));return{txHex:w,sigHashes:e.map((t=>{const e=P(t.txid)+T(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+y.slice(2)+b.slice(2)+e+r+T(t.value,8)+c+E.slice(2)+u+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}function P(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 T(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`numToLittleEndianHex: value must be a non-negative safe integer (got ${t})`);let r=t.toString(16).padStart(2*e,"0");if(r.length>2*e)throw new Error(`numToLittleEndianHex: value ${t} does not fit in ${e} byte(s)`);const n=r.match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function x(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+T(t,2):t<=4294967295?"fe"+T(t,4):"ff"+T(t,8)}function E(t){return Math.floor(t/f)*f}async function A(){const t=Math.floor(Date.now()/1e3),e=t%f;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%f;return e<8||e>=52}(t))return;let r;r=e>=52?f-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: ${E(Math.floor(Date.now()/1e3))}`)}var I=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),n=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,n){try{const o=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await o.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,n){try{const o=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],n),i=await o.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,n,o){try{const i=new ethers.Contract(n,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],o);if("renew"===r){const[r]=await i.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await i.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[s,,a]=await i.canMint(t,e);return{ok:!0===s,effectiveFloorBps:Number(a)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async verifyActionAuthorization(t,e,r,n){const o=Math.floor(Date.now()/1e3);await A();const i=n?.strictCurrentQuantum?o:void 0;try{!function(t,e,r){const n=e??Math.floor(Date.now()/1e3),o=E(n),i=E(t);if(r?.strictCurrentQuantum){if(i!==o)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${o}`);return}const s=o-f,a=o+f;if(i!==s&&i!==o&&i!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${s} (past), ${o} (current), ${a} (next)]`);if(i===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(i===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===n?.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,n,o,i,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,c,o))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,o);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyMintAuthorization(t,e,r,n,o,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,o,i)}static async verifyPaymentAuthorization(t,e,r,n,o,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,o,i)}static async verifyWithdrawAuthorization(e,r,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))))}static async verifyRecoveryAuthorization(e,r,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,n,o,i,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,c,o))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,o);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,n,o,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,n,o,i)}static async verifyBtcExecutionAuthorization(e,r,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],n)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))),{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 k(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 S(...t){k()&&console.log(...t)}var C=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},B=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${n}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const n=Date.now()-r;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-o;i<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${i}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const n=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${n}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},M=class{static create(t="LIT Action",e){return k(e)?new B(t):new C}};function U(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function O(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function D(t){return t instanceof Error&&"AbortError"===t.name}function N(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function F(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&N(r,"provider url"),{url:r,auth:{provider:"esplora"}};let n;try{n=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof n.url||0===n.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=n.url.trim();switch(n.provider){case void 0:case"esplora":return e?.requireHttps&&N(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof n.apiKey||0===n.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return N(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:n.apiKey}};case"blockstream-enterprise":{if("string"!=typeof n.clientId||0===n.clientId.length||"string"!=typeof n.clientSecret||0===n.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");N(o,"blockstream-enterprise provider url");const t="string"==typeof n.tokenUrl&&n.tokenUrl.length>0;return t&&N(n.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:n.clientId,clientSecret:n.clientSecret,...t?{tokenUrl:n.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(n.provider)}"`)}}var R=new Map;async function q(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",n=`${r}\n${t.clientId}`,o=R.get(n);if(o)return o;const i=(async()=>{const n=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,i=setTimeout((()=>o.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,signal:o.signal})}finally{clearTimeout(i)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return i.catch((()=>R.delete(n))),R.set(n,i),i}(t,e);return{Authorization:`Bearer ${r}`}}}}function L(t,e){if(!Number.isSafeInteger(t)||t<0||t>h)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var _=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=M.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await q(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),n=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),S(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const o=await n.text();if(o.trim().startsWith("<!DOCTYPE")||o.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 i=parseInt(o.trim(),10);if(isNaN(i)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),i}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),D(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: ${O(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: ${O(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${O(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return L(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,n=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,i=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===i||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");L(s,`parseBlockstreamUTXOs ${o}:${i}`),n.push({txid:o,vout:i,satoshis:BigInt(s),confirmations:r})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const n=new AbortController,o=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[i,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:n.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(o),S(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${i}`),!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: ${O(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,i);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],n=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(O(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${O(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),i=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-i;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:i,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const n=new AbortController,o=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),i=await fetch(r,{signal:n.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),S(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`);const s=await i.json();if(!s.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=s.chain_stats.funded_txo_sum,c=s.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);L(a,`getBalance ${e} funded_txo_sum`),L(c,`getBalance ${e} spent_txo_sum`);const u=a-c;L(u,`getBalance ${e} confirmed balance`);const l=BigInt(u);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=O(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=O(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const n=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),S(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();if(i.status){if(!i.status.confirmed||!i.status.block_height)return{txid:i.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:i.txid??t,confirmations:1};const n=(await r.text()).trim(),o=Number.parseInt(n,10);if(!Number.isFinite(o)||o<=0)return{txid:i.txid??t,confirmations:1};const s=o-i.status.block_height+1;return{txid:i.txid??t,confirmations:s>0?s:0}}catch{return{txid:i.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(O(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return L(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},z="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",X={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 j(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var H=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),K=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)"]),V=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function G(t,e,r){return t.call({to:e,data:r})}async function J(t,e){const r=new ethers.utils.Interface([z]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([z]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?j({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):j(e)}(await t.call({to:e,data:r}))}catch(t){n=t}try{return await async function(t,e){const r=await G(t,e,H.encodeFunctionData("views",[])),[n]=H.decodeFunctionResult("views",r),[o,i,s,a,c,u,l,d]=await Promise.all([G(t,e,H.encodeFunctionData("paused",[])),G(t,e,H.encodeFunctionData("liquidationPaused",[])),G(t,e,H.encodeFunctionData("simplePsm",[])),G(t,n,K.encodeFunctionData("core",[])),G(t,n,K.encodeFunctionData("loanOps",[])),G(t,n,K.encodeFunctionData("collateralManager",[])),G(t,n,K.encodeFunctionData("liquidationManager",[])),G(t,n,K.encodeFunctionData("circuitBreaker",[]))]),h=H.decodeFunctionResult("paused",o)[0],p=H.decodeFunctionResult("liquidationPaused",i)[0],g=H.decodeFunctionResult("simplePsm",s)[0],f=K.decodeFunctionResult("core",a)[0],m=K.decodeFunctionResult("loanOps",c)[0],w=K.decodeFunctionResult("collateralManager",u)[0],v=K.decodeFunctionResult("liquidationManager",l)[0],y=K.decodeFunctionResult("circuitBreaker",d)[0],$=await G(t,m,V.encodeFunctionData("getUcdController",[])),b=await G(t,m,V.encodeFunctionData("ucdToken",[])),P=V.decodeFunctionResult("getUcdController",$)[0],T=V.decodeFunctionResult("ucdToken",b)[0],x=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await G(t,e,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,A,I,k,S,C,B,M]=await Promise.all([x(f),x(m),x(w),x(v),x(y),x(P),x(T),x(g)]);return j({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:A,collateralManagerPaused:I,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var Q={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function Z(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(w).join(", ")}`)}(t),r=Q[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var Y=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry"];function tt(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const n=(o=t.chainId,m[o]??null);var o;if(!n)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of Y){const o=n[e];if(!o)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const i=r[e];if("string"==typeof i&&i.length>0&&i.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${i}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}function et(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return v[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var rt=[{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"}],nt=[{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 ot(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),n="string"==typeof e?e:String(e??"");if(!n)throw new Error("Decrypt returned empty plaintext");return n}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function it(t){const{policy:e,ethersProvider:r,registryAddress:n,devBitcoinProviderUrl:o}=t;if(e.allowArbitraryBitcoinProvider){if(!o)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:o,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!n)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const n=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const n=new ethers.Contract(r,rt,e),[o,i]=await n.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:i[t].ciphertext,pkpId:i[t].pkpId,addedAt:Number(i[t].addedAt)});return s}(t.chainId,e,r);if(n.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${n.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:n}=t;if(!n||"string"!=typeof n)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const i=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(n,nt,r);let a;try{a=await s.isAllowedCid(e,i)}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=${i.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 o=[];for(const e of n){const r=await ot(e.ciphertext,e.pkpId),{url:n,auth:i}=F(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:n,auth:i,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}(e,r,n)}var st=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new _({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const n=this.providerConfigs,o=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const i=new Set,s=t.filter((t=>t.confirmations>=r));for(const t of s)i.add(`${t.txid}:${t.vout}`);if(!n||n.length<=1||!o)return i;const a=t=>n[t].name||n[t].providerUrl,c=await Promise.allSettled(o.slice(1).map((t=>t.getUTXOSet(e,r)))),u=c.map(((t,e)=>({r:t,name:a(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${n.length-1} secondary provider(s): ${u.join("; ")}`);const l=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of s){const e=`${t.txid}:${t.vout}`;let n=t.confirmations,o=t.confirmations;for(let r=0;r<l.length;r++){const i=l[r].get(e),s=a(r+1);if(!i)throw new Error(`Confirmed UTXO ${e} present on ${a(0)} but absent on ${s}; refusing to sign (possible fabricated UTXO).`);if(i.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${s}=${i.value.toString()}; refusing to sign.`);i.confirmations<n&&(n=i.confirmations),i.confirmations>o&&(o=i.confirmations)}if(o-n>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${o-n} exceeds tolerance 3 (min ${n}, max ${o}); providers disagree on depth, refusing to sign.`);n<r&&(i.delete(e),d.push(e))}d.length>0&&S(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<l.length;t++){const e=a(t+1);for(const[n,o]of l[t]){if(o.confirmations<r)continue;const t=h.get(n);if(!t)throw new Error(`Confirmed UTXO ${n} present on ${e} (${o.confirmations} confs) but absent on ${a(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==o.value)throw new Error(`Confirmed UTXO ${n} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${e}=${o.value.toString()}; refusing to sign.`);if(o.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${n} depth disagreement: ${a(0)}=${t.confirmations} vs ${e}=${o.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return i}async classifySelfChange(t,e,r){const n=this.providerConfigs,o=this.readers,i=new Set,s=t.filter((t=>t.confirmations<r));if(0===s.length)return i;if(this.assertProviderFloor("classifySelfChange"),!n||0===n.length||!o)return S(`[VaultBalance] ${s.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),i;const a=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of s){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),l=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),d=l.slice(0,5),h=l.length-d.length;h>0&&S(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const n=new Array(t.length);let o=0;const i=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=o++;if(e>=t.length)return;n[e]=await r(t[e])}}));return await Promise.all(i),n}(d,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),a,r,n,o)}))),g=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of s)g.has(t.txid)&&i.add(`${t.txid}:${t.vout}`);return g.size>0&&S(`[VaultBalance] self-change: ${i.size}/${s.length} unconfirmed UTXO(s) verified as protocol change by ${n.length} provider(s)`),i}async verifyParentIsSelfSpendConsensus(t,e,r,n,o,i){const s=t=>o[t].name||o[t].providerUrl,a=await Promise.allSettled(o.map(((o,s)=>this.evaluateParentForProvider(t,e,r,n,i[s],o)))),c=a.map(((t,e)=>({r:t,name:s(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${o.length} provider(s): ${c.join("; ")}`);const u=a.map((t=>t.value)),l=u.map((t=>t.selfSpend)),d=l.map(((t,e)=>({vote:t,name:s(e)}))).filter((t=>t.vote!==l[0])).map((t=>`${s(0)}=${l[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!l[0])return!1;const h=u.map(((t,e)=>t.outputMismatch?`${s(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,n,o,i){const s=await this.fetchParentTransaction(t,i);if(!s||0===s.inputs.length)return{selfSpend:!1,outputMismatch:null};const a=await this.verifyInputsAreSelfSpend(s.inputs,r,n,o),c=a?function(t,e,r){for(const n of t){const t=e.find((t=>t.index===n.vout));if(!t)return`claimed output ${n.txid}:${n.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${n.txid}:${n.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==n.satoshis)return`claimed output ${n.txid}:${n.vout} value ${t.value?.toString()??"<missing>"} != reported ${n.satoshis.toString()}`}return null}(e,s.outputs,r):null;return{selfSpend:a,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,n){const o=[...new Set(t.map((t=>t.txid)))],i=new Map,s=o.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(s.map((async t=>{i.set(t,await n.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=i.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const a=await Promise.all(o.map((t=>n.getTransaction(t))));for(const t of a)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,n=new AbortController,o=setTimeout((()=>n.abort()),r);try{const o=await fetch(`${e.providerUrl}/tx/${t}`,{signal:n.signal,headers:await q(e.auth,r)});if(!o.ok){if(404===o.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();if(!i.vin||!Array.isArray(i.vin)||0===i.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const s=[];for(const e of i.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);s.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:s,outputs:Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(D(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(o)}}};var at,ct=500,ut=2000000n,lt=11,dt=68,ht=34;function pt(t,e){const r=function(t,e){if(!Number.isInteger(t)||t<1)throw new Error(`estimateP2WPKHVBytes: numInputs must be a positive integer (got ${t})`);if(!Number.isInteger(e)||e<1)throw new Error(`estimateP2WPKHVBytes: numOutputs must be a positive integer (got ${e})`);return lt+dt*t+ht*e}(t,e),n=BigInt(ct)*BigInt(r);return n<ut?n:ut}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=U();console.log("[Step 0] Validating configuration...");const r=e.chain,n=e.bitcoinNetwork;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!n)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(n))throw new Error(`Invalid bitcoinNetwork: "${n}". Must be "mainnet", "testnet", or "regtest"`);const o=Z(r);if(n!==o.bitcoinNetwork)throw new Error(`bitcoinNetwork "${n}" does not match chain "${r}" policy (expected "${o.bitcoinNetwork}")`);const a=e.auth;if(!a||"object"!=typeof a)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!a.positionId)throw new Error("auth.positionId is required");if(!a.utxo||"object"!=typeof a.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===a.networkFee||a.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!a.targetAddress||"string"!=typeof a.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===a.targetAmount||null===a.targetAmount)throw new Error("auth.targetAmount is required");if(!a.utxo.txid||void 0===a.utxo.vout||!a.utxo.value||!a.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const c=a.positionId,u=a.utxo,l=a.utxos&&a.utxos.length>0?a.utxos:[u],d=a.networkFee,h=t=>String(t).toLowerCase().replace(/^0x/,"");if(!l.some((t=>h(t.txid)===h(u.txid)&&Number(t.vout)===Number(u.vout))))throw new Error(`Authorized UTXO ${u.txid}:${u.vout} is not present in the utxos[] input set; refusing to sign.`);console.log(" \u2705 Parameters validated"),console.log(` Position: ${c}`),console.log(` UTXOs to spend: ${l.length}`),console.log(` Network fee: ${d} sats`),console.log(` Bitcoin network: ${n}`);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 f=p,m=tt(o,e.contractAddresses);if(!m.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!m.PositionManager)throw new Error("contractAddresses.PositionManager is required");const w=m.LoanOperationsManagerModule,v=m.PositionManager,P=m.BTCSpendAuthorizer??w;console.log(` \u2705 Contract addresses resolved (${o.pinContractAddresses?"pinned":"caller-supplied"})`);let T="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${c}`),console.log(` UTXO: ${u.txid}:${u.vout} (${u.value} sats)`),T="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;if(!t||"string"!=typeof t)return Lit.Actions.setResponse({response:JSON.stringify({success:!1,error:"rpcUrl jsParam is required but was not provided"})}),void 0;const p=t;!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!y.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${y.join(", ")}`)}(o,p),console.log(` \u2705 Using RPC URL: ${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}(p)}`);const w=new ethers.providers.JsonRpcProvider(p);!function(t,e){const r=X[t],n=[];for(const t of r)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await J(w,v)),T="2",console.log("[Step 2] Resolving Bitcoin providers from registry...");const x=m.BitcoinProviderRegistry;if(!o.allowArbitraryBitcoinProvider&&!x)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 btc-transaction-signer resolves providers from the on-chain registry (no single-provider fallback)");const E=await it({policy:o,ethersProvider:w,registryAddress:x,devBitcoinProviderUrl:e.devBitcoinProviderUrl});if(E.length<o.minConsensusProviders)throw new Error(`btc-transaction-signer requires at least ${o.minConsensusProviders} Bitcoin provider(s) on ${o.chain}; ${E.length} registered. Refusing to sign without cross-provider consensus.`);const A=E[0];console.log(` \u2705 Bitcoin providers: ${E.length} (${E.map((t=>t.name)).join(", ")})`),T="3",console.log("[Step 3] Querying authorization from contract...");const k=[{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"}],S=new ethers.Contract(P,k,w),C=await S.getAuthorizedSpends(c);let B=null;for(const t of C){const e=t.txid.toLowerCase(),r=u.txid.toLowerCase(),n=Number(t.vout),o=Number(u.vout);if(e===r&&n===o){B=t;break}}if(!B)throw new Error(`No authorization found for UTXO ${u.txid}:${u.vout}`);const M=BigInt(B.targetAmount.toString()),U=B.targetAddress,O=BigInt(B.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${U}`),console.log(` Authorized at: ${O.toString()}`),T="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const D=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],N=new ethers.Contract(v,D,w),F=await N.core();console.log(` Core facet address: ${F}`);const R=[{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"}],q=new ethers.Contract(F,R,w),L=await q.getPositionDetails(c);let z;if(5===L.status){if(!m.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(m.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],w),e=await t.pkpOwners(L.pkpId);if(!e||e===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");z=e,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${z}`)}else z=L.borrower;console.log(` Position owner: ${z}`);const j=`${u.txid}:${u.vout}`,H=function(t){if(!Array.isArray(t)||0===t.length)throw new Error("hashBtcInputSet: at least one input is required");const e=t.map((t=>{const e=String(t.txid).toLowerCase().replace(/^0x/,""),r=Number(t.vout),n=Number(t.value);if(!/^[0-9a-f]{64}$/.test(e))throw new Error(`hashBtcInputSet: invalid txid "${t.txid}"`);if(!Number.isSafeInteger(r)||r<0)throw new Error(`hashBtcInputSet: invalid vout ${t.vout} for ${e}`);if(!Number.isSafeInteger(n)||n<=0)throw new Error(`hashBtcInputSet: invalid value ${t.value} for ${e}:${r}`);return{txid:e,vout:r,value:n}})),r=new Set;for(const t of e){const e=`${t.txid}:${t.vout}`;if(r.has(e))throw new Error(`hashBtcInputSet: duplicate outpoint ${e}`);r.add(e)}const n=e.sort(((t,e)=>t.txid<e.txid?-1:t.txid>e.txid?1:t.vout-e.vout)).map((t=>`${t.txid}:${t.vout}:${t.value}`)).join("|");return ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n))}(l.map((t=>({txid:t.txid,vout:t.vout,value:t.value})))),K=await I.verifyBtcExecutionAuthorization({positionId:a.positionId,timestamp:a.timestamp,chainId:a.chainId,utxoIdentifier:j,networkFee:a.networkFee,targetAddress:a.targetAddress,targetAmount:a.targetAmount,utxosHash:H,action:"execute-btc-withdrawal",signature:a.signature},z,function(t){return $[t]}(r),w);if(!K)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const V=String(U);if(a.targetAddress.toLowerCase()!==V.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${a.targetAddress}" but on-chain authorizer records "${V}"`);const W=BigInt(a.targetAmount.toString());if(W!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${W.toString()} but on-chain authorizer records ${M.toString()}`);T="4",console.log("[Step 4] Validating network fee...");const G=2,Q=pt(l.length,G);if(BigInt(d)>Q)throw new Error(`Network fee ${d} sats exceeds maximum ${Q.toString()} sats for a ${l.length}-input transaction (cap = ${ct} sat/vB)`);if(d<g)throw new Error(`Network fee ${d} sats below minimum ${g} sats`);if(BigInt(d)>=M)throw new Error(`Network fee ${d} sats cannot exceed target amount ${M.toString()} sats`);const Z=Number(M)-d;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${Z} sats`),T="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const Y=await i(f,n);console.log(` \u2705 PKP BTC address: ${Y}`);const tt=et(String(L.vaultAddress),r);if("string"!=typeof tt||0===tt.length)throw new Error(`Position ${c} has no on-chain vaultAddress for chain "${r}" \u2014 cannot bind PKP address`);const rt=tt.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");if(rt.toLowerCase()!==Y.toLowerCase())throw new Error(`Derived PKP BTC address ${Y} does not match position ${c}'s on-chain vault address ${rt} \u2014 the supplied publicKey is not this position's PKP`);console.log(" \u2705 PKP BTC address matches on-chain vaultAddress"),T="5.5",console.log("[Step 5.5] Checking UTXO existence on Bitcoin network..."),console.log(` Authorized UTXO: ${u.txid}:${u.vout}`);const nt=new _({providerUrl:A.url,auth:A.auth}),ot=await nt.getUTXOs(Y),at=new Map(ot.map((t=>[`${h(t.txid)}:${Number(t.vout)}`,t])));if(!at.has(`${h(u.txid)}:${Number(u.vout)}`))throw new Error(`Authorized UTXO ${u.txid}:${u.vout} no longer exists on Bitcoin (already spent) \u2014 refusing to sign a doomed transaction`);console.log(` \u2705 Authorized UTXO ${u.txid}:${u.vout} confirmed unspent on Bitcoin network`);const ut=o.minBitcoinSpendConfirmations,lt=new st(nt,E.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),o.minConsensusProviders),dt=function(t,e,r){const n=new Set;for(const o of t)e.has(`${o.txid}:${o.vout}`)&&n.add(`${r(o.txid)}:${Number(o.vout)}`);return n}(ot,await lt.confirmedUtxoConsensus(ot,Y,ut),h);!function(t,e,r,n,o){for(const i of t){const t=`${n(i.txid)}:${Number(i.vout)}`,s=e.get(t);if(!s)throw new Error(`Input ${i.txid}:${i.vout} is not an unspent output of the vault \u2014 refusing to sign`);if(s.satoshis!==BigInt(i.value))throw new Error(`Input ${i.txid}:${i.vout} declared value ${i.value} sats does not match the on-chain output value ${s.satoshis.toString()} sats \u2014 refusing to sign a corrupted sighash`);if(!r.has(t))throw new Error(`Input ${i.txid}:${i.vout} is not confirmed at the spend depth (${o}) \u2014 refusing to sign (reorg-vulnerable, or providers disagree on its depth)`)}}(l,at,dt,h,ut),console.log(` \u2705 All ${l.length} input(s) consensus-confirmed at >=${ut} conf across ${E.length} provider(s)`),T="6",console.log("[Step 6] Validating UTXO ownership...");const ht=s(Y);for(const t of l){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==ht)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${ht}, got ${e}`)}console.log(` \u2705 All ${l.length} UTXO(s) belong to vault (PKP address)`),T="7",console.log("[Step 7] Validating UTXO value...");const gt=Number(M),ft=l.reduce(((t,e)=>t+e.value),0);if(ft<gt)throw new Error(`Insufficient UTXO value: total ${ft} sats across ${l.length} input(s), need ${gt} sats`);const mt=ft-gt;console.log(` \u2705 Total UTXO value sufficient (${l.length} input(s))`),console.log(` Total value: ${ft} sats`),console.log(` Total required: ${gt} sats`),console.log(` Change: ${mt} sats`),T="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:wt,sigHashes:vt}=b({utxos:l,destination:U,amount:Z,changeAddress:Y,changeAmount:mt,network:n,pkpPublicKey:f});console.log(` \u2705 Transaction built (${l.length} input(s))`),console.log(` Signature hashes: ${vt.length}`),T="9",console.log(`[Step 9] Signing ${vt.length} input(s)...`);const yt=globalThis.pkpId;if(!yt)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const $t=await Lit.Actions.getPrivateKey({pkpId:yt}),bt="string"==typeof $t?$t.startsWith("0x")?$t:`0x${$t}`:String($t),Pt=new ethers.utils.SigningKey(bt),Tt=[];for(let t=0;t<vt.length;t++){const e=Pt.signDigest(vt[t]);Tt.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${vt[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:wt,sigHashes:vt,sigHash:vt[0],signatures:Tt,signature:Tt[0],pkpPublicKey:f,pkpBtcAddress:Y,destination:U,userReceivesAmount:Z,networkFee:d,changeAmount:mt,utxos:l.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:u.txid,vout:u.vout,value:u.value},authorization:{targetAmount:M.toString(),authorizedAt:O.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: ${T}`),{success:!1,error:t.message||t.toString(),positionId:a?.positionId,timestamp:Date.now()}}}return at=o,((o,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of r(i))n.call(o,c)||c===s||t(o,c,{get:()=>i[c],enumerable:!(a=e(i,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),at)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
1
+ var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};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),n=e.slice(66,130),o=(BigInt("0x"+n)%2n===0n?"02":"03")+r,i=ethers.utils.sha256("0x"+o);let s;s="mainnet"===t?"bc":"testnet"===t?"tb":"bcrt";const u=function(t,e,r){const n="qpzry9x8gf2tvdw0s3jn54khce6mua7l",o=[];for(let t=0;t<r.length;t+=2)o.push(parseInt(r.substr(t,2),16));const i=d(o,8,5,!0),s=[e,...i],u=function(t,e){const r=a(t).concat(e).concat([0,0,0,0,0,0]),n=1^c(r),o=[];for(let t=0;t<6;t++)o.push(n>>5*(5-t)&31);return o}(t,s),l=[...s,...u];let h=t+"1";for(let t=0;t<l.length;t++)h+=n[l[t]];return h}(s,0,ethers.utils.ripemd160(i).slice(2));return u}function s(t){if(/^(bc1|tb1|bcrt1)[0-9a-zA-Z]+$/.test(t)){const{version:e,program:r}=function(t){const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)throw new Error(`Mixed-case bech32 address not allowed: ${t}`);const o=r;if(o.length>90)throw new Error(`Bech32 address too long (${o.length} > 90): ${t}`);const i=o.lastIndexOf("1");if(i<1||i+7>o.length)throw new Error(`Invalid bech32 separator position in ${t}`);const s=o.slice(0,i),h=o.slice(i+1),p=[];for(let r=0;r<h.length;r++){const n=e.indexOf(h[r]);if(-1===n)throw new Error(`Invalid bech32 character '${h[r]}' in ${t}`);p.push(n)}const g=p[0];if(void 0===g||g<0||g>16)throw new Error(`Invalid witness version ${g} in ${t}`);const f=0===g?u:l;if(c(a(s).concat(p))!==f)throw new Error(`Invalid bech32${0===g?"":"m"} checksum for ${t}`);const m=d(p.slice(1,p.length-6),5,8,!1);if(m.length<2||m.length>40)throw new Error(`Invalid witness program length ${m.length} in ${t}`);if(0===g&&20!==m.length&&32!==m.length)throw new Error(`Witness v0 program must be 20 (P2WPKH) or 32 (P2WSH) bytes, got ${m.length} in ${t}`);const w=m.map((t=>t.toString(16).padStart(2,"0"))).join("");return{version:g,program:w}}(t);return(0===e?"00":(80+e).toString(16).padStart(2,"0"))+(r.length/2).toString(16).padStart(2,"0")+r}const{version:e,hash:r}=function(t){const e=function(t){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let r=0n;for(let n=0;n<t.length;n++){const o=e.indexOf(t[n]);if(o<0)throw new Error(`Invalid Base58 character: ${t[n]}`);r=58n*r+BigInt(o)}let n=r.toString(16);n.length%2&&(n="0"+n);for(let e=0;e<t.length&&"1"===t[e];e++)n="00"+n;return n}(t);if(50!==e.length)throw new Error(`Invalid Base58Check length for ${t} (expected 25 bytes)`);const r=e.slice(0,e.length-8),n=e.slice(e.length-8);if(ethers.utils.sha256(ethers.utils.sha256("0x"+r)).slice(2,10)!==n)throw new Error(`Invalid Base58Check checksum for ${t}`);const o=parseInt(r.slice(0,2),16),i=r.slice(2);return{version:o,hash:i}}(t);if(0===e||111===e)return"76a914"+r+"88ac";if(5===e||196===e)return"a914"+r+"87";throw new Error(`Unsupported base58 address version 0x${e.toString(16).padStart(2,"0")}: ${t}`)}function a(t){const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r)>>5);e.push(0);for(let r=0;r<t.length;r++)e.push(31&t.charCodeAt(r));return e}function c(t){const e=[996825010,642813549,513874426,1027748829,705979059];let r=1;for(let n=0;n<t.length;n++){const o=r>>25;r=(33554431&r)<<5^t[n];for(let t=0;t<5;t++)o>>t&1&&(r^=e[t])}return r}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(o,{main:()=>main});var u=1,l=734539939;function d(t,e,r,n){let o=0,i=0;const s=[],a=(1<<r)-1;for(let n=0;n<t.length;n++){const c=t[n];if(c<0||c>>e)throw new Error("Invalid data for bit conversion");for(o=o<<e|c,i+=e;i>=r;)i-=r,s.push(o>>i&a)}if(n)i>0&&s.push(o<<r-i&a);else if(i>=e||o<<r-i&a)throw new Error("Invalid padding in bit conversion");return s}var h=25e14,p=546n,g=100,f=60,m={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9"}};var w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),v={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){const{utxos:e,destination:r,amount:n,changeAddress:o,changeAmount:i}=t;if(0===e.length)throw new Error("buildBitcoinTransactionMultiInput: at least one UTXO required");const a="02000000",c="ffffffff",u="00000000",l=x(e.length),d=e.map((t=>P(t.txid)+T(t.vout,4)+"00"+c)).join(""),h=[],g=s(r);if(h.push(T(n,8)+x(g.length/2)+g),i>0){const t=s(o),e=function(t){const e=t.toLowerCase();return e.startsWith("0014")?294:e.startsWith("0020")||e.startsWith("5120")?330:Number(p)}(t);i<e?console.log(`[bitcoin/transaction] Sub-dust change of ${i} sats folded into the miner fee (dust limit ${e} sats for this script type \u2014 an output would be non-standard)`):h.push(T(i,8)+x(t.length/2)+t)}const f=x(h.length),m=h.join(""),w=a+l+d+f+m+u,v=e.map((t=>P(t.txid)+T(t.vout,4))).join(""),y=ethers.utils.sha256(ethers.utils.sha256("0x"+v)),$=e.map((()=>c)).join(""),b=ethers.utils.sha256(ethers.utils.sha256("0x"+$)),E=ethers.utils.sha256(ethers.utils.sha256("0x"+m));return{txHex:w,sigHashes:e.map((t=>{const e=P(t.txid)+T(t.vout,4),r="1976a914"+(t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey).slice(4)+"88ac",n=a+y.slice(2)+b.slice(2)+e+r+T(t.value,8)+c+E.slice(2)+u+"01000000";return ethers.utils.sha256(ethers.utils.sha256("0x"+n))}))}}function P(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 T(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`numToLittleEndianHex: value must be a non-negative safe integer (got ${t})`);let r=t.toString(16).padStart(2*e,"0");if(r.length>2*e)throw new Error(`numToLittleEndianHex: value ${t} does not fit in ${e} byte(s)`);const n=r.match(/../g);if(!n)throw new Error(`Invalid hex conversion: ${t}`);return n.reverse().join("")}function x(t){return t<253?t.toString(16).padStart(2,"0"):t<=65535?"fd"+T(t,2):t<=4294967295?"fe"+T(t,4):"ff"+T(t,8)}function E(t){return Math.floor(t/f)*f}async function A(){const t=Math.floor(Date.now()/1e3),e=t%f;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%f;return e<8||e>=52}(t))return;let r;r=e>=52?f-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: ${E(Math.floor(Date.now()/1e3))}`)}var I=class t{static verifyAmountPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.amount||null===t.amount)throw new Error("auth.amount is required");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async recoverSigner(t,e){try{const r=ethers.utils.arrayify(t),n=ethers.utils.hashMessage(r);return ethers.utils.recoverAddress(n,e)}catch(t){throw new Error(`Failed to recover signer: ${t instanceof Error?t.message:String(t)}`)}}static async checkEIP1271(t,e,r,n){try{const o=new ethers.Contract(t,["function isValidSignature(bytes32,bytes) view returns (bytes4)"],n);return"0x1626ba7e"===await o.isValidSignature(e,r)}catch{return!1}}static async checkPositionDelegate(t,e,r,n){try{const o=new ethers.Contract(r,["function positionDelegate(bytes32) view returns (address)"],n),i=await o.positionDelegate(t);return!(!i||i===ethers.constants.AddressZero)&&i.toLowerCase()===e.toLowerCase()}catch{return!1}}static async checkAgentDelegationGrant(t,e,r,n,o){try{const i=new ethers.Contract(n,["function canRenew(bytes32,address) view returns (bool,uint8)","function canRepay(bytes32,address) view returns (bool,uint8)","function canMint(bytes32,address) view returns (bool,uint8,uint32)"],o);if("renew"===r){const[r]=await i.canRenew(t,e);return{ok:!0===r,effectiveFloorBps:0}}if("repay"===r){const[r]=await i.canRepay(t,e);return{ok:!0===r,effectiveFloorBps:0}}const[s,,a]=await i.canMint(t,e);return{ok:!0===s,effectiveFloorBps:Number(a)}}catch{return{ok:!1,effectiveFloorBps:0}}}static async verifyActionAuthorization(t,e,r,n){const o=Math.floor(Date.now()/1e3);await A();const i=n?.strictCurrentQuantum?o:void 0;try{!function(t,e,r){const n=e??Math.floor(Date.now()/1e3),o=E(n),i=E(t);if(r?.strictCurrentQuantum){if(i!==o)throw new Error(`[Quantum] Signature must come from current quantum (strict mode). Signature quantum: ${i}, current quantum: ${o}`);return}const s=o-f,a=o+f;if(i!==s&&i!==o&&i!==a)throw new Error(`[Quantum] Signature outside 3-quantum window. Signature quantum: ${i}, Valid range: [${s} (past), ${o} (current), ${a} (next)]`);if(i===s){if(n<s+8)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in first 8 seconds of PAST quantum (${s}). This is unsafe due to boundary instability.`)}else if(i===a&&n>=a+52)throw new Error(`[Quantum] Dead zone violation: Current time (${n}) is in last 8 seconds of NEXT quantum (${a}). This is unsafe due to boundary instability.`)}(t.timestamp,i,{strictCurrentQuantum:!0===n?.strictCurrentQuantum})}catch{return!1}const s=e();let a="0x0000000000000000000000000000000000000000";try{a=await this.recoverSigner(s,t.signature)}catch{}return await r(a,s,t.signature)}static async verifyAmountPositionActionAuthorization(e,r,n,o,i,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],n)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,c,o))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,o);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyMintAuthorization(t,e,r,n,o,i){return"mint-ucd"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,o,i)}static async verifyPaymentAuthorization(t,e,r,n,o,i){return"make-payment"===t.action&&this.verifyAmountPositionActionAuthorization(t,e,r,n,o,i)}static async verifyWithdrawAuthorization(e,r,n,o){if("withdraw-btc"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="string"==typeof e.amount?BigInt(e.amount):e.amount,n=[e.positionId,e.timestamp,e.chainId,r.toString(),e.destinationAddress,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","string","bytes32"],n)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))))}static async verifyRecoveryAuthorization(e,r,n,o){if("btc-utxo-invalidator"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.utxoTxid,e.utxoVout,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint32","bytes32"],r)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))))}static verifyTermPositionActionAuthorizationStructure(t){if(!t||"object"!=typeof t)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!t.positionId)throw new Error("auth.positionId is required");if("number"!=typeof t.chainId)throw new Error("auth.chainId must be a number");if("number"!=typeof t.timestamp)throw new Error("auth.timestamp must be a number");if(void 0===t.newTerm||null===t.newTerm)throw new Error("auth.newTerm is required");if("number"!=typeof t.newTerm)throw new Error("auth.newTerm must be a number");if(!t.action)throw new Error("auth.action is required");if(!t.signature)throw new Error("auth.signature is required");return t}static async verifyTermPositionActionAuthorization(e,r,n,o,i,s){if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r=[e.positionId,e.timestamp,e.chainId,e.newTerm,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","uint256","bytes32"],r)}),(async(n,a,c)=>{if(n.toLowerCase()===r.toLowerCase())return!0;if(o){if(await t.checkEIP1271(r,a,c,o))return!0;if(s){const r=await t.checkAgentDelegationGrant(e.positionId,n,s.op,s.registry,o);return r.ok&&(s.outcome={viaAgent:!0,effectiveFloorBps:r.effectiveFloorBps}),r.ok}if(i)return t.checkPositionDelegate(e.positionId,n,i,o)}return!1}))}static async verifyExtendAuthorization(t,e,r,n,o,i){return"extend-position"===t.action&&this.verifyTermPositionActionAuthorization(t,e,r,n,o,i)}static async verifyBtcExecutionAuthorization(e,r,n,o){if("execute-btc-withdrawal"!==e.action)return!1;if(e.chainId!==n)throw new Error(`auth.chainId (${e.chainId}) does not match LIT action target chain (${n})`);if("string"!=typeof e.utxosHash||!/^0x[0-9a-fA-F]{64}$/.test(e.utxosHash))throw new Error("auth.utxosHash is required (bytes32 hex) \u2014 the input set must be bound into the user signature");return this.verifyActionAuthorization(e,(()=>{const t=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(e.action)),r="bigint"==typeof e.targetAmount?e.targetAmount:BigInt(e.targetAmount),n=[e.positionId,e.timestamp,e.chainId,e.utxoIdentifier,e.networkFee,e.targetAddress,r.toString(),e.utxosHash,t];return ethers.utils.solidityKeccak256(["bytes32","uint256","uint256","string","uint256","string","uint256","bytes32","bytes32"],n)}),(async(e,n,i)=>e.toLowerCase()===r.toLowerCase()||!(!o||!await t.checkEIP1271(r,n,i,o))),{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 k(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 S(...t){k()&&console.log(...t)}var C=class{stepStart(t,e){}stepEnd(t,e){}log(t,e,...r){}warn(t,e){}error(t,e){}getElapsed(){return 0}getRemaining(){return 3e4}summary(){}getExecutionId(){return""}isDebugEnabled(){return!1}},B=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${n}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const n=Date.now()-r;this.stepDurations.set(t,n),console.log(`[Step ${t}] Duration: ${n}ms`),n>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${n}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-o;i<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${i}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const n=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${n}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},M=class{static create(t="LIT Action",e){return k(e)?new B(t):new C}};function U(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function O(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function D(t){return t instanceof Error&&"AbortError"===t.name}function N(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function F(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error("parseProviderPlaintext: empty plaintext");const r=t.trim();if(!r.startsWith("{"))return e?.requireHttps&&N(r,"provider url"),{url:r,auth:{provider:"esplora"}};let n;try{n=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof n.url||0===n.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=n.url.trim();switch(n.provider){case void 0:case"esplora":return e?.requireHttps&&N(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof n.apiKey||0===n.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return N(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:n.apiKey}};case"blockstream-enterprise":{if("string"!=typeof n.clientId||0===n.clientId.length||"string"!=typeof n.clientSecret||0===n.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");N(o,"blockstream-enterprise provider url");const t="string"==typeof n.tokenUrl&&n.tokenUrl.length>0;return t&&N(n.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:n.clientId,clientSecret:n.clientSecret,...t?{tokenUrl:n.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(n.provider)}"`)}}var R=new Map;async function q(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",n=`${r}\n${t.clientId}`,o=R.get(n);if(o)return o;const i=(async()=>{const n=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,i=setTimeout((()=>o.abort()),e&&e>0?e:1e4);let s;try{s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,signal:o.signal})}finally{clearTimeout(i)}if(!s.ok)throw new Error(`Blockstream OAuth token exchange failed: ${s.status} ${s.statusText}`);const a=await s.json(),c=a?.access_token;if("string"!=typeof c||0===c.length)throw new Error("Blockstream OAuth token exchange returned no access_token");return c})();return i.catch((()=>R.delete(n))),R.set(n,i),i}(t,e);return{Authorization:`Bearer ${r}`}}}}function L(t,e){if(!Number.isSafeInteger(t)||t<0||t>h)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var _=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=M.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await q(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),n=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),S(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Failed to fetch block height: ${n.status} ${n.statusText}`);const o=await n.text();if(o.trim().startsWith("<!DOCTYPE")||o.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 i=parseInt(o.trim(),10);if(isNaN(i)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),i}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),D(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: ${O(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: ${O(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${O(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return L(e,`fetchUTXOsFromRPC ${t.txid}:${t.vout}`),{txid:t.txid,vout:t.vout,satoshis:BigInt(e),confirmations:t.confirmations}}))}parseBlockstreamUTXOs(t,e){if(!Array.isArray(t))throw new Error("Invalid Blockstream response format: expected an array");const r=t,n=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,i=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===i||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");L(s,`parseBlockstreamUTXOs ${o}:${i}`),n.push({txid:o,vout:i,satoshis:BigInt(s),confirmations:r})}return n}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const n=new AbortController,o=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),[i,s]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:n.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(o),S(`[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now()-t}ms endpoint tail .../${e.slice(0,12)}.../utxo (timeout budget ${this.timeout}ms)`),this.logger.log("1",`Current block height: ${i}`),!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: ${O(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(c,null,2)}`);const u=this.parseBlockstreamUTXOs(c,i);return this.logger.stepEnd("1"),u}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],n=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),n=null;break}catch(t){n=t instanceof Error?t:new Error(O(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${O(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(n)throw new Error(`Failed to query UTXOs after 3 attempts: ${n.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),i=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-i;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:i,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const n=new AbortController,o=setTimeout((()=>n.abort()),this.timeout);try{const t=Date.now(),i=await fetch(r,{signal:n.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),S(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`);const s=await i.json();if(!s.chain_stats)throw new Error("Invalid response: missing chain_stats");const a=s.chain_stats.funded_txo_sum,c=s.chain_stats.spent_txo_sum;if(void 0===a||void 0===c)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${a}, spent_txo_sum: ${c}`);L(a,`getBalance ${e} funded_txo_sum`),L(c,`getBalance ${e} spent_txo_sum`);const u=a-c;L(u,`getBalance ${e} confirmed balance`);const l=BigInt(u);return this.logger.log("3",`Balance: ${l.toString()} sats`),this.logger.log("3",` - Funded: ${a} sats, Spent: ${c} sats`),l}catch(t){if(clearTimeout(o),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=O(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=O(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const n=Date.now(),o=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),S(`[BitcoinDataProvider] GET tx/${t.slice(0,10)}\u2026 ${Date.now()-n}ms (timeout budget ${this.timeout}ms)`),!o.ok){if(404===o.status)return null;throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();if(i.status){if(!i.status.confirmed||!i.status.block_height)return{txid:i.txid??t,confirmations:0};try{const r=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:e.signal,headers:await this.withAuth()});if(!r.ok)return{txid:i.txid??t,confirmations:1};const n=(await r.text()).trim(),o=Number.parseInt(n,10);if(!Number.isFinite(o)||o<=0)return{txid:i.txid??t,confirmations:1};const s=o-i.status.block_height+1;return{txid:i.txid??t,confirmations:s>0?s:0}}catch{return{txid:i.txid??t,confirmations:1}}}return null}catch(t){if(clearTimeout(r),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(O(t).includes("404"))return null;throw t}}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const n=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!n.ok){if(404===n.status)return null;throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`)}const o=await n.json();return o.vout&&Array.isArray(o.vout)?o.vout.map(((e,r)=>{if(void 0===e.value)throw new Error(`getTransactionOutputs(${t}): output ${r} is missing its value \u2014 malformed provider response, refusing to return outputs that cannot be value-verified`);return L(e.value,`getTransactionOutputs(${t}) output ${r}`),{index:r,scriptpubkey:e.scriptpubkey,scriptpubkey_address:e.scriptpubkey_address,value:e.value}})):null}catch(t){if(clearTimeout(r),D(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}},z="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",X={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 j(t){return{positionManagerPaused:t.positionManagerPaused,positionManagerLiquidationsPaused:t.positionManagerLiquidationsPaused,positionManagerCorePaused:t.positionManagerCorePaused,loanOperationsPaused:t.loanOperationsPaused,collateralManagerPaused:t.collateralManagerPaused,liquidationManagerPaused:t.liquidationManagerPaused,circuitBreakerPaused:t.circuitBreakerPaused,ucdControllerPaused:t.ucdControllerPaused,ucdTokenPaused:t.ucdTokenPaused,simplePsmPaused:t.simplePsmPaused}}var H=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),K=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)"]),V=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function G(t,e,r){return t.call({to:e,data:r})}async function J(t,e){const r=new ethers.utils.Interface([z]).encodeFunctionData("getProtocolPauseStatus",[]);let n;try{return function(t){const e=new ethers.utils.Interface([z]).decodeFunctionResult("getProtocolPauseStatus",t)[0];return Array.isArray(e)?j({positionManagerPaused:e[0],positionManagerLiquidationsPaused:e[1],positionManagerCorePaused:e[2],loanOperationsPaused:e[3],collateralManagerPaused:e[4],liquidationManagerPaused:e[5],circuitBreakerPaused:e[6],ucdControllerPaused:e[7],ucdTokenPaused:e[8],simplePsmPaused:e[9]}):j(e)}(await t.call({to:e,data:r}))}catch(t){n=t}try{return await async function(t,e){const r=await G(t,e,H.encodeFunctionData("views",[])),[n]=H.decodeFunctionResult("views",r),[o,i,s,a,c,u,l,d]=await Promise.all([G(t,e,H.encodeFunctionData("paused",[])),G(t,e,H.encodeFunctionData("liquidationPaused",[])),G(t,e,H.encodeFunctionData("simplePsm",[])),G(t,n,K.encodeFunctionData("core",[])),G(t,n,K.encodeFunctionData("loanOps",[])),G(t,n,K.encodeFunctionData("collateralManager",[])),G(t,n,K.encodeFunctionData("liquidationManager",[])),G(t,n,K.encodeFunctionData("circuitBreaker",[]))]),h=H.decodeFunctionResult("paused",o)[0],p=H.decodeFunctionResult("liquidationPaused",i)[0],g=H.decodeFunctionResult("simplePsm",s)[0],f=K.decodeFunctionResult("core",a)[0],m=K.decodeFunctionResult("loanOps",c)[0],w=K.decodeFunctionResult("collateralManager",u)[0],v=K.decodeFunctionResult("liquidationManager",l)[0],y=K.decodeFunctionResult("circuitBreaker",d)[0],$=await G(t,m,V.encodeFunctionData("getUcdController",[])),b=await G(t,m,V.encodeFunctionData("ucdToken",[])),P=V.decodeFunctionResult("getUcdController",$)[0],T=V.decodeFunctionResult("ucdToken",b)[0],x=async e=>{if(!e||e===ethers.constants.AddressZero)return!1;try{const r=await G(t,e,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch{return!1}},[E,A,I,k,S,C,B,M]=await Promise.all([x(f),x(m),x(w),x(v),x(y),x(P),x(T),x(g)]);return j({positionManagerPaused:h,positionManagerLiquidationsPaused:p,positionManagerCorePaused:E,loanOperationsPaused:A,collateralManagerPaused:I,liquidationManagerPaused:k,circuitBreakerPaused:S,ucdControllerPaused:C,ucdTokenPaused:B,simplePsmPaused:M})}(t,e)}catch(t){const e=n instanceof Error?n.message:String(n),r=t instanceof Error?t.message:String(t);throw new Error(`getProtocolPauseStatus failed (aggregate: ${e}; decomposed: ${r})`)}}var Q={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:v.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:v.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:v.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function Z(t){const e=function(t){const e=t.toLowerCase().trim();if("sepolia"===e)return"sepolia";if("ethereum"===e||"mainnet"===e)return"ethereum";if("hardhat"===e)return"hardhat";throw new Error(`Unsupported EVM chain: "${t}". Supported chains: ${Object.values(w).join(", ")}`)}(t),r=Q[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var Y=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry"];function tt(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const n=(o=t.chainId,m[o]??null);var o;if(!n)throw new Error(`No pinned contract-address set for chainId ${t.chainId} (${t.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const e of Y){const o=n[e];if(!o)throw new Error(`Pinned address set for ${t.chain} is missing required "${e}"; refusing to fall through to a caller-supplied value`);const i=r[e];if("string"==typeof i&&i.length>0&&i.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${i}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}function et(t,e){try{const r=JSON.parse(t);if("object"==typeof r&&null!==r){if("sepolia"===e.toLowerCase())return r.regtest||r.testnet||r.mainnet;const t=function(t){return v[t]}(e);return"regtest"===t?r.regtest||r.testnet||r.mainnet:"testnet"===t&&(r.testnet||r.regtest)||r.mainnet}}catch(t){}return t}var rt=[{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"}],nt=[{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 ot(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),n="string"==typeof e?e:String(e??"");if(!n)throw new Error("Decrypt returned empty plaintext");return n}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function it(t){const{policy:e,ethersProvider:r,registryAddress:n,devBitcoinProviderUrl:o}=t;if(e.allowArbitraryBitcoinProvider){if(!o)throw new Error("resolveAllBitcoinProviders: devBitcoinProviderUrl is required on hardhat (no on-chain registry)");return[{name:"Dev Provider",url:o,minConfirmations:e.minBitcoinBalanceConfirmations,network:e.bitcoinNetwork}]}if(!n)throw new Error(`resolveAllBitcoinProviders: BitcoinProviderRegistry address required on chain "${e.chain}"`);return async function(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const n=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const n=new ethers.Contract(r,rt,e),[o,i]=await n.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:i[t].ciphertext,pkpId:i[t].pkpId,addedAt:Number(i[t].addedAt)});return s}(t.chainId,e,r);if(n.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${n.length} provider(s) for chainId=${t.chainId} in ${r}; chain "${t.chain}" requires at least ${t.minConsensusProviders} for balance consensus. Admin must addProvider(...) via AdminModule before LIT Actions can sign.`);await async function(t){const{chainId:e,ethersProvider:r,registryAddress:n}=t;if(!n||"string"!=typeof n)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const i=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(n,nt,r);let a;try{a=await s.isAllowedCid(e,i)}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=${i.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 o=[];for(const e of n){const r=await ot(e.ciphertext,e.pkpId),{url:n,auth:i}=F(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:n,auth:i,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}(e,r,n)}var st=class{constructor(t,e,r){this.primaryProvider=t,this.providerConfigs=e,this.minConsensusProviders=r,this.readers=this.buildReaders()}assertProviderFloor(t){const e=this.providerConfigs?.length??0;if(this.minConsensusProviders>1&&e<this.minConsensusProviders)throw new Error(`${t}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers for consensus; ${e} configured. Refusing to proceed without cross-check.`)}buildReaders(){const t=this.providerConfigs;return t&&0!==t.length?t.map(((t,e)=>0===e?this.primaryProvider:new _({providerUrl:t.providerUrl,auth:t.auth,...t.timeout?{timeout:t.timeout}:{}}))):null}async confirmedUtxoConsensus(t,e,r){const n=this.providerConfigs,o=this.readers;this.assertProviderFloor("confirmedUtxoConsensus");const i=new Set,s=t.filter((t=>t.confirmations>=r));for(const t of s)i.add(`${t.txid}:${t.vout}`);if(!n||n.length<=1||!o)return i;const a=t=>n[t].name||n[t].providerUrl,c=await Promise.allSettled(o.slice(1).map((t=>t.getUTXOSet(e,r)))),u=c.map(((t,e)=>({r:t,name:a(e+1)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(u.length>0)throw new Error(`Confirmed UTXO set read failed for ${e} on ${u.length}/${n.length-1} secondary provider(s): ${u.join("; ")}`);const l=c.map((t=>{const e=new Map;for(const r of t.value.utxos)e.set(`${r.txid}:${r.vout}`,{value:r.satoshis,confirmations:r.confirmations});return e})),d=[];for(const t of s){const e=`${t.txid}:${t.vout}`;let n=t.confirmations,o=t.confirmations;for(let r=0;r<l.length;r++){const i=l[r].get(e),s=a(r+1);if(!i)throw new Error(`Confirmed UTXO ${e} present on ${a(0)} but absent on ${s}; refusing to sign (possible fabricated UTXO).`);if(i.value!==t.satoshis)throw new Error(`Confirmed UTXO ${e} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${s}=${i.value.toString()}; refusing to sign.`);i.confirmations<n&&(n=i.confirmations),i.confirmations>o&&(o=i.confirmations)}if(o-n>3)throw new Error(`Confirmed UTXO ${e} confirmation spread ${o-n} exceeds tolerance 3 (min ${n}, max ${o}); providers disagree on depth, refusing to sign.`);n<r&&(i.delete(e),d.push(e))}d.length>0&&S(`[VaultBalance] confirmed-consensus: ${d.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${d.join(", ")}`);const h=new Map(t.map((t=>[`${t.txid}:${t.vout}`,t])));for(let t=0;t<l.length;t++){const e=a(t+1);for(const[n,o]of l[t]){if(o.confirmations<r)continue;const t=h.get(n);if(!t)throw new Error(`Confirmed UTXO ${n} present on ${e} (${o.confirmations} confs) but absent on ${a(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 may be transient during an in-flight vault spend).`);if(t.satoshis!==o.value)throw new Error(`Confirmed UTXO ${n} value mismatch: ${a(0)}=${t.satoshis.toString()} vs ${e}=${o.value.toString()}; refusing to sign.`);if(o.confirmations-t.confirmations>3)throw new Error(`Confirmed UTXO ${n} depth disagreement: ${a(0)}=${t.confirmations} vs ${e}=${o.confirmations} exceeds tolerance 3; the primary may be under-reporting depth to suppress collateral, refusing to sign.`)}}return i}async classifySelfChange(t,e,r){const n=this.providerConfigs,o=this.readers,i=new Set,s=t.filter((t=>t.confirmations<r));if(0===s.length)return i;if(this.assertProviderFloor("classifySelfChange"),!n||0===n.length||!o)return S(`[VaultBalance] ${s.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`),i;const a=e.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");const c=new Map;for(const t of s){const e=c.get(t.txid)??[];e.push(t),c.set(t.txid,e)}const u=t=>c.get(t).reduce(((t,e)=>t+e.satoshis),0n),l=[...c.keys()].sort(((t,e)=>{const r=u(e)-u(t);return 0n!==r?r>0n?1:-1:t<e?-1:t>e?1:0})),d=l.slice(0,5),h=l.length-d.length;h>0&&S(`[VaultBalance] self-change: ${h} parent tx(s) beyond the 5-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`);const p=await async function(t,e,r){const n=new Array(t.length);let o=0;const i=Array.from({length:Math.min(e,t.length)},(async()=>{for(;;){const e=o++;if(e>=t.length)return;n[e]=await r(t[e])}}));return await Promise.all(i),n}(d,2,(async t=>({parentTxid:t,verified:await this.verifyParentIsSelfSpendConsensus(t,c.get(t),a,r,n,o)}))),g=new Set(p.filter((t=>t.verified)).map((t=>t.parentTxid)));for(const t of s)g.has(t.txid)&&i.add(`${t.txid}:${t.vout}`);return g.size>0&&S(`[VaultBalance] self-change: ${i.size}/${s.length} unconfirmed UTXO(s) verified as protocol change by ${n.length} provider(s)`),i}async verifyParentIsSelfSpendConsensus(t,e,r,n,o,i){const s=t=>o[t].name||o[t].providerUrl,a=await Promise.allSettled(o.map(((o,s)=>this.evaluateParentForProvider(t,e,r,n,i[s],o)))),c=a.map(((t,e)=>({r:t,name:s(e)}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(c.length>0)throw new Error(`Self-change classification failed for tx ${t} on ${c.length}/${o.length} provider(s): ${c.join("; ")}`);const u=a.map((t=>t.value)),l=u.map((t=>t.selfSpend)),d=l.map(((t,e)=>({vote:t,name:s(e)}))).filter((t=>t.vote!==l[0])).map((t=>`${s(0)}=${l[0]} vs ${t.name}=${t.vote}`));if(d.length>0)throw new Error(`Self-change consensus mismatch for tx ${t}: ${d.join("; ")}. A provider may be compromised or out of sync; refusing to sign.`);if(!l[0])return!1;const h=u.map(((t,e)=>t.outputMismatch?`${s(e)} \u2192 ${t.outputMismatch}`:null)).filter((t=>null!==t));if(h.length>0)throw new Error(`Self-change output claim mismatch for tx ${t}: ${h.join("; ")}. The reported UTXO set contradicts the parent transaction; refusing to sign.`);return!0}async evaluateParentForProvider(t,e,r,n,o,i){const s=await this.fetchParentTransaction(t,i);if(!s||0===s.inputs.length)return{selfSpend:!1,outputMismatch:null};const a=await this.verifyInputsAreSelfSpend(s.inputs,r,n,o),c=a?function(t,e,r){for(const n of t){const t=e.find((t=>t.index===n.vout));if(!t)return`claimed output ${n.txid}:${n.vout} not present in parent tx`;if(t.scriptpubkey_address!==r)return`claimed output ${n.txid}:${n.vout} pays ${t.scriptpubkey_address??"<no address>"}, not the vault`;if(void 0===t.value||t.value!==n.satoshis)return`claimed output ${n.txid}:${n.vout} value ${t.value?.toString()??"<missing>"} != reported ${n.satoshis.toString()}`}return null}(e,s.outputs,r):null;return{selfSpend:a,outputMismatch:c}}async verifyInputsAreSelfSpend(t,e,r,n){const o=[...new Set(t.map((t=>t.txid)))],i=new Map,s=o.filter((e=>t.some((t=>t.txid===e&&void 0===t.prevoutAddress))));await Promise.all(s.map((async t=>{i.set(t,await n.getTransactionOutputs(t))})));for(const r of t){let t=r.prevoutAddress;if(void 0===t){const e=i.get(r.txid);t=e?.find((t=>t.index===r.vout))?.scriptpubkey_address}if(t!==e)return!1}const a=await Promise.all(o.map((t=>n.getTransaction(t))));for(const t of a)if(!t||t.confirmations<r)return!1;return!0}async fetchParentTransaction(t,e){if(!e.providerUrl)return null;const r=e.timeout||15e3,n=new AbortController,o=setTimeout((()=>n.abort()),r);try{const o=await fetch(`${e.providerUrl}/tx/${t}`,{signal:n.signal,headers:await q(e.auth,r)});if(!o.ok){if(404===o.status)throw new Error(`parent tx ${t} not found on this provider \u2014 cannot verify the self-change proof`);throw new Error(`Bitcoin provider error: ${o.status} ${o.statusText}`)}const i=await o.json();if(!i.vin||!Array.isArray(i.vin)||0===i.vin.length)throw new Error(`provider returned tx ${t} without a vin array \u2014 malformed response`);const s=[];for(const e of i.vin){if(e.is_coinbase)return null;if(void 0===e.txid||void 0===e.vout)throw new Error(`provider returned tx ${t} with a malformed vin row (missing txid/vout)`);s.push({txid:e.txid,vout:e.vout,prevoutAddress:e.prevout?.scriptpubkey_address})}return{inputs:s,outputs:Array.isArray(i.vout)?i.vout.map(((t,e)=>({index:e,scriptpubkey_address:t?.scriptpubkey_address,value:"number"==typeof t?.value?BigInt(t.value):void 0}))):[]}}catch(t){if(D(t))throw new Error(`Request timeout after ${r}ms`);throw t}finally{clearTimeout(o)}}};var at,ct=500,ut=2000000n,lt=11,dt=68,ht=34;function pt(t,e){const r=function(t,e){if(!Number.isInteger(t)||t<1)throw new Error(`estimateP2WPKHVBytes: numInputs must be a positive integer (got ${t})`);if(!Number.isInteger(e)||e<1)throw new Error(`estimateP2WPKHVBytes: numOutputs must be a positive integer (got ${e})`);return lt+dt*t+ht*e}(t,e),n=BigInt(ct)*BigInt(r);return n<ut?n:ut}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=U();console.log("[Step 0] Validating configuration...");const r=e.chain,n=e.bitcoinNetwork;if(!r)throw new Error('Missing required parameter: "chain". Must be "sepolia" or "ethereum"');if(!n)throw new Error('Missing required parameter: "bitcoinNetwork". Must be "mainnet", "testnet", or "regtest"');if(!["mainnet","testnet","regtest"].includes(n))throw new Error(`Invalid bitcoinNetwork: "${n}". Must be "mainnet", "testnet", or "regtest"`);const o=Z(r);if(n!==o.bitcoinNetwork)throw new Error(`bitcoinNetwork "${n}" does not match chain "${r}" policy (expected "${o.bitcoinNetwork}")`);const a=e.auth;if(!a||"object"!=typeof a)throw new Error('Missing or invalid "auth" parameter - must be an object');if(!a.positionId)throw new Error("auth.positionId is required");if(!a.utxo||"object"!=typeof a.utxo)throw new Error("auth.utxo is required and must be an object");if(void 0===a.networkFee||a.networkFee<0)throw new Error("auth.networkFee is required and must be non-negative");if(!a.targetAddress||"string"!=typeof a.targetAddress)throw new Error("auth.targetAddress is required (string)");if(void 0===a.targetAmount||null===a.targetAmount)throw new Error("auth.targetAmount is required");if(!a.utxo.txid||void 0===a.utxo.vout||!a.utxo.value||!a.utxo.scriptPubKey)throw new Error("Invalid UTXO: must have txid, vout, value, scriptPubKey");const c=a.positionId,u=a.utxo,l=a.utxos&&a.utxos.length>0?a.utxos:[u],d=a.networkFee,h=t=>String(t).toLowerCase().replace(/^0x/,"");if(!l.some((t=>h(t.txid)===h(u.txid)&&Number(t.vout)===Number(u.vout))))throw new Error(`Authorized UTXO ${u.txid}:${u.vout} is not present in the utxos[] input set; refusing to sign.`);console.log(" \u2705 Parameters validated"),console.log(` Position: ${c}`),console.log(` UTXOs to spend: ${l.length}`),console.log(` Network fee: ${d} sats`),console.log(` Bitcoin network: ${n}`);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 f=p,m=tt(o,e.contractAddresses);if(!m.LoanOperationsManagerModule)throw new Error("contractAddresses.LoanOperationsManagerModule is required");if(!m.PositionManager)throw new Error("contractAddresses.PositionManager is required");const w=m.LoanOperationsManagerModule,v=m.PositionManager,P=m.BTCSpendAuthorizer??w;console.log(` \u2705 Contract addresses resolved (${o.pinContractAddresses?"pinned":"caller-supplied"})`);let T="0.5";try{console.log("[BTC Transaction Signer] Started"),console.log(` Position: ${c}`),console.log(` UTXO: ${u.txid}:${u.vout} (${u.value} sats)`),T="1",console.log("[Step 1] Setting up RPC connection...");const t=e.rpcUrl;if(!t||"string"!=typeof t)return Lit.Actions.setResponse({response:JSON.stringify({success:!1,error:"rpcUrl jsParam is required but was not provided"})}),void 0;const p=t;!function(t,e){if(t.allowArbitraryEvmRpc)return;if(!e||"string"!=typeof e)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(e).hostname}catch(t){throw new Error(`Invalid rpcUrl: ${t?.message??String(t)}`)}if(!y.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${y.join(", ")}`)}(o,p),console.log(` \u2705 Using RPC URL: ${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}(p)}`);const w=new ethers.providers.JsonRpcProvider(p);!function(t,e){const r=X[t],n=[];for(const t of r)e[t]&&n.push(t);if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:t,paused:n,status:e}))}("btcTransactionSign",await J(w,v)),T="2",console.log("[Step 2] Resolving Bitcoin providers from registry...");const x=m.BitcoinProviderRegistry;if(!o.allowArbitraryBitcoinProvider&&!x)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains \u2014 btc-transaction-signer resolves providers from the on-chain registry (no single-provider fallback)");const E=await it({policy:o,ethersProvider:w,registryAddress:x,devBitcoinProviderUrl:e.devBitcoinProviderUrl});if(E.length<o.minConsensusProviders)throw new Error(`btc-transaction-signer requires at least ${o.minConsensusProviders} Bitcoin provider(s) on ${o.chain}; ${E.length} registered. Refusing to sign without cross-provider consensus.`);const A=E[0];console.log(` \u2705 Bitcoin providers: ${E.length} (${E.map((t=>t.name)).join(", ")})`),T="3",console.log("[Step 3] Querying authorization from contract...");const k=[{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"}],S=new ethers.Contract(P,k,w),C=await S.getAuthorizedSpends(c);let B=null;for(const t of C){const e=t.txid.toLowerCase(),r=u.txid.toLowerCase(),n=Number(t.vout),o=Number(u.vout);if(e===r&&n===o){B=t;break}}if(!B)throw new Error(`No authorization found for UTXO ${u.txid}:${u.vout}`);const M=BigInt(B.targetAmount.toString()),U=B.targetAddress,O=BigInt(B.authorizedAt.toString());console.log(" \u2705 Authorization found on-chain"),console.log(` Target amount: ${M.toString()} sats`),console.log(` Destination: ${U}`),console.log(` Authorized at: ${O.toString()}`),T="3.5",console.log("[Step 3.5] Verifying owner signature for network fee...");const D=[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],N=new ethers.Contract(v,D,w),F=await N.core();console.log(` Core facet address: ${F}`);const R=[{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"}],q=new ethers.Contract(F,R,w),L=await q.getPositionDetails(c);let z;if(5===L.status){if(!m.LITActionValidator)throw new Error("LITActionValidator address required for liquidated position BTC signing");const t=new ethers.Contract(m.LITActionValidator,["function pkpOwners(bytes32) view returns (address)"],w),e=await t.pkpOwners(L.pkpId);if(!e||e===ethers.constants.AddressZero)throw new Error("No PKP owner registered for liquidated position \u2014 cannot authorize BTC signing");z=e,console.log(` \u2139\ufe0f LIQUIDATED position \u2014 verifying against PKP owner: ${z}`)}else z=L.borrower;console.log(` Position owner: ${z}`);const j=`${u.txid}:${u.vout}`,H=function(t){if(!Array.isArray(t)||0===t.length)throw new Error("hashBtcInputSet: at least one input is required");const e=t.map((t=>{const e=String(t.txid).toLowerCase().replace(/^0x/,""),r=Number(t.vout),n=Number(t.value);if(!/^[0-9a-f]{64}$/.test(e))throw new Error(`hashBtcInputSet: invalid txid "${t.txid}"`);if(!Number.isSafeInteger(r)||r<0)throw new Error(`hashBtcInputSet: invalid vout ${t.vout} for ${e}`);if(!Number.isSafeInteger(n)||n<=0)throw new Error(`hashBtcInputSet: invalid value ${t.value} for ${e}:${r}`);return{txid:e,vout:r,value:n}})),r=new Set;for(const t of e){const e=`${t.txid}:${t.vout}`;if(r.has(e))throw new Error(`hashBtcInputSet: duplicate outpoint ${e}`);r.add(e)}const n=e.sort(((t,e)=>t.txid<e.txid?-1:t.txid>e.txid?1:t.vout-e.vout)).map((t=>`${t.txid}:${t.vout}:${t.value}`)).join("|");return ethers.utils.keccak256(ethers.utils.toUtf8Bytes(n))}(l.map((t=>({txid:t.txid,vout:t.vout,value:t.value})))),K=await I.verifyBtcExecutionAuthorization({positionId:a.positionId,timestamp:a.timestamp,chainId:a.chainId,utxoIdentifier:j,networkFee:a.networkFee,targetAddress:a.targetAddress,targetAmount:a.targetAmount,utxosHash:H,action:"execute-btc-withdrawal",signature:a.signature},z,function(t){return $[t]}(r),w);if(!K)throw new Error("Caller not authorized for execution");console.log(" \u2705 Owner signature verified");const V=String(U);if(a.targetAddress.toLowerCase()!==V.toLowerCase())throw new Error(`targetAddress mismatch \u2014 user signed "${a.targetAddress}" but on-chain authorizer records "${V}"`);const W=BigInt(a.targetAmount.toString());if(W!==M)throw new Error(`targetAmount mismatch \u2014 user signed ${W.toString()} but on-chain authorizer records ${M.toString()}`);T="4",console.log("[Step 4] Validating network fee...");const G=2,Q=pt(l.length,G);if(BigInt(d)>Q)throw new Error(`Network fee ${d} sats exceeds maximum ${Q.toString()} sats for a ${l.length}-input transaction (cap = ${ct} sat/vB)`);if(d<g)throw new Error(`Network fee ${d} sats below minimum ${g} sats`);if(BigInt(d)>=M)throw new Error(`Network fee ${d} sats cannot exceed target amount ${M.toString()} sats`);const Z=Number(M)-d;console.log(" \u2705 Network fee validated"),console.log(` User receives: ${Z} sats`),T="5",console.log("[Step 5] Deriving PKP Bitcoin address...");const Y=await i(f,n);console.log(` \u2705 PKP BTC address: ${Y}`);const tt=et(String(L.vaultAddress),r);if("string"!=typeof tt||0===tt.length)throw new Error(`Position ${c} has no on-chain vaultAddress for chain "${r}" \u2014 cannot bind PKP address`);const rt=tt.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"");if(rt.toLowerCase()!==Y.toLowerCase())throw new Error(`Derived PKP BTC address ${Y} does not match position ${c}'s on-chain vault address ${rt} \u2014 the supplied publicKey is not this position's PKP`);console.log(" \u2705 PKP BTC address matches on-chain vaultAddress"),T="5.5",console.log("[Step 5.5] Checking UTXO existence on Bitcoin network..."),console.log(` Authorized UTXO: ${u.txid}:${u.vout}`);const nt=new _({providerUrl:A.url,auth:A.auth}),ot=await nt.getUTXOs(Y),at=new Map(ot.map((t=>[`${h(t.txid)}:${Number(t.vout)}`,t])));if(!at.has(`${h(u.txid)}:${Number(u.vout)}`))throw new Error(`Authorized UTXO ${u.txid}:${u.vout} no longer exists on Bitcoin (already spent) \u2014 refusing to sign a doomed transaction`);console.log(` \u2705 Authorized UTXO ${u.txid}:${u.vout} confirmed unspent on Bitcoin network`);const ut=o.minBitcoinSpendConfirmations,lt=new st(nt,E.map((t=>({name:t.name,providerUrl:t.url,auth:t.auth}))),o.minConsensusProviders),dt=function(t,e,r){const n=new Set;for(const o of t)e.has(`${o.txid}:${o.vout}`)&&n.add(`${r(o.txid)}:${Number(o.vout)}`);return n}(ot,await lt.confirmedUtxoConsensus(ot,Y,ut),h);!function(t,e,r,n,o){for(const i of t){const t=`${n(i.txid)}:${Number(i.vout)}`,s=e.get(t);if(!s)throw new Error(`Input ${i.txid}:${i.vout} is not an unspent output of the vault \u2014 refusing to sign`);if(s.satoshis!==BigInt(i.value))throw new Error(`Input ${i.txid}:${i.vout} declared value ${i.value} sats does not match the on-chain output value ${s.satoshis.toString()} sats \u2014 refusing to sign a corrupted sighash`);if(!r.has(t))throw new Error(`Input ${i.txid}:${i.vout} is not confirmed at the spend depth (${o}) \u2014 refusing to sign (reorg-vulnerable, or providers disagree on its depth)`)}}(l,at,dt,h,ut),console.log(` \u2705 All ${l.length} input(s) consensus-confirmed at >=${ut} conf across ${E.length} provider(s)`),T="6",console.log("[Step 6] Validating UTXO ownership...");const ht=s(Y);for(const t of l){const e=t.scriptPubKey.startsWith("0x")?t.scriptPubKey.slice(2):t.scriptPubKey;if(e!==ht)throw new Error(`UTXO ${t.txid}:${t.vout} does not belong to vault. Expected scriptPubKey ${ht}, got ${e}`)}console.log(` \u2705 All ${l.length} UTXO(s) belong to vault (PKP address)`),T="7",console.log("[Step 7] Validating UTXO value...");const gt=Number(M),ft=l.reduce(((t,e)=>t+e.value),0);if(ft<gt)throw new Error(`Insufficient UTXO value: total ${ft} sats across ${l.length} input(s), need ${gt} sats`);const mt=ft-gt;console.log(` \u2705 Total UTXO value sufficient (${l.length} input(s))`),console.log(` Total value: ${ft} sats`),console.log(` Total required: ${gt} sats`),console.log(` Change: ${mt} sats`),T="8",console.log("[Step 8] Building Bitcoin transaction...");const{txHex:wt,sigHashes:vt}=b({utxos:l,destination:U,amount:Z,changeAddress:Y,changeAmount:mt,network:n,pkpPublicKey:f});console.log(` \u2705 Transaction built (${l.length} input(s))`),console.log(` Signature hashes: ${vt.length}`),T="9",console.log(`[Step 9] Signing ${vt.length} input(s)...`);const yt=globalThis.pkpId;if(!yt)throw new Error("Missing required parameter: pkpId (user PKP ID for BTC signing)");const $t=await Lit.Actions.getPrivateKey({pkpId:yt}),bt="string"==typeof $t?$t.startsWith("0x")?$t:`0x${$t}`:String($t),Pt=new ethers.utils.SigningKey(bt),Tt=[];for(let t=0;t<vt.length;t++){const e=Pt.signDigest(vt[t]);Tt.push(ethers.utils.joinSignature(e)),console.log(` \u2705 Signed input ${t}: ${vt[t]}`)}return console.log("[BTC Transaction Signer] \u2705 Complete"),{success:!0,unsignedTxHex:wt,sigHashes:vt,sigHash:vt[0],signatures:Tt,signature:Tt[0],pkpPublicKey:f,pkpBtcAddress:Y,destination:U,userReceivesAmount:Z,networkFee:d,changeAmount:mt,utxos:l.map((t=>({txid:t.txid,vout:t.vout,value:t.value}))),utxo:{txid:u.txid,vout:u.vout,value:u.value},authorization:{targetAmount:M.toString(),authorizedAt:O.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: ${T}`),{success:!1,error:t.message||t.toString(),positionId:a?.positionId,timestamp:Date.now()}}}return at=o,((o,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of r(i))n.call(o,c)||c===s||t(o,c,{get:()=>i[c],enumerable:!(a=e(i,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),at)})();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
- 13639ec13bfed381c3c9d81e17e37917446ba30d04d4d8e45809a6868139c3cb
1
+ 9e0d9909519d5133bab03a9491566870b08d8b42c80e2d768bd24f02946cc781
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "actionName": "btc-transaction-signer",
3
- "originalSize": 153457,
4
- "minifiedSize": 66562,
5
- "compressionRatio": 0.5662498289423096,
6
- "hash": "13639ec13bfed381c3c9d81e17e37917446ba30d04d4d8e45809a6868139c3cb",
7
- "buildTime": 1785191241490,
3
+ "originalSize": 153575,
4
+ "minifiedSize": 66624,
5
+ "compressionRatio": 0.5661793911769494,
6
+ "hash": "9e0d9909519d5133bab03a9491566870b08d8b42c80e2d768bd24f02946cc781",
7
+ "buildTime": 1785704148493,
8
8
  "version": "0.1.0"
9
9
  }