Skip to content
This repository has been archived by the owner on Sep 8, 2024. It is now read-only.

Commit

Permalink
🛠️ Chore : init
Browse files Browse the repository at this point in the history
  • Loading branch information
ooMia committed Sep 2, 2024
0 parents commit 1254011
Show file tree
Hide file tree
Showing 13 changed files with 1,080 additions and 0 deletions.
48 changes: 48 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: CI

on:
push:
pull_request:
workflow_dispatch:

env:
FOUNDRY_PROFILE: ci

jobs:
check:
strategy:
fail-fast: true

name: Foundry project
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive

- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly

- name: Show Forge version
run: |
forge --version
- name: Run Forge fmt
run: |
forge fmt --check
id: fmt

- name: Run Forge build
run: |
forge build --sizes
id: build

- name: Run Forge tests
run: |
forge test -vvv
id: test

- name: Run snapshot
run: NO_COLOR=1 forge snapshot >> $GITHUB_STEP_SUMMARY
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Compiler files
cache/
out/

# Ignores development broadcast logs
!/broadcast
/broadcast/*/31337/
/broadcast/**/dry-run/

# Docs
docs/

# Dotenv file
.env

# vscode
.vscode

# yarn
node_modules/
.editorconfig
.gitattributes
.pnp.cjs
package-lock.json
package.json
yarn.lock
.pnp.loader.mjs
install-state.gz
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
[submodule "lib/openzeppelin-contracts"]
path = lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org>
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Lending

- 예치된 token에 대한 과담보를 조건으로 대출 지원
- block.number에 대한 이율 연산으로 사용자로부터 예치된 USDC에 대한 이자 지급

## Description

- 28개 중 21개 테스트 케이스 통과
- ![image](https://github.com/user-attachments/assets/559adcb2-fad4-4283-aaa5-1126629f0413)

- 이후 고도화에 필요한 시간이 부족하다고 판단하여 중단
- **PR#1** [[21/28] 구현 중단](https://github.com/ooMia/Upside_Lending_solidity/pull/1)

### Maintainer notes
- [assignment-description](https://docs.google.com/document/d/1Q7QQe-ts4imDnLM9qq4Ca5OTKHPd3KExOdBMjFv9S7Y/edit#heading=h.jd3axzxuo8lq)
- [foundry/crates/forge](https://github.com/foundry-rs/foundry/tree/master/crates/forge)
Binary file added calc.xlsx
Binary file not shown.
15 changes: 15 additions & 0 deletions foundry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
evm_version = "cancun"
verbosity = 3
via_ir = true

[rpc_endpoints]
local = "http://localhost:8545"
upside = "https://${UPSIDE_RPC_URL}"

# https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
# https://book.getfoundry.sh/config/
# https://github.com/juanfranblanco/vscode-solidity?tab=readme-ov-file
1 change: 1 addition & 0 deletions lib/forge-std
Submodule forge-std added at 1714be
1 change: 1 addition & 0 deletions lib/openzeppelin-contracts
Submodule openzeppelin-contracts added at dbb610
5 changes: 5 additions & 0 deletions remappings.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/
ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/
erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/
forge-std/=lib/forge-std/src/
openzeppelin-contracts/=lib/openzeppelin-contracts/
9 changes: 9 additions & 0 deletions script/LendingScript.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import {Script} from "forge-std/Script.sol";

contract LendingScript is Script {
constructor() {}
function run() external {}
}
146 changes: 146 additions & 0 deletions src/DreamAcademyLending.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

interface IPriceOracle {
function getPrice(address token) external view returns (uint256);
function setPrice(address token, uint256 price) external;
}

interface ILending {
function initializeLendingProtocol(address usdc) external payable;
function deposit(address token, uint256 amount) external payable;
function borrow(address token, uint256 amount) external;
function repay(address token, uint256 amount) external;
function withdraw(address token, uint256 amount) external;
function getAccruedSupplyAmount(address token) external view returns (uint256);
function liquidate(address borrower, address token, uint256 amount) external;
}
/// 1 block 당 12sec 고정

contract DreamAcademyLending is ILending {
IPriceOracle internal _oracle;
address internal _usdc;

address constant NATIVE_ETH = address(0);
uint256 constant OC_RATE = 175;
mapping(address => uint256) internal _price;

struct Deposit {
uint256 amount;
uint256 blockNumber;
}

struct Balance {
mapping(address => Deposit) _deposit;
mapping(address => uint256) locked;
uint256 borrowed;
}

mapping(address => Balance) internal _balances;

modifier updateBalance(address token, int256 amount) {
_;
Deposit storage _deposit = _balances[msg.sender]._deposit[token];
_deposit.amount = uint256(int256(_deposit.amount) + amount);
}

modifier updatePrice(address token) {
_price[token] = _oracle.getPrice(token);
_price[NATIVE_ETH] = _oracle.getPrice(NATIVE_ETH);
_;
}

constructor(IPriceOracle oracle, address usdc) {
_oracle = oracle;
_usdc = usdc;
}

function initializeLendingProtocol(address usdc) external payable override {
(bool res,) =
address(this).call{value: msg.value}(abi.encodeWithSelector(ILending.deposit.selector, usdc, msg.value));
res = res && ERC20(usdc).transferFrom(msg.sender, address(this), msg.value);
require(res);
}

function deposit(address token, uint256 amount) external payable override updateBalance(token, int256(amount)) {
require(msg.value >= amount || ERC20(token).transferFrom(msg.sender, address(this), amount));
}

/// @dev 맡겨둔 ETH를 담보로 USDC를 빌립니다.
/// OC_RATE%의 과담보율을 적용합니다. 예를 들어, OC_RATE가 1750이라면 1000 USDC를 빌릴 때, 1750 USDC의 가치에 해당하는 ETH를 담보로 제공해야 합니다.
/// @param amount 빌릴 USDC의 양
function borrow(address token, uint256 amount) external override updatePrice(token) {
Balance storage balance = _balances[msg.sender];

uint256 valueToBorrow = amount * _price[token];
uint256 valueNeededToBorrow = (valueToBorrow * OC_RATE) / 100;
require(valueNeededToBorrow <= totalValueOwned());

balance._deposit[NATIVE_ETH].amount -= valueNeededToBorrow / _price[NATIVE_ETH];

balance._deposit[token].amount += valueToBorrow / _price[token];
balance.locked[token] += valueNeededToBorrow - valueToBorrow;
balance.borrowed += amount;

require(ERC20(token).transfer(msg.sender, amount));
}

event Log(uint256 value);

function totalValueOwned() internal view returns (uint256 totalValue) {
totalValue += _balances[msg.sender]._deposit[NATIVE_ETH].amount * _price[NATIVE_ETH];
}

// TODO block number를 이용한 이자 계산
function repay(address usdc, uint256 amount) external override {
Balance storage balance = _balances[msg.sender];
balance.borrowed -= amount;
require(ERC20(usdc).transferFrom(msg.sender, address(this), amount));

if (balance.borrowed == 0) {
require(ERC20(usdc).transfer(msg.sender, balance.locked[usdc]));
balance.locked[usdc] = 0;
}
}

function withdraw(address token, uint256 amount) external override updateBalance(token, -int256(amount)) {
require(_balances[msg.sender]._deposit[token].amount >= amount);

if (token == NATIVE_ETH) {
(bool res,) = msg.sender.call{value: amount}("");
require(res);
return;
}
require(ERC20(token).transfer(msg.sender, amount));
}

function getAccruedSupplyAmount(address usdc) external view override returns (uint256) {
Deposit storage _deposit = _balances[msg.sender]._deposit[usdc];
return (_deposit.amount * (block.number - _deposit.blockNumber)) / 100;
}

/// @dev can liquidate the whole position when the borrowed amount is less than 100, otherwise only 25% can be liquidated at once.
function liquidate(address borrower, address usdc, uint256 amount) external override {
Balance storage balance = _balances[borrower];
amount = amount < 100 ? Math.min(amount, balance.locked[usdc]) : Math.min(amount, balance.locked[usdc] / 4);

emit Log(amount);
emit Log(_price[usdc]);
emit Log(balance.borrowed);

if (amount / _price[usdc] == 0) {}
balance.borrowed -= amount * _price[usdc];

require(ERC20(usdc).transferFrom(msg.sender, address(this), amount));
if (balance.borrowed == 0) {
require(ERC20(usdc).transfer(borrower, balance.locked[usdc] / _price[usdc]));
balance.locked[usdc] = 0;
}
}

// receive() external payable {}
// fallback() external payable {}
}
Loading

0 comments on commit 1254011

Please sign in to comment.