编译器
0.8.10+commit.fc410830
文件 1 的 5:Address.sol
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 5:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 3 的 5:ReentrancyGuard.sol
pragma solidity ^0.8.0;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
文件 4 的 5:SafeERC20.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
文件 5 的 5:Staking.sol
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract Staking is ReentrancyGuard {
using SafeERC20 for IERC20;
uint128 constant private BASE_MULTIPLIER = uint128(1 * 10 ** 18);
uint256 public epoch1Start;
uint256 public epochDuration;
mapping(address => mapping(address => uint256)) private balances;
struct Pool {
uint256 size;
bool set;
}
mapping(address => mapping(uint256 => Pool)) private poolSize;
struct Checkpoint {
uint128 epochId;
uint128 multiplier;
uint256 startBalance;
uint256 newDeposits;
}
mapping(address => mapping(address => Checkpoint[])) private balanceCheckpoints;
mapping(address => uint128) private lastWithdrawEpochId;
event Deposit(address indexed user, address indexed tokenAddress, uint256 amount);
event Withdraw(address indexed user, address indexed tokenAddress, uint256 amount);
event ManualEpochInit(address indexed caller, uint128 indexed epochId, address[] tokens);
event EmergencyWithdraw(address indexed user, address indexed tokenAddress, uint256 amount);
constructor (uint256 _epoch1Start, uint256 _epochDuration) {
epoch1Start = _epoch1Start;
epochDuration = _epochDuration;
}
function deposit(address tokenAddress, uint256 amount) public nonReentrant {
require(amount > 0, "Staking: Amount must be > 0");
IERC20 token = IERC20(tokenAddress);
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= amount, "Staking: Token allowance too small");
balances[msg.sender][tokenAddress] = balances[msg.sender][tokenAddress] + amount;
token.safeTransferFrom(msg.sender, address(this), amount);
uint128 currentEpoch = getCurrentEpoch();
uint128 currentMultiplier = currentEpochMultiplier();
if (!epochIsInitialized(tokenAddress, currentEpoch)) {
address[] memory tokens = new address[](1);
tokens[0] = tokenAddress;
manualEpochInit(tokens, currentEpoch);
}
Pool storage pNextEpoch = poolSize[tokenAddress][currentEpoch + 1];
pNextEpoch.size = token.balanceOf(address(this));
pNextEpoch.set = true;
Checkpoint[] storage checkpoints = balanceCheckpoints[msg.sender][tokenAddress];
uint256 balanceBefore = getEpochUserBalance(msg.sender, tokenAddress, currentEpoch);
if (checkpoints.length == 0) {
checkpoints.push(Checkpoint(currentEpoch, currentMultiplier, 0, amount));
checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, amount, 0));
} else {
uint256 last = checkpoints.length - 1;
if (checkpoints[last].epochId < currentEpoch) {
uint128 multiplier = computeNewMultiplier(
getCheckpointBalance(checkpoints[last]),
BASE_MULTIPLIER,
amount,
currentMultiplier
);
checkpoints.push(Checkpoint(currentEpoch, multiplier, getCheckpointBalance(checkpoints[last]), amount));
checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0));
}
else if (checkpoints[last].epochId == currentEpoch) {
checkpoints[last].multiplier = computeNewMultiplier(
getCheckpointBalance(checkpoints[last]),
checkpoints[last].multiplier,
amount,
currentMultiplier
);
checkpoints[last].newDeposits = checkpoints[last].newDeposits + amount;
checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0));
}
else {
if (last >= 1 && checkpoints[last - 1].epochId == currentEpoch) {
checkpoints[last - 1].multiplier = computeNewMultiplier(
getCheckpointBalance(checkpoints[last - 1]),
checkpoints[last - 1].multiplier,
amount,
currentMultiplier
);
checkpoints[last - 1].newDeposits = checkpoints[last - 1].newDeposits + amount;
}
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
}
}
uint256 balanceAfter = getEpochUserBalance(msg.sender, tokenAddress, currentEpoch);
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size + (balanceAfter - balanceBefore);
emit Deposit(msg.sender, tokenAddress, amount);
}
function withdraw(address tokenAddress, uint256 amount) public nonReentrant {
require(balances[msg.sender][tokenAddress] >= amount, "Staking: balance too small");
balances[msg.sender][tokenAddress] = balances[msg.sender][tokenAddress] - amount;
IERC20 token = IERC20(tokenAddress);
token.safeTransfer(msg.sender, amount);
uint128 currentEpoch = getCurrentEpoch();
lastWithdrawEpochId[tokenAddress] = currentEpoch;
if (!epochIsInitialized(tokenAddress, currentEpoch)) {
address[] memory tokens = new address[](1);
tokens[0] = tokenAddress;
manualEpochInit(tokens, currentEpoch);
}
Pool storage pNextEpoch = poolSize[tokenAddress][currentEpoch + 1];
pNextEpoch.size = token.balanceOf(address(this));
pNextEpoch.set = true;
Checkpoint[] storage checkpoints = balanceCheckpoints[msg.sender][tokenAddress];
uint256 last = checkpoints.length - 1;
if (checkpoints[last].epochId < currentEpoch) {
checkpoints.push(Checkpoint(currentEpoch, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0));
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size - amount;
}
else if (checkpoints[last].epochId == currentEpoch) {
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
checkpoints[last].newDeposits = 0;
checkpoints[last].multiplier = BASE_MULTIPLIER;
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size - amount;
}
else {
Checkpoint storage currentEpochCheckpoint = checkpoints[last - 1];
uint256 balanceBefore = getCheckpointEffectiveBalance(currentEpochCheckpoint);
if (amount < currentEpochCheckpoint.newDeposits) {
uint128 avgDepositMultiplier = uint128(
(balanceBefore - currentEpochCheckpoint.startBalance) * BASE_MULTIPLIER / currentEpochCheckpoint.newDeposits
);
currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits - amount;
currentEpochCheckpoint.multiplier = computeNewMultiplier(
currentEpochCheckpoint.startBalance,
BASE_MULTIPLIER,
currentEpochCheckpoint.newDeposits,
avgDepositMultiplier
);
} else {
currentEpochCheckpoint.startBalance = currentEpochCheckpoint.startBalance - (amount - currentEpochCheckpoint.newDeposits);
currentEpochCheckpoint.newDeposits = 0;
currentEpochCheckpoint.multiplier = BASE_MULTIPLIER;
}
uint256 balanceAfter = getCheckpointEffectiveBalance(currentEpochCheckpoint);
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size - (balanceBefore - balanceAfter);
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
}
emit Withdraw(msg.sender, tokenAddress, amount);
}
function manualEpochInit(address[] memory tokens, uint128 epochId) public {
require(epochId <= getCurrentEpoch(), "can't init a future epoch");
for (uint256 i = 0; i < tokens.length; i++) {
Pool storage p = poolSize[tokens[i]][epochId];
if (epochId == 0) {
p.size = uint256(0);
p.set = true;
} else {
require(!epochIsInitialized(tokens[i], epochId), "Staking: epoch already initialized");
require(epochIsInitialized(tokens[i], epochId - 1), "Staking: previous epoch not initialized");
p.size = poolSize[tokens[i]][epochId - 1].size;
p.set = true;
}
}
emit ManualEpochInit(msg.sender, epochId, tokens);
}
function emergencyWithdraw(address tokenAddress) public {
require((getCurrentEpoch() - lastWithdrawEpochId[tokenAddress]) >= 10, "At least 10 epochs must pass without success");
uint256 totalUserBalance = balances[msg.sender][tokenAddress];
require(totalUserBalance > 0, "Amount must be > 0");
balances[msg.sender][tokenAddress] = 0;
IERC20 token = IERC20(tokenAddress);
token.safeTransfer(msg.sender, totalUserBalance);
emit EmergencyWithdraw(msg.sender, tokenAddress, totalUserBalance);
}
function getEpochUserBalance(address user, address token, uint128 epochId) public view returns (uint256) {
Checkpoint[] storage checkpoints = balanceCheckpoints[user][token];
if (checkpoints.length == 0 || epochId < checkpoints[0].epochId) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length - 1;
if (epochId >= checkpoints[max].epochId) {
return getCheckpointEffectiveBalance(checkpoints[max]);
}
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].epochId <= epochId) {
min = mid;
} else {
max = mid - 1;
}
}
return getCheckpointEffectiveBalance(checkpoints[min]);
}
function balanceOf(address user, address token) public view returns (uint256) {
return balances[user][token];
}
function getCurrentEpoch() public view returns (uint128) {
if (block.timestamp < epoch1Start) {
return 0;
}
return uint128((block.timestamp - epoch1Start) / epochDuration + 1);
}
function getEpochPoolSize(address tokenAddress, uint128 epochId) public view returns (uint256) {
if (epochIsInitialized(tokenAddress, epochId)) {
return poolSize[tokenAddress][epochId].size;
}
if (!epochIsInitialized(tokenAddress, 0)) {
return 0;
}
IERC20 token = IERC20(tokenAddress);
return token.balanceOf(address(this));
}
function currentEpochMultiplier() public view returns (uint128) {
uint128 currentEpoch = getCurrentEpoch();
uint256 currentEpochEnd = epoch1Start + currentEpoch * epochDuration;
uint256 timeLeft = currentEpochEnd - block.timestamp;
uint128 multiplier = uint128(timeLeft * BASE_MULTIPLIER / epochDuration);
return multiplier;
}
function computeNewMultiplier(uint256 prevBalance, uint128 prevMultiplier, uint256 amount, uint128 currentMultiplier) public pure returns (uint128) {
uint256 prevAmount = prevBalance * prevMultiplier / BASE_MULTIPLIER;
uint256 addAmount = amount * currentMultiplier / BASE_MULTIPLIER;
uint128 newMultiplier = uint128((prevAmount + addAmount) * BASE_MULTIPLIER / (prevBalance + amount));
return newMultiplier;
}
function epochIsInitialized(address token, uint128 epochId) public view returns (bool) {
return poolSize[token][epochId].set;
}
function getCheckpointBalance(Checkpoint memory c) internal pure returns (uint256) {
return c.startBalance + c.newDeposits;
}
function getCheckpointEffectiveBalance(Checkpoint memory c) internal pure returns (uint256) {
return getCheckpointBalance(c) * c.multiplier / BASE_MULTIPLIER;
}
}
{
"compilationTarget": {
"contracts/Staking.sol": "Staking"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 2
},
"remappings": []
}
[{"inputs":[{"internalType":"uint256","name":"_epoch1Start","type":"uint256"},{"internalType":"uint256","name":"_epochDuration","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"EmergencyWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"uint128","name":"epochId","type":"uint128"},{"indexed":false,"internalType":"address[]","name":"tokens","type":"address[]"}],"name":"ManualEpochInit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"prevBalance","type":"uint256"},{"internalType":"uint128","name":"prevMultiplier","type":"uint128"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint128","name":"currentMultiplier","type":"uint128"}],"name":"computeNewMultiplier","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"currentEpochMultiplier","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"emergencyWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"epoch1Start","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"epochDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint128","name":"epochId","type":"uint128"}],"name":"epochIsInitialized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentEpoch","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint128","name":"epochId","type":"uint128"}],"name":"getEpochPoolSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint128","name":"epochId","type":"uint128"}],"name":"getEpochUserBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"uint128","name":"epochId","type":"uint128"}],"name":"manualEpochInit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]