@gvnrdao/dh-lit-actions 0.0.332 → 0.0.333
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.meta.json +1 -1
- package/dist/backing-attestation.meta.json +1 -1
- package/dist/btc-address-balance.meta.json +1 -1
- package/dist/btc-provider-probe.meta.json +1 -1
- package/dist/btc-transaction-signer.meta.json +1 -1
- package/dist/btc-utxo-invalidator.meta.json +1 -1
- package/dist/btc-withdrawal.meta.json +1 -1
- 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-repay-validator.action.js +1 -1
- package/dist/carry-repay-validator.hash +1 -1
- package/dist/carry-repay-validator.meta.json +5 -5
- package/dist/encrypt-parameter.meta.json +1 -1
- package/dist/extend-position-validator.meta.json +1 -1
- package/dist/liquidation-validator.meta.json +1 -1
- package/dist/loan-vault-btc-balance.meta.json +1 -1
- package/dist/pkp-validator.meta.json +1 -1
- package/dist/price-oracle.meta.json +1 -1
- package/dist/process-payment-validator.meta.json +1 -1
- package/dist/stale-spend-recovery-validator.meta.json +1 -1
- package/dist/ucd-mint-validator.meta.json +1 -1
- package/package.json +1 -1
- package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
- package/pkg-dist/pkg-src/index.js +20 -18
- package/pkg-dist/pkg-src/index.js.map +2 -2
- package/pkg-dist/src/modules/carry-attestation.module.d.ts +23 -3
- package/pkg-dist/src/modules/carry-attestation.module.d.ts.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,n={};((t,r)=>{for(var a in r)e(t,a,{get:r[a],enumerable:!0})})(n,{main:()=>main});var i=1000000000000000000n,o=60,s=8e3,c={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 d={1:{AgentDelegationRegistry:"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa",BitcoinWithdrawalAddressRegistry:"0xf667f77FDba7458345f227eB6Bfe4148243E7270"},11155111:{AgentModuleFactory:"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5",AgentDelegationRegistry:"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",BitcoinWithdrawalAddressRegistry:"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe"}};var l="DiamondHands.Protocol",u="1",h=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(h||{}),p={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org","drpc.live"],g={ethereum:1,sepolia:11155111,hardhat:1337};function f(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(", ")}`)}function m(e){return g[e]}function w(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`calculateLiquidationThreshold: ${e} must be a non-negative integer, got ${String(t)}`)}var A=["drpc.org","drpc.live"],b="Drpc-Key",v=/^[A-Za-z0-9_-]{16,128}$/;function E(e){return A.some((t=>e===t||e.endsWith(`.${t}`)))}function C(e,t){if("string"!=typeof e||!v.test(e))throw new Error(`Invalid ${t}: expected 16-128 characters of [A-Za-z0-9_-]`)}function T(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 B(e,t){if(void 0===t)return;C(t,'"drpcKey"');const r=new URL(e);if(!E(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${A.join(" or ")})`);if(T(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return t}async function I(e,t){if(void 0!==t)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:e})}function P(e,t,r){const a={url:e},n=B(e,t);if(void 0!==n)a.headers={[b]:n};else{const t=new URL(e),r=t.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&&!E(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 ${A.join(" or ")}`);if(1===r.length){const e=r[0];C(e,"dRPC key in rpcUrl (?dkey=)"),T(t),t.searchParams.delete("dkey"),a.url=t.toString(),a.headers={[b]:e}}}return void 0!==r&&(a.timeout=r),a}var D=class{constructor(e){this.termManagerAddress=e.termManagerAddress,this.loanOpsManagerAddress=e.loanOpsManagerAddress,this.liquidationManagerAddress=e.liquidationManagerAddress,this.chain=e.chain,this.chainId=e.chainId,this.rpcUrl=e.rpcUrl,this.drpcKey=e.drpcKey}async getLiquidationThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(P(e,this.drpcKey,s),{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],a=new ethers.Contract(this.loanOpsManagerAddress,r,t),n=await a.liquidationThreshold();return Number(n.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",e.message),new Error(`Failed to fetch liquidation threshold: ${e.message}`)}}async getTermFees(e){try{let t;t=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,a,r),i=await n.getTermFees(e);return{originationFeeBps:Number(i.originationFee?.toString?.()??i[0]?.toString?.()??i[0]),extensionFeeBps:Number(i.extensionFee?.toString?.()??i[1]?.toString?.()??i[1])}}catch(e){throw console.error("[ProtocolParameters] Error fetching term fees:",e.message),new Error(`Failed to fetch term fees: ${e.message}`)}}async getAuthorizedSpendsHash(e){try{const t=this.rpcUrl||await I(this.chain,this.drpcKey),r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(a)}catch(e){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",e.message),new Error(`Failed to fetch authorized spends hash: ${e.message}`)}}async readLiquidationManagerUint(e,t){try{let t;t=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=[{inputs:[],name:e,outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.liquidationManagerAddress,a,r),i=await n[e]();return Number(i.toString())}catch(e){throw console.error(`[ProtocolParameters] Error fetching ${t}:`,e.message),new Error(`Failed to fetch ${t}: ${e.message}`)}}async getMaxEscalatedThreshold(){return this.readLiquidationManagerUint("maxEscalatedThreshold","max escalated threshold")}async getExpiryLiquidationIncrementBps(){return this.readLiquidationManagerUint("expiryLiquidationIncrementBps","expiry liquidation increment")}async getExpiredLoanGracePeriodDays(){return this.readLiquidationManagerUint("expiredLoanGracePeriodDays","expired loan grace period")}};function x(e,t){try{const r=JSON.parse(e);if("object"==typeof r&&null!==r){if("sepolia"===t.toLowerCase())return r.regtest||r.testnet||void 0;const e=function(e){return p[e]}(t);return"regtest"===e?r.regtest||r.testnet||void 0:"testnet"===e?r.testnet||r.regtest||void 0:r.mainnet}}catch(e){}return e}var S=class{constructor(e){if(!Number.isInteger(e.chainId)||e.chainId<=0)throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(e.chainId)}`);this.config=e}async getVaultSnapshot(e){const t=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${t.vaultAddress}"`);const[r,a]=await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,t.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=(o={termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId,rpcUrl:this.config.rpcUrl,drpcKey:this.config.drpcKey},new D(o));var o;const s=this.config.termOverride??t.selectedTerm,[c,d,l,u,h]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getExpiryLiquidationIncrementBps(),n.getExpiredLoanGracePeriodDays(),n.getTermFees(s)]),p=function(e,t){if(0===e)return{termDurationDays:0,termLengthDays:30*t,isExpired:!1,daysUntilExpiry:30*t,daysIntoGracePeriod:0};const r=30*t,a=Math.floor(Date.now()/1e3)-e,n=Math.floor(a/86400);return{termDurationDays:n,termLengthDays:r,isExpired:n>r,daysUntilExpiry:Math.max(0,r-n),daysIntoGracePeriod:Math.max(0,n-r)}}(t.termStartTimestamp,t.selectedTerm),y=function(e,t,r,a){if(!e)return r;if(w("daysSinceExpiry",t),w("dailyIncrementBps",a.dailyIncrementBps),w("gracePeriodDays",a.gracePeriodDays),w("maxEscalatedThresholdBps",a.maxEscalatedThresholdBps),t<=a.gracePeriodDays)return 11e3;const n=t-a.gracePeriodDays;if(n>=365)return a.maxEscalatedThresholdBps;const i=1e4+a.dailyIncrementBps;let o=11e3;for(let e=0;e<n;e++)if(o=Math.floor(o*i/1e4),o>=a.maxEscalatedThresholdBps)return a.maxEscalatedThresholdBps;return o}(p.isExpired,p.daysIntoGracePeriod,c,{dailyIncrementBps:l,gracePeriodDays:u,maxEscalatedThresholdBps:d}),g=function(e,t,r){const a=e*t/10000000000000000n;return 0n===r?{collateralValueUsd:a,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:a,collateralRatioBps:Number(a*i*10000n/r)}}(r.availableBalance,a,t.ucdDebt),f=g.collateralRatioBps<y,m=g.collateralRatioBps-y;return{positionId:t.positionId,pkpId:t.pkpId,borrower:t.borrower,vaultAddress:t.vaultAddress,ucdDebt:t.ucdDebt,termStartTimestamp:t.termStartTimestamp,selectedTerm:t.selectedTerm,status:t.status,expiryAt:t.expiryAt,previousExpiryAt:t.previousExpiryAt,totalTerm:t.totalTerm,lastRenewedAt:t.lastRenewedAt,totalBTCSats:r.totalBalance,totalUTXOs:r.totalUTXOs,authorizedSpendsSats:r.authorizedBalance,authorizedSpendsHash:r.authorizedSpendsHash,availableBTCSats:r.availableBalance,availableUTXOs:r.availableUTXOs,btcPriceUsd:a,collateralValueUsd:g.collateralValueUsd,collateralRatioBps:g.collateralRatioBps,termDurationDays:p.termDurationDays,termLengthDays:p.termLengthDays,isExpired:p.isExpired,daysUntilExpiry:p.daysUntilExpiry,daysIntoGracePeriod:p.daysIntoGracePeriod,currentLiquidationThreshold:y,isLiquidatable:f,marginToLiquidationBps:m,liquidationThresholdBps:c,originationFeeBps:h.originationFeeBps,extensionFeeBps:h.extensionFeeBps,timestamp:Date.now()}}async queryPositionState(e){const t=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await I(this.config.chain,this.config.drpcKey);const a=new ethers.providers.StaticJsonRpcProvider(P(r,this.config.drpcKey,s),this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],a),i=await n.core(),o=new ethers.Contract(i,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],a),c=await o.getPositionDetails(t),d=Number(c.status);if(d<0||d>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",t),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",d,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(c,null,2)),new Error(`Invalid position status decoded from contract: ${d} (expected 0-7). This indicates an ABI decoding issue. Position: ${t}`);const l=Number(c.expiryAt),u=Number(c.selectedTerm),h=Number(c.totalTerm),p=Number(c.previousExpiryAt),y=Number(c.lastRenewedAt),g=(w=u,0===(m=l)?0:m-30*w*86400);var m,w;const A=x(c.vaultAddress,f(this.config.chain));if("string"!=typeof A||0===A.length)throw new Error(`Position ${t} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:c.positionId,pkpId:c.pkpId,borrower:c.borrower,vaultAddress:A,ucdDebt:BigInt(c.ucdDebt.toString()),termStartTimestamp:g,selectedTerm:u,status:d,expiryAt:l,previousExpiryAt:p,totalTerm:h,lastRenewedAt:y}}async isLiquidatable(e){return(await this.getVaultSnapshot(e)).isLiquidatable}async getCollateralRatio(e){return(await this.getVaultSnapshot(e)).collateralRatioBps}async getAvailableBalance(e){return(await this.getVaultSnapshot(e)).availableBTCSats}async hasSufficientCollateral(e,t,r){const a=await this.getVaultSnapshot(e);return function(e,t,r,a){const n=t+r;return 0n===n||Number(e*i*10000n/n)>=a}(a.collateralValueUsd,a.ucdDebt,t,r)}},M="carry-collateral",$=0,U=1,R={CarryCollateralAttestation:[{name:"actionTag",type:"bytes32"},{name:"loanId",type:"bytes32"},{name:"borrower",type:"address"},{name:"borrowerKind",type:"uint8"},{name:"actor",type:"address"},{name:"actorValidUntil",type:"uint64"},{name:"btcVaultAddress",type:"string"},{name:"btcBalance",type:"uint128"},{name:"quantumTimestamp",type:"uint256"}]},L={11155111:{hyperEvmChainId:998,vault:"0x5310AE7e24835cC6f7740db18ebbF9f3aB422554",signer:"0x1d2ff7E2fC89ead767b44F3aB2cAA6b18Fff3a67"}};function F(){const e=Math.floor(Date.now()/1e3);return t=e,Math.floor(t/o)*o;var t}var q={hardhat:{chain:"hardhat",chainId:g.hardhat,bitcoinNetwork:p.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:g.sepolia,bitcoinNetwork:p.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:g.ethereum,bitcoinNetwork:p.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var N=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function O(e,t){const r={...t??{}};if(!e.pinContractAddresses)return r;const a=(n=e.chainId,c[n]??null);var n;if(!a)throw new Error(`No pinned contract-address set for chainId ${e.chainId} (${e.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const t of N){const n=a[t];if(!n)throw new Error(`Pinned address set for ${e.chain} is missing required "${t}"; refusing to fall through to a caller-supplied value`);const i=r[t];if("string"==typeof i&&i.length>0&&i.toLowerCase()!==n.toLowerCase())throw new Error(`Caller-supplied "${t}" (${i}) contradicts the pinned ${e.chain} address (${n}); refusing to sign`);r[t]=n}return r}var V=["AgentModuleFactory","AgentDelegationRegistry","BitcoinWithdrawalAddressRegistry"];function _(e,t){if(!e.pinContractAddresses){const e={};for(const r of V){const a=t?.[r];"string"==typeof a&&a.length>0&&(e[r]=a)}return e}const r=(a=e.chainId,d[a]??{});var a;const n={};for(const a of V){const i=r[a];if(!i)continue;const o=t?.[a];if("string"==typeof o&&o.length>0&&o.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${a}" (${o}) contradicts the pinned ${e.chain} address (${i}); refusing to evaluate the Safe-agent authorization arm`);n[a]=i}return n}async function k(e,t){const r=t.rpcUrl,a=t.rpcSource??"params-or-lit-node";let n;if("string"==typeof r&&r.length>0)!function(e,t){if(e.allowArbitraryEvmRpc)return;if(!t||"string"!=typeof t)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(t).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!y.some((e=>r===e||r.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${y.join(", ")}`)}(e,r),n=r;else{if("params-only"===a)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(n=await I(t.chain,t.drpcKey),"string"!=typeof n||0===n.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${t.chain}"`)}return{rpcUrl:n,drpcKey:B(n,t.drpcKey),addresses:O(e,t.contractAddresses)}}var K=["NONE","PAUSED","NO_GRANT","SCOPE_DISABLED","NO_AGENT","AGENT_REVOKED","AGENT_EXPIRED","NOT_CALLER"],z=["function agentOf(address user) view returns (tuple(address agent, uint64 validUntil, uint8 status, uint64 registeredAt, uint64 revokedAt))","function canCarry(bytes32 positionId, address caller) view returns (bool ok, uint8 reason)"],j="0x0000000000000000000000000000000000000000";var G={BalanceConfirmation:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"collateralValue",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},W="updateBalance(bytes32,uint256,uint256,uint256,bytes)",H=180;var J,X=class extends S{read(e){return this.queryPositionState(e)}},Z={getBTCPrice:async()=>{throw new Error("[carry-collateral] a price was requested; collateral attestations sign no price")}},Y={calculateTrustedBalance:async()=>{throw new Error("[carry-collateral] a BTC read was requested; the BTC comes from the verified BalanceConfirmation")}};async function main(e){if(!e||"object"!=typeof e)throw new Error("[carry-collateral] missing args");for(const t of["chain","positionId","validatorWalletAddress","rpcUrl"])if("string"!=typeof e[t]||0===e[t].length)throw new Error(`[carry-collateral] missing "${t}"`);if(!e.carryVault||"object"!=typeof e.carryVault)throw new Error('[carry-collateral] missing "carryVault"');if(!e.balanceConfirmation||"object"!=typeof e.balanceConfirmation)throw new Error('[carry-collateral] missing "balanceConfirmation" (the loans\' signed vault balance, D81)');const t=function(e){const t=f(e),r=q[t];if(!r)throw new Error(`No chain policy registered for "${e}"`);return r}(e.chain),r=function(e,t,r,a,n,i){if(!Number.isInteger(t.chainId)||t.chainId<=0)throw new Error(`[carry] invalid carryVault.chainId: ${t.chainId}`);const o=ethers.utils.getAddress(t.vault),s=ethers.utils.getAddress(r);if(e.pinContractAddresses){if(!a)throw new Error(`[carry] no pinned carry pairing for ${e.chain} (${e.chainId}) \u2014 the vault is not deployed/pinned there; refusing to sign`);if(t.chainId!==a.hyperEvmChainId||o!==ethers.utils.getAddress(a.vault))throw new Error(`[carry] requested domain (${t.chainId}, ${o}) is not the pinned pairing (${a.hyperEvmChainId}, ${a.vault}) for ${e.chain}; refusing to sign`);if(s!==ethers.utils.getAddress(a.signer))throw new Error(`[carry] signer ${s} is not the pinned carry signer ${a.signer}; refusing to sign`)}return{name:n,version:i,chainId:t.chainId,verifyingContract:o}}(t,e.carryVault,e.validatorWalletAddress,(a=t.chainId,L[a]??null),l,u);var a;const{rpcUrl:n,drpcKey:i,addresses:o}=await k(t,{chain:e.chain,rpcUrl:e.rpcUrl,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses,rpcSource:"params-only"});for(const e of["PositionManager","TermManagerModule","LoanOperationsManagerModule","LiquidationManagerModule"])if(!o[e])throw new Error(`[carry-collateral] contractAddresses.${e} is required`);const s=new ethers.providers.JsonRpcProvider(P(n,i)),c=new X({contractAddress:o.PositionManager,termManagerAddress:o.TermManagerModule,loanOpsManagerAddress:o.LoanOperationsManagerModule,liquidationManagerAddress:o.LiquidationManagerModule,chain:t.chain,chainId:m(t.chain),vaultBalance:Y,priceOracle:Z,rpcUrl:n,drpcKey:i}),d=function(e){if("string"!=typeof e)throw new Error("positionId must be a string");const t=e.trim(),r=/^0x/i.test(t)?t.slice(2):t;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(e.positionId),h=await c.read(d),p=ethers.utils.getAddress(h.borrower),y=function(e){const t=e.toLowerCase();return"0x"===t||/^0xef0100[0-9a-f]{40}$/.test(t)}(await s.getCode(p))?$:U;const g=_(t,e.contractAddresses).AgentDelegationRegistry,w=await async function(e,t,r){const a=e=>({actor:r,actorValidUntil:"0",denied:e});if(!e)return a("NO_REGISTRY");const n=await e.agentOf(r);if(!n.agent||n.agent.toLowerCase()===j)return a("NO_AGENT");const i=ethers.utils.getAddress(n.agent),{ok:o,reason:s}=await e.canCarry(t,i);if(!o){const e=K[Number(s)];if(void 0===e)throw new Error(`[carry] AgentDelegationRegistry.canCarry returned an unknown reason ${s}`);return a(e)}const c=n.validUntil.toString();if(!/^[1-9]\d*$/.test(c))throw new Error(`[carry] registry agent ${i} is allowed to carry but has validUntil ${c}`);return{actor:i,actorValidUntil:c,denied:"NONE"}}(g?new ethers.Contract(g,z,s):void 0,d,p);!function(e,t,r,a){if(r===U&&a.actor===t)throw new Error(`[carry] borrower ${t} of loan ${e} is a contract (Safe) with no active carry agent (${a.denied}); a Safe is attested only through an agent allowed by canCarry`)}(d,p,y,w);const A=new ethers.Contract(o.PositionManager,["function authorizationRegistry() view returns (address)"],s),b=new ethers.Contract(await A.authorizationRegistry(),["function getValidator(bytes4) view returns (tuple(address pkpAddress, uint256 version, bool active))"],s),v=await b.getValidator(ethers.utils.id(W).slice(0,10));if(!v.active)throw new Error("[carry-collateral] the updateBalance validator is not active");const E=F(),C=function(e){const t=e.confirmation;if(!t||"string"!=typeof t.signature||!/^0x[0-9a-fA-F]{130}$/.test(t.signature))throw new Error("[carry] balanceConfirmation.signature is missing or malformed");if(!/^\d+$/.test(String(t.vaultBalance))||!/^\d+$/.test(String(t.btcPrice))||!/^\d+$/.test(String(t.quantumTimestamp)))throw new Error("[carry] balanceConfirmation fields must be unsigned integers");const r=Number(t.quantumTimestamp);if(r>e.nowSeconds+60||e.nowSeconds-r>H)throw new Error(`[carry] balanceConfirmation at ${r} is outside the window at ${e.nowSeconds}`);const a={actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes("balance-confirmation")),positionId:e.positionId,collateralValue:String(t.vaultBalance),btcPrice:String(t.btcPrice),quantumTimestamp:String(t.quantumTimestamp),borrower:ethers.utils.getAddress(e.borrower)},n=ethers.utils._TypedDataEncoder.hash(e.domain,G,a),i=ethers.utils.recoverAddress(n,t.signature);if(i!==ethers.utils.getAddress(e.validator))throw new Error(`[carry] balanceConfirmation signed by ${i}, not the updateBalance validator ${e.validator}`);return BigInt(t.vaultBalance)}({confirmation:e.balanceConfirmation,positionId:d,borrower:p,validator:v.pkpAddress,domain:{name:l,version:u,chainId:m(t.chain),verifyingContract:ethers.utils.getAddress(o.LoanOperationsManagerModule)},nowSeconds:E}),T={actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(M)),loanId:d,borrower:p,borrowerKind:y,actor:w.actor,actorValidUntil:w.actorValidUntil,btcVaultAddress:h.vaultAddress,btcBalance:C.toString(),quantumTimestamp:E.toString()},{signature:B,signer:I}=await async function(e,t,r,a){const n=await Lit.Actions.getPrivateKey({pkpId:e}),i="string"==typeof n?n.startsWith("0x")?n:`0x${n}`:String(n),o=new ethers.Wallet(i);if(o.address!==ethers.utils.getAddress(e))throw new Error(`[carry] key for ${e} derives ${o.address}; refusing to sign`);return{signature:await o._signTypedData(t,r,a),signer:o.address}}(e.validatorWalletAddress,r,R,T);return{attestation:T,signature:B,signer:I,domain:r}}return J=n,((n,i,o,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of r(i))a.call(n,c)||c===o||e(n,c,{get:()=>i[c],enumerable:!(s=t(i,c))||s.enumerable});return n})(e({},"__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
|
+
var _LIT_ACTION_=(()=>{var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,n={};((t,r)=>{for(var a in r)e(t,a,{get:r[a],enumerable:!0})})(n,{main:()=>main});var i=1000000000000000000n,o=60,s=8e3,c={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 d={1:{AgentDelegationRegistry:"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa",BitcoinWithdrawalAddressRegistry:"0xf667f77FDba7458345f227eB6Bfe4148243E7270"},11155111:{AgentModuleFactory:"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5",AgentDelegationRegistry:"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025",BitcoinWithdrawalAddressRegistry:"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe"}};var l="DiamondHands.Protocol",u="1",h=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(h||{}),p={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},y=["infura.io","drpc.org","drpc.live"],g={ethereum:1,sepolia:11155111,hardhat:1337};function f(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(", ")}`)}function m(e){return g[e]}function w(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`calculateLiquidationThreshold: ${e} must be a non-negative integer, got ${String(t)}`)}var A=["drpc.org","drpc.live"],b="Drpc-Key",v=/^[A-Za-z0-9_-]{16,128}$/;function E(e){return A.some((t=>e===t||e.endsWith(`.${t}`)))}function C(e,t){if("string"!=typeof e||!v.test(e))throw new Error(`Invalid ${t}: expected 16-128 characters of [A-Za-z0-9_-]`)}function I(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 T(e,t){if(void 0===t)return;C(t,'"drpcKey"');const r=new URL(e);if(!E(r.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${r.hostname}" (expected ${A.join(" or ")})`);if(I(r),r.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return t}async function B(e,t){if(void 0!==t)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:e})}function P(e,t,r){const a={url:e},n=T(e,t);if(void 0!==n)a.headers={[b]:n};else{const t=new URL(e),r=t.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&&!E(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 ${A.join(" or ")}`);if(1===r.length){const e=r[0];C(e,"dRPC key in rpcUrl (?dkey=)"),I(t),t.searchParams.delete("dkey"),a.url=t.toString(),a.headers={[b]:e}}}return void 0!==r&&(a.timeout=r),a}var x=class{constructor(e){this.termManagerAddress=e.termManagerAddress,this.loanOpsManagerAddress=e.loanOpsManagerAddress,this.liquidationManagerAddress=e.liquidationManagerAddress,this.chain=e.chain,this.chainId=e.chainId,this.rpcUrl=e.rpcUrl,this.drpcKey=e.drpcKey}async getLiquidationThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await B(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(P(e,this.drpcKey,s),{name:"any",chainId:this.chainId}),r=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],a=new ethers.Contract(this.loanOpsManagerAddress,r,t),n=await a.liquidationThreshold();return Number(n.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",e.message),new Error(`Failed to fetch liquidation threshold: ${e.message}`)}}async getTermFees(e){try{let t;t=this.rpcUrl?this.rpcUrl:await B(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,a,r),i=await n.getTermFees(e);return{originationFeeBps:Number(i.originationFee?.toString?.()??i[0]?.toString?.()??i[0]),extensionFeeBps:Number(i.extensionFee?.toString?.()??i[1]?.toString?.()??i[1])}}catch(e){throw console.error("[ProtocolParameters] Error fetching term fees:",e.message),new Error(`Failed to fetch term fees: ${e.message}`)}}async getAuthorizedSpendsHash(e){try{const t=this.rpcUrl||await B(this.chain,this.drpcKey),r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],r);return await n.getAuthorizedSpendsHash(a)}catch(e){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",e.message),new Error(`Failed to fetch authorized spends hash: ${e.message}`)}}async readLiquidationManagerUint(e,t){try{let t;t=this.rpcUrl?this.rpcUrl:await B(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(P(t,this.drpcKey,s),{name:"any",chainId:this.chainId}),a=[{inputs:[],name:e,outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.liquidationManagerAddress,a,r),i=await n[e]();return Number(i.toString())}catch(e){throw console.error(`[ProtocolParameters] Error fetching ${t}:`,e.message),new Error(`Failed to fetch ${t}: ${e.message}`)}}async getMaxEscalatedThreshold(){return this.readLiquidationManagerUint("maxEscalatedThreshold","max escalated threshold")}async getExpiryLiquidationIncrementBps(){return this.readLiquidationManagerUint("expiryLiquidationIncrementBps","expiry liquidation increment")}async getExpiredLoanGracePeriodDays(){return this.readLiquidationManagerUint("expiredLoanGracePeriodDays","expired loan grace period")}};function $(e,t){try{const r=JSON.parse(e);if("object"==typeof r&&null!==r){if("sepolia"===t.toLowerCase())return r.regtest||r.testnet||void 0;const e=function(e){return p[e]}(t);return"regtest"===e?r.regtest||r.testnet||void 0:"testnet"===e?r.testnet||r.regtest||void 0:r.mainnet}}catch(e){}return e}var D=class{constructor(e){if(!Number.isInteger(e.chainId)||e.chainId<=0)throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(e.chainId)}`);this.config=e}async getVaultSnapshot(e){const t=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${t.vaultAddress}"`);const[r,a]=await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,t.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=(o={termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId,rpcUrl:this.config.rpcUrl,drpcKey:this.config.drpcKey},new x(o));var o;const s=this.config.termOverride??t.selectedTerm,[c,d,l,u,h]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getExpiryLiquidationIncrementBps(),n.getExpiredLoanGracePeriodDays(),n.getTermFees(s)]),p=function(e,t){if(0===e)return{termDurationDays:0,termLengthDays:30*t,isExpired:!1,daysUntilExpiry:30*t,daysIntoGracePeriod:0};const r=30*t,a=Math.floor(Date.now()/1e3)-e,n=Math.floor(a/86400);return{termDurationDays:n,termLengthDays:r,isExpired:n>r,daysUntilExpiry:Math.max(0,r-n),daysIntoGracePeriod:Math.max(0,n-r)}}(t.termStartTimestamp,t.selectedTerm),y=function(e,t,r,a){if(!e)return r;if(w("daysSinceExpiry",t),w("dailyIncrementBps",a.dailyIncrementBps),w("gracePeriodDays",a.gracePeriodDays),w("maxEscalatedThresholdBps",a.maxEscalatedThresholdBps),t<=a.gracePeriodDays)return 11e3;const n=t-a.gracePeriodDays;if(n>=365)return a.maxEscalatedThresholdBps;const i=1e4+a.dailyIncrementBps;let o=11e3;for(let e=0;e<n;e++)if(o=Math.floor(o*i/1e4),o>=a.maxEscalatedThresholdBps)return a.maxEscalatedThresholdBps;return o}(p.isExpired,p.daysIntoGracePeriod,c,{dailyIncrementBps:l,gracePeriodDays:u,maxEscalatedThresholdBps:d}),g=function(e,t,r){const a=e*t/10000000000000000n;return 0n===r?{collateralValueUsd:a,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:a,collateralRatioBps:Number(a*i*10000n/r)}}(r.availableBalance,a,t.ucdDebt),f=g.collateralRatioBps<y,m=g.collateralRatioBps-y;return{positionId:t.positionId,pkpId:t.pkpId,borrower:t.borrower,vaultAddress:t.vaultAddress,ucdDebt:t.ucdDebt,termStartTimestamp:t.termStartTimestamp,selectedTerm:t.selectedTerm,status:t.status,expiryAt:t.expiryAt,previousExpiryAt:t.previousExpiryAt,totalTerm:t.totalTerm,lastRenewedAt:t.lastRenewedAt,totalBTCSats:r.totalBalance,totalUTXOs:r.totalUTXOs,authorizedSpendsSats:r.authorizedBalance,authorizedSpendsHash:r.authorizedSpendsHash,availableBTCSats:r.availableBalance,availableUTXOs:r.availableUTXOs,btcPriceUsd:a,collateralValueUsd:g.collateralValueUsd,collateralRatioBps:g.collateralRatioBps,termDurationDays:p.termDurationDays,termLengthDays:p.termLengthDays,isExpired:p.isExpired,daysUntilExpiry:p.daysUntilExpiry,daysIntoGracePeriod:p.daysIntoGracePeriod,currentLiquidationThreshold:y,isLiquidatable:f,marginToLiquidationBps:m,liquidationThresholdBps:c,originationFeeBps:h.originationFeeBps,extensionFeeBps:h.extensionFeeBps,timestamp:Date.now()}}async queryPositionState(e){const t=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`;let r;r=this.config.rpcUrl?this.config.rpcUrl:await B(this.config.chain,this.config.drpcKey);const a=new ethers.providers.StaticJsonRpcProvider(P(r,this.config.drpcKey,s),this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],a),i=await n.core(),o=new ethers.Contract(i,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],a),c=await o.getPositionDetails(t),d=Number(c.status);if(d<0||d>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",t),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",d,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(c,null,2)),new Error(`Invalid position status decoded from contract: ${d} (expected 0-7). This indicates an ABI decoding issue. Position: ${t}`);const l=Number(c.expiryAt),u=Number(c.selectedTerm),h=Number(c.totalTerm),p=Number(c.previousExpiryAt),y=Number(c.lastRenewedAt),g=(w=u,0===(m=l)?0:m-30*w*86400);var m,w;const A=$(c.vaultAddress,f(this.config.chain));if("string"!=typeof A||0===A.length)throw new Error(`Position ${t} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:c.positionId,pkpId:c.pkpId,borrower:c.borrower,vaultAddress:A,ucdDebt:BigInt(c.ucdDebt.toString()),termStartTimestamp:g,selectedTerm:u,status:d,expiryAt:l,previousExpiryAt:p,totalTerm:h,lastRenewedAt:y}}async isLiquidatable(e){return(await this.getVaultSnapshot(e)).isLiquidatable}async getCollateralRatio(e){return(await this.getVaultSnapshot(e)).collateralRatioBps}async getAvailableBalance(e){return(await this.getVaultSnapshot(e)).availableBTCSats}async hasSufficientCollateral(e,t,r){const a=await this.getVaultSnapshot(e);return function(e,t,r,a){const n=t+r;return 0n===n||Number(e*i*10000n/n)>=a}(a.collateralValueUsd,a.ucdDebt,t,r)}},S="carry-collateral",M=0,U=1,R={CarryCollateralAttestation:[{name:"actionTag",type:"bytes32"},{name:"loanId",type:"bytes32"},{name:"borrower",type:"address"},{name:"borrowerKind",type:"uint8"},{name:"actor",type:"address"},{name:"actorValidUntil",type:"uint64"},{name:"btcVaultAddress",type:"string"},{name:"btcBalance",type:"uint128"},{name:"quantumTimestamp",type:"uint256"}]},L={11155111:{hyperEvmChainId:998,vault:"0x5310AE7e24835cC6f7740db18ebbF9f3aB422554",signer:"0x1d2ff7E2fC89ead767b44F3aB2cAA6b18Fff3a67"}};function F(){const e=Math.floor(Date.now()/1e3);return t=e,Math.floor(t/o)*o;var t}var q={hardhat:{chain:"hardhat",chainId:g.hardhat,bitcoinNetwork:p.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:g.sepolia,bitcoinNetwork:p.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:g.ethereum,bitcoinNetwork:p.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var N=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function O(e,t){const r={...t??{}};if(!e.pinContractAddresses)return r;const a=(n=e.chainId,c[n]??null);var n;if(!a)throw new Error(`No pinned contract-address set for chainId ${e.chainId} (${e.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const t of N){const n=a[t];if(!n)throw new Error(`Pinned address set for ${e.chain} is missing required "${t}"; refusing to fall through to a caller-supplied value`);const i=r[t];if("string"==typeof i&&i.length>0&&i.toLowerCase()!==n.toLowerCase())throw new Error(`Caller-supplied "${t}" (${i}) contradicts the pinned ${e.chain} address (${n}); refusing to sign`);r[t]=n}return r}var _=["AgentModuleFactory","AgentDelegationRegistry","BitcoinWithdrawalAddressRegistry"];function V(e,t){if(!e.pinContractAddresses){const e={};for(const r of _){const a=t?.[r];"string"==typeof a&&a.length>0&&(e[r]=a)}return e}const r=(a=e.chainId,d[a]??{});var a;const n={};for(const a of _){const i=r[a];if(!i)continue;const o=t?.[a];if("string"==typeof o&&o.length>0&&o.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${a}" (${o}) contradicts the pinned ${e.chain} address (${i}); refusing to evaluate the Safe-agent authorization arm`);n[a]=i}return n}async function k(e,t){const r=t.rpcUrl,a=t.rpcSource??"params-or-lit-node";let n;if("string"==typeof r&&r.length>0)!function(e,t){if(e.allowArbitraryEvmRpc)return;if(!t||"string"!=typeof t)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let r;try{r=new URL(t).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!y.some((e=>r===e||r.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${r}" is not in the approved list: ${y.join(", ")}`)}(e,r),n=r;else{if("params-only"===a)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(n=await B(t.chain,t.drpcKey),"string"!=typeof n||0===n.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${t.chain}"`)}return{rpcUrl:n,drpcKey:T(n,t.drpcKey),addresses:O(e,t.contractAddresses)}}var K=["NONE","PAUSED","NO_GRANT","SCOPE_DISABLED","NO_AGENT","AGENT_REVOKED","AGENT_EXPIRED","NOT_CALLER"],z=["function agentOf(address user) view returns (tuple(address agent, uint64 validUntil, uint8 status, uint64 registeredAt, uint64 revokedAt))","function canCarry(bytes32 positionId, address caller) view returns (bool ok, uint8 reason)"],j="0x0000000000000000000000000000000000000000";var G={BalanceConfirmation:[{name:"actionTag",type:"bytes32"},{name:"positionId",type:"bytes32"},{name:"collateralValue",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"quantumTimestamp",type:"uint256"},{name:"borrower",type:"address"}]},W="updateBalance(bytes32,uint256,uint256,uint256,bytes)",H=180;var J,X=class extends D{read(e){return this.queryPositionState(e)}},Z={getBTCPrice:async()=>{throw new Error("[carry-collateral] a price was requested; collateral attestations sign no price")}},Y={calculateTrustedBalance:async()=>{throw new Error("[carry-collateral] a BTC read was requested; the BTC comes from the verified BalanceConfirmation")}};async function main(e){if(!e||"object"!=typeof e)throw new Error("[carry-collateral] missing args");for(const t of["chain","positionId","validatorWalletAddress","rpcUrl"])if("string"!=typeof e[t]||0===e[t].length)throw new Error(`[carry-collateral] missing "${t}"`);if(!e.carryVault||"object"!=typeof e.carryVault)throw new Error('[carry-collateral] missing "carryVault"');if(!e.balanceConfirmation||"object"!=typeof e.balanceConfirmation)throw new Error('[carry-collateral] missing "balanceConfirmation" (the loans\' signed vault balance, D81)');const t=function(e){const t=f(e),r=q[t];if(!r)throw new Error(`No chain policy registered for "${e}"`);return r}(e.chain),r=function(e,t,r,a,n,i){if(!Number.isInteger(t.chainId)||t.chainId<=0)throw new Error(`[carry] invalid carryVault.chainId: ${t.chainId}`);const o=ethers.utils.getAddress(t.vault),s=ethers.utils.getAddress(r);if(e.pinContractAddresses){if(!a)throw new Error(`[carry] no pinned carry pairing for ${e.chain} (${e.chainId}) \u2014 the vault is not deployed/pinned there; refusing to sign`);if(t.chainId!==a.hyperEvmChainId||o!==ethers.utils.getAddress(a.vault))throw new Error(`[carry] requested domain (${t.chainId}, ${o}) is not the pinned pairing (${a.hyperEvmChainId}, ${a.vault}) for ${e.chain}; refusing to sign`);if(s!==ethers.utils.getAddress(a.signer))throw new Error(`[carry] signer ${s} is not the pinned carry signer ${a.signer}; refusing to sign`)}else{if(t.chainId!==e.chainId)throw new Error(`[carry] carryVault.chainId ${t.chainId} is not the local chain ${e.chainId}: on ${e.chain} (unpinned) an attestation is signed only for a vault on the local chain; refusing to sign`);for(const t of Object.keys(L)){const r=L[Number(t)];if(o===ethers.utils.getAddress(r.vault))throw new Error(`[carry] ${o} is a pinned carry vault (source chain ${t}); refusing to sign for it on ${e.chain}`);if(s===ethers.utils.getAddress(r.signer))throw new Error(`[carry] ${s} is a pinned carry signer (source chain ${t}); refusing to sign with it on ${e.chain}`)}}return{name:n,version:i,chainId:t.chainId,verifyingContract:o}}(t,e.carryVault,e.validatorWalletAddress,(a=t.chainId,L[a]??null),l,u);var a;const{rpcUrl:n,drpcKey:i,addresses:o}=await k(t,{chain:e.chain,rpcUrl:e.rpcUrl,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses,rpcSource:"params-only"});for(const e of["PositionManager","TermManagerModule","LoanOperationsManagerModule","LiquidationManagerModule"])if(!o[e])throw new Error(`[carry-collateral] contractAddresses.${e} is required`);const s=new ethers.providers.JsonRpcProvider(P(n,i));await async function(e,t,r){const a=await e.send("eth_chainId",[]);if("string"!=typeof a||!/^0x[0-9a-fA-F]+$/.test(a))throw new Error(`${r} eth_chainId answered ${JSON.stringify(a)}, not a hex quantity; refusing to sign`);const n=ethers.BigNumber.from(a);if(!n.eq(t.chainId))throw new Error(`${r} the RPC reports chain ${n.toString()}, not ${t.chain} (${t.chainId}); refusing to sign`)}(s,t,"[carry-collateral]");const c=new X({contractAddress:o.PositionManager,termManagerAddress:o.TermManagerModule,loanOpsManagerAddress:o.LoanOperationsManagerModule,liquidationManagerAddress:o.LiquidationManagerModule,chain:t.chain,chainId:m(t.chain),vaultBalance:Y,priceOracle:Z,rpcUrl:n,drpcKey:i}),d=function(e){if("string"!=typeof e)throw new Error("positionId must be a string");const t=e.trim(),r=/^0x/i.test(t)?t.slice(2):t;if(0===r.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(r))throw new Error("positionId must be hexadecimal (bytes32)");if(r.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+r.padStart(64,"0").toLowerCase()}(e.positionId),h=await c.read(d),p=ethers.utils.getAddress(h.borrower),y=function(e){const t=e.toLowerCase();return"0x"===t||/^0xef0100[0-9a-f]{40}$/.test(t)}(await s.getCode(p))?M:U;const g=V(t,e.contractAddresses).AgentDelegationRegistry,w=await async function(e,t,r){const a=e=>({actor:r,actorValidUntil:"0",denied:e});if(!e)return a("NO_REGISTRY");const n=await e.agentOf(r);if(!n.agent||n.agent.toLowerCase()===j)return a("NO_AGENT");const i=ethers.utils.getAddress(n.agent),{ok:o,reason:s}=await e.canCarry(t,i);if(!o){const e=K[Number(s)];if(void 0===e)throw new Error(`[carry] AgentDelegationRegistry.canCarry returned an unknown reason ${s}`);return a(e)}const c=n.validUntil.toString();if(!/^[1-9]\d*$/.test(c))throw new Error(`[carry] registry agent ${i} is allowed to carry but has validUntil ${c}`);return{actor:i,actorValidUntil:c,denied:"NONE"}}(g?new ethers.Contract(g,z,s):void 0,d,p);!function(e,t,r,a){if(r===U&&a.actor===t)throw new Error(`[carry] borrower ${t} of loan ${e} is a contract (Safe) with no active carry agent (${a.denied}); a Safe is attested only through an agent allowed by canCarry`)}(d,p,y,w);const A=new ethers.Contract(o.PositionManager,["function authorizationRegistry() view returns (address)"],s),b=new ethers.Contract(await A.authorizationRegistry(),["function getValidator(bytes4) view returns (tuple(address pkpAddress, uint256 version, bool active))"],s),v=await b.getValidator(ethers.utils.id(W).slice(0,10));if(!v.active)throw new Error("[carry-collateral] the updateBalance validator is not active");const E=F(),C=function(e){const t=e.confirmation;if(!t||"string"!=typeof t.signature||!/^0x[0-9a-fA-F]{130}$/.test(t.signature))throw new Error("[carry] balanceConfirmation.signature is missing or malformed");if(!/^\d+$/.test(String(t.vaultBalance))||!/^\d+$/.test(String(t.btcPrice))||!/^\d+$/.test(String(t.quantumTimestamp)))throw new Error("[carry] balanceConfirmation fields must be unsigned integers");const r=Number(t.quantumTimestamp);if(r>e.nowSeconds+60||e.nowSeconds-r>H)throw new Error(`[carry] balanceConfirmation at ${r} is outside the window at ${e.nowSeconds}`);const a={actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes("balance-confirmation")),positionId:e.positionId,collateralValue:String(t.vaultBalance),btcPrice:String(t.btcPrice),quantumTimestamp:String(t.quantumTimestamp),borrower:ethers.utils.getAddress(e.borrower)},n=ethers.utils._TypedDataEncoder.hash(e.domain,G,a),i=ethers.utils.recoverAddress(n,t.signature);if(i!==ethers.utils.getAddress(e.validator))throw new Error(`[carry] balanceConfirmation signed by ${i}, not the updateBalance validator ${e.validator}`);return BigInt(t.vaultBalance)}({confirmation:e.balanceConfirmation,positionId:d,borrower:p,validator:v.pkpAddress,domain:{name:l,version:u,chainId:m(t.chain),verifyingContract:ethers.utils.getAddress(o.LoanOperationsManagerModule)},nowSeconds:E}),I={actionTag:ethers.utils.keccak256(ethers.utils.toUtf8Bytes(S)),loanId:d,borrower:p,borrowerKind:y,actor:w.actor,actorValidUntil:w.actorValidUntil,btcVaultAddress:h.vaultAddress,btcBalance:C.toString(),quantumTimestamp:E.toString()},{signature:T,signer:B}=await async function(e,t,r,a){const n=await Lit.Actions.getPrivateKey({pkpId:e}),i="string"==typeof n?n.startsWith("0x")?n:`0x${n}`:String(n),o=new ethers.Wallet(i);if(o.address!==ethers.utils.getAddress(e))throw new Error(`[carry] key for ${e} derives ${o.address}; refusing to sign`);return{signature:await o._signTypedData(t,r,a),signer:o.address}}(e.validatorWalletAddress,r,R,I);return{attestation:I,signature:T,signer:B,domain:r}}return J=n,((n,i,o,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of r(i))a.call(n,c)||c===o||e(n,c,{get:()=>i[c],enumerable:!(s=t(i,c))||s.enumerable});return n})(e({},"__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
|
+
d8ed063ef94a2545db53f3f704a6da3d076f51b871e4db007d4388964acffdc7
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "carry-collateral-attestation",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 55210,
|
|
4
|
+
"minifiedSize": 26364,
|
|
5
|
+
"compressionRatio": 0.5224778119905814,
|
|
6
|
+
"hash": "d8ed063ef94a2545db53f3f704a6da3d076f51b871e4db007d4388964acffdc7",
|
|
7
|
+
"buildTime": 1794778215482,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _LIT_ACTION_=(()=>{var e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,t=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,i={};((r,t)=>{for(var a in t)e(r,a,{get:t[a],enumerable:!0})})(i,{main:()=>main});var n=1000000000000000000n,o=1000000000000n,s=100000000000000n,c=60,d=8e3,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"}};function l(e){switch(e){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${e})`}}var p="DiamondHands.Protocol",h="1",y=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(y||{}),m={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},g=["infura.io","drpc.org","drpc.live"],f={ethereum:1,sepolia:11155111,hardhat:1337};function w(e){const r=e.toLowerCase().trim();if("sepolia"===r)return"sepolia";if("ethereum"===r||"mainnet"===r)return"ethereum";if("hardhat"===r)return"hardhat";throw new Error(`Unsupported EVM chain: "${e}". Supported chains: ${Object.values(y).join(", ")}`)}function P(e,r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`calculateLiquidationThreshold: ${e} must be a non-negative integer, got ${String(r)}`)}var v=["drpc.org","drpc.live"],E="Drpc-Key",C=/^[A-Za-z0-9_-]{16,128}$/;function b(e){return v.some((r=>e===r||e.endsWith(`.${r}`)))}function A(e,r){if("string"!=typeof e||!C.test(e))throw new Error(`Invalid ${r}: expected 16-128 characters of [A-Za-z0-9_-]`)}function T(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 M(e,r){if(void 0===r)return;A(r,'"drpcKey"');const t=new URL(e);if(!b(t.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${t.hostname}" (expected ${v.join(" or ")})`);if(T(t),t.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return r}async function I(e,r){if(void 0!==r)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:e})}function S(e,r,t){const a={url:e},i=M(e,r);if(void 0!==i)a.headers={[E]:i};else{const r=new URL(e),t=r.searchParams.getAll("dkey");if(t.length>1)throw new Error(`rpcUrl carries ${t.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===t.length&&!b(r.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${r.hostname}" \u2014 a dRPC key is only sent to ${v.join(" or ")}`);if(1===t.length){const e=t[0];A(e,"dRPC key in rpcUrl (?dkey=)"),T(r),r.searchParams.delete("dkey"),a.url=r.toString(),a.headers={[E]:e}}}return void 0!==t&&(a.timeout=t),a}var D=class{constructor(e){this.termManagerAddress=e.termManagerAddress,this.loanOpsManagerAddress=e.loanOpsManagerAddress,this.liquidationManagerAddress=e.liquidationManagerAddress,this.chain=e.chain,this.chainId=e.chainId,this.rpcUrl=e.rpcUrl,this.drpcKey=e.drpcKey}async getLiquidationThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(S(e,this.drpcKey,d),{name:"any",chainId:this.chainId}),t=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],a=new ethers.Contract(this.loanOpsManagerAddress,t,r),i=await a.liquidationThreshold();return Number(i.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",e.message),new Error(`Failed to fetch liquidation threshold: ${e.message}`)}}async getTermFees(e){try{let r;r=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.termManagerAddress,a,t),n=await i.getTermFees(e);return{originationFeeBps:Number(n.originationFee?.toString?.()??n[0]?.toString?.()??n[0]),extensionFeeBps:Number(n.extensionFee?.toString?.()??n[1]?.toString?.()??n[1])}}catch(e){throw console.error("[ProtocolParameters] Error fetching term fees:",e.message),new Error(`Failed to fetch term fees: ${e.message}`)}}async getAuthorizedSpendsHash(e){try{const r=this.rpcUrl||await I(this.chain,this.drpcKey),t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`,i=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],t);return await i.getAuthorizedSpendsHash(a)}catch(e){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",e.message),new Error(`Failed to fetch authorized spends hash: ${e.message}`)}}async readLiquidationManagerUint(e,r){try{let r;r=this.rpcUrl?this.rpcUrl:await I(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=[{inputs:[],name:e,outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],i=new ethers.Contract(this.liquidationManagerAddress,a,t),n=await i[e]();return Number(n.toString())}catch(e){throw console.error(`[ProtocolParameters] Error fetching ${r}:`,e.message),new Error(`Failed to fetch ${r}: ${e.message}`)}}async getMaxEscalatedThreshold(){return this.readLiquidationManagerUint("maxEscalatedThreshold","max escalated threshold")}async getExpiryLiquidationIncrementBps(){return this.readLiquidationManagerUint("expiryLiquidationIncrementBps","expiry liquidation increment")}async getExpiredLoanGracePeriodDays(){return this.readLiquidationManagerUint("expiredLoanGracePeriodDays","expired loan grace period")}};function B(e,r){try{const t=JSON.parse(e);if("object"==typeof t&&null!==t){if("sepolia"===r.toLowerCase())return t.regtest||t.testnet||void 0;const e=function(e){return m[e]}(r);return"regtest"===e?t.regtest||t.testnet||void 0:"testnet"===e?t.testnet||t.regtest||void 0:t.mainnet}}catch(e){}return e}var R=class{constructor(e){if(!Number.isInteger(e.chainId)||e.chainId<=0)throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(e.chainId)}`);this.config=e}async getVaultSnapshot(e){const r=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${r.vaultAddress}"`);const[t,a]=await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,r.vaultAddress),this.config.priceOracle.getBTCPrice()]),i=(o={termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId,rpcUrl:this.config.rpcUrl,drpcKey:this.config.drpcKey},new D(o));var o;const s=this.config.termOverride??r.selectedTerm,[c,d,u,l,p]=await Promise.all([i.getLiquidationThreshold(),i.getMaxEscalatedThreshold(),i.getExpiryLiquidationIncrementBps(),i.getExpiredLoanGracePeriodDays(),i.getTermFees(s)]),h=function(e,r){if(0===e)return{termDurationDays:0,termLengthDays:30*r,isExpired:!1,daysUntilExpiry:30*r,daysIntoGracePeriod:0};const t=30*r,a=Math.floor(Date.now()/1e3)-e,i=Math.floor(a/86400);return{termDurationDays:i,termLengthDays:t,isExpired:i>t,daysUntilExpiry:Math.max(0,t-i),daysIntoGracePeriod:Math.max(0,i-t)}}(r.termStartTimestamp,r.selectedTerm),y=function(e,r,t,a){if(!e)return t;if(P("daysSinceExpiry",r),P("dailyIncrementBps",a.dailyIncrementBps),P("gracePeriodDays",a.gracePeriodDays),P("maxEscalatedThresholdBps",a.maxEscalatedThresholdBps),r<=a.gracePeriodDays)return 11e3;const i=r-a.gracePeriodDays;if(i>=365)return a.maxEscalatedThresholdBps;const n=1e4+a.dailyIncrementBps;let o=11e3;for(let e=0;e<i;e++)if(o=Math.floor(o*n/1e4),o>=a.maxEscalatedThresholdBps)return a.maxEscalatedThresholdBps;return o}(h.isExpired,h.daysIntoGracePeriod,c,{dailyIncrementBps:u,gracePeriodDays:l,maxEscalatedThresholdBps:d}),m=function(e,r,t){const a=e*r/10000000000000000n;return 0n===t?{collateralValueUsd:a,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:a,collateralRatioBps:Number(a*n*10000n/t)}}(t.availableBalance,a,r.ucdDebt),g=m.collateralRatioBps<y,f=m.collateralRatioBps-y;return{positionId:r.positionId,pkpId:r.pkpId,borrower:r.borrower,vaultAddress:r.vaultAddress,ucdDebt:r.ucdDebt,termStartTimestamp:r.termStartTimestamp,selectedTerm:r.selectedTerm,status:r.status,expiryAt:r.expiryAt,previousExpiryAt:r.previousExpiryAt,totalTerm:r.totalTerm,lastRenewedAt:r.lastRenewedAt,totalBTCSats:t.totalBalance,totalUTXOs:t.totalUTXOs,authorizedSpendsSats:t.authorizedBalance,authorizedSpendsHash:t.authorizedSpendsHash,availableBTCSats:t.availableBalance,availableUTXOs:t.availableUTXOs,btcPriceUsd:a,collateralValueUsd:m.collateralValueUsd,collateralRatioBps:m.collateralRatioBps,termDurationDays:h.termDurationDays,termLengthDays:h.termLengthDays,isExpired:h.isExpired,daysUntilExpiry:h.daysUntilExpiry,daysIntoGracePeriod:h.daysIntoGracePeriod,currentLiquidationThreshold:y,isLiquidatable:g,marginToLiquidationBps:f,liquidationThresholdBps:c,originationFeeBps:p.originationFeeBps,extensionFeeBps:p.extensionFeeBps,timestamp:Date.now()}}async queryPositionState(e){const r=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`;let t;t=this.config.rpcUrl?this.config.rpcUrl:await I(this.config.chain,this.config.drpcKey);const a=new ethers.providers.StaticJsonRpcProvider(S(t,this.config.drpcKey,d),this.config.chainId),i=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],a),n=await i.core(),o=new ethers.Contract(n,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],a),s=await o.getPositionDetails(r),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",r),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${r}`);const u=Number(s.expiryAt),l=Number(s.selectedTerm),p=Number(s.totalTerm),h=Number(s.previousExpiryAt),y=Number(s.lastRenewedAt),m=(f=l,0===(g=u)?0:g-30*f*86400);var g,f;const P=B(s.vaultAddress,w(this.config.chain));if("string"!=typeof P||0===P.length)throw new Error(`Position ${r} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:P,ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:h,totalTerm:p,lastRenewedAt:y}}async isLiquidatable(e){return(await this.getVaultSnapshot(e)).isLiquidatable}async getCollateralRatio(e){return(await this.getVaultSnapshot(e)).collateralRatioBps}async getAvailableBalance(e){return(await this.getVaultSnapshot(e)).availableBTCSats}async hasSufficientCollateral(e,r,t){const a=await this.getVaultSnapshot(e);return function(e,r,t,a){const i=r+t;return 0n===i||Number(e*n*10000n/i)>=a}(a.collateralValueUsd,a.ucdDebt,r,t)}},$=class e{requiredCount(){return this.devSingleProvider?1:e.REQUIRED_PROVIDER_COUNT}constructor(r,t,a,i){if(this.devSingleProvider=!0===i?.devSingleProvider,t&&Array.isArray(t))this.sources=t;else{if(!Array.isArray(r))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${e.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+e.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(r)}this.sources.sort(((e,r)=>e.priority-r.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(r){if(r.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${r.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`));const t=[],a=new Set;let i=1;for(const n of r){if(!n||"string"!=typeof n.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const r=n.name.toLowerCase();if(!e.ACTIVE_PROVIDER_NAMES.includes(r))throw new Error(`Unsupported price provider "${n.name}". Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(a.has(r))throw new Error(`Duplicate price provider "${r}" \u2014 the oracle requires ${e.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${e.REQUIRED_PROVIDER_COUNT} different provider names from: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(a.add(r),r){case"cryptocompare":if(!n.apiKey)throw new Error("CryptoCompare provider requires an apiKey");t.push(this.createCryptoCompareSource(n.apiKey,i++));break;case"coinmarketcap":if(!n.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");t.push(this.createCoinMarketCapSource(n.apiKey,i++));break;case"coingecko":if(!n.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");t.push(this.createCoinGeckoSource(n.apiKey,i++));break;default:throw new Error(`Unhandled provider: ${r}`)}}return t}createCryptoCompareSource(e,r){return{name:"CryptoCompare",fetchPrice:async()=>{const r=new URL("https://min-api.cryptocompare.com/data/price");r.searchParams.set("fsym","BTC"),r.searchParams.set("tsyms","USDT"),r.searchParams.set("api_key",e);const t=await(async e=>{const r=new AbortController,t=setTimeout((()=>r.abort()),5e3);try{const a=await fetch(e,{signal:r.signal,headers:{Accept:"application/json"}});if(clearTimeout(t),!a.ok)throw new Error(`CryptoCompare HTTP ${a.status} ${a.statusText}`);return await a.json()}catch(e){if(clearTimeout(t),"AbortError"===e.name)throw new Error("Request timeout after 5000ms");throw e}})(r.toString()),a=Number(t?.USDT);if(!Number.isFinite(a)||a<=0)throw new Error("Invalid CryptoCompare price payload");return a},priority:r}}createFetchJson(e){return async(r,t)=>{const a=new AbortController,i=setTimeout((()=>a.abort()),5e3);try{const i=await fetch(r,{headers:{Accept:"application/json",...t||{}},signal:a.signal});if(!i.ok)throw new Error(`${e} HTTP ${i.status} ${i.statusText}`);return await i.json()}finally{clearTimeout(i)}}}createCoinGeckoSource(e,r){if(!e)throw new Error("createCoinGeckoSource requires an apiKey");const t=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const r=e.startsWith("pro:"),a=r?e.slice(4):e,i=r?{"x-cg-pro-api-key":a}:{"x-cg-demo-api-key":a},n=new URL("https://api.coingecko.com/api/v3/simple/price");n.searchParams.set("ids","bitcoin"),n.searchParams.set("vs_currencies","usd");const o=await t(n.toString(),i),s=Number(o?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:r}}createCoinMarketCapSource(e,r){const t=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const r=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");r.searchParams.set("symbol","BTC"),r.searchParams.set("convert","USDT");const a=await t(r.toString(),{"X-CMC_PRO_API_KEY":e}),i=Number(a?.data?.BTC?.[0]?.quote?.USDT?.price??a?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(i)||i<=0)throw new Error("Invalid CoinMarketCap price payload");return i},priority:r}}async getBTCPrice(){const e=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const r=new Promise(((e,r)=>{setTimeout((()=>{r(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),t=Promise.all(this.sources.map((async e=>{const r=Date.now();try{const t=await e.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-r}ms] ${e.name}: $${t.toLocaleString()}`),t}catch(r){const t=r instanceof Error?r.message:String(r);throw console.log(`[Price Oracle] \u274c ${e.name}: ${t}`),new Error(`${e.name} price fetch failed: ${t}`)}}))),a=[...await Promise.race([t,r])].sort(((e,r)=>e-r));let i;if(this.devSingleProvider)i=a[0];else{i=a[1];if((a[2]-a[0])/a[0]>.01){const e=this.sources.map((e=>e.name)).join(", "),r=a.map((e=>`$${e.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${e}]. Prices: [${r}]`)}}const n=Math.round(100*i),o=1000000n*BigInt(n),s=Date.now()-e;return console.log(`[Price Oracle] Median price: $${i.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${o}`),o}};$.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],$.REQUIRED_PROVIDER_COUNT=3;var x=$;async function U(e,r,t,a){try{const e=await Lit.Actions.Decrypt({pkpId:t,ciphertext:a});return"string"==typeof e?e:String(e??"")}catch(t){const a=t instanceof Error?t.message:String(t);throw new Error(`Failed to decrypt ${r} for provider ${e}: ${a}`)}}function k(){const e=Math.floor(Date.now()/1e3);return r=e,Math.floor(r/c)*c;var r}var q={hardhat:{chain:"hardhat",chainId:f.hardhat,bitcoinNetwork:m.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:m.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:m.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var F=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function L(e,r){const t={...r??{}};if(!e.pinContractAddresses)return t;const a=(i=e.chainId,u[i]??null);var i;if(!a)throw new Error(`No pinned contract-address set for chainId ${e.chainId} (${e.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const r of F){const i=a[r];if(!i)throw new Error(`Pinned address set for ${e.chain} is missing required "${r}"; refusing to fall through to a caller-supplied value`);const n=t[r];if("string"==typeof n&&n.length>0&&n.toLowerCase()!==i.toLowerCase())throw new Error(`Caller-supplied "${r}" (${n}) contradicts the pinned ${e.chain} address (${i}); refusing to sign`);t[r]=i}return t}async function O(e,r){const t=r.rpcUrl,a=r.rpcSource??"params-or-lit-node";let i;if("string"==typeof t&&t.length>0)!function(e,r){if(e.allowArbitraryEvmRpc)return;if(!r||"string"!=typeof r)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let t;try{t=new URL(r).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!g.some((e=>t===e||t.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${t}" is not in the approved list: ${g.join(", ")}`)}(e,t),i=t;else{if("params-only"===a)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(i=await I(r.chain,r.drpcKey),"string"!=typeof i||0===i.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${r.chain}"`)}return{rpcUrl:i,drpcKey:M(i,r.drpcKey),addresses:L(e,r.contractAddresses)}}var N="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",_="unreadable",K={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]},V=[];function j(e){return{positionManagerPaused:e.positionManagerPaused,positionManagerLiquidationsPaused:e.positionManagerLiquidationsPaused,positionManagerCorePaused:e.positionManagerCorePaused,loanOperationsPaused:e.loanOperationsPaused,collateralManagerPaused:e.collateralManagerPaused,liquidationManagerPaused:e.liquidationManagerPaused,circuitBreakerPaused:e.circuitBreakerPaused,ucdControllerPaused:e.ucdControllerPaused,ucdTokenPaused:e.ucdTokenPaused,simplePsmPaused:e.simplePsmPaused}}var G=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),z=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),J=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function H(e,r,t){return e.call({to:r,data:t})}async function X(e,r){const t=new ethers.utils.Interface([N]).encodeFunctionData("getProtocolPauseStatus",[]);let a;try{return function(e){const r=new ethers.utils.Interface([N]).decodeFunctionResult("getProtocolPauseStatus",e)[0];return Array.isArray(r)?j({positionManagerPaused:r[0],positionManagerLiquidationsPaused:r[1],positionManagerCorePaused:r[2],loanOperationsPaused:r[3],collateralManagerPaused:r[4],liquidationManagerPaused:r[5],circuitBreakerPaused:r[6],ucdControllerPaused:r[7],ucdTokenPaused:r[8],simplePsmPaused:r[9]}):j(r)}(await e.call({to:r,data:t}))}catch(e){a=e}try{return await async function(e,r){const t=await H(e,r,G.encodeFunctionData("views",[])),[a]=G.decodeFunctionResult("views",t),[i,n,o,s,c,d,u,l]=await Promise.all([H(e,r,G.encodeFunctionData("paused",[])),H(e,r,G.encodeFunctionData("liquidationPaused",[])),H(e,r,G.encodeFunctionData("simplePsm",[])),H(e,a,z.encodeFunctionData("core",[])),H(e,a,z.encodeFunctionData("loanOps",[])),H(e,a,z.encodeFunctionData("collateralManager",[])),H(e,a,z.encodeFunctionData("liquidationManager",[])),H(e,a,z.encodeFunctionData("circuitBreaker",[]))]),p=G.decodeFunctionResult("paused",i)[0],h=G.decodeFunctionResult("liquidationPaused",n)[0],y=G.decodeFunctionResult("simplePsm",o)[0],m=z.decodeFunctionResult("core",s)[0],g=z.decodeFunctionResult("loanOps",c)[0],f=z.decodeFunctionResult("collateralManager",d)[0],w=z.decodeFunctionResult("liquidationManager",u)[0],P=z.decodeFunctionResult("circuitBreaker",l)[0],v=await H(e,g,J.encodeFunctionData("getUcdController",[])),E=await H(e,g,J.encodeFunctionData("ucdToken",[])),C=J.decodeFunctionResult("getUcdController",v)[0],b=J.decodeFunctionResult("ucdToken",E)[0],A=async(r,t)=>{if(!t||t===ethers.constants.AddressZero)return!(V.indexOf(r)>=0)&&_;try{const r=await H(e,t,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch(e){return console.log(`[protocol-pause] ${r} unreadable at ${t}: ${e instanceof Error?e.message:String(e)}`),_}},[T,M,I,S,D,B,R,$]=await Promise.all([A("positionManagerCorePaused",m),A("loanOperationsPaused",g),A("collateralManagerPaused",f),A("liquidationManagerPaused",w),A("circuitBreakerPaused",P),A("ucdControllerPaused",C),A("ucdTokenPaused",b),A("simplePsmPaused",y)]);return j({positionManagerPaused:p,positionManagerLiquidationsPaused:h,positionManagerCorePaused:T,loanOperationsPaused:M,collateralManagerPaused:I,liquidationManagerPaused:S,circuitBreakerPaused:D,ucdControllerPaused:B,ucdTokenPaused:R,simplePsmPaused:$})}(e,r)}catch(e){const r=a instanceof Error?a.message:String(a),t=e instanceof Error?e.message:String(e);throw new Error(`getProtocolPauseStatus failed (aggregate: ${r}; decomposed: ${t})`)}}var Q={PayerPayment:[{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"paymentAmount",type:"uint256"},{name:"borrower",type:"address"},{name:"payer",type:"address"}]},Z=[1,2,3,4];var Y,ee=class extends R{read(e){return this.queryPositionState(e)}},re={getBTCPrice:async()=>{throw new Error("[carry-repay] the position reader requested a price; the price is read once, after the refusals")}},te={calculateTrustedBalance:async()=>{throw new Error("[carry-repay] the position reader requested a BTC read; this action reads none")}};async function main(e){if(!e||"object"!=typeof e)throw new Error("[carry-repay] missing args");for(const r of["chain","positionId","receiver","validatorWalletAddress","rpcUrl"])if("string"!=typeof e[r]||0===e[r].length)throw new Error(`[carry-repay] missing "${r}"`);if(!Array.isArray(e.priceProviders))throw new Error('[carry-repay] missing "priceProviders"');for(const r of["amount","paymentAmount"])if(r in e)throw new Error(`[carry-repay] "${r}" is not an input; the amount is derived as min(credit, debt)`);const r=function(e){const r=w(e),t=q[r];if(!t)throw new Error(`No chain policy registered for "${e}"`);return t}(e.chain),t=!0===e.devPriceMode;if(t&&!r.allowDevSinglePriceProvider)throw new Error(`[carry-repay] devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${r.chain}`);const{rpcUrl:a,drpcKey:i,addresses:n}=await O(r,{chain:e.chain,rpcUrl:e.rpcUrl,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses,rpcSource:"params-only"});for(const e of["PositionManager","TermManagerModule","LoanOperationsManagerModule","LiquidationManagerModule"])if(!n[e])throw new Error(`[carry-repay] contractAddresses.${e} is required`);const c=(d=r.chain,f[d]);var d;const u=ethers.utils.getAddress(e.receiver),y=function(e){if("string"!=typeof e)throw new Error("positionId must be a string");const r=e.trim(),t=/^0x/i.test(r)?r.slice(2):r;if(0===t.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("positionId must be hexadecimal (bytes32)");if(t.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+t.padStart(64,"0").toLowerCase()}(e.positionId),m=new ethers.providers.StaticJsonRpcProvider(S(a,i),{chainId:c,name:r.chain});!function(e,r){const t=K[e],a=[],i=[];for(const e of t)r[e]===_?i.push(e):r[e]&&a.push(e);if(a.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:e,paused:a,status:r}));if(i.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSE_UNREADABLE",operation:e,unreadable:i,status:r}))}("processPayment",await X(m,n.PositionManager));const g=new ethers.Contract(n.PositionManager,["function repaymentPayer() view returns (address)","function views() view returns (address)"],m);!function(e,r){const t=ethers.utils.getAddress(e),a=ethers.utils.getAddress(r);if(t!==a)throw new Error(`[carry-repay] receiver ${a} is not PositionManager.repaymentPayer ${t}; refusing to sign`)}(await g.repaymentPayer(),u);const P=ethers.utils.getAddress(await g.views());if(P===ethers.constants.AddressZero)throw new Error("[carry-repay] PositionManager.views() is unset");const v=new ee({contractAddress:n.PositionManager,termManagerAddress:n.TermManagerModule,loanOpsManagerAddress:n.LoanOperationsManagerModule,liquidationManagerAddress:n.LiquidationManagerModule,chain:r.chain,chainId:c,vaultBalance:te,priceOracle:re,rpcUrl:a,drpcKey:i}),E=await v.read(y),C=ethers.utils.getAddress(E.borrower),b=new ethers.Contract(u,["function credits(bytes32) view returns (uint256)"],m),A=BigInt((await b.credits(y)).toString()),T=function(e){if(!Z.includes(e.status))throw new Error(`[carry-repay] position ${e.positionId} is ${l(e.status)}; a payment needs ${Z.map((e=>l(e))).join(", ")}`);if(e.debt<=0n)throw new Error(`[carry-repay] position ${e.positionId} has no debt; nothing to repay`);if(e.credit<=0n)throw new Error(`[carry-repay] the receiver holds no credit for position ${e.positionId}; nothing to repay with`);return e.credit<e.debt?e.credit:e.debt}({positionId:y,status:E.status,debt:E.ucdDebt,credit:A}),M=new x(await async function(e){if(!e)return e;const r=[];for(const a of e){if(!a?.name||"string"!=typeof a.name)throw new Error("Each price provider must include a valid name");let e,i;if(a.pkpId&&"string"==typeof a.pkpId){const r=(t=a.pkpId).startsWith("0x")||t.startsWith("0X")?t:`0x${t}`;a.apiKey&&(e=await U(a.name,"apiKey",r,a.apiKey)),a.apiSecret&&(i=await U(a.name,"apiSecret",r,a.apiSecret))}else e=a.apiKey,i=a.apiSecret;r.push({name:a.name,apiKey:e,apiSecret:i})}var t;return r}(e.priceProviders),void 0,void 0,{devSingleProvider:t}),I=await M.getBTCPrice();if(I<o||I>s)throw new Error(`[carry-repay] BTC price ${I} is outside the acceptable range (${o} - ${s})`);const D=k(),B={name:p,version:h,chainId:c,verifyingContract:P},R={positionId:($={positionId:y,quantumTimestamp:D,btcPrice:I,amount:T,borrower:C,payer:u}).positionId,quantumTimestamp:$.quantumTimestamp.toString(),btcPrice:$.btcPrice.toString(),paymentAmount:$.amount.toString(),borrower:ethers.utils.getAddress($.borrower),payer:ethers.utils.getAddress($.payer)};var $;const F=function(e,r){return ethers.utils._TypedDataEncoder.hash(e,Q,r)}(B,R),{signature:L}=await async function(e,r,t,a){const i=await Lit.Actions.getPrivateKey({pkpId:e}),n="string"==typeof i?i.startsWith("0x")?i:`0x${i}`:String(i),o=new ethers.Wallet(n);if(o.address!==ethers.utils.getAddress(e))throw new Error(`[carry] key for ${e} derives ${o.address}; refusing to sign`);return{signature:await o._signTypedData(r,t,a),signer:o.address}}(e.validatorWalletAddress,B,Q,R);return{positionId:y,amount:R.paymentAmount,quantumTimestamp:D,btcPrice:R.btcPrice,borrower:C,payer:u,signature:L,digest:F}}return Y=i,((i,n,o,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of t(n))a.call(i,c)||c===o||e(i,c,{get:()=>n[c],enumerable:!(s=r(n,c))||s.enumerable});return i})(e({},"__esModule",{value:!0}),Y)})();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,r=Object.getOwnPropertyDescriptor,t=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,n={};((r,t)=>{for(var a in t)e(r,a,{get:t[a],enumerable:!0})})(n,{main:()=>main});var i=1000000000000000000n,o=1000000000000n,s=100000000000000n,c=60,d=8e3,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"}};function l(e){switch(e){case 0:return"PENDING_DEPOSIT";case 1:return"PENDING_MINT";case 2:return"ACTIVE";case 3:return"EXPIRED";case 4:return"LIQUIDATABLE";case 5:return"LIQUIDATED";case 6:return"REPAID";case 7:return"CLOSED";default:return`UNKNOWN(${e})`}}var p="DiamondHands.Protocol",h="1",y=(e=>(e.SEPOLIA="sepolia",e.ETHEREUM="ethereum",e.HARDHAT="hardhat",e))(y||{}),m={sepolia:"regtest",ethereum:"mainnet",hardhat:"regtest"},g=["infura.io","drpc.org","drpc.live"],f={ethereum:1,sepolia:11155111,hardhat:1337};function w(e){const r=e.toLowerCase().trim();if("sepolia"===r)return"sepolia";if("ethereum"===r||"mainnet"===r)return"ethereum";if("hardhat"===r)return"hardhat";throw new Error(`Unsupported EVM chain: "${e}". Supported chains: ${Object.values(y).join(", ")}`)}function P(e,r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`calculateLiquidationThreshold: ${e} must be a non-negative integer, got ${String(r)}`)}var v=["drpc.org","drpc.live"],E="Drpc-Key",C=/^[A-Za-z0-9_-]{16,128}$/;function b(e){return v.some((r=>e===r||e.endsWith(`.${r}`)))}function A(e,r){if("string"!=typeof e||!C.test(e))throw new Error(`Invalid ${r}: expected 16-128 characters of [A-Za-z0-9_-]`)}function T(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 I(e,r){if(void 0===r)return;A(r,'"drpcKey"');const t=new URL(e);if(!b(t.hostname))throw new Error(`"drpcKey" is only sent to dRPC, but the RPC host is "${t.hostname}" (expected ${v.join(" or ")})`);if(T(t),t.searchParams.has("dkey"))throw new Error('"drpcKey" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one');return r}async function M(e,r){if(void 0!==r)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:e})}function S(e,r,t){const a={url:e},n=I(e,r);if(void 0!==n)a.headers={[E]:n};else{const r=new URL(e),t=r.searchParams.getAll("dkey");if(t.length>1)throw new Error(`rpcUrl carries ${t.length} "dkey" parameters \u2014 send exactly one dRPC key`);if(1===t.length&&!b(r.hostname))throw new Error(`rpcUrl carries a dRPC key (?dkey=) but the RPC host is "${r.hostname}" \u2014 a dRPC key is only sent to ${v.join(" or ")}`);if(1===t.length){const e=t[0];A(e,"dRPC key in rpcUrl (?dkey=)"),T(r),r.searchParams.delete("dkey"),a.url=r.toString(),a.headers={[E]:e}}}return void 0!==t&&(a.timeout=t),a}var D=class{constructor(e){this.termManagerAddress=e.termManagerAddress,this.loanOpsManagerAddress=e.loanOpsManagerAddress,this.liquidationManagerAddress=e.liquidationManagerAddress,this.chain=e.chain,this.chainId=e.chainId,this.rpcUrl=e.rpcUrl,this.drpcKey=e.drpcKey}async getLiquidationThreshold(){try{let e;e=this.rpcUrl?this.rpcUrl:await M(this.chain,this.drpcKey);const r=new ethers.providers.StaticJsonRpcProvider(S(e,this.drpcKey,d),{name:"any",chainId:this.chainId}),t=[{inputs:[],name:"liquidationThreshold",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],a=new ethers.Contract(this.loanOpsManagerAddress,t,r),n=await a.liquidationThreshold();return Number(n.toString())}catch(e){throw console.error("[ProtocolParameters] Error fetching liquidation threshold:",e.message),new Error(`Failed to fetch liquidation threshold: ${e.message}`)}}async getTermFees(e){try{let r;r=this.rpcUrl?this.rpcUrl:await M(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=[{inputs:[{internalType:"uint256",name:"_termMonths",type:"uint256"}],name:"getTermFees",outputs:[{internalType:"uint88",name:"originationFee",type:"uint88"},{internalType:"uint88",name:"extensionFee",type:"uint88"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.termManagerAddress,a,t),i=await n.getTermFees(e);return{originationFeeBps:Number(i.originationFee?.toString?.()??i[0]?.toString?.()??i[0]),extensionFeeBps:Number(i.extensionFee?.toString?.()??i[1]?.toString?.()??i[1])}}catch(e){throw console.error("[ProtocolParameters] Error fetching term fees:",e.message),new Error(`Failed to fetch term fees: ${e.message}`)}}async getAuthorizedSpendsHash(e){try{const r=this.rpcUrl||await M(this.chain,this.drpcKey),t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`,n=new ethers.Contract(this.loanOpsManagerAddress,[{inputs:[{name:"positionId",type:"bytes32"}],name:"getAuthorizedSpendsHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}],t);return await n.getAuthorizedSpendsHash(a)}catch(e){throw console.error("[ProtocolParameters] Error fetching authorized spends hash:",e.message),new Error(`Failed to fetch authorized spends hash: ${e.message}`)}}async readLiquidationManagerUint(e,r){try{let r;r=this.rpcUrl?this.rpcUrl:await M(this.chain,this.drpcKey);const t=new ethers.providers.StaticJsonRpcProvider(S(r,this.drpcKey,d),{name:"any",chainId:this.chainId}),a=[{inputs:[],name:e,outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],n=new ethers.Contract(this.liquidationManagerAddress,a,t),i=await n[e]();return Number(i.toString())}catch(e){throw console.error(`[ProtocolParameters] Error fetching ${r}:`,e.message),new Error(`Failed to fetch ${r}: ${e.message}`)}}async getMaxEscalatedThreshold(){return this.readLiquidationManagerUint("maxEscalatedThreshold","max escalated threshold")}async getExpiryLiquidationIncrementBps(){return this.readLiquidationManagerUint("expiryLiquidationIncrementBps","expiry liquidation increment")}async getExpiredLoanGracePeriodDays(){return this.readLiquidationManagerUint("expiredLoanGracePeriodDays","expired loan grace period")}};function B(e,r){try{const t=JSON.parse(e);if("object"==typeof t&&null!==t){if("sepolia"===r.toLowerCase())return t.regtest||t.testnet||void 0;const e=function(e){return m[e]}(r);return"regtest"===e?t.regtest||t.testnet||void 0:"testnet"===e?t.testnet||t.regtest||void 0:t.mainnet}}catch(e){}return e}var $=class{constructor(e){if(!Number.isInteger(e.chainId)||e.chainId<=0)throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(e.chainId)}`);this.config=e}async getVaultSnapshot(e){const r=await this.queryPositionState(e);console.log(`[Vault Snapshot] Raw vault address from contract: "${r.vaultAddress}"`);const[t,a]=await Promise.all([this.config.vaultBalance.calculateTrustedBalance(e,r.vaultAddress),this.config.priceOracle.getBTCPrice()]),n=(o={termManagerAddress:this.config.termManagerAddress,loanOpsManagerAddress:this.config.loanOpsManagerAddress,liquidationManagerAddress:this.config.liquidationManagerAddress,chain:this.config.chain,chainId:this.config.chainId,rpcUrl:this.config.rpcUrl,drpcKey:this.config.drpcKey},new D(o));var o;const s=this.config.termOverride??r.selectedTerm,[c,d,u,l,p]=await Promise.all([n.getLiquidationThreshold(),n.getMaxEscalatedThreshold(),n.getExpiryLiquidationIncrementBps(),n.getExpiredLoanGracePeriodDays(),n.getTermFees(s)]),h=function(e,r){if(0===e)return{termDurationDays:0,termLengthDays:30*r,isExpired:!1,daysUntilExpiry:30*r,daysIntoGracePeriod:0};const t=30*r,a=Math.floor(Date.now()/1e3)-e,n=Math.floor(a/86400);return{termDurationDays:n,termLengthDays:t,isExpired:n>t,daysUntilExpiry:Math.max(0,t-n),daysIntoGracePeriod:Math.max(0,n-t)}}(r.termStartTimestamp,r.selectedTerm),y=function(e,r,t,a){if(!e)return t;if(P("daysSinceExpiry",r),P("dailyIncrementBps",a.dailyIncrementBps),P("gracePeriodDays",a.gracePeriodDays),P("maxEscalatedThresholdBps",a.maxEscalatedThresholdBps),r<=a.gracePeriodDays)return 11e3;const n=r-a.gracePeriodDays;if(n>=365)return a.maxEscalatedThresholdBps;const i=1e4+a.dailyIncrementBps;let o=11e3;for(let e=0;e<n;e++)if(o=Math.floor(o*i/1e4),o>=a.maxEscalatedThresholdBps)return a.maxEscalatedThresholdBps;return o}(h.isExpired,h.daysIntoGracePeriod,c,{dailyIncrementBps:u,gracePeriodDays:l,maxEscalatedThresholdBps:d}),m=function(e,r,t){const a=e*r/10000000000000000n;return 0n===t?{collateralValueUsd:a,collateralRatioBps:Number.MAX_SAFE_INTEGER}:{collateralValueUsd:a,collateralRatioBps:Number(a*i*10000n/t)}}(t.availableBalance,a,r.ucdDebt),g=m.collateralRatioBps<y,f=m.collateralRatioBps-y;return{positionId:r.positionId,pkpId:r.pkpId,borrower:r.borrower,vaultAddress:r.vaultAddress,ucdDebt:r.ucdDebt,termStartTimestamp:r.termStartTimestamp,selectedTerm:r.selectedTerm,status:r.status,expiryAt:r.expiryAt,previousExpiryAt:r.previousExpiryAt,totalTerm:r.totalTerm,lastRenewedAt:r.lastRenewedAt,totalBTCSats:t.totalBalance,totalUTXOs:t.totalUTXOs,authorizedSpendsSats:t.authorizedBalance,authorizedSpendsHash:t.authorizedSpendsHash,availableBTCSats:t.availableBalance,availableUTXOs:t.availableUTXOs,btcPriceUsd:a,collateralValueUsd:m.collateralValueUsd,collateralRatioBps:m.collateralRatioBps,termDurationDays:h.termDurationDays,termLengthDays:h.termLengthDays,isExpired:h.isExpired,daysUntilExpiry:h.daysUntilExpiry,daysIntoGracePeriod:h.daysIntoGracePeriod,currentLiquidationThreshold:y,isLiquidatable:g,marginToLiquidationBps:f,liquidationThresholdBps:c,originationFeeBps:p.originationFeeBps,extensionFeeBps:p.extensionFeeBps,timestamp:Date.now()}}async queryPositionState(e){const r=e.startsWith("0x")?e:`0x${e.padStart(64,"0")}`;let t;t=this.config.rpcUrl?this.config.rpcUrl:await M(this.config.chain,this.config.drpcKey);const a=new ethers.providers.StaticJsonRpcProvider(S(t,this.config.drpcKey,d),this.config.chainId),n=new ethers.Contract(this.config.contractAddress,[{inputs:[],name:"core",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],a),i=await n.core(),o=new ethers.Contract(i,[{inputs:[{internalType:"bytes32",name:"positionId",type:"bytes32"}],name:"getPositionDetails",outputs:[{components:[{internalType:"bytes32",name:"positionId",type:"bytes32"},{internalType:"bytes32",name:"pkpId",type:"bytes32"},{internalType:"uint256",name:"ucdDebt",type:"uint256"},{internalType:"string",name:"vaultAddress",type:"string"},{internalType:"address",name:"borrower",type:"address"},{internalType:"uint40",name:"createdAt",type:"uint40"},{internalType:"uint40",name:"lastUpdated",type:"uint40"},{internalType:"uint16",name:"selectedTerm",type:"uint16"},{internalType:"uint40",name:"expiryAt",type:"uint40"},{internalType:"enum LoanStatusLib.LoanStatus",name:"status",type:"uint8"},{internalType:"uint40",name:"previousExpiryAt",type:"uint40"},{internalType:"uint16",name:"totalTerm",type:"uint16"},{internalType:"uint40",name:"lastRenewedAt",type:"uint40"}],internalType:"struct IPositionManagerCore.Position",name:"",type:"tuple"}],stateMutability:"view",type:"function"}],a),s=await o.getPositionDetails(r),c=Number(s.status);if(c<0||c>7)throw console.error("[VaultSnapshot] INVALID STATUS - ABI decoding error detected"),console.error(" Position ID:",r),console.error(" Contract:",this.config.contractAddress),console.error(" Status decoded:",c,"(expected 0-7)"),console.error(" Full position:",JSON.stringify(s,null,2)),new Error(`Invalid position status decoded from contract: ${c} (expected 0-7). This indicates an ABI decoding issue. Position: ${r}`);const u=Number(s.expiryAt),l=Number(s.selectedTerm),p=Number(s.totalTerm),h=Number(s.previousExpiryAt),y=Number(s.lastRenewedAt),m=(f=l,0===(g=u)?0:g-30*f*86400);var g,f;const P=B(s.vaultAddress,w(this.config.chain));if("string"!=typeof P||0===P.length)throw new Error(`Position ${r} vaultAddress has no entry for chain "${this.config.chain}"`);return{positionId:s.positionId,pkpId:s.pkpId,borrower:s.borrower,vaultAddress:P,ucdDebt:BigInt(s.ucdDebt.toString()),termStartTimestamp:m,selectedTerm:l,status:c,expiryAt:u,previousExpiryAt:h,totalTerm:p,lastRenewedAt:y}}async isLiquidatable(e){return(await this.getVaultSnapshot(e)).isLiquidatable}async getCollateralRatio(e){return(await this.getVaultSnapshot(e)).collateralRatioBps}async getAvailableBalance(e){return(await this.getVaultSnapshot(e)).availableBTCSats}async hasSufficientCollateral(e,r,t){const a=await this.getVaultSnapshot(e);return function(e,r,t,a){const n=r+t;return 0n===n||Number(e*i*10000n/n)>=a}(a.collateralValueUsd,a.ucdDebt,r,t)}},R=class e{requiredCount(){return this.devSingleProvider?1:e.REQUIRED_PROVIDER_COUNT}constructor(r,t,a,n){if(this.devSingleProvider=!0===n?.devSingleProvider,t&&Array.isArray(t))this.sources=t;else{if(!Array.isArray(r))throw new Error(`Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. Pass exactly ${e.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: `+e.ACTIVE_PROVIDER_NAMES.join(", "));this.sources=this.buildSources(r)}this.sources.sort(((e,r)=>e.priority-r.priority)),this.validateProviderCount()}validateProviderCount(){if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length} provider(s). `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`))}buildSources(r){if(r.length!==this.requiredCount())throw new Error(`priceProviders must contain exactly ${this.requiredCount()} entr${1===this.requiredCount()?"y":"ies"}. Received: ${r.length}. `+(this.devSingleProvider?"(hardhat dev single-provider mode)":`Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`));const t=[],a=new Set;let n=1;for(const i of r){if(!i||"string"!=typeof i.name)throw new Error("priceProviders entries must be {name, apiKey, apiSecret?} objects");const r=i.name.toLowerCase();if(!e.ACTIVE_PROVIDER_NAMES.includes(r))throw new Error(`Unsupported price provider "${i.name}". Locked production set: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);if(a.has(r))throw new Error(`Duplicate price provider "${r}" \u2014 the oracle requires ${e.REQUIRED_PROVIDER_COUNT} DISTINCT providers so a single upstream failure or manipulation cannot compromise consensus. Use ${e.REQUIRED_PROVIDER_COUNT} different provider names from: ${e.ACTIVE_PROVIDER_NAMES.join(", ")}`);switch(a.add(r),r){case"cryptocompare":if(!i.apiKey)throw new Error("CryptoCompare provider requires an apiKey");t.push(this.createCryptoCompareSource(i.apiKey,n++));break;case"coinmarketcap":if(!i.apiKey)throw new Error("CoinMarketCap provider requires an apiKey");t.push(this.createCoinMarketCapSource(i.apiKey,n++));break;case"coingecko":if(!i.apiKey)throw new Error("CoinGecko provider requires an apiKey (Demo or Pro). Unauthenticated CoinGecko access is not accepted \u2014 the free tier is rate-limited and edge-cached, which breaks median consensus under load.");t.push(this.createCoinGeckoSource(i.apiKey,n++));break;default:throw new Error(`Unhandled provider: ${r}`)}}return t}createCryptoCompareSource(e,r){return{name:"CryptoCompare",fetchPrice:async()=>{const r=new URL("https://min-api.cryptocompare.com/data/price");r.searchParams.set("fsym","BTC"),r.searchParams.set("tsyms","USDT"),r.searchParams.set("api_key",e);const t=await(async e=>{const r=new AbortController,t=setTimeout((()=>r.abort()),5e3);try{const a=await fetch(e,{signal:r.signal,headers:{Accept:"application/json"}});if(clearTimeout(t),!a.ok)throw new Error(`CryptoCompare HTTP ${a.status} ${a.statusText}`);return await a.json()}catch(e){if(clearTimeout(t),"AbortError"===e.name)throw new Error("Request timeout after 5000ms");throw e}})(r.toString()),a=Number(t?.USDT);if(!Number.isFinite(a)||a<=0)throw new Error("Invalid CryptoCompare price payload");return a},priority:r}}createFetchJson(e){return async(r,t)=>{const a=new AbortController,n=setTimeout((()=>a.abort()),5e3);try{const n=await fetch(r,{headers:{Accept:"application/json",...t||{}},signal:a.signal});if(!n.ok)throw new Error(`${e} HTTP ${n.status} ${n.statusText}`);return await n.json()}finally{clearTimeout(n)}}}createCoinGeckoSource(e,r){if(!e)throw new Error("createCoinGeckoSource requires an apiKey");const t=this.createFetchJson("CoinGecko");return{name:"CoinGecko",fetchPrice:async()=>{const r=e.startsWith("pro:"),a=r?e.slice(4):e,n=r?{"x-cg-pro-api-key":a}:{"x-cg-demo-api-key":a},i=new URL("https://api.coingecko.com/api/v3/simple/price");i.searchParams.set("ids","bitcoin"),i.searchParams.set("vs_currencies","usd");const o=await t(i.toString(),n),s=Number(o?.bitcoin?.usd);if(!Number.isFinite(s)||s<=0)throw new Error("Invalid CoinGecko price payload");return s},priority:r}}createCoinMarketCapSource(e,r){const t=this.createFetchJson("CoinMarketCap");return{name:"CoinMarketCap",fetchPrice:async()=>{const r=new URL("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");r.searchParams.set("symbol","BTC"),r.searchParams.set("convert","USDT");const a=await t(r.toString(),{"X-CMC_PRO_API_KEY":e}),n=Number(a?.data?.BTC?.[0]?.quote?.USDT?.price??a?.data?.BTC?.quote?.USDT?.price);if(!Number.isFinite(n)||n<=0)throw new Error("Invalid CoinMarketCap price payload");return n},priority:r}}async getBTCPrice(){const e=Date.now();if(this.sources.length!==this.requiredCount())throw new Error(`Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`);const r=new Promise(((e,r)=>{setTimeout((()=>{r(new Error("Price oracle global timeout after 8000ms"))}),8e3)})),t=Promise.all(this.sources.map((async e=>{const r=Date.now();try{const t=await e.fetchPrice();return console.log(`[Price Oracle] \u2705 [+${Date.now()-r}ms] ${e.name}: $${t.toLocaleString()}`),t}catch(r){const t=r instanceof Error?r.message:String(r);throw console.log(`[Price Oracle] \u274c ${e.name}: ${t}`),new Error(`${e.name} price fetch failed: ${t}`)}}))),a=[...await Promise.race([t,r])].sort(((e,r)=>e-r));let n;if(this.devSingleProvider)n=a[0];else{n=a[1];if((a[2]-a[0])/a[0]>.01){const e=this.sources.map((e=>e.name)).join(", "),r=a.map((e=>`$${e.toLocaleString()}`)).join(", ");throw new Error(`Price consensus failed: prices not within 1% tolerance. Providers: [${e}]. Prices: [${r}]`)}}const i=Math.round(100*n),o=1000000n*BigInt(i),s=Date.now()-e;return console.log(`[Price Oracle] Median price: $${n.toLocaleString()} \u2014 total time: ${s}ms`),console.log(`[Price Oracle] Price with 8 decimals: ${o}`),o}};R.ACTIVE_PROVIDER_NAMES=["cryptocompare","coinmarketcap","coingecko"],R.REQUIRED_PROVIDER_COUNT=3;var x=R;async function U(e,r,t,a){try{const e=await Lit.Actions.Decrypt({pkpId:t,ciphertext:a});return"string"==typeof e?e:String(e??"")}catch(t){const a=t instanceof Error?t.message:String(t);throw new Error(`Failed to decrypt ${r} for provider ${e}: ${a}`)}}function k(){const e=Math.floor(Date.now()/1e3);return r=e,Math.floor(r/c)*c;var r}var q={hardhat:{chain:"hardhat",chainId:f.hardhat,bitcoinNetwork:m.hardhat,allowArbitraryBitcoinProvider:!0,allowArbitraryEvmRpc:!0,pinContractAddresses:!1,allowDevSinglePriceProvider:!0,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:1},sepolia:{chain:"sepolia",chainId:f.sepolia,bitcoinNetwork:m.sepolia,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:1,minBitcoinSpendConfirmations:1,minConsensusProviders:2},ethereum:{chain:"ethereum",chainId:f.ethereum,bitcoinNetwork:m.ethereum,allowArbitraryBitcoinProvider:!1,allowArbitraryEvmRpc:!1,pinContractAddresses:!0,allowDevSinglePriceProvider:!1,minBitcoinBalanceConfirmations:6,minBitcoinSpendConfirmations:6,minConsensusProviders:2}};var F=["PositionManager","LoanOperationsManagerModule","BTCSpendAuthorizer","BitcoinProviderRegistry","LITActionValidator","PositionDelegateRegistry","TermManagerModule","UCDController","LiquidationManagerModule"];function O(e,r){const t={...r??{}};if(!e.pinContractAddresses)return t;const a=(n=e.chainId,u[n]??null);var n;if(!a)throw new Error(`No pinned contract-address set for chainId ${e.chainId} (${e.chain}); refusing to trust caller-supplied addresses on an enforced chain`);for(const r of F){const n=a[r];if(!n)throw new Error(`Pinned address set for ${e.chain} is missing required "${r}"; refusing to fall through to a caller-supplied value`);const i=t[r];if("string"==typeof i&&i.length>0&&i.toLowerCase()!==n.toLowerCase())throw new Error(`Caller-supplied "${r}" (${i}) contradicts the pinned ${e.chain} address (${n}); refusing to sign`);t[r]=n}return t}async function L(e,r){const t=r.rpcUrl,a=r.rpcSource??"params-or-lit-node";let n;if("string"==typeof t&&t.length>0)!function(e,r){if(e.allowArbitraryEvmRpc)return;if(!r||"string"!=typeof r)throw new Error("validateEvmRpcForPolicy: rpcUrl must be a non-empty string");let t;try{t=new URL(r).hostname}catch(e){throw new Error(`Invalid rpcUrl: ${e?.message??String(e)}`)}if(!g.some((e=>t===e||t.endsWith(`.${e}`))))throw new Error(`Custom RPC domain "${t}" is not in the approved list: ${g.join(", ")}`)}(e,t),n=t;else{if("params-only"===a)throw new Error('Missing required parameter "rpcUrl" \u2014 this action cannot resolve an RPC endpoint itself (Chipotle has no Lit.Actions.getRpcUrl)');if(n=await M(r.chain,r.drpcKey),"string"!=typeof n||0===n.length)throw new Error(`Lit.Actions.getRpcUrl returned no endpoint for chain "${r.chain}"`)}return{rpcUrl:n,drpcKey:I(n,r.drpcKey),addresses:O(e,r.contractAddresses)}}var N="function getProtocolPauseStatus() view returns (tuple(bool positionManagerPaused, bool positionManagerLiquidationsPaused, bool positionManagerCorePaused, bool loanOperationsPaused, bool collateralManagerPaused, bool liquidationManagerPaused, bool circuitBreakerPaused, bool ucdControllerPaused, bool ucdTokenPaused, bool simplePsmPaused))",_="unreadable",K={mintUcd:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],withdrawBtc:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],processPayment:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused"],extendPosition:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","circuitBreakerPaused","ucdControllerPaused","ucdTokenPaused","simplePsmPaused"],liquidation:["positionManagerLiquidationsPaused","liquidationManagerPaused","circuitBreakerPaused"],btcTransactionSign:["positionManagerPaused","positionManagerCorePaused","loanOperationsPaused","collateralManagerPaused","circuitBreakerPaused"]},V=[];function j(e){return{positionManagerPaused:e.positionManagerPaused,positionManagerLiquidationsPaused:e.positionManagerLiquidationsPaused,positionManagerCorePaused:e.positionManagerCorePaused,loanOperationsPaused:e.loanOperationsPaused,collateralManagerPaused:e.collateralManagerPaused,liquidationManagerPaused:e.liquidationManagerPaused,circuitBreakerPaused:e.circuitBreakerPaused,ucdControllerPaused:e.ucdControllerPaused,ucdTokenPaused:e.ucdTokenPaused,simplePsmPaused:e.simplePsmPaused}}var G=new ethers.utils.Interface(["function views() view returns (address)","function paused() view returns (bool)","function liquidationPaused() view returns (bool)","function simplePsm() view returns (address)"]),z=new ethers.utils.Interface(["function core() view returns (address)","function loanOps() view returns (address)","function collateralManager() view returns (address)","function liquidationManager() view returns (address)","function circuitBreaker() view returns (address)"]),J=new ethers.utils.Interface(["function getUcdController() view returns (address)","function ucdToken() view returns (address)"]),W=new ethers.utils.Interface(["function paused() view returns (bool)"]);async function H(e,r,t){return e.call({to:r,data:t})}async function X(e,r){const t=new ethers.utils.Interface([N]).encodeFunctionData("getProtocolPauseStatus",[]);let a;try{return function(e){const r=new ethers.utils.Interface([N]).decodeFunctionResult("getProtocolPauseStatus",e)[0];return Array.isArray(r)?j({positionManagerPaused:r[0],positionManagerLiquidationsPaused:r[1],positionManagerCorePaused:r[2],loanOperationsPaused:r[3],collateralManagerPaused:r[4],liquidationManagerPaused:r[5],circuitBreakerPaused:r[6],ucdControllerPaused:r[7],ucdTokenPaused:r[8],simplePsmPaused:r[9]}):j(r)}(await e.call({to:r,data:t}))}catch(e){a=e}try{return await async function(e,r){const t=await H(e,r,G.encodeFunctionData("views",[])),[a]=G.decodeFunctionResult("views",t),[n,i,o,s,c,d,u,l]=await Promise.all([H(e,r,G.encodeFunctionData("paused",[])),H(e,r,G.encodeFunctionData("liquidationPaused",[])),H(e,r,G.encodeFunctionData("simplePsm",[])),H(e,a,z.encodeFunctionData("core",[])),H(e,a,z.encodeFunctionData("loanOps",[])),H(e,a,z.encodeFunctionData("collateralManager",[])),H(e,a,z.encodeFunctionData("liquidationManager",[])),H(e,a,z.encodeFunctionData("circuitBreaker",[]))]),p=G.decodeFunctionResult("paused",n)[0],h=G.decodeFunctionResult("liquidationPaused",i)[0],y=G.decodeFunctionResult("simplePsm",o)[0],m=z.decodeFunctionResult("core",s)[0],g=z.decodeFunctionResult("loanOps",c)[0],f=z.decodeFunctionResult("collateralManager",d)[0],w=z.decodeFunctionResult("liquidationManager",u)[0],P=z.decodeFunctionResult("circuitBreaker",l)[0],v=await H(e,g,J.encodeFunctionData("getUcdController",[])),E=await H(e,g,J.encodeFunctionData("ucdToken",[])),C=J.decodeFunctionResult("getUcdController",v)[0],b=J.decodeFunctionResult("ucdToken",E)[0],A=async(r,t)=>{if(!t||t===ethers.constants.AddressZero)return!(V.indexOf(r)>=0)&&_;try{const r=await H(e,t,W.encodeFunctionData("paused",[]));return W.decodeFunctionResult("paused",r)[0]}catch(e){return console.log(`[protocol-pause] ${r} unreadable at ${t}: ${e instanceof Error?e.message:String(e)}`),_}},[T,I,M,S,D,B,$,R]=await Promise.all([A("positionManagerCorePaused",m),A("loanOperationsPaused",g),A("collateralManagerPaused",f),A("liquidationManagerPaused",w),A("circuitBreakerPaused",P),A("ucdControllerPaused",C),A("ucdTokenPaused",b),A("simplePsmPaused",y)]);return j({positionManagerPaused:p,positionManagerLiquidationsPaused:h,positionManagerCorePaused:T,loanOperationsPaused:I,collateralManagerPaused:M,liquidationManagerPaused:S,circuitBreakerPaused:D,ucdControllerPaused:B,ucdTokenPaused:$,simplePsmPaused:R})}(e,r)}catch(e){const r=a instanceof Error?a.message:String(a),t=e instanceof Error?e.message:String(e);throw new Error(`getProtocolPauseStatus failed (aggregate: ${r}; decomposed: ${t})`)}}var Q={PayerPayment:[{name:"positionId",type:"bytes32"},{name:"quantumTimestamp",type:"uint256"},{name:"btcPrice",type:"uint256"},{name:"paymentAmount",type:"uint256"},{name:"borrower",type:"address"},{name:"payer",type:"address"}]},Z=[1,2,3,4];var Y,ee=class extends ${read(e){return this.queryPositionState(e)}},re={getBTCPrice:async()=>{throw new Error("[carry-repay] the position reader requested a price; the price is read once, after the refusals")}},te={calculateTrustedBalance:async()=>{throw new Error("[carry-repay] the position reader requested a BTC read; this action reads none")}};async function main(e){if(!e||"object"!=typeof e)throw new Error("[carry-repay] missing args");for(const r of["chain","positionId","receiver","validatorWalletAddress","rpcUrl"])if("string"!=typeof e[r]||0===e[r].length)throw new Error(`[carry-repay] missing "${r}"`);if(!Array.isArray(e.priceProviders))throw new Error('[carry-repay] missing "priceProviders"');for(const r of["amount","paymentAmount"])if(r in e)throw new Error(`[carry-repay] "${r}" is not an input; the amount is derived as min(credit, debt)`);const r=function(e){const r=w(e),t=q[r];if(!t)throw new Error(`No chain policy registered for "${e}"`);return t}(e.chain),t=!0===e.devPriceMode;if(t&&!r.allowDevSinglePriceProvider)throw new Error(`[carry-repay] devPriceMode (single-provider price) is only permitted on hardhat; refusing on ${r.chain}`);const{rpcUrl:a,drpcKey:n,addresses:i}=await L(r,{chain:e.chain,rpcUrl:e.rpcUrl,drpcKey:e.drpcKey,contractAddresses:e.contractAddresses,rpcSource:"params-only"});for(const e of["PositionManager","TermManagerModule","LoanOperationsManagerModule","LiquidationManagerModule"])if(!i[e])throw new Error(`[carry-repay] contractAddresses.${e} is required`);const c=(d=r.chain,f[d]);var d;const u=ethers.utils.getAddress(e.receiver),y=function(e){if("string"!=typeof e)throw new Error("positionId must be a string");const r=e.trim(),t=/^0x/i.test(r)?r.slice(2):r;if(0===t.length)throw new Error("positionId is empty");if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("positionId must be hexadecimal (bytes32)");if(t.length>64)throw new Error("positionId exceeds 32 bytes");return"0x"+t.padStart(64,"0").toLowerCase()}(e.positionId),m=new ethers.providers.StaticJsonRpcProvider(S(a,n),{chainId:c,name:r.chain});await async function(e,r,t){const a=await e.send("eth_chainId",[]);if("string"!=typeof a||!/^0x[0-9a-fA-F]+$/.test(a))throw new Error(`${t} eth_chainId answered ${JSON.stringify(a)}, not a hex quantity; refusing to sign`);const n=ethers.BigNumber.from(a);if(!n.eq(r.chainId))throw new Error(`${t} the RPC reports chain ${n.toString()}, not ${r.chain} (${r.chainId}); refusing to sign`)}(m,r,"[carry-repay]"),function(e,r){const t=K[e],a=[],n=[];for(const e of t)r[e]===_?n.push(e):r[e]&&a.push(e);if(a.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSED",operation:e,paused:a,status:r}));if(n.length>0)throw new Error(JSON.stringify({code:"PROTOCOL_PAUSE_UNREADABLE",operation:e,unreadable:n,status:r}))}("processPayment",await X(m,i.PositionManager));const g=new ethers.Contract(i.PositionManager,["function repaymentPayer() view returns (address)","function views() view returns (address)"],m);!function(e,r){const t=ethers.utils.getAddress(e),a=ethers.utils.getAddress(r);if(t!==a)throw new Error(`[carry-repay] receiver ${a} is not PositionManager.repaymentPayer ${t}; refusing to sign`)}(await g.repaymentPayer(),u);const P=ethers.utils.getAddress(await g.views());if(P===ethers.constants.AddressZero)throw new Error("[carry-repay] PositionManager.views() is unset");const v=new ee({contractAddress:i.PositionManager,termManagerAddress:i.TermManagerModule,loanOpsManagerAddress:i.LoanOperationsManagerModule,liquidationManagerAddress:i.LiquidationManagerModule,chain:r.chain,chainId:c,vaultBalance:te,priceOracle:re,rpcUrl:a,drpcKey:n}),E=await v.read(y),C=ethers.utils.getAddress(E.borrower),b=new ethers.Contract(u,["function credits(bytes32) view returns (uint256)"],m),A=BigInt((await b.credits(y)).toString()),T=function(e){if(!Z.includes(e.status))throw new Error(`[carry-repay] position ${e.positionId} is ${l(e.status)}; a payment needs ${Z.map((e=>l(e))).join(", ")}`);if(e.debt<=0n)throw new Error(`[carry-repay] position ${e.positionId} has no debt; nothing to repay`);if(e.credit<=0n)throw new Error(`[carry-repay] the receiver holds no credit for position ${e.positionId}; nothing to repay with`);return e.credit<e.debt?e.credit:e.debt}({positionId:y,status:E.status,debt:E.ucdDebt,credit:A}),I=new x(await async function(e){if(!e)return e;const r=[];for(const a of e){if(!a?.name||"string"!=typeof a.name)throw new Error("Each price provider must include a valid name");let e,n;if(a.pkpId&&"string"==typeof a.pkpId){const r=(t=a.pkpId).startsWith("0x")||t.startsWith("0X")?t:`0x${t}`;a.apiKey&&(e=await U(a.name,"apiKey",r,a.apiKey)),a.apiSecret&&(n=await U(a.name,"apiSecret",r,a.apiSecret))}else e=a.apiKey,n=a.apiSecret;r.push({name:a.name,apiKey:e,apiSecret:n})}var t;return r}(e.priceProviders),void 0,void 0,{devSingleProvider:t}),M=await I.getBTCPrice();if(M<o||M>s)throw new Error(`[carry-repay] BTC price ${M} is outside the acceptable range (${o} - ${s})`);const D=k(),B={name:p,version:h,chainId:c,verifyingContract:P},$={positionId:(R={positionId:y,quantumTimestamp:D,btcPrice:M,amount:T,borrower:C,payer:u}).positionId,quantumTimestamp:R.quantumTimestamp.toString(),btcPrice:R.btcPrice.toString(),paymentAmount:R.amount.toString(),borrower:ethers.utils.getAddress(R.borrower),payer:ethers.utils.getAddress(R.payer)};var R;const F=function(e,r){return ethers.utils._TypedDataEncoder.hash(e,Q,r)}(B,$),{signature:O}=await async function(e,r,t,a){const n=await Lit.Actions.getPrivateKey({pkpId:e}),i="string"==typeof n?n.startsWith("0x")?n:`0x${n}`:String(n),o=new ethers.Wallet(i);if(o.address!==ethers.utils.getAddress(e))throw new Error(`[carry] key for ${e} derives ${o.address}; refusing to sign`);return{signature:await o._signTypedData(r,t,a),signer:o.address}}(e.validatorWalletAddress,B,Q,$);return{positionId:y,amount:$.paymentAmount,quantumTimestamp:D,btcPrice:$.btcPrice,borrower:C,payer:u,signature:O,digest:F}}return Y=n,((n,i,o,s)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of t(i))a.call(n,c)||c===o||e(n,c,{get:()=>i[c],enumerable:!(s=r(i,c))||s.enumerable});return n})(e({},"__esModule",{value:!0}),Y)})();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
|
+
1ed1a999238f5475963cb809c330f6fdb4f4a14305c1ae75a2b8e52341dfc8b3
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"actionName": "carry-repay-validator",
|
|
3
|
-
"originalSize":
|
|
4
|
-
"minifiedSize":
|
|
5
|
-
"compressionRatio": 0.
|
|
6
|
-
"hash": "
|
|
7
|
-
"buildTime":
|
|
3
|
+
"originalSize": 74983,
|
|
4
|
+
"minifiedSize": 34667,
|
|
5
|
+
"compressionRatio": 0.5376685382019925,
|
|
6
|
+
"hash": "1ed1a999238f5475963cb809c330f6fdb4f4a14305c1ae75a2b8e52341dfc8b3",
|
|
7
|
+
"buildTime": 1794778215544,
|
|
8
8
|
"version": "0.1.0"
|
|
9
9
|
}
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lit-actions-registry.d.ts","sourceRoot":"","sources":["../../../../pkg-src/constants/chunks/lit-actions-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAE7C;;;GAGG;AACH,eAAO,MAAM,uBAAuB,EAAE,OAAO,CAAC,sBAAsB,
|
|
1
|
+
{"version":3,"file":"lit-actions-registry.d.ts","sourceRoot":"","sources":["../../../../pkg-src/constants/chunks/lit-actions-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAE7C;;;GAGG;AACH,eAAO,MAAM,uBAAuB,EAAE,OAAO,CAAC,sBAAsB,CA2VnE,CAAC;AAEF,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,sBAAsB,CAAC,CAGjC;AAED,eAAO,MAAM,oBAAoB,iCAA0B,CAAC"}
|