Transaction Hash:
Block:
12599392 at Jun-09-2021 08:48:45 AM +UTC
Transaction Fee:
0.001904353 ETH
$3.92
Gas Used:
173,123 Gas / 11 Gwei
Emitted Events:
| 260 |
EPNS.Transfer( from=[Sender] 0x718ee21c21491abae6638fe823a6e871b86f6c24, to=[Receiver] Staking, amount=43000000000000000000 )
|
| 261 |
Staking.Deposit( user=[Sender] 0x718ee21c21491abae6638fe823a6e871b86f6c24, tokenAddress=EPNS, amount=43000000000000000000 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x718ee21C...1B86f6C24 |
4.999664327049360197 Eth
Nonce: 191
|
4.997759974049360197 Eth
Nonce: 192
| 0.001904353 | ||
| 0xB72ff1e6...844cfec85 | (Push Protocol: Staking) | ||||
|
0xEA674fdD...16B898ec8
Miner
| (Ethermine) | 1,060.033337220869874695 Eth | 1,060.035241573869874695 Eth | 0.001904353 | |
| 0xf4185885...EBBeEEEEE |
Execution Trace
Staking.deposit( tokenAddress=0xf418588522d5dd018b425E472991E52EBBeEEEEE, amount=43000000000000000000 )
-
EPNS.transferFrom( src=0x718ee21C21491abAE6638FE823A6e871B86f6C24, dst=0xB72ff1e675117beDefF05a7D0a472c3844cfec85, rawAmount=43000000000000000000 ) => ( True )
-
EPNS.balanceOf( account=0xB72ff1e675117beDefF05a7D0a472c3844cfec85 ) => ( 1529048979999999999989827 )
deposit[Staking (ln:43)]
add[Staking (ln:46)]transferFrom[Staking (ln:47)]getCurrentEpoch[Staking (ln:49)]currentEpochMultiplier[Staking (ln:50)]getCurrentEpoch[Staking (ln:275)]
epochIsInitialized[Staking (ln:52)]manualEpochInit[Staking (ln:55)]getCurrentEpoch[Staking (ln:185)]epochIsInitialized[Staking (ln:192)]epochIsInitialized[Staking (ln:193)]ManualEpochInit[Staking (ln:198)]
balanceOf[Staking (ln:59)]getEpochUserBalance[Staking (ln:62)]getCheckpointEffectiveBalance[Staking (ln:224)]div[Staking (ln:297)]mul[Staking (ln:297)]getCheckpointBalance[Staking (ln:297)]
getCheckpointEffectiveBalance[Staking (ln:235)]div[Staking (ln:297)]mul[Staking (ln:297)]getCheckpointBalance[Staking (ln:297)]
push[Staking (ln:68)]Checkpoint[Staking (ln:68)]push[Staking (ln:70)]Checkpoint[Staking (ln:70)]computeNewMultiplier[Staking (ln:75)]getCheckpointBalance[Staking (ln:76)]push[Staking (ln:81)]Checkpoint[Staking (ln:81)]getCheckpointBalance[Staking (ln:81)]push[Staking (ln:82)]Checkpoint[Staking (ln:82)]computeNewMultiplier[Staking (ln:86)]getCheckpointBalance[Staking (ln:87)]add[Staking (ln:92)]push[Staking (ln:93)]Checkpoint[Staking (ln:93)]computeNewMultiplier[Staking (ln:98)]getCheckpointBalance[Staking (ln:99)]add[Staking (ln:104)]getEpochUserBalance[Staking (ln:109)]getCheckpointEffectiveBalance[Staking (ln:224)]div[Staking (ln:297)]mul[Staking (ln:297)]getCheckpointBalance[Staking (ln:297)]
getCheckpointEffectiveBalance[Staking (ln:235)]div[Staking (ln:297)]mul[Staking (ln:297)]getCheckpointBalance[Staking (ln:297)]
add[Staking (ln:110)]sub[Staking (ln:110)]Deposit[Staking (ln:111)]
File 1 of 2: Staking
File 2 of 2: EPNS
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract Staking is ReentrancyGuard {
using SafeMath for uint256;
uint128 constant private BASE_MULTIPLIER = uint128(1 * 10 ** 18);
// timestamp for the epoch 1
// everything before that is considered epoch 0 which won't have a reward but allows for the initial stake
uint256 public immutable epoch1Start;
// duration of each epoch
uint256 public immutable epochDuration;
// holds the current balance of the user for each token
mapping(address => mapping(address => uint256)) private balances;
struct Pool {
uint256 size;
bool set;
}
// for each token, we store the total pool size
mapping(address => mapping(uint256 => Pool)) private poolSize;
// a checkpoint of the valid balance of a user for an epoch
struct Checkpoint {
uint128 epochId;
uint128 multiplier;
uint256 startBalance;
uint256 newDeposits;
}
// balanceCheckpoints[user][token][]
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) public {
epoch1Start = _epoch1Start;
epochDuration = _epochDuration;
}
/*
* Stores `amount` of `tokenAddress` tokens for the `user` into the vault
*/
function deposit(address tokenAddress, uint256 amount) public nonReentrant {
require(amount > 0, "Staking: Amount must be > 0");
IERC20 token = IERC20(tokenAddress);
balances[msg.sender][tokenAddress] = balances[msg.sender][tokenAddress].add(amount);
token.transferFrom(msg.sender, address(this), amount);
// epoch logic
uint128 currentEpoch = getCurrentEpoch();
uint128 currentMultiplier = currentEpochMultiplier();
uint256 balance = balances[msg.sender][tokenAddress];
if (!epochIsInitialized(tokenAddress, currentEpoch)) {
address[] memory tokens = new address[](1);
tokens[0] = tokenAddress;
manualEpochInit(tokens, currentEpoch);
}
// update the next epoch pool size
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 there's no checkpoint yet, it means the user didn't have any activity
// we want to store checkpoints both for the current epoch and next epoch because
// if a user does a withdraw, the current epoch can also be modified and
// we don't want to insert another checkpoint in the middle of the array as that could be expensive
if (checkpoints.length == 0) {
checkpoints.push(Checkpoint(currentEpoch, currentMultiplier, 0, amount));
// next epoch => multiplier is 1, epoch deposits is 0
checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, amount, 0));
} else {
uint256 last = checkpoints.length - 1;
// the last action happened in an older epoch (e.g. a deposit in epoch 3, current epoch is >=5)
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, balance, 0));
}
// the last action happened in the previous epoch
else if (checkpoints[last].epochId == currentEpoch) {
checkpoints[last].multiplier = computeNewMultiplier(
getCheckpointBalance(checkpoints[last]),
checkpoints[last].multiplier,
amount,
currentMultiplier
);
checkpoints[last].newDeposits = checkpoints[last].newDeposits.add(amount);
checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, balance, 0));
}
// the last action happened in the current epoch
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.add(amount);
}
checkpoints[last].startBalance = balance;
}
}
uint256 balanceAfter = getEpochUserBalance(msg.sender, tokenAddress, currentEpoch);
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.add(balanceAfter.sub(balanceBefore));
emit Deposit(msg.sender, tokenAddress, amount);
}
/*
* Removes the deposit of the user and sends the amount of `tokenAddress` back to the `user`
*/
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].sub(amount);
IERC20 token = IERC20(tokenAddress);
token.transfer(msg.sender, amount);
// epoch logic
uint128 currentEpoch = getCurrentEpoch();
lastWithdrawEpochId[tokenAddress] = currentEpoch;
if (!epochIsInitialized(tokenAddress, currentEpoch)) {
address[] memory tokens = new address[](1);
tokens[0] = tokenAddress;
manualEpochInit(tokens, currentEpoch);
}
// update the pool size of the next epoch to its current balance
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;
// note: it's impossible to have a withdraw and no checkpoints because the checkpoints[last] will be out of bound and revert
// there was a deposit in an older epoch (more than 1 behind [eg: previous 0, now 5]) but no other action since then
if (checkpoints[last].epochId < currentEpoch) {
checkpoints.push(Checkpoint(currentEpoch, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0));
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(amount);
}
// there was a deposit in the `epochId - 1` epoch => we have a checkpoint for the current epoch
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.sub(amount);
}
// there was a deposit in the current epoch
else {
Checkpoint storage currentEpochCheckpoint = checkpoints[last - 1];
uint256 balanceBefore = getCheckpointEffectiveBalance(currentEpochCheckpoint);
// in case of withdraw, we have 2 branches:
// 1. the user withdraws less than he added in the current epoch
// 2. the user withdraws more than he added in the current epoch (including 0)
if (amount < currentEpochCheckpoint.newDeposits) {
uint128 avgDepositMultiplier = uint128(
balanceBefore.sub(currentEpochCheckpoint.startBalance).mul(BASE_MULTIPLIER).div(currentEpochCheckpoint.newDeposits)
);
currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits.sub(amount);
currentEpochCheckpoint.multiplier = computeNewMultiplier(
currentEpochCheckpoint.startBalance,
BASE_MULTIPLIER,
currentEpochCheckpoint.newDeposits,
avgDepositMultiplier
);
} else {
currentEpochCheckpoint.startBalance = currentEpochCheckpoint.startBalance.sub(
amount.sub(currentEpochCheckpoint.newDeposits)
);
currentEpochCheckpoint.newDeposits = 0;
currentEpochCheckpoint.multiplier = BASE_MULTIPLIER;
}
uint256 balanceAfter = getCheckpointEffectiveBalance(currentEpochCheckpoint);
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(balanceBefore.sub(balanceAfter));
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
}
emit Withdraw(msg.sender, tokenAddress, amount);
}
/*
* manualEpochInit can be used by anyone to initialize an epoch based on the previous one
* This is only applicable if there was no action (deposit/withdraw) in the current epoch.
* Any deposit and withdraw will automatically initialize the current and next epoch.
*/
function manualEpochInit(address[] memory tokens, uint128 epochId) public {
require(epochId <= getCurrentEpoch(), "can't init a future epoch");
for (uint 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.transfer(msg.sender, totalUserBalance);
emit EmergencyWithdraw(msg.sender, tokenAddress, totalUserBalance);
}
/*
* Returns the valid balance of a user that was taken into consideration in the total pool size for the epoch
* A deposit will only change the next epoch balance.
* A withdraw will decrease the current epoch (and subsequent) balance.
*/
function getEpochUserBalance(address user, address token, uint128 epochId) public view returns (uint256) {
Checkpoint[] storage checkpoints = balanceCheckpoints[user][token];
// if there are no checkpoints, it means the user never deposited any tokens, so the balance is 0
if (checkpoints.length == 0 || epochId < checkpoints[0].epochId) {
return 0;
}
uint min = 0;
uint max = checkpoints.length - 1;
// shortcut for blocks newer than the latest checkpoint == current balance
if (epochId >= checkpoints[max].epochId) {
return getCheckpointEffectiveBalance(checkpoints[max]);
}
// binary search of the value in the array
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].epochId <= epochId) {
min = mid;
} else {
max = mid - 1;
}
}
return getCheckpointEffectiveBalance(checkpoints[min]);
}
/*
* Returns the amount of `token` that the `user` has currently staked
*/
function balanceOf(address user, address token) public view returns (uint256) {
return balances[user][token];
}
/*
* Returns the id of the current epoch derived from block.timestamp
*/
function getCurrentEpoch() public view returns (uint128) {
if (block.timestamp < epoch1Start) {
return 0;
}
return uint128((block.timestamp - epoch1Start) / epochDuration + 1);
}
/*
* Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId`
*/
function getEpochPoolSize(address tokenAddress, uint128 epochId) public view returns (uint256) {
// Premises:
// 1. it's impossible to have gaps of uninitialized epochs
// - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized
if (epochIsInitialized(tokenAddress, epochId)) {
return poolSize[tokenAddress][epochId].size;
}
// epochId not initialized and epoch 0 not initialized => there was never any action on this pool
if (!epochIsInitialized(tokenAddress, 0)) {
return 0;
}
// epoch 0 is initialized => there was an action at some point but none that initialized the epochId
// which means the current pool size is equal to the current balance of token held by the staking contract
IERC20 token = IERC20(tokenAddress);
return token.balanceOf(address(this));
}
/*
* Returns the percentage of time left in the current epoch
*/
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.mul(prevMultiplier).div(BASE_MULTIPLIER);
uint256 addAmount = amount.mul(currentMultiplier).div(BASE_MULTIPLIER);
uint128 newMultiplier = uint128(prevAmount.add(addAmount).mul(BASE_MULTIPLIER).div(prevBalance.add(amount)));
return newMultiplier;
}
/*
* Checks if an epoch is initialized, meaning we have a pool size set for it
*/
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.add(c.newDeposits);
}
function getCheckpointEffectiveBalance(Checkpoint memory c) internal pure returns (uint256) {
return getCheckpointBalance(c).mul(c.multiplier).div(BASE_MULTIPLIER);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
File 2 of 2: EPNS
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
//import "hardhat/console.sol";
//import "@openzeppelin/contracts/math/SafeMath.sol";
contract EPNS {
/// @notice EIP-20 token name for this token
string public constant name = "Ethereum Push Notification Service";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "PUSH";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 100_000_000e18; // 100 million PUSH
/// @notice block number when tokens came into circulation
uint public born;
/// @dev Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @dev Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice Official record of the token block information for the holder
mapping (address => uint) public holderWeight;
/// @notice Allows holder weight to be reset by other adddresses
mapping (address => mapping(address => bool)) public holderDelegation;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its total token weight
event HolderWeightChanged(address indexed holder, uint256 amount, uint weight);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new PUSH token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
// holder weight initial adjustments
holderWeight[account] = block.number;
born = block.number;
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount >= uint(uint96(-1))) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Push::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends | Approve by signature
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Push::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Push::permit: invalid signature");
require(signatory == owner, "Push::permit: unauthorized");
require(now <= deadline, "Push::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Push::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Push::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Push::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Return holder units
*/
function returnHolderUnits(address account, uint atBlock) external view returns (uint) {
return mul256(balances[account], sub256(atBlock, holderWeight[account], "Push::returnHolderUnits: atBlock should be greater than holderWeight"), "Push::returnHolderUnits: ratio exceeds max range");
}
/**
* @notice toggle holder whitelist
*/
function returnHolderDelegation(address account, address delegate) external view returns (bool) {
return holderDelegation[account][delegate];
}
/**
* @notice toggle holder whitelist
*/
function setHolderDelegation(address delegate, bool value) external {
holderDelegation[msg.sender][delegate] = value;
}
/**
* @notice Reset holder weight to current block
*/
function resetHolderWeight(address holder) external {
require(holderDelegation[holder][msg.sender] == true || holder == msg.sender, "Push::resetHolderWeight: unauthorized");
holderWeight[holder] = block.number;
emit HolderWeightChanged(holder, balances[holder], block.number);
}
/**
* @notice Destory `RawAmount` of tokens from a holder `account`
* @param rawAmount The number of tokens
*/
function burn(uint256 rawAmount) external {
address account = msg.sender;
uint96 balance = balances[account];
uint96 amount = safe96(rawAmount, "Push::burn: amount exceeds 96 bits");
balances[account] = sub96(balance, amount, "Push::burn: burn amount exceeds balance");
totalSupply = sub256(totalSupply, rawAmount, "Push::burn: supply underflow");
emit Transfer(account, address(0), amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Push::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Push::delegateBySig: invalid nonce");
require(now <= expiry, "Push::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Push::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
Checkpoint memory lastCheckpoint = checkpoints[account][nCheckpoints - 1];
// First check most recent balance
if (lastCheckpoint.fromBlock <= blockNumber) {
return lastCheckpoint.votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Push::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Push::_transferTokens: cannot transfer to the zero address");
// adjust holder weight
_adjustHolderWeight(src, dst, amount);
// update balance
balances[src] = sub96(balances[src], amount, "Push::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Push::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _adjustHolderWeight(address src, address dst, uint96 amount) internal {
// change holderWeight block
uint96 balance = balances[dst];
if (balance == 0) {
holderWeight[dst] = holderWeight[src];
}
else {
uint256 dstWeight = mul256(holderWeight[dst], balance, "Push::_adjustHolderWeight: holder dst weight exceeded limit");
uint256 srcWeight = mul256(holderWeight[src], amount, "Push::_adjustHolderWeight: holder src weight exceeded limit");
uint256 totalWeight = add256(dstWeight, srcWeight, "Push::_adjustHolderWeight: total weight exceeded limit");
uint256 totalAmount = add256(balance, amount, "Push::_adjustHolderWeight: total amount exceeded limit");
uint256 totalAmountBy2 = div256(totalAmount, 2, "");
uint256 roundUpWeight = add256(totalWeight, totalAmountBy2, "Push::_adjustHolderWeight: round up amount exceeded limit");
holderWeight[dst] = div256(roundUpWeight, totalAmount, "Push::_adjustHolderWeight: adjusted holder negative divide");
}
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Push::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Push::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Push::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function add256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}