-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlender.sol
81 lines (66 loc) · 2.72 KB
/
lender.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.0;
interface IUniswapV2Pair {
function mint(address to) external returns (uint liquidity);
function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
interface ERC20Like {
function transfer(address dst, uint qty) external returns (bool);
function transferFrom(address src, address dst, uint qty) external returns (bool);
function approve(address dst, uint qty) external returns (bool);
function balanceOf(address who) external view returns (uint);
}
interface WETH9 is ERC20Like {
function deposit() external payable;
}
contract Lender {
IUniswapV2Pair public pair;
WETH9 public constant weth = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
ERC20Like public token;
mapping(address => uint256) public deposited;
mapping(address => uint256) public debt;
constructor (IUniswapV2Pair _pair, ERC20Like _token) {
pair = _pair;
token = _token;
}
function rate() public view returns (uint256) {
(uint112 _reserve0, uint112 _reserve1,) = pair.getReserves();
uint256 _rate = uint256(_reserve0 / _reserve1);
return _rate;
}
function safeDebt(address user) public view returns (uint256) {
return deposited[user] * rate() * 2 / 3;
}
// borrow some tokens
function borrow(uint256 amount) public {
debt[msg.sender] += amount;
require(safeDebt(msg.sender) >= debt[msg.sender], "err: undercollateralized");
token.transfer(msg.sender, amount);
}
// repay your loan
function repay(uint256 amount) public {
debt[msg.sender] -= amount;
token.transferFrom(msg.sender, address(this), amount);
}
// repay a user's loan and get back their collateral.
function liquidate(address user, uint256 amount) public returns (uint256) {
require(safeDebt(user) <= debt[user], "err: overcollateralized");
debt[user] -= amount;
token.transferFrom(msg.sender, address(this), amount);
uint256 collateralValueRepaid = amount / rate();
weth.transfer(msg.sender, collateralValueRepaid);
return collateralValueRepaid;
}
// deposit collateral
function deposit(uint256 amount) public {
deposited[msg.sender] += amount;
weth.transferFrom(msg.sender, address(this), amount);
}
// remove collateral
function withdraw(uint256 amount) public {
deposited[msg.sender] -= amount;
require(safeDebt(msg.sender) >= debt[msg.sender], "err: undercollateralized");
weth.transfer(msg.sender, amount);
}
}