Created
May 5, 2023 04:26
-
-
Save bluenights004/2d22fab05bf9f154d021441e97c93afd to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.18+commit.87f61d96.js&optimize=false&runs=200&gist=
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
contract SimpleLineOfCredit { | |
/// @notice - positions ids of all open credit lines. | |
/// @dev - may contain null elements | |
bytes32[] public ids; | |
/// @notice id -> position data | |
mapping(bytes32 => Credit) public credits; | |
struct Credit { | |
bool isOpen; | |
uint256 principal; | |
uint256 interestAccrued; | |
} | |
event NewCreditLine(bytes32 indexed id, uint256 principal); | |
function createCreditLine(uint256 principal) external { | |
bytes32 id = keccak256(abi.encodePacked(msg.sender, block.timestamp)); | |
ids.push(id); | |
credits[id] = Credit({ | |
isOpen: true, | |
principal: principal, | |
interestAccrued: 0 | |
}); | |
emit NewCreditLine(id, principal); | |
} | |
function closeCreditLine(bytes32 id) external { | |
Credit storage credit = credits[id]; | |
require(credit.isOpen, "Credit line is already closed"); | |
require(credit.principal == 0, "Cannot close credit line with outstanding principal"); | |
credit.isOpen = false; | |
// Remove the closed credit line from the ids array | |
for (uint256 i = 0; i < ids.length; i++) { | |
if (ids[i] == id) { | |
ids[i] = ids[ids.length - 1]; | |
ids.pop(); | |
break; | |
} | |
} | |
} | |
function repay(bytes32 id, uint256 amount) external { | |
Credit storage credit = credits[id]; | |
require(credit.isOpen, "Credit line is closed"); | |
require(credit.principal >= amount, "Repayment amount exceeds outstanding principal"); | |
credit.principal -= amount; | |
} | |
function accrueInterest(bytes32 id, uint256 interest) external { | |
Credit storage credit = credits[id]; | |
require(credit.isOpen, "Credit line is closed"); | |
credit.interestAccrued += interest; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment