// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; interface ISettlementAsset { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address owner, address recipient, uint256 amount) external returns (bool); } /// @notice Single-asset, fully principal-backed credit lines for agent wallets. /// @dev Deploy with an exact-transfer, non-rebasing ERC20. Lender capital, /// sponsor backing and the fee reserve are accounted for independently. contract ElysianCredit { struct Agent { string name; address sponsor; uint256 limit; uint256 principal; uint256 fee; uint64 dueAt; uint64 repaid; uint64 late; bool defaulted; bool closing; uint256 volumeRepaid; } ISettlementAsset public immutable asset; address public immutable reserveRecipient; uint256 public constant GRACE = 3 days; uint256 public lenderAssets; uint256 public totalShares; uint256 public totalPrincipalOut; uint256 public totalBacking; uint256 public reserve; uint256 public totalRepaid; uint256 public repaidCount; uint256 public defaultCount; mapping(address => uint256) public sharesOf; mapping(address => uint256) public backingOf; mapping(address => uint256) public lockedBacking; mapping(address => mapping(address => uint256)) public offers; mapping(address => uint256) public loanIdOf; mapping(address => Agent) private agents; address[] private agentList; uint256 private lastLoanId; uint256 private unlocked = 1; event AgentRegistered(address indexed agent, string name); event LiquidityDeposited(address indexed lender, uint256 assets, uint256 shares); event LiquidityWithdrawn(address indexed lender, uint256 assets, uint256 shares); event BackingDeposited(address indexed sponsor, uint256 assets); event BackingWithdrawn(address indexed sponsor, uint256 assets); event LineOffered(address indexed sponsor, address indexed agent, uint256 limit); event LineOpened(address indexed agent, address indexed sponsor, uint256 limit); event LineClosing(address indexed agent, address indexed sponsor); event LineClosed(address indexed agent, address indexed sponsor); event Borrowed(address indexed agent, address indexed sponsor, uint256 principal, uint256 fee, uint64 dueAt); event Repaid(address indexed agent, address indexed payer, uint256 principal, uint256 fee, bool late); event Defaulted(address indexed agent, address indexed sponsor, uint256 principal); event ReserveWithdrawn(address indexed recipient, uint256 assets); error InvalidInput(); error Unauthorized(); error InvalidState(); error InsufficientFunds(); error TokenTransferFailed(); error Reentrancy(); error StaleLoan(); error StillInGrace(); modifier guarded() { if (unlocked != 1) revert Reentrancy(); unlocked = 2; _; unlocked = 1; } constructor(address asset_, address reserveRecipient_) { if (asset_.code.length == 0 || reserveRecipient_ == address(0) || reserveRecipient_ == address(this)) revert InvalidInput(); asset = ISettlementAsset(asset_); reserveRecipient = reserveRecipient_; } function protocolId() external pure returns (bytes32) { return keccak256("elysian-credit/v1"); } function registerAgent(string calldata name) external guarded { if (!_validName(bytes(name))) revert InvalidInput(); if (bytes(agents[msg.sender].name).length != 0) revert InvalidState(); agents[msg.sender].name = name; agentList.push(msg.sender); emit AgentRegistered(msg.sender, name); } /// @dev Solidity accepts arbitrary bytes in a string. RPC clients expect valid UTF-8. function _validName(bytes calldata name) private pure returns (bool) { if (name.length == 0 || name.length > 64) return false; bool visible; uint256 i; while (i < name.length) { uint8 lead = uint8(name[i++]); if (lead < 0x80) { if (lead < 0x20 || lead == 0x7f) return false; if (lead != 0x20) visible = true; continue; } if (lead < 0xc2 || lead > 0xf4) return false; uint256 trailing = lead < 0xe0 ? 1 : lead < 0xf0 ? 2 : 3; if (i + trailing > name.length) return false; uint8 next = uint8(name[i]); // Exclude overlong encodings, UTF-16 surrogates and values above U+10FFFF. if ((lead == 0xe0 && next < 0xa0) || (lead == 0xed && next >= 0xa0) || (lead == 0xf0 && next < 0x90) || (lead == 0xf4 && next >= 0x90)) return false; for (uint256 end = i + trailing; i < end; ++i) { if ((uint8(name[i]) & 0xc0) != 0x80) return false; } visible = true; } return visible; } function agentCount() external view returns (uint256) { return agentList.length; } function agentAt(uint256 index) external view returns (address) { return agentList[index]; } function getAgent(address agent) external view returns (Agent memory) { return agents[agent]; } function liquidAssets() public view returns (uint256) { return lenderAssets - totalPrincipalOut; } function previewRedeem(uint256 shares) public view returns (uint256) { return totalShares == 0 ? 0 : _mulDiv(shares, lenderAssets, totalShares); } function depositLiquidity(uint256 assets) external guarded returns (uint256 shares) { if (assets == 0) revert InvalidInput(); shares = totalShares == 0 ? assets : _mulDiv(assets, totalShares, lenderAssets); if (shares == 0) revert InvalidInput(); _pull(msg.sender, assets); sharesOf[msg.sender] += shares; totalShares += shares; lenderAssets += assets; emit LiquidityDeposited(msg.sender, assets, shares); } function withdrawLiquidity(uint256 shares) external guarded returns (uint256 assets) { if (shares == 0 || shares > sharesOf[msg.sender]) revert InvalidInput(); assets = previewRedeem(shares); if (assets > liquidAssets()) revert InsufficientFunds(); sharesOf[msg.sender] -= shares; totalShares -= shares; lenderAssets -= assets; _push(msg.sender, assets); emit LiquidityWithdrawn(msg.sender, assets, shares); } function depositBacking(uint256 assets) external guarded { if (assets == 0) revert InvalidInput(); _pull(msg.sender, assets); backingOf[msg.sender] += assets; totalBacking += assets; emit BackingDeposited(msg.sender, assets); } function withdrawBacking(uint256 assets) external guarded { if (assets == 0 || assets > backingOf[msg.sender] - lockedBacking[msg.sender]) revert InsufficientFunds(); backingOf[msg.sender] -= assets; totalBacking -= assets; _push(msg.sender, assets); emit BackingWithdrawn(msg.sender, assets); } /// @notice A zero offer withdraws consent. Other offers may compete for the same stake. function offerLine(address agent, uint256 limit) external guarded { Agent storage record = agents[agent]; if (bytes(record.name).length == 0 || record.defaulted) revert InvalidState(); if (limit > backingOf[msg.sender] - lockedBacking[msg.sender]) revert InsufficientFunds(); offers[msg.sender][agent] = limit; emit LineOffered(msg.sender, agent, limit); } function acceptLine(address sponsor) external guarded { Agent storage record = agents[msg.sender]; uint256 limit = offers[sponsor][msg.sender]; if (record.defaulted || record.sponsor != address(0) || limit == 0) revert InvalidState(); if (limit > backingOf[sponsor] - lockedBacking[sponsor]) revert InsufficientFunds(); delete offers[sponsor][msg.sender]; lockedBacking[sponsor] += limit; record.sponsor = sponsor; record.limit = limit; emit LineOpened(msg.sender, sponsor, limit); } /// @notice Either party can end a line at any time. Outstanding principal stays secured. function closeLine(address agent) external guarded { Agent storage record = agents[agent]; if (record.sponsor == address(0) || record.closing) revert InvalidState(); if (msg.sender != agent && msg.sender != record.sponsor) revert Unauthorized(); if (record.principal == 0) { _close(agent, record); } else { lockedBacking[record.sponsor] -= record.limit - record.principal; record.limit = record.principal; record.closing = true; emit LineClosing(agent, record.sponsor); } } /// @notice 1% per 30 days, prorated for the selected term and rounded up to one atomic unit. function quoteFee(uint256 amount, uint8 termDays) public pure returns (uint256) { if (amount == 0 || termDays == 0 || termDays > 30) revert InvalidInput(); // Divide first so even the largest ERC20 amount can be quoted. return (amount / 3000) * termDays + ((amount % 3000) * termDays + 2999) / 3000; } function borrow(uint256 amount, uint8 termDays) external guarded { Agent storage record = agents[msg.sender]; if (record.sponsor == address(0) || record.principal != 0 || record.defaulted || record.closing) { revert InvalidState(); } if (amount > record.limit || amount > liquidAssets()) revert InsufficientFunds(); uint256 fee = quoteFee(amount, termDays); uint64 dueAt = uint64(block.timestamp + uint256(termDays) * 1 days); totalPrincipalOut += amount; record.principal = amount; record.fee = fee; record.dueAt = dueAt; loanIdOf[msg.sender] = ++lastLoanId; _push(msg.sender, amount); emit Borrowed(msg.sender, record.sponsor, amount, fee, dueAt); } /// @notice Repay from the agent wallet. For a third-party payer use repayChecked. function repay(address agent) external guarded { if (msg.sender != agent) revert Unauthorized(); _repay(agent); } function repayChecked(address agent, uint256 expectedLoanId, uint256 maxDue) external guarded { Agent storage record = agents[agent]; if (expectedLoanId == 0 || loanIdOf[agent] != expectedLoanId || record.principal + record.fee > maxDue) revert StaleLoan(); _repay(agent); } function _repay(address agent) private { Agent storage record = agents[agent]; uint256 principal = record.principal; if (principal == 0) revert InvalidState(); uint256 fee = record.fee; _pull(msg.sender, principal + fee); bool late = block.timestamp > record.dueAt; record.repaid += 1; if (late) record.late += 1; record.volumeRepaid += principal; repaidCount += 1; totalRepaid += principal; uint256 lenderFee = fee / 2; uint256 sponsorFee = fee / 4; lenderAssets += lenderFee; totalBacking += sponsorFee; backingOf[record.sponsor] += sponsorFee; reserve += fee - lenderFee - sponsorFee; _clearDebt(agent, record, principal); emit Repaid(agent, msg.sender, principal, fee, late); if (record.closing) _close(agent, record); } /// @notice Slashes the principal from this line's sponsor. Unpaid interest is waived. function markDefault(address agent) external guarded { Agent storage record = agents[agent]; uint256 principal = record.principal; if (principal == 0) revert InvalidState(); if (block.timestamp <= uint256(record.dueAt) + GRACE) revert StillInGrace(); backingOf[record.sponsor] -= principal; totalBacking -= principal; _clearDebt(agent, record, principal); record.defaulted = true; defaultCount += 1; emit Defaulted(agent, record.sponsor, principal); _close(agent, record); } function _clearDebt(address agent, Agent storage record, uint256 principal) private { totalPrincipalOut -= principal; record.principal = 0; record.fee = 0; record.dueAt = 0; delete loanIdOf[agent]; } function _close(address agent, Agent storage record) private { address sponsor = record.sponsor; lockedBacking[sponsor] -= record.limit; record.limit = 0; record.sponsor = address(0); record.closing = false; emit LineClosed(agent, sponsor); } function withdrawReserve(uint256 assets) external guarded { if (msg.sender != reserveRecipient) revert Unauthorized(); if (assets == 0 || assets > reserve) revert InsufficientFunds(); reserve -= assets; _push(reserveRecipient, assets); emit ReserveWithdrawn(reserveRecipient, assets); } function _pull(address from, uint256 amount) private { uint256 beforeBalance = asset.balanceOf(address(this)); _callAsset(abi.encodeCall(ISettlementAsset.transferFrom, (from, address(this), amount))); if (asset.balanceOf(address(this)) != beforeBalance + amount) revert TokenTransferFailed(); } function _push(address to, uint256 amount) private { uint256 poolBalance = asset.balanceOf(address(this)); uint256 recipientBalance = asset.balanceOf(to); _callAsset(abi.encodeCall(ISettlementAsset.transfer, (to, amount))); if (asset.balanceOf(address(this)) != poolBalance - amount || asset.balanceOf(to) != recipientBalance + amount) revert TokenTransferFailed(); } function _callAsset(bytes memory callData) private { (bool ok, bytes memory data) = address(asset).call(callData); if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TokenTransferFailed(); } /// @dev Full-precision floor(x*y/d), based on Remco Bloemen's mulDiv (MIT). function _mulDiv(uint256 x, uint256 y, uint256 d) private pure returns (uint256 result) { unchecked { uint256 low = x * y; uint256 high; assembly ("memory-safe") { let modResult := mulmod(x, y, not(0)) high := sub(sub(modResult, low), lt(modResult, low)) } if (high == 0) return low / d; if (d <= high) revert InvalidInput(); uint256 remainder = mulmod(x, y, d); assembly ("memory-safe") { high := sub(high, gt(remainder, low)) low := sub(low, remainder) } uint256 twos = d & (0 - d); assembly ("memory-safe") { d := div(d, twos) low := div(low, twos) twos := add(div(sub(0, twos), twos), 1) } low |= high * twos; uint256 inverse = (3 * d) ^ 2; // Newton iteration doubles the correct inverse bits from 4 to 256. for (uint256 i; i < 6; ++i) inverse *= 2 - d * inverse; return low * inverse; } } }