dagger-contracts/contracts/Collateral.sol

76 lines
2.0 KiB
Solidity
Raw Normal View History

2022-02-14 14:47:01 +00:00
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
abstract contract Collateral {
IERC20 public immutable token;
CollateralFunds private funds;
2022-02-14 14:47:01 +00:00
mapping(address => uint256) private balances;
constructor(IERC20 _token) collateralInvariant {
2022-02-14 14:47:01 +00:00
token = _token;
}
function balanceOf(address account) public view returns (uint256) {
return balances[account];
}
function _add(address account, uint256 amount) private {
balances[account] += amount;
funds.balance += amount;
}
function _subtract(address account, uint256 amount) private {
balances[account] -= amount;
funds.balance -= amount;
}
function _transferFrom(address sender, uint256 amount) internal {
address receiver = address(this);
require(token.transferFrom(sender, receiver, amount), "Transfer failed");
}
function deposit(uint256 amount) public collateralInvariant {
_transferFrom(msg.sender, amount);
funds.deposited += amount;
_add(msg.sender, amount);
2022-02-14 15:43:56 +00:00
}
function _isWithdrawAllowed() internal virtual returns (bool);
function withdraw() public collateralInvariant {
require(_isWithdrawAllowed(), "Account locked");
uint256 amount = balanceOf(msg.sender);
funds.withdrawn += amount;
_subtract(msg.sender, amount);
2022-02-14 15:43:56 +00:00
assert(token.transfer(msg.sender, amount));
2022-02-14 15:19:47 +00:00
}
function _slash(
address account,
uint256 percentage
) internal collateralInvariant {
uint256 amount = (balanceOf(account) * percentage) / 100;
funds.slashed += amount;
_subtract(account, amount);
2022-02-14 16:19:00 +00:00
}
modifier collateralInvariant() {
CollateralFunds memory oldFunds = funds;
2022-02-14 15:19:47 +00:00
_;
assert(funds.deposited >= oldFunds.deposited);
assert(funds.withdrawn >= oldFunds.withdrawn);
assert(funds.slashed >= oldFunds.slashed);
assert(funds.deposited == funds.balance + funds.withdrawn + funds.slashed);
2022-02-14 15:43:56 +00:00
}
struct CollateralFunds {
2022-02-14 15:43:56 +00:00
uint256 balance;
uint256 deposited;
uint256 withdrawn;
2022-02-14 16:19:00 +00:00
uint256 slashed;
2022-02-14 14:47:01 +00:00
}
}