@gvnrdao/dh-lit-actions 0.0.324 → 0.0.326
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a_dev_address-probe-signer.meta.json +1 -1
- package/dist/a_dev_address-probe.meta.json +1 -1
- package/dist/a_dev_always-signer.meta.json +1 -1
- package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
- package/dist/a_dev_authorization-dummy.meta.json +1 -1
- package/dist/a_dev_ethers-version-probe.meta.json +1 -1
- package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
- package/dist/agent-module-executor.action.js +1 -1
- package/dist/agent-module-executor.hash +1 -1
- package/dist/agent-module-executor.meta.json +5 -5
- package/dist/btc-address-balance.action.js +1 -1
- package/dist/btc-address-balance.hash +1 -1
- package/dist/btc-address-balance.meta.json +5 -5
- package/dist/btc-provider-probe.meta.json +1 -1
- package/dist/btc-transaction-signer.action.js +1 -1
- package/dist/btc-transaction-signer.hash +1 -1
- package/dist/btc-transaction-signer.meta.json +5 -5
- package/dist/btc-utxo-invalidator.action.js +1 -1
- package/dist/btc-utxo-invalidator.hash +1 -1
- package/dist/btc-utxo-invalidator.meta.json +5 -5
- package/dist/btc-withdrawal.action.js +1 -1
- package/dist/btc-withdrawal.hash +1 -1
- package/dist/btc-withdrawal.meta.json +5 -5
- package/dist/carry-collateral-attestation.action.js +1 -1
- package/dist/carry-collateral-attestation.hash +1 -1
- package/dist/carry-collateral-attestation.meta.json +5 -5
- package/dist/carry-funding-attestation.meta.json +1 -1
- package/dist/encrypt-parameter.meta.json +1 -1
- package/dist/extend-position-validator.action.js +1 -1
- package/dist/extend-position-validator.hash +1 -1
- package/dist/extend-position-validator.meta.json +5 -5
- package/dist/liquidation-validator.action.js +1 -1
- package/dist/liquidation-validator.hash +1 -1
- package/dist/liquidation-validator.meta.json +5 -5
- package/dist/loan-vault-btc-balance.action.js +1 -1
- package/dist/loan-vault-btc-balance.hash +1 -1
- package/dist/loan-vault-btc-balance.meta.json +5 -5
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-validator.action.js +1 -1
- package/dist/process-payment-validator.hash +1 -1
- package/dist/process-payment-validator.meta.json +5 -5
- package/dist/stale-spend-recovery-validator.action.js +1 -1
- package/dist/stale-spend-recovery-validator.hash +1 -1
- package/dist/stale-spend-recovery-validator.meta.json +5 -5
- package/dist/ucd-mint-validator.action.js +1 -1
- package/dist/ucd-mint-validator.hash +1 -1
- package/dist/ucd-mint-validator.meta.json +5 -5
- package/package.json +6 -2
- package/pkg-dist/pkg-src/executors/chunks/vault-snapshot-executor.d.ts.map +1 -1
- package/pkg-dist/pkg-src/index.d.ts +6 -0
- package/pkg-dist/pkg-src/index.d.ts.map +1 -1
- package/pkg-dist/pkg-src/index.js +271 -123
- package/pkg-dist/pkg-src/index.js.map +3 -3
- package/pkg-dist/src/constants/agent-binding-consent-types.d.ts +52 -0
- package/pkg-dist/src/constants/agent-binding-consent-types.d.ts.map +1 -0
- package/pkg-dist/src/constants/btc-spend-request-types.d.ts +83 -0
- package/pkg-dist/src/constants/btc-spend-request-types.d.ts.map +1 -0
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +3 -0
- package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +1 -0
- package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
- package/pkg-dist/src/interfaces/chunks/vault-snapshot.i.d.ts +2 -7
- package/pkg-dist/src/interfaces/chunks/vault-snapshot.i.d.ts.map +1 -1
- package/pkg-dist/src/modules/action-bootstrap.d.ts +7 -0
- package/pkg-dist/src/modules/action-bootstrap.d.ts.map +1 -1
- package/pkg-dist/src/modules/bitcoin/transaction.d.ts +0 -47
- package/pkg-dist/src/modules/bitcoin/transaction.d.ts.map +1 -1
- package/pkg-dist/src/modules/btc-spend-request-authorization.module.d.ts +147 -0
- package/pkg-dist/src/modules/btc-spend-request-authorization.module.d.ts.map +1 -0
- package/pkg-dist/src/modules/evm-rpc.d.ts +52 -0
- package/pkg-dist/src/modules/evm-rpc.d.ts.map +1 -0
- package/pkg-dist/src/modules/position-id.d.ts +0 -5
- package/pkg-dist/src/modules/position-id.d.ts.map +1 -1
- package/pkg-dist/src/modules/protocol-parameters.module.d.ts +2 -0
- package/pkg-dist/src/modules/protocol-parameters.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/quantum-time.module.d.ts +0 -22
- package/pkg-dist/src/modules/quantum-time.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/vault-address.d.ts.map +1 -1
- package/pkg-dist/src/modules/vault-balance.module.d.ts.map +1 -1
- package/pkg-dist/src/modules/vault-snapshot.d.ts +0 -1
- package/pkg-dist/src/modules/vault-snapshot.d.ts.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i={};((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(i,{main:()=>main});var o=1,a=["function agentOf(address user) view returns (tuple(address agent, uint64 validUntil, uint8 status, uint64 registeredAt, uint64 revokedAt))","function canMint(bytes32 positionId, address agent) view returns (bool ok, uint8 reason, uint32 effectiveFloorBps)","function canRepay(bytes32 positionId, address agent) view returns (bool ok, uint8 reason)","function canRenew(bytes32 positionId, address agent) view returns (bool ok, uint8 reason)","function canWithdraw(bytes32 positionId, address agent) view returns (bool ok, uint8 reason, uint32 effectiveFloorBps)"],s=["NONE","PAUSED","NO_GRANT","SCOPE_DISABLED","NO_AGENT","AGENT_REVOKED","AGENT_EXPIRED","NOT_BORROWER","POSITION_TERMINAL"],d=e=>{const t=Number(e);return Number.isInteger(t)&&t>=0&&t<s.length?s[t]:`UNKNOWN(${String(e)})`};var u={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var c={1:{AgentDelegationRegistry:"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa",BitcoinWithdrawalAddressRegistry:"0xf667f77FDba7458345f227eB6Bfe4148243E7270"},11155111:{AgentModuleFactory:"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5",AgentDelegationRegistry:"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",BitcoinWithdrawalAddressRegistry:"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe"}};var p="DiamondHands.Protocol",m="1",l={MintRequest:[{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RepayRequest:[{name:"positionId",type:"bytes32"},{name:"paymentAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RenewRequest:[{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],WithdrawRequest:[{name:"positionId",type:"bytes32"},{name:"totalDeduction",type:"uint256"},{name:"withdrawalAddress",type:"string"},{name:"quantumTimestamp",type:"uint256"}]};function g(e){const t=l[e];if(!t)throw new Error(`Unknown borrower authorization primary type "${e}"; expected one of ${Object.keys(l).join(", ")}`);return{[e]:t.map((e=>({...e})))}}function f(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`Borrower authorization domain requires a positive integer chainId, got ${String(e)}`);const n=function(e){return u[e]??null}(e),r=n?.LoanOperationsManagerModule;if(r&&t&&r.toLowerCase()!==t.toLowerCase())throw new Error(`Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${e}: caller ${t}, pinned ${r}`);const i=r??t;if(!i)throw new Error(`No pinned LoanOperationsManagerModule for chainId ${e} and no verifyingContract supplied; refusing to build a borrower authorization domain without one`);return{name:p,version:m,chainId:e,verifyingContract:i}}var h=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(h||{}),w={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org"],b={ethereum:1,sepolia:11155111,hardhat:1337};var A={hardhat:{chain:"hardhat",chainId:b.hardhat,bitcoinNetwork:w.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:b.sepolia,bitcoinNetwork:w.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:b.ethereum,bitcoinNetwork:w.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function E(e){const t=function(e){const t=e.toLowerCase().trim();if("sepolia"===t)return"sepolia";if("ethereum"===t||"mainnet"===t)return"ethereum";if("hardhat"===t)return"hardhat";throw new Error(`Unsupported EVM chain: "${e}". Supported chains: ${Object.values(h).join(", ")}`)}(e),n=A[t];if(!n)throw new Error(`No chain policy registered for "${e}"`);return n}var v=["AgentModuleFactory","AgentDelegationRegistry","BitcoinWithdrawalAddressRegistry"];function I(e,t){if(!e.pinContractAddresses){const e={};for(const n of v){const r=t?.[n];"string"==typeof r&&r.length>0&&(e[n]=r)}return e}const n=(r=e.chainId,c[r]??{});var r;const i={};for(const r of v){const o=n[r];if(!o)continue;const a=t?.[r];if("string"==typeof a&&a.length>0&&a.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${r}" (${a}) contradicts the pinned ${e.chain} address (${o}); refusing to evaluate the Safe-agent authorization arm`);i[r]=o}return i}var C=["function execute(address target, bytes calldata data)"],x=["function safe() view returns (address)","function agent() view returns (address)","function isWhitelisted(address target, bytes4 selector) view returns (bool)"],D=["function isFromFactory(address) view returns (bool)"],F={mint:[{signature:"mintUCD(bytes32,uint256,uint256,uint256,uint256,uint256,bytes32,bytes32,bytes32,uint256,bytes)",positionIdPath:"flat"}],repay:[{signature:"approve(address,uint256)",positionIdPath:null},{signature:"makePayment(bytes32,uint256,uint256,uint256,bytes)",positionIdPath:"flat"}],renew:[{signature:"extendPosition(bytes32,uint256,uint256,uint256,uint256,uint256,bytes)",positionIdPath:"flat"}],withdraw:[{signature:"withdrawBTC((bytes32,bytes32,bytes32,bytes32,bytes32,string,uint256,uint256,uint256,uint256,string,uint32),bytes,bytes)",positionIdPath:"tuple"}]};var B,P=(e,t)=>"string"==typeof e&&"string"==typeof t&&e.toLowerCase()===t.toLowerCase();function $(e,t){if("string"!=typeof e||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new Error(`[agent-module-executor] ${t} must be a 0x address, got ${JSON.stringify(e)}`);return e}async function main(e){const t=e?.mode;if("authorize"!==t&&"execute"!==t)throw new Error(`[agent-module-executor] mode must be "authorize" or "execute", got ${JSON.stringify(t)}`);const n=$(e?.safe,"safe"),r=$(e?.module,"module"),i=$(e?.pkpId,"pkpId");if("string"!=typeof e?.positionId||!/^0x[0-9a-fA-F]{64}$/.test(e.positionId))throw new Error("[agent-module-executor] positionId must be a bytes32 hex string");if("string"!=typeof e?.chain||0===e.chain.length)throw new Error('[agent-module-executor] chain is required (e.g. "sepolia")');const s=E(e.chain);if("number"!=typeof e?.chainId||!Number.isInteger(e.chainId))throw new Error("[agent-module-executor] chainId must be an integer");if(e.chainId!==s.chainId)throw new Error(`[agent-module-executor] chainId ${e.chainId} does not match the policy chainId ${s.chainId} derived from chain=${e.chain} \u2014 refusing`);if("string"!=typeof e?.rpcUrl||!e.rpcUrl.startsWith("http"))throw new Error("[agent-module-executor] rpcUrl is required (server-supplied)");!function(e,t){if(e.allowArbitraryEvmRpc)return;if(!t||"string"!=typeof t)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let n;try{n=new URL(t).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!y.some((e=>n===e||n.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${n}" is not in the approved list: ${y.join(", ")}`)}(s,e.rpcUrl);const u=I(s,e?.contractAddresses),c=$(u.AgentDelegationRegistry,"AgentDelegationRegistry (pinned; unavailable on this chain)"),p=$(u.AgentModuleFactory,"AgentModuleFactory (pinned; unavailable on this chain)"),m=new ethers.providers.JsonRpcProvider(e.rpcUrl),l=new ethers.Contract(p,D,m);if(!0!==await l.isFromFactory(r))throw new Error(`[agent-module-executor] module ${r} was not deployed by the canonical AgentModuleFactory ${p} \u2014 refusing to act through an unprovenanced module`);const h=new ethers.Contract(r,x,m),[w,b]=await Promise.all([h.safe(),h.agent()]);if(!P(w,n))throw new Error(`[agent-module-executor] module ${r} is bound to Safe ${w}, not ${n}`);const A=await async function(e){const{provider:t,registryAddress:n,safe:r,positionId:i,op:s,candidateAgent:u}=e,c=new ethers.Contract(n,a,t),p=await c.agentOf(r),m=p.agent??p[0],l=Number(p.status??p[2]),g=Number(p.validUntil??p[1]);if(l!==o)throw new Error(`[agent-authorization] Safe ${r} has no Active agent registration (status=${l}) \u2014 refusing`);if(m.toLowerCase()!==u.toLowerCase())throw new Error(`[agent-authorization] Safe ${r}'s registered agent is ${m}, but ${u} was supplied \u2014 refusing to sign with a key that is merely group-co-member`);if(!Number.isFinite(g)||0===g)throw new Error(`[agent-authorization] agent record for ${r} has no validUntil`);const f="mint"===s?"canMint":"repay"===s?"canRepay":"renew"===s?"canRenew":"withdraw"===s?"canWithdraw":null;if(!f)throw new Error(`[agent-authorization] unknown op ${String(s)}`);const h=await c[f](i,m),w=h.ok??h[0],y=h.reason??h[1];if(!0!==w)throw new Error(`[agent-authorization] registry refused ${s} for position ${i} (agent ${m}): ${d(y)}`);const b=h.effectiveFloorBps??h[2];return{agent:m,validUntil:g,effectiveFloorBps:void 0!==b?Number(b):void 0}}({provider:m,registryAddress:c,safe:n,positionId:e.positionId,op:e.op,candidateAgent:i});if(!P(b,i))throw new Error(`[agent-module-executor] module agent is ${b} but pkpId ${i} was supplied \u2014 refusing to sign with a key the module does not recognise`);const v=await Lit.Actions.getPrivateKey({pkpId:i}),B="string"==typeof v?v.startsWith("0x")?v:`0x${v}`:String(v),R=new ethers.Wallet(B);if(!P(R.address,i))throw new Error(`[agent-module-executor] getPrivateKey returned a key for ${R.address}, not ${i}`);const T={success:!0,mode:t,module:r,agent:A.agent,op:e.op};if("authorize"===t){if("number"!=typeof e.timestamp||!Number.isInteger(e.timestamp))throw new Error("[agent-module-executor] timestamp is required for mode=authorize (quantum-aligned)");const{domain:t,types:n,message:r}=function(e){const t=f(e.chainId,e.contractAddresses?.LoanOperationsManagerModule);if("renew"===e.op){if("number"!=typeof e.selectedTerm)throw new Error("[agent-module-executor] selectedTerm is required for op=renew");return{domain:t,types:g("RenewRequest"),message:{positionId:e.positionId,selectedTerm:e.selectedTerm,quantumTimestamp:e.timestamp}}}if("string"!=typeof e.amount||0===e.amount.length)throw new Error(`[agent-module-executor] amount is required for op=${e.op}`);if("withdraw"===e.op){if("string"!=typeof e.destinationAddress||0===e.destinationAddress.length)throw new Error("[agent-module-executor] destinationAddress is required for op=withdraw");return{domain:t,types:g("WithdrawRequest"),message:{positionId:e.positionId,totalDeduction:e.amount,withdrawalAddress:e.destinationAddress,quantumTimestamp:e.timestamp}}}const n="mint"===e.op?"MintRequest":"RepayRequest";return{domain:t,types:g(n),message:{positionId:e.positionId,["mint"===e.op?"mintAmount":"paymentAmount"]:e.amount,quantumTimestamp:e.timestamp}}}(e),i=await R._signTypedData(t,n,r);return{...T,authorization:{timestamp:e.timestamp,signature:i,signer:R.address}}}const N=$(e?.target,"target");if("string"!=typeof e?.innerData||!/^0x[0-9a-fA-F]{8,}$/.test(e.innerData))throw new Error("[agent-module-executor] innerData must be 0x-hex with a 4-byte selector for mode=execute");const O=e?.tx;if(!O||"number"!=typeof O.nonce||!Number.isInteger(O.nonce)||"string"!=typeof O.gasLimit||"string"!=typeof O.maxFeePerGas||"string"!=typeof O.maxPriorityFeePerGas)throw new Error("[agent-module-executor] tx.{nonce,gasLimit,maxFeePerGas,maxPriorityFeePerGas} are required for mode=execute and must be caller-supplied (multi-node determinism)");const L=e.innerData.slice(0,10);if(!0!==await h.isWhitelisted(N,L))throw new Error(`[agent-module-executor] (${N}, ${L}) is not on module ${r}'s whitelist \u2014 refusing`);const M=(F[e.op]??[]).find((e=>{return(t=e.signature,ethers.utils.id(t).slice(0,10)).toLowerCase()===L.toLowerCase();var t}));if(!M)throw new Error(`[agent-module-executor] op=${e.op} does not authorize selector ${L}. createPosition, setPositionDelegate, and approve-outside-a-repay-grant have no corresponding AgentDelegationRegistry scope and are never reachable through this action (setPositionDelegate specifically: vigil concern C-43) \u2014 refusing to sign`);if(null!==M.positionIdPath){const t=M.signature.slice(0,M.signature.indexOf("(")),n=new ethers.utils.Interface([`function ${M.signature}`]).decodeFunctionData(t,e.innerData),r="tuple"===M.positionIdPath?n[0][0]:n[0];if(!P(r,e.positionId))throw new Error(`[agent-module-executor] innerData targets position ${r}, but the scope grant checked in step 3 was for ${e.positionId} \u2014 refusing to sign a call against a different position than the one authorized`)}const _=new ethers.utils.Interface(C).encodeFunctionData("execute",[N,e.innerData]),q=await R.signTransaction({to:r,data:_,value:0,chainId:e.chainId,nonce:O.nonce,gasLimit:ethers.BigNumber.from(O.gasLimit),maxFeePerGas:ethers.BigNumber.from(O.maxFeePerGas),maxPriorityFeePerGas:ethers.BigNumber.from(O.maxPriorityFeePerGas),type:2});return{...T,signedTransaction:q}}return B=i,((i,o,a,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let d of n(o))r.call(i,d)||d===a||e(i,d,{get:()=>o[d],enumerable:!(s=t(o,d))||s.enumerable});return i})(e({},"__esModule",{value:!0}),B)})();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 e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o={};((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(o,{main:()=>main});var i=1,a=["function agentOf(address user) view returns (tuple(address agent, uint64 validUntil, uint8 status, uint64 registeredAt, uint64 revokedAt))","function canMint(bytes32 positionId, address agent) view returns (bool ok, uint8 reason, uint32 effectiveFloorBps)","function canRepay(bytes32 positionId, address agent) view returns (bool ok, uint8 reason)","function canRenew(bytes32 positionId, address agent) view returns (bool ok, uint8 reason)","function canWithdraw(bytes32 positionId, address agent) view returns (bool ok, uint8 reason, uint32 effectiveFloorBps)"],s=["NONE","PAUSED","NO_GRANT","SCOPE_DISABLED","NO_AGENT","AGENT_REVOKED","AGENT_EXPIRED","NOT_BORROWER","POSITION_TERMINAL"],d=e=>{const t=Number(e);return Number.isInteger(t)&&t>=0&&t<s.length?s[t]:`UNKNOWN(${String(e)})`};var u={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var c={1:{AgentDelegationRegistry:"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa",BitcoinWithdrawalAddressRegistry:"0xf667f77FDba7458345f227eB6Bfe4148243E7270"},11155111:{AgentModuleFactory:"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5",AgentDelegationRegistry:"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",BitcoinWithdrawalAddressRegistry:"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe"}};var g="DiamondHands.Protocol",p="1",l={MintRequest:[{name:"positionId",type:"bytes32"},{name:"mintAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RepayRequest:[{name:"positionId",type:"bytes32"},{name:"paymentAmount",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],RenewRequest:[{name:"positionId",type:"bytes32"},{name:"selectedTerm",type:"uint256"},{name:"quantumTimestamp",type:"uint256"}],WithdrawRequest:[{name:"positionId",type:"bytes32"},{name:"totalDeduction",type:"uint256"},{name:"withdrawalAddress",type:"string"},{name:"quantumTimestamp",type:"uint256"}]};function m(e){const t=l[e];if(!t)throw new Error(`Unknown borrower authorization primary type "${e}"; expected one of ${Object.keys(l).join(", ")}`);return{[e]:t.map((e=>({...e})))}}function f(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`Borrower authorization domain requires a positive integer chainId, got ${String(e)}`);const n=function(e){return u[e]??null}(e),r=n?.LoanOperationsManagerModule;if(r&&t&&r.toLowerCase()!==t.toLowerCase())throw new Error(`Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${e}: caller ${t}, pinned ${r}`);const o=r??t;if(!o)throw new Error(`No pinned LoanOperationsManagerModule for chainId ${e} and no verifyingContract supplied; refusing to build a borrower authorization domain without one`);return{name:g,version:p,chainId:e,verifyingContract:o}}var h=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(h||{}),w={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org","drpc.live"],b={ethereum:1,sepolia:11155111,hardhat:1337};var A="AgentBindingConsent",v=[{name:"user",type:"address"},{name:"agent",type:"address"}];var E={hardhat:{chain:"hardhat",chainId:b.hardhat,bitcoinNetwork:w.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:b.sepolia,bitcoinNetwork:w.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:b.ethereum,bitcoinNetwork:w.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function I(e){const t=function(e){const t=e.toLowerCase().trim();if("sepolia"===t)return"sepolia";if("ethereum"===t||"mainnet"===t)return"ethereum";if("hardhat"===t)return"hardhat";throw new Error(`Unsupported EVM chain: "${e}". Supported chains: ${Object.values(h).join(", ")}`)}(e),n=E[t];if(!n)throw new Error(`No chain policy registered for "${e}"`);return n}var C=["drpc.org","drpc.live"],x="Drpc-Key",$=/^[A-Za-z0-9_-]{16,128}$/;function P(e){return C.some((t=>e===t||e.endsWith(`.${t}`)))}function D(e,t){if("string"!=typeof e||!$.test(e))throw new Error(`Invalid ${t}: expected 16-128 characters of [A-Za-z0-9_-]`)}function F(e){if("https:"!==e.protocol)throw new Error(`A dRPC key is only sent over https, but the RPC URL scheme is "${e.protocol}"`)}function R(e,t){if(void 0===t)return;D(t,'"drpcKey"');const n=new URL(e);if(!P(n.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${n.hostname}" (expected ${C.join(" or ")})`);if(F(n),n.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return t}var B=["AgentModuleFactory","AgentDelegationRegistry","BitcoinWithdrawalAddressRegistry"];function T(e,t){if(!e.pinContractAddresses){const e={};for(const n of B){const r=t?.[n];"string"==typeof r&&r.length>0&&(e[n]=r)}return e}const n=(r=e.chainId,c[r]??{});var r;const o={};for(const r of B){const i=n[r];if(!i)continue;const a=t?.[r];if("string"==typeof a&&a.length>0&&a.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${r}" (${a}) contradicts the pinned ${e.chain} address (${i}); refusing to evaluate the Safe-agent authorization arm`);o[r]=i}return o}var N=["function execute(address target, bytes calldata data)"],k=["function keyOfAgent(address) view returns (bytes32)"],O="0x"+"00".repeat(32),L=["function safe() view returns (address)","function agent() view returns (address)","function isWhitelisted(address target, bytes4 selector) view returns (bool)"],M=["function isFromFactory(address) view returns (bool)"],_={mint:[{signature:"mintUCD(bytes32,uint256,uint256,uint256,uint256,uint256,bytes32,bytes32,bytes32,uint256,bytes)",positionIdPath:"flat"}],repay:[{signature:"approve(address,uint256)",positionIdPath:null},{signature:"makePayment(bytes32,uint256,uint256,uint256,bytes)",positionIdPath:"flat"}],renew:[{signature:"extendPosition(bytes32,uint256,uint256,uint256,uint256,uint256,bytes)",positionIdPath:"flat"}],withdraw:[{signature:"withdrawBTC((bytes32,bytes32,bytes32,bytes32,bytes32,string,uint256,uint256,uint256,uint256,string,uint32),bytes,bytes)",positionIdPath:"tuple"}]};var q,S=(e,t)=>"string"==typeof e&&"string"==typeof t&&e.toLowerCase()===t.toLowerCase();function U(e,t){if("string"!=typeof e||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new Error(`[agent-module-executor] ${t} must be a 0x address, got ${JSON.stringify(e)}`);return e}function z(e){if("string"!=typeof e?.chain||0===e.chain.length)throw new Error('[agent-module-executor] chain is required (e.g. "sepolia")');const t=I(e.chain);if("number"!=typeof e?.chainId||!Number.isInteger(e.chainId))throw new Error("[agent-module-executor] chainId must be an integer");if(e.chainId!==t.chainId)throw new Error(`[agent-module-executor] chainId ${e.chainId} does not match the policy chainId ${t.chainId} derived from chain=${e.chain} \u2014 refusing`);if("string"!=typeof e?.rpcUrl||!e.rpcUrl.startsWith("http"))throw new Error("[agent-module-executor] rpcUrl is required (server-supplied)");!function(e,t){if(e.allowArbitraryEvmRpc)return;if(!t||"string"!=typeof t)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let n;try{n=new URL(t).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!y.some((e=>n===e||n.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${n}" is not in the approved list: ${y.join(", ")}`)}(t,e.rpcUrl);const n=R(e.rpcUrl,e.drpcKey),r=T(t,e?.contractAddresses),o=U(r.AgentDelegationRegistry,"AgentDelegationRegistry (pinned; unavailable on this chain)"),i=new ethers.providers.JsonRpcProvider(function(e,t,n){const r={url:e},o=R(e,t);if(void 0!==o)r.headers={[x]:o};else{const t=new URL(e),n=t.searchParams.getAll("dkey");if(n.length>1)throw new Error(`rpcUrl carries ${n.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===n.length&&!P(t.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${t.hostname}" \u2014 a dRPC key is only sent to ${C.join(" or ")}`);if(1===n.length){const e=n[0];D(e,"dRPC key in rpcUrl (?dkey=)"),F(t),t.searchParams.delete("dkey"),r.url=t.toString(),r.headers={[x]:e}}}return void 0!==n&&(r.timeout=n),r}(e.rpcUrl,n));return{policy:t,provider:i,agentPathAddresses:r,registryAddress:o}}async function W(e){const t=await Lit.Actions.getPrivateKey({pkpId:e}),n="string"==typeof t?t.startsWith("0x")?t:`0x${t}`:String(t),r=new ethers.Wallet(n);if(!S(r.address,e))throw new Error(`[agent-module-executor] getPrivateKey returned a key for ${r.address}, not ${e}`);return r}async function j(e){const t=U(e?.pkpId,"pkpId"),n=U(e?.user,"user");if(/^0x0{40}$/.test(n))throw new Error("[agent-module-executor] user must not be the zero address");if(S(n,t))throw new Error("[agent-module-executor] an agent cannot consent to be bound to itself");const{provider:r,registryAddress:o}=z(e),i=await new ethers.Contract(o,k,r).keyOfAgent(t);if(i!==O)throw new Error(`[agent-module-executor] agent ${t} is already bound in registry ${o} (key ${i}) \u2014 AR-1 burns an agent on first bind; refusing to sign a consent for it`);const a=await W(t);return{success:!0,mode:"consent",agent:t,user:n,consent:{signature:await a._signTypedData(function(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`Agent binding consent domain requires a positive integer chainId, got ${String(e)}`);if("string"!=typeof t||!/^0x[0-9a-fA-F]{40}$/.test(t))throw new Error(`Agent binding consent domain requires the AgentDelegationRegistry address, got ${String(t)}`);return{name:g,version:p,chainId:e,verifyingContract:t}}(e.chainId,o),{[A]:v.map((e=>({...e})))},{user:n,agent:t}),signer:a.address}}}async function main(e){const t=e?.mode;if("authorize"!==t&&"execute"!==t&&"consent"!==t)throw new Error('[agent-module-executor] mode must be "authorize", "execute" or "consent", got '+JSON.stringify(t));if("consent"===t)return j(e);const n=U(e?.safe,"safe"),r=U(e?.module,"module"),o=U(e?.pkpId,"pkpId");if("string"!=typeof e?.positionId||!/^0x[0-9a-fA-F]{64}$/.test(e.positionId))throw new Error("[agent-module-executor] positionId must be a bytes32 hex string");const{provider:s,agentPathAddresses:u,registryAddress:c}=z(e),g=U(u.AgentModuleFactory,"AgentModuleFactory (pinned; unavailable on this chain)"),p=new ethers.Contract(g,M,s);if(!0!==await p.isFromFactory(r))throw new Error(`[agent-module-executor] module ${r} was not deployed by the canonical AgentModuleFactory ${g} \u2014 refusing to act through an unprovenanced module`);const l=new ethers.Contract(r,L,s),[h,w]=await Promise.all([l.safe(),l.agent()]);if(!S(h,n))throw new Error(`[agent-module-executor] module ${r} is bound to Safe ${h}, not ${n}`);const y=await async function(e){const{provider:t,registryAddress:n,safe:r,positionId:o,op:s,candidateAgent:u}=e,c=new ethers.Contract(n,a,t),g=await c.agentOf(r),p=g.agent??g[0],l=Number(g.status??g[2]),m=Number(g.validUntil??g[1]);if(l!==i)throw new Error(`[agent-authorization] Safe ${r} has no Active agent registration (status=${l}) \u2014 refusing`);if(p.toLowerCase()!==u.toLowerCase())throw new Error(`[agent-authorization] Safe ${r}'s registered agent is ${p}, but ${u} was supplied \u2014 refusing to sign with a key that is merely group-co-member`);if(!Number.isFinite(m)||0===m)throw new Error(`[agent-authorization] agent record for ${r} has no validUntil`);const f="mint"===s?"canMint":"repay"===s?"canRepay":"renew"===s?"canRenew":"withdraw"===s?"canWithdraw":null;if(!f)throw new Error(`[agent-authorization] unknown op ${String(s)}`);const h=await c[f](o,p),w=h.ok??h[0],y=h.reason??h[1];if(!0!==w)throw new Error(`[agent-authorization] registry refused ${s} for position ${o} (agent ${p}): ${d(y)}`);const b=h.effectiveFloorBps??h[2];return{agent:p,validUntil:m,effectiveFloorBps:void 0!==b?Number(b):void 0}}({provider:s,registryAddress:c,safe:n,positionId:e.positionId,op:e.op,candidateAgent:o});if(!S(w,o))throw new Error(`[agent-module-executor] module agent is ${w} but pkpId ${o} was supplied \u2014 refusing to sign with a key the module does not recognise`);const b=await W(o),A={success:!0,mode:t,module:r,agent:y.agent,op:e.op};if("authorize"===t){if("number"!=typeof e.timestamp||!Number.isInteger(e.timestamp))throw new Error("[agent-module-executor] timestamp is required for mode=authorize (quantum-aligned)");const{domain:t,types:n,message:r}=function(e){const t=f(e.chainId,e.contractAddresses?.LoanOperationsManagerModule);if("renew"===e.op){if("number"!=typeof e.selectedTerm)throw new Error("[agent-module-executor] selectedTerm is required for op=renew");return{domain:t,types:m("RenewRequest"),message:{positionId:e.positionId,selectedTerm:e.selectedTerm,quantumTimestamp:e.timestamp}}}if("string"!=typeof e.amount||0===e.amount.length)throw new Error(`[agent-module-executor] amount is required for op=${e.op}`);if("withdraw"===e.op){if("string"!=typeof e.destinationAddress||0===e.destinationAddress.length)throw new Error("[agent-module-executor] destinationAddress is required for op=withdraw");return{domain:t,types:m("WithdrawRequest"),message:{positionId:e.positionId,totalDeduction:e.amount,withdrawalAddress:e.destinationAddress,quantumTimestamp:e.timestamp}}}const n="mint"===e.op?"MintRequest":"RepayRequest";return{domain:t,types:m(n),message:{positionId:e.positionId,["mint"===e.op?"mintAmount":"paymentAmount"]:e.amount,quantumTimestamp:e.timestamp}}}(e),o=await b._signTypedData(t,n,r);return{...A,authorization:{timestamp:e.timestamp,signature:o,signer:b.address}}}const v=U(e?.target,"target");if("string"!=typeof e?.innerData||!/^0x[0-9a-fA-F]{8,}$/.test(e.innerData))throw new Error("[agent-module-executor] innerData must be 0x-hex with a 4-byte selector for mode=execute");const E=e?.tx;if(!E||"number"!=typeof E.nonce||!Number.isInteger(E.nonce)||"string"!=typeof E.gasLimit||"string"!=typeof E.maxFeePerGas||"string"!=typeof E.maxPriorityFeePerGas)throw new Error("[agent-module-executor] tx.{nonce,gasLimit,maxFeePerGas,maxPriorityFeePerGas} are required for mode=execute and must be caller-supplied (multi-node determinism)");const I=e.innerData.slice(0,10);if(!0!==await l.isWhitelisted(v,I))throw new Error(`[agent-module-executor] (${v}, ${I}) is not on module ${r}'s whitelist \u2014 refusing`);const C=(_[e.op]??[]).find((e=>{return(t=e.signature,ethers.utils.id(t).slice(0,10)).toLowerCase()===I.toLowerCase();var t}));if(!C)throw new Error(`[agent-module-executor] op=${e.op} does not authorize selector ${I}. createPosition, setPositionDelegate, and approve-outside-a-repay-grant have no corresponding AgentDelegationRegistry scope and are never reachable through this action (setPositionDelegate specifically: vigil concern C-43) \u2014 refusing to sign`);if(null!==C.positionIdPath){const t=C.signature.slice(0,C.signature.indexOf("(")),n=new ethers.utils.Interface([`function ${C.signature}`]).decodeFunctionData(t,e.innerData),r="tuple"===C.positionIdPath?n[0][0]:n[0];if(!S(r,e.positionId))throw new Error(`[agent-module-executor] innerData targets position ${r}, but the scope grant checked in step 3 was for ${e.positionId} \u2014 refusing to sign a call against a different position than the one authorized`)}const x=new ethers.utils.Interface(N).encodeFunctionData("execute",[v,e.innerData]),$=await b.signTransaction({to:r,data:x,value:0,chainId:e.chainId,nonce:E.nonce,gasLimit:ethers.BigNumber.from(E.gasLimit),maxFeePerGas:ethers.BigNumber.from(E.maxFeePerGas),maxPriorityFeePerGas:ethers.BigNumber.from(E.maxPriorityFeePerGas),type:2});return{...A,signedTransaction:$}}return q=o,((o,i,a,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let d of n(i))r.call(o,d)||d===a||e(o,d,{get:()=>i[d],enumerable:!(s=t(i,d))||s.enumerable});return o})(e({},"__esModule",{value:!0}),q)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
a10d463ffd48f2392401efe3dde566faa1869e5e089db830632873a5b9528ee0
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "agent-module-executor",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 30462,
|
|
4
|
+
"minifiedSize": 17562,
|
|
5
|
+
"compressionRatio": 0.4234784321449675,
|
|
6
|
+
"hash": "a10d463ffd48f2392401efe3dde566faa1869e5e089db830632873a5b9528ee0",
|
|
7
|
+
"buildTime": 1792491258184,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function n(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){n()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=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}},c=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},l=class{static create(t="LIT Action",e){return n(e)?new c(t):new a}},d=25e14,u=60,h=16,p={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var g="DiamondHands.Protocol",m="1",f="address-balance",w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["infura.io","drpc.org"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){return $[t]}function T(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function E(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function A(t){return t instanceof Error&&"AbortError"===t.name}function B(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function C(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&&B(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&B(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return B(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");B(o,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&B(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var P=new Map;async function x(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,o=P.get(i);if(o)return o;const n=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,n=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:i,signal:o.signal})}finally{clearTimeout(n)}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 n.catch((()=>P.delete(i))),P.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function k(t,e){if(!Number.isSafeInteger(t)||t<0||t>d)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var I="Bitcoin tip-height read failed",S=class extends Error{constructor(t){super(t),this.isBitcoinTipUnreadable=!0,this.name="BitcoinTipUnreadableError"}};var D=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await x(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),s(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const o=await i.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 n=parseInt(o.trim(),10);if(isNaN(n)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${E(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${E(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${E(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return k(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,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,n=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===n||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");k(s,`parseBlockstreamUTXOs ${o}:${n}`),i.push({txid:o,vout:n,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(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: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const c=await a.text();if(c.trim().startsWith("<!DOCTYPE")||c.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 l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${E(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,n);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(E(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${E(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-n;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),s(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const a=await n.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const c=a.chain_stats.funded_txo_sum,l=a.chain_stats.spent_txo_sum;if(void 0===c||void 0===l)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${c}, spent_txo_sum: ${l}`);k(c,`getBalance ${e} funded_txo_sum`),k(l,`getBalance ${e} spent_txo_sum`);const d=c-l;k(d,`getBalance ${e} confirmed balance`);const u=BigInt(d);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${c} sats, Spent: ${l} sats`),u}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=E(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=E(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=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()-i}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 n=await o.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};const r=await this.fetchTipHeight(e.signal)-n.status.block_height+1;return{txid:n.txid??t,confirmations:r>0?r:0}}return null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(function(t){return"object"==typeof t&&null!==t&&!0===t.isBitcoinTipUnreadable}(t))throw t;if(E(t).includes("404"))return null;throw t}}async fetchTipHeight(t){const e=`${this.config.providerUrl}/blocks/tip/height`;let r;try{r=await fetch(e,{signal:t,headers:await this.withAuth()})}catch(t){throw new S(`${I}: GET ${e} threw \u2014 ${E(t)}`)}if(!r.ok)throw new S(`${I}: GET ${e} \u2192 ${r.status} ${r.statusText}`);const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)throw new S(`${I}: GET ${e} returned an unusable tip height "${i.slice(0,64)}"`);return o}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.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 k(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),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};var U={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:y.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:y.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:y.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function O(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=U[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function N(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const i=(o=t.chainId,p[o]??null);var o;if(!i)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 _){const o=i[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 n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}async function M(t,e){const r=e.rpcUrl,i=e.rpcSource??"params-or-lit-node";let o;if("string"==typeof r&&r.length>0)!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(!v.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(t,r),o=r;else{if("params-only"===i)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(o=await Lit.Actions.getRpcUrl({chain:e.chain}),"string"!=typeof o||0===o.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${e.chain}"`)}return{rpcUrl:o,addresses:N(t,e.contractAddresses)}}var F=[{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"}],R=[{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 L(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function q(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,F,e),[o,n]=await i.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return s}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.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:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(i,R,r);let a;try{a=await s.isAllowedCid(e,n)}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=${n.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 i){const r=await L(e.ciphertext,e.pkpId),{url:i,auth:n}=C(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}var H,j={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},W="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function X(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/u)*u;var e}async function G(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=u-8}(t))return;const r=h/2;let i;i=e>=u-r?u-e+r:r-e,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${X()}`)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=T();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "vaultAddress"');if(!o)throw new Error('Missing required parameter: "publicKey"');const a=O(r),c=a.chain,l=a.bitcoinNetwork,d=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=j[e],o=new RegExp(`^q[${W}]{38}$`);if(!r.startsWith(i)){const o=r.startsWith("bcrt1")?"bcrt1":r.startsWith("tb1")?"tb1":r.startsWith("bc1")?"bc1":null;if(o&&o!==i)throw new Error(`vaultAddress network mismatch: address prefix "${o}" does not match chain network "${e}" (expected "${i}")`);throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`)}const n=r.slice(i.length);if(!o.test(n))throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`);return r}(i,l),{rpcUrl:u,addresses:h}=await M(a,{chain:r,rpcUrl:n,contractAddresses:e.contractAddresses}),p=h.BitcoinProviderRegistry;if(a.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!p)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${c})`),s(` \u2705 Bitcoin Network: ${l}`),s(` \u2705 Vault Address: ${d}`);try{const t=new ethers.providers.JsonRpcProvider(u);let r;r=a.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:a.minBitcoinBalanceConfirmations,network:a.bitcoinNetwork}]:await q(a,t,p),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=await async function(t,e,r,i,o){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=o??(t=>new D({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),s=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=s.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const c=s.map((t=>t.value)),l=c[0],d=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(d.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${d.join("; ")}`);return e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`),l}(d,r,a.minConsensusProviders),o=r.length;s("[Step 2] Signing address balance attestation..."),await G();const n=X(),l=a.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:p,{domain:h,types:y,value:v}=(w={verifyingContract:l,chainId:b(c),vaultAddress:d,totalBalanceSats:i,providerCount:o,timestamp:n},{domain:{name:g,version:m,chainId:w.chainId,verifyingContract:ethers.utils.getAddress(w.verifyingContract)},types:{AddressBalanceAttestation:[{name:"actionTag",type:"bytes32"},{name:"vaultAddressHash",type:"bytes32"},{name:"totalBalanceSats",type:"uint256"},{name:"providerCount",type:"uint256"},{name:"timestamp",type:"uint256"}]},value:{actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(w.vaultAddress)),totalBalanceSats:w.totalBalanceSats.toString(),providerCount:w.providerCount,timestamp:w.timestamp}}),$=globalThis.validatorWalletAddress;if(!$||!$.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const T=await Lit.Actions.getPrivateKey({pkpId:$}),E="string"==typeof T?T.startsWith("0x")?T:`0x${T}`:String(T),A=new ethers.Wallet(E),B=await A._signTypedData(h,y,v);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:d,totalBalanceSats:i.toString(),providerCount:o,signature:B,timestamp:n,validatorPkp:A.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:d||null,timestamp:Date.now()}}var w}return H=o,((o,n,s,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))i.call(o,c)||c===s||t(o,c,{get:()=>n[c],enumerable:!(a=e(n,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),H)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
1
|
+
var _LIT_ACTION_=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,o={};function n(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){n()&&console.log(...t)}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(o,{main:()=>main});var a=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}},c=class{constructor(t){this.stepStartTimes=new Map,this.stepDurations=new Map,this.TIMEOUT_MS=3e4,this.actionName=t,this.executionStartTime=Date.now();const e=Date.now(),r=Math.random().toString(36).substring(2,9);this.executionId=`exec_${e}_${r}`,this.logHeader()}logHeader(){console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution started`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);void 0!==globalThis.litNodeContext?(console.log(`[${this.actionName}] Context: LIT Node`),console.log(`[${this.actionName}] Node: ${globalThis.litNodeContext?.nodeAddress||"unknown"}`)):console.log(`[${this.actionName}] Context: Browser/Test`),console.log(`[${this.actionName}] ========================================`)}stepStart(t,e){this.stepStartTimes.set(t,Date.now());const r=Date.now()-this.executionStartTime,i=this.TIMEOUT_MS-r;console.log(`[Step ${t}] ${e}...`),console.log(`[Step ${t}] Elapsed: ${r}ms | Remaining: ${i}ms`)}stepEnd(t,e=5e3){const r=this.stepStartTimes.get(t);if(!r)return console.warn(`[Step ${t}] \u26a0\ufe0f stepEnd called without matching stepStart`),void 0;const i=Date.now()-r;this.stepDurations.set(t,i),console.log(`[Step ${t}] Duration: ${i}ms`),i>e&&console.warn(`\u26a0\ufe0f [Step ${t}] Took ${i}ms (> ${e}ms threshold)`);const o=Date.now()-this.executionStartTime,n=this.TIMEOUT_MS-o;n<5e3&&console.warn(`\u26a0\ufe0f [Step ${t}] Time remaining: ${n}ms (approaching timeout)`)}log(t,e,...r){r.length>0?console.log(`[Step ${t}] ${e}`,...r):console.log(`[Step ${t}] ${e}`)}warn(t,e){console.warn(`\u26a0\ufe0f [Step ${t}] ${e}`)}error(t,e){console.error(`\u274c [Step ${t}] ${e}`)}getElapsed(){return Date.now()-this.executionStartTime}getRemaining(){return this.TIMEOUT_MS-this.getElapsed()}summary(){const t=Date.now()-this.executionStartTime,e=this.TIMEOUT_MS-t;if(console.log(`[${this.actionName}] ========================================`),console.log(`[${this.actionName}] Execution Summary`),console.log(`[${this.actionName}] Execution ID: ${this.executionId}`),console.log(`[${this.actionName}] Total time: ${(t/1e3).toFixed(2)}s`),console.log(`[${this.actionName}] Time remaining: ${e}ms`),this.stepDurations.size>0){console.log(`[${this.actionName}] Step breakdown:`);for(const[e,r]of this.stepDurations.entries()){const i=(r/t*100).toFixed(1);console.log(`[${this.actionName}] Step ${e}: ${r}ms (${i}%)`)}}t>2e4&&console.warn(`\u26a0\ufe0f [${this.actionName}] Slow execution: ${(t/1e3).toFixed(2)}s (${e}ms remaining)`),e<5e3&&console.warn(`\u26a0\ufe0f [${this.actionName}] CRITICAL: Only ${e}ms remaining before timeout!`),console.log(`[${this.actionName}] ========================================`)}getExecutionId(){return this.executionId}isDebugEnabled(){return!0}},l=class{static create(t="LIT Action",e){return n(e)?new c(t):new a}},d=25e14,u=60,h=16,p={1:{PositionManager:"0x12A1836e56139ccaD8722B89519d84233efc224B",LoanOperationsManagerModule:"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9",BTCSpendAuthorizer:"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a",BitcoinProviderRegistry:"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC",LITActionValidator:"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512",PositionDelegateRegistry:"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C",TermManagerModule:"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E",UCDController:"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157",LiquidationManagerModule:"0x74B28695352E7bf736D6c9F76ccb7B4439477De9"},11155111:{PositionManager:"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF",LoanOperationsManagerModule:"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0",BTCSpendAuthorizer:"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD",BitcoinProviderRegistry:"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2",LITActionValidator:"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856",PositionDelegateRegistry:"0x482369De283622E7b05731875ec137d4E3D208F9",TermManagerModule:"0x94Adc6F9558368B1482197584f1fc7133Ecf835b",UCDController:"0x360Bde4e489ee94E26601B206932De09EE60FF04",LiquidationManagerModule:"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76"}};var g="DiamondHands.Protocol",m="1",f="address-balance",w=(t=>(t.SEPOLIA="sepolia",t.ETHEREUM="ethereum",t.HARDHAT="hardhat",t))(w||{}),y={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},v=["infura.io","drpc.org","drpc.live"],$={ethereum:1,sepolia:11155111,hardhat:1337};function b(t){return $[t]}function E(){const t=globalThis,e=t.jsParams;return null==e||"object"!=typeof e||Array.isArray(e)?t:e}function T(t){if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch{return String(t)}}function A(t){return t instanceof Error&&"AbortError"===t.name}function C(t,e){if(!/^https:\/\//i.test(t.trim()))throw new Error(`parseProviderPlaintext: ${e} must use https:// (credentials must not be sent over http)`)}function B(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&&C(r,"provider url"),{url:r,auth:{provider:"esplora"}};let i;try{i=JSON.parse(r)}catch(t){throw new Error(`parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${t?.message??String(t)}`)}if("string"!=typeof i.url||0===i.url.trim().length)throw new Error("parseProviderPlaintext: JSON provider config missing non-empty string `url`");const o=i.url.trim();switch(i.provider){case void 0:case"esplora":return e?.requireHttps&&C(o,"esplora provider url"),{url:o,auth:{provider:"esplora"}};case"maestro":if("string"!=typeof i.apiKey||0===i.apiKey.length)throw new Error("parseProviderPlaintext: maestro provider requires a non-empty `apiKey`");return C(o,"maestro provider url"),{url:o,auth:{provider:"maestro",apiKey:i.apiKey}};case"blockstream-enterprise":{if("string"!=typeof i.clientId||0===i.clientId.length||"string"!=typeof i.clientSecret||0===i.clientSecret.length)throw new Error("parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`");C(o,"blockstream-enterprise provider url");const t="string"==typeof i.tokenUrl&&i.tokenUrl.length>0;return t&&C(i.tokenUrl,"blockstream-enterprise tokenUrl"),{url:o,auth:{provider:"blockstream-enterprise",clientId:i.clientId,clientSecret:i.clientSecret,...t?{tokenUrl:i.tokenUrl}:{}}}}default:throw new Error(`parseProviderPlaintext: unknown provider type "${String(i.provider)}"`)}}var P=new Map;async function k(t,e){if(!t)return{};switch(t.provider){case"esplora":default:return{};case"maestro":return{"api-key":t.apiKey};case"blockstream-enterprise":{const r=await async function(t,e){const r=t.tokenUrl||"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token",i=`${r}\n${t.clientId}`,o=P.get(i);if(o)return o;const n=(async()=>{const i=`grant_type=client_credentials&client_id=${encodeURIComponent(t.clientId)}&client_secret=${encodeURIComponent(t.clientSecret)}&scope=openid`,o=new AbortController,n=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:i,signal:o.signal})}finally{clearTimeout(n)}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 n.catch((()=>P.delete(i))),P.set(i,n),n}(t,e);return{Authorization:`Bearer ${r}`}}}}function x(t,e){if(!Number.isSafeInteger(t)||t<0||t>d)throw new Error(`${e}: satoshi value ${t} is not a sane amount (must be an integer in [0, 2500000000000000])`)}var I="Bitcoin tip-height read failed",S=class extends Error{constructor(t){super(t),this.isBitcoinTipUnreadable=!0,this.name="BitcoinTipUnreadableError"}};var U=class{constructor(t){this.config=t,this.timeout=t.timeout||15e3,this.logger=l.create("BitcoinDataProvider")}async withAuth(t={}){return{...t,...await k(this.config.auth,this.timeout)}}async getCurrentBlockHeight(){if(this.logger.stepStart("0","getCurrentBlockHeight"),this.config.rpcHelper){const t=await this.config.rpcHelper.getBlockCount();return this.logger.stepEnd("0"),t}const t=new AbortController,e=setTimeout((()=>t.abort()),this.timeout);try{const r=Date.now(),i=await fetch(`${this.config.providerUrl}/blocks/tip/height`,{signal:t.signal,headers:await this.withAuth({Accept:"text/plain","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(e),s(`[BitcoinDataProvider] blocks/tip/height ${Date.now()-r}ms (timeout budget ${this.timeout}ms)`),!i.ok)throw new Error(`Failed to fetch block height: ${i.status} ${i.statusText}`);const o=await i.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 n=parseInt(o.trim(),10);if(isNaN(n)){const t=o.length>200?o.substring(0,200)+"... (truncated)":o;throw new Error(`Invalid block height response: ${t}`)}return this.logger.stepEnd("0"),n}catch(t){if(clearTimeout(e),this.logger.stepEnd("0"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOs(t){this.logger.log("0",`Original address: "${t}"`);const e=this.stripNetworkPrefix(t);if(this.logger.log("0",`Cleaned address: "${e}"`),this.config.rpcHelper)return await this.fetchUTXOsFromRPC(e);try{return await this.fetchUTXOsFromProvider(this.config.providerUrl,e)}catch(t){if(this.logger.warn("0",`Primary provider failed: ${T(t)}`),this.config.fallbackProviders&&this.config.fallbackProviders.length>0){const t=[...this.config.fallbackProviders].sort(((t,e)=>t.priority-e.priority));for(const r of t)try{return this.logger.log("0",`Trying fallback: ${r.name} (${r.url})`),await this.fetchUTXOsFromProvider(r.url,e)}catch(t){this.logger.warn("0",`Fallback ${r.name} failed: ${T(t)}`);continue}}throw new Error(`Failed to fetch UTXOs: ${T(t)}`)}}stripNetworkPrefix(t){return t.replace(/^(REGTEST_|TESTNET_|MAINNET_)/,"")}async fetchUTXOsFromRPC(t){if(!this.config.rpcHelper)throw new Error("RPC helper not configured");const e=this.config.rpcWallet||"";return(await this.config.rpcHelper.listUnspent(e,t)).map((t=>{const e=Math.round(1e8*t.amount);return x(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,i=[];for(const t of r){let r=0;t.status&&"object"==typeof t.status?t.status.confirmed&&(r=void 0!==t.status.block_height&&t.status.block_height>0?e-t.status.block_height+1:1):void 0!==t.confirmations&&(r=t.confirmations);const o=t.txid,n=void 0!==t.vout?t.vout:t.n,s=void 0!==t.value?t.value:t.satoshis;if(void 0===o||void 0===n||void 0===s)throw new Error("Invalid UTXO row: missing txid, vout/n, or value/satoshis");x(s,`parseBlockstreamUTXOs ${o}:${n}`),i.push({txid:o,vout:n,satoshis:BigInt(s),confirmations:r})}return i}async fetchUTXOsFromProvider(t,e){this.logger.stepStart("1","fetchUTXOsFromProvider");const r=`${t}/address/${e}/utxo`;this.logger.log("1",`Fetching UTXOs from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),[n,a]=await Promise.all([this.getCurrentBlockHeight(),fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})})]);if(clearTimeout(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: ${n}`),!a.ok)throw new Error(`Bitcoin provider error: ${a.status} ${a.statusText}`);const c=await a.text();if(c.trim().startsWith("<!DOCTYPE")||c.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 l;try{l=JSON.parse(c)}catch(t){const e=c.length>200?c.substring(0,200)+"... (truncated)":c;throw new Error(`Failed to parse JSON response: ${T(t)}. Response: ${e}`)}this.logger.log("1",`Raw API Response: ${JSON.stringify(l,null,2)}`);const d=this.parseBlockstreamUTXOs(l,n);return this.logger.stepEnd("1"),d}catch(t){if(clearTimeout(o),this.logger.stepEnd("1"),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}async getUTXOSet(t,e){let r=[],i=null;for(let e=1;e<=3;e++)try{this.logger.log("2",`UTXO query attempt ${e}/3...`),r=await this.getUTXOs(t),this.logger.log("2",`UTXO query succeeded on attempt ${e}`),i=null;break}catch(t){i=t instanceof Error?t:new Error(T(t)),this.logger.error("2",`UTXO query failed on attempt ${e}: ${T(t)}`),e<3&&(this.logger.log("2","Waiting 500ms before retry..."),await new Promise((t=>setTimeout(t,500))))}if(i)throw new Error(`Failed to query UTXOs after 3 attempts: ${i.message}`);const o=r.reduce(((t,e)=>t+e.satoshis),0n),n=r.filter((t=>t.confirmations>=e)).reduce(((t,e)=>t+e.satoshis),0n),s=o-n;return{utxos:r,totalBalance:o,totalUTXOs:r.length,confirmedBalance:n,unconfirmedBalance:s}}async getBalance(t){const e=this.stripNetworkPrefix(t),r=`${this.config.providerUrl}/address/${e}`;this.logger.log("3",`Fetching balance from ${r}`);const i=new AbortController,o=setTimeout((()=>i.abort()),this.timeout);try{const t=Date.now(),n=await fetch(r,{signal:i.signal,headers:await this.withAuth({Accept:"application/json","Content-Type":"application/json","User-Agent":"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)","ngrok-skip-browser-warning":"true"})});if(clearTimeout(o),s(`[BitcoinDataProvider] GET address chain_stats ${Date.now()-t}ms (timeout budget ${this.timeout}ms)`),!n.ok)throw new Error(`Bitcoin provider error: ${n.status} ${n.statusText}`);const a=await n.json();if(!a.chain_stats)throw new Error("Invalid response: missing chain_stats");const c=a.chain_stats.funded_txo_sum,l=a.chain_stats.spent_txo_sum;if(void 0===c||void 0===l)throw new Error(`Invalid response: missing required fields. funded_txo_sum: ${c}, spent_txo_sum: ${l}`);x(c,`getBalance ${e} funded_txo_sum`),x(l,`getBalance ${e} spent_txo_sum`);const d=c-l;x(d,`getBalance ${e} confirmed balance`);const u=BigInt(d);return this.logger.log("3",`Balance: ${u.toString()} sats`),this.logger.log("3",` - Funded: ${c} sats, Spent: ${l} sats`),u}catch(t){if(clearTimeout(o),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);const r=T(t);throw this.logger.log("3",`Balance fetch failed: ${r}`),new Error(`Failed to fetch Bitcoin balance for address ${e}: ${r}`)}}async getTransaction(t){if(this.config.rpcHelper)try{const e=this.config.rpcWallet||"",r=await this.config.rpcHelper.getTransaction(e,t);return{txid:r.txid,confirmations:r.confirmations||0}}catch(t){const e=T(t),r=null!==t&&"object"==typeof t&&"code"in t&&"number"==typeof t.code?t.code:void 0;if(e.includes("Invalid or non-wallet transaction")||-5===r)return null;throw t}const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=Date.now(),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()-i}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 n=await o.json();if(n.status){if(!n.status.confirmed||!n.status.block_height)return{txid:n.txid??t,confirmations:0};const r=await this.fetchTipHeight(e.signal)-n.status.block_height+1;return{txid:n.txid??t,confirmations:r>0?r:0}}return null}catch(t){if(clearTimeout(r),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);if(function(t){return"object"==typeof t&&null!==t&&!0===t.isBitcoinTipUnreadable}(t))throw t;if(T(t).includes("404"))return null;throw t}}async fetchTipHeight(t){const e=`${this.config.providerUrl}/blocks/tip/height`;let r;try{r=await fetch(e,{signal:t,headers:await this.withAuth()})}catch(t){throw new S(`${I}: GET ${e} threw \u2014 ${T(t)}`)}if(!r.ok)throw new S(`${I}: GET ${e} \u2192 ${r.status} ${r.statusText}`);const i=(await r.text()).trim(),o=Number.parseInt(i,10);if(!Number.isFinite(o)||o<=0)throw new S(`${I}: GET ${e} returned an unusable tip height "${i.slice(0,64)}"`);return o}async getTransactionOutputs(t){if(!this.config.providerUrl)return null;const e=new AbortController,r=setTimeout((()=>e.abort()),this.timeout);try{const i=await fetch(`${this.config.providerUrl}/tx/${t}`,{signal:e.signal,headers:await this.withAuth()});if(clearTimeout(r),!i.ok){if(404===i.status)return null;throw new Error(`Bitcoin provider error: ${i.status} ${i.statusText}`)}const o=await i.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 x(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),A(t))throw new Error(`Request timeout after ${this.timeout}ms`);throw t}}};var D={hardhat:{chain:"hardhat",chainId:$.hardhat,bitcoinNetwork:y.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:$.sepolia,bitcoinNetwork:y.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:$.ethereum,bitcoinNetwork:y.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};function R(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=D[e];if(!r)throw new Error(`No chain policy registered for "${t}"`);return r}var _=["drpc.org","drpc.live"],O="Drpc-Key",N=/^[A-Za-z0-9_-]{16,128}$/;function M(t){return _.some((e=>t===e||t.endsWith(`.${e}`)))}function F(t,e){if("string"!=typeof t||!N.test(t))throw new Error(`Invalid ${e}: expected 16-128 characters of [A-Za-z0-9_-]`)}function L(t){if("https:"!==t.protocol)throw new Error(`A dRPC key is only sent over https, but the RPC URL scheme is "${t.protocol}"`)}function q(t,e){if(void 0===e)return;F(e,'"drpcKey"');const r=new URL(t);if(!M(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${_.join(" or ")})`);if(L(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return e}var H=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function j(t,e){const r={...e??{}};if(!t.pinContractAddresses)return r;const i=(o=t.chainId,p[o]??null);var o;if(!i)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 H){const o=i[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 n=r[e];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==o.toLowerCase())throw new Error(`Caller-supplied "${e}" (${n}) contradicts the pinned ${t.chain} address (${o}); refusing to sign`);r[e]=o}return r}async function W(t,e){const r=e.rpcUrl,i=e.rpcSource??"params-or-lit-node";let o;if("string"==typeof r&&r.length>0)!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(!v.some((t=>r===t||r.endsWith(`.${t}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${v.join(", ")}`)}(t,r),o=r;else{if("params-only"===i)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(o=await async function(t,e){if(void 0!==e)throw new Error('"drpcKey" was supplied without an "rpcUrl" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\'s own endpoint');return Lit.Actions.getRpcUrl({chain:t})}(e.chain,e.drpcKey),"string"!=typeof o||0===o.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${e.chain}"`)}return{rpcUrl:o,drpcKey:q(o,e.drpcKey),addresses:j(t,e.contractAddresses)}}var K=[{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"}],X=[{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 G(t,e){const r=66===e.length?"0x"+e.slice(-40):e;try{const e=await Lit.Actions.Decrypt({pkpId:r,ciphertext:t}),i="string"==typeof e?e:String(e??"");if(!i)throw new Error("Decrypt returned empty plaintext");return i}catch(t){throw new Error(`Failed to decrypt Bitcoin provider URL (pkpId=${e}): ${t?.message??String(t)}`)}}async function z(t,e,r){if(t.allowArbitraryBitcoinProvider)throw new Error("fetchAllDecryptedProviderConfigs called with allowArbitraryBitcoinProvider policy \u2014 caller should bypass the registry");const i=await async function(t,e,r){if(!r||"string"!=typeof r)throw new Error("fetchBitcoinProviderEntries: registryAddress (BitcoinProviderRegistry) is required");if(!e)throw new Error("fetchBitcoinProviderEntries: ethers provider is required");const i=new ethers.Contract(r,K,e),[o,n]=await i.getProviders(t),s=[];for(let t=0;t<o.length;t++)s.push({providerId:o[t],ciphertext:n[t].ciphertext,pkpId:n[t].pkpId,addedAt:Number(n[t].addedAt)});return s}(t.chainId,e,r);if(i.length<t.minConsensusProviders)throw new Error(`BitcoinProviderRegistry has ${i.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:i}=t;if(!i||"string"!=typeof i)throw new Error("assertSelfCidAllowedForDecrypt: registryAddress (BitcoinProviderRegistry) is required");if(!r)throw new Error("assertSelfCidAllowedForDecrypt: ethers provider is required");const o=globalThis.ipfsId;if("string"!=typeof o||0===o.length)throw new Error("assertSelfCidAllowedForDecrypt: globalThis.ipfsId is missing \u2014 refusing to decrypt");const n=ethers.utils.keccak256(ethers.utils.toUtf8Bytes(o)),s=new ethers.Contract(i,X,r);let a;try{a=await s.isAllowedCid(e,n)}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=${n.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 i){const r=await G(e.ciphertext,e.pkpId),{url:i,auth:n}=B(r,{requireHttps:!0});o.push({name:`Registry Provider ${e.providerId.slice(0,10)}`,url:i,auth:n,minConfirmations:t.minBitcoinBalanceConfirmations,network:t.bitcoinNetwork})}return o}var J,V={mainnet:"bc1",testnet:"tb1",regtest:"bcrt1"},Z="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function Q(){const t=Math.floor(Date.now()/1e3);return e=t,Math.floor(e/u)*u;var e}async function Y(){const t=Math.floor(Date.now()/1e3),e=t%u;if(!function(t){const e=(t??Math.floor(Date.now()/1e3))%u;return e<8||e>=u-8}(t))return;const r=h/2;let i;i=e>=u-r?u-e+r:r-e,console.log(`[Quantum] Waiting ${i}s for safe moment (current time in quantum: ${e}s)`),await new Promise((t=>setTimeout(t,1e3*i))),console.log(`[Quantum] Safe quantum ready: ${Q()}`)}async function main(t){for(const[e,r]of Object.entries(t))globalThis[e]=r;const e=E();s("[BTC Address Balance] Starting...");const r=e.chain,i=e.vaultAddress,o=e.publicKey,n=e.rpcUrl;if(!r)throw new Error('Missing required parameter: "chain"');if(!i)throw new Error('Missing required parameter: "vaultAddress"');if(!o)throw new Error('Missing required parameter: "publicKey"');const a=R(r),c=a.chain,l=a.bitcoinNetwork,d=function(t,e){if(!t||"string"!=typeof t)throw new Error('Missing required parameter: "vaultAddress"');const r=t.trim().toLowerCase(),i=V[e],o=new RegExp(`^q[${Z}]{38}$`);if(!r.startsWith(i)){const o=r.startsWith("bcrt1")?"bcrt1":r.startsWith("tb1")?"tb1":r.startsWith("bc1")?"bc1":null;if(o&&o!==i)throw new Error(`vaultAddress network mismatch: address prefix "${o}" does not match chain network "${e}" (expected "${i}")`);throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`)}const n=r.slice(i.length);if(!o.test(n))throw new Error(`vaultAddress "${t}" is not a recognised Bech32 P2WPKH address`);return r}(i,l),{rpcUrl:u,drpcKey:h,addresses:p}=await W(a,{chain:r,rpcUrl:n,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses}),w=p.BitcoinProviderRegistry;if(a.allowArbitraryBitcoinProvider){if(!e.devBitcoinProviderUrl)throw new Error('Missing required parameter: "devBitcoinProviderUrl" (required on hardhat \u2014 no on-chain registry)')}else if(!w)throw new Error("contractAddresses.BitcoinProviderRegistry is required on non-hardhat chains (action pulls all registered providers from on-chain registry)");s(` \u2705 Chain: ${r} (${c})`),s(` \u2705 Bitcoin Network: ${l}`),s(` \u2705 Vault Address: ${d}`);try{const t=new ethers.providers.JsonRpcProvider(function(t,e,r){const i={url:t},o=q(t,e);if(void 0!==o)i.headers={[O]:o};else{const e=new URL(t),r=e.searchParams.getAll("dkey");if(r.length>1)throw new Error(`rpcUrl carries ${r.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===r.length&&!M(e.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${e.hostname}" \u2014 a dRPC key is only sent to ${_.join(" or ")}`);if(1===r.length){const t=r[0];F(t,"dRPC key in rpcUrl (?dkey=)"),L(e),e.searchParams.delete("dkey"),i.url=e.toString(),i.headers={[O]:t}}}return void 0!==r&&(i.timeout=r),i}(u,h));let r;r=a.allowArbitraryBitcoinProvider?[{name:"Dev Provider",url:e.devBitcoinProviderUrl,minConfirmations:a.minBitcoinBalanceConfirmations,network:a.bitcoinNetwork}]:await z(a,t,w),s(` \u2705 Bitcoin Providers: ${r.length} (${r.map((t=>t.name)).join(", ")})`);const i=await async function(t,e,r,i,o){if(0===e.length)throw new Error("readConsensusBalance: at least one provider is required");if(e.length<r)throw new Error(`readConsensusBalance: this chain requires at least ${r} provider(s); ${e.length} configured. Refusing to read a balance without cross-check.`);const n=o??(t=>new U({providerUrl:t.url,auth:t.auth,...i?{timeout:i}:{}})),s=await Promise.allSettled(e.map((e=>n(e).getBalance(t)))),a=s.map(((t,r)=>({r:t,name:e[r].name}))).filter((t=>"rejected"===t.r.status)).map((({r:t,name:e})=>`${e} \u2192 ${t.reason?.message??String(t.reason)}`));if(a.length>0)throw new Error(`Bitcoin balance read failed for ${t} on ${a.length}/${e.length} provider(s): ${a.join("; ")}`);const c=s.map((t=>t.value)),l=c[0],d=c.map(((t,r)=>({bal:t,name:e[r].name}))).slice(1).filter((t=>t.bal!==l)).map((t=>`${e[0].name}=${l.toString()} vs ${t.name}=${t.bal.toString()}`));if(d.length>0)throw new Error(`Bitcoin provider balance mismatch for ${t}: ${d.join("; ")}`);return e.length>1&&console.log(` \u2705 Consensus reached across ${e.length} providers (${l.toString()} sats)`),l}(d,r,a.minConsensusProviders),o=r.length;s("[Step 2] Signing address balance attestation..."),await Y();const n=Q(),l=a.allowArbitraryBitcoinProvider?ethers.constants.AddressZero:w,{domain:p,types:v,value:$}=(y={verifyingContract:l,chainId:b(c),vaultAddress:d,totalBalanceSats:i,providerCount:o,timestamp:n},{domain:{name:g,version:m,chainId:y.chainId,verifyingContract:ethers.utils.getAddress(y.verifyingContract)},types:{AddressBalanceAttestation:[{name:"actionTag",type:"bytes32"},{name:"vaultAddressHash",type:"bytes32"},{name:"totalBalanceSats",type:"uint256"},{name:"providerCount",type:"uint256"},{name:"timestamp",type:"uint256"}]},value:{actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(f)),vaultAddressHash:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(y.vaultAddress)),totalBalanceSats:y.totalBalanceSats.toString(),providerCount:y.providerCount,timestamp:y.timestamp}}),E=globalThis.validatorWalletAddress;if(!E||!E.startsWith("0x"))throw new Error("validatorWalletAddress required \u2014 must be a createWallet-derived address");const T=await Lit.Actions.getPrivateKey({pkpId:E}),A="string"==typeof T?T.startsWith("0x")?T:`0x${T}`:String(T),C=new ethers.Wallet(A),B=await C._signTypedData(p,v,$);return s("[BTC Address Balance] \u2705 Complete"),{vaultAddress:d,totalBalanceSats:i.toString(),providerCount:o,signature:B,timestamp:n,validatorPkp:C.address}}catch(t){return console.error("[BTC Address Balance] \u274c Failed:",t.message),{error:t.message||t.toString(),vaultAddress:d||null,timestamp:Date.now()}}var y}return J=o,((o,n,s,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of r(n))i.call(o,c)||c===s||t(o,c,{get:()=>n[c],enumerable:!(a=e(n,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),J)})();if("object"==typeof _LIT_ACTION_)if("function"==typeof _LIT_ACTION_.main)var main=_LIT_ACTION_.main;else"function"==typeof _LIT_ACTION_.go&&_LIT_ACTION_.go();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
2297c7b625340f048b5926325a14c958016594b77f4c4270ef413b164a8ac975
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "btc-address-balance",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 65366,
|
|
4
|
+
"minifiedSize": 31909,
|
|
5
|
+
"compressionRatio": 0.5118410182663771,
|
|
6
|
+
"hash": "2297c7b625340f048b5926325a14c958016594b77f4c4270ef413b164a8ac975",
|
|
7
|
+
"buildTime": 1792491258281,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|