file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.8.0;
import "../token/SyntheticToken.sol";
import "./UniProxy.sol";
import "../utils/math/SafeMath.sol";
import "./CompProxy.sol";
import "./LandOracleProxy.sol";
import "../access/Ownable.sol";
import "../token/ProperlyToken.sol";
contract CollateralAndMint is Ownable {
using SafeMath for uint256;
// Address of Oracle smart contract that is used to set price for Decentraland Land Index.
// The price is requested though Chainlink, GET API call.
// The API call link is: https://whispering-beyond-26434.herokuapp.com/decentraland/orders/price-mean/750
// API request is a proxy to communicate with The Graph.
// This request allows us to collect last 750 Land sale prices.
// We take the mean price and set the dLand Token minting price accordingly.
// Price will be updated by Keepers in the future.
address public oracleAddress;
// All ETH collateral deposits are re-routed to Compound protocol to earn interest.
// The earned interest is then used to buyback protocol tokens and burn them.
// With the purpose of creating deflation for the protocol token.
address public compAddress;
// Collateral requirements for minting dLand, which is set on the contract deployment.
uint256 public collateralRequirementPercent;
// Compound ETH balance.
uint256 public cETHCurrentBalance;
// For transparancy purposes we keep a balance of how much protocol tokens have we burned.
uint256 public tokenBurnBalance;
// Since we re-route the collateral deposits to Compound we might have to keep track of the TVL
// TODO: uint256 public totalValueLocked;
constructor(
SyntheticToken _dlandindextoken,
ProperlyToken _protocolToken,
uint256 _collateralrequirementpercent,
address _oracleaddress,
address _compeaddress,
address _uniswap
) public {
dLandIndexToken = _dlandindextoken;
protocolToken = _protocolToken;
collateralRequirementPercent = _collateralrequirementpercent;
oracleAddress = _oracleaddress;
compAddress = _compeaddress;
uniswap = IUniswap(_uniswap);
}
// Uniswap contract interface.
IUniswap uniswap;
// TODO: Make Index tokens independant of this contract.
// ^^^^ This contract will be used to interact with other Index tokens
// ^^^^ That are accepted by the protocol.
// Contracts of tokens used in the protocol.
SyntheticToken public dLandIndexToken;
ProperlyToken public protocolToken;
// CONTRACT IS ABLE TO RECIEVE ETH.
// ETH is used to buyback and burn Protocol native tokens.
receive() external payable {}
// ##### ACCOUNTING HAPPENS HERE #####
// TODO: Impliment liquidation functinality.
// Liquidation function should use the liquidated collateral, buy Dland from market and burn it.
// Needs to be though though.
// We keep track of each users deposits.
mapping(address => uint256) public collateralBalance;
// Portion of used collateral.
mapping(address => uint256) public collateralUsedEth;
// Borrow limit of the user in ETH.
// It is based on the collateral requarement %
mapping(address => uint256) public currentBorrowLimitEth;
// We keep track how much of the Comp Eth we got belongs to the user.
mapping(address => uint256) public cETH;
event TokensMinted(
address account,
address token,
uint256 amount,
uint256 rate
);
event EthUncollaterased(address account, uint256 amount);
event TokensBurned(address account, address token, uint256 amount);
// #### RETURNS THE PRICE OF DECENTRALAND INDEX #####
function landIndexPrice() public view returns (uint256) {
return ILandEthPriceOracle(oracleAddress).landIndexTokenPerEth();
}
// ##### ACCOUNTING CALCULATION HAPPENS HERE #####
// Adjust Collateral Balance Based on Deposits and withdraws.
function calculateCollateralBalance(uint256 _deposit, uint256 _withdraw)
private
{
// Increase borrow limit on deposit.
if (_deposit > 0) {
collateralBalance[msg.sender] = collateralBalance[msg.sender].add(
_deposit
);
calculateBorrowLimit();
}
// Decreases borrow limit on withdraw.
if (_withdraw > 0) {
collateralBalance[msg.sender] = collateralBalance[msg.sender].sub(
_withdraw
);
calculateBorrowLimit();
}
}
// Everytime we mint or burn, we calculate the new borrow limit.
function calculateCollateralUse(uint256 _mint, uint256 _burn) private {
uint256 landPerEthPrice = landIndexPrice();
//
if (_mint > 0) {
collateralUsedEth[msg.sender] = _mint
.mul(1e18)
.div(landPerEthPrice)
.add(collateralUsedEth[msg.sender]);
calculateBorrowLimit();
}
if (_burn > 0) {
uint256 balance = dLandIndexToken.balanceOf(msg.sender);
// Avoiding rounding errors.
if (balance == _burn) {
collateralUsedEth[msg.sender] = collateralUsedEth[msg.sender]
.sub(collateralUsedEth[msg.sender]);
} else {
collateralUsedEth[msg.sender] = collateralUsedEth[msg.sender]
.sub(_burn.mul(1e18).div(landPerEthPrice));
}
calculateBorrowLimit();
}
}
// Function used whenever we have any interaction deposit, withdraw, mint or burn.
function calculateBorrowLimit() private {
currentBorrowLimitEth[msg.sender] = collateralBalance[msg.sender].sub(
collateralBalance[msg.sender]
.div(10000)
.mul(collateralRequirementPercent)
.add(collateralUsedEth[msg.sender])
);
}
// ^^^^^^ ACCOUNTING CALCULATION ENDS HERE ^^^^^^^^
// ##### MINTING AND BURNING STARTS HERE #####
// Creates the Land Index Sythetic Token & updates borrow limits.
function mintAsset(uint256 _amount) public {
uint256 tokenPricePerEth = landIndexPrice();
require(
currentBorrowLimitEth[msg.sender].mul(1e18).div(tokenPricePerEth) >=
_amount,
"Reason: Over allowed ammount"
);
calculateCollateralUse(_amount, 0);
dLandIndexToken.mint(msg.sender, _amount);
emit TokensMinted(
msg.sender,
address(dLandIndexToken),
_amount,
tokenPricePerEth
);
}
// Return the Shyntetic asset in order to free the collateral
function burnAsset(uint256 _amount) public {
require(
collateralUsedEth[msg.sender] > 0,
"Reason: No deposit was made."
);
// Re-calculating the collateral usage.
calculateCollateralUse(0, _amount);
dLandIndexToken.burnFrom(msg.sender, _amount);
emit TokensBurned(msg.sender, address(dLandIndexToken), _amount);
}
// ^^^^^ MINTING AND BURNING STARTS HERE ^^^^^^^
// ##### COLLATERAL DEPOSITS AND WITHDRAWS START HERE #####
// User sends ETH as collateral though this function.
function collateralizeEth() public payable {
// We set his balance and borrow limit.
calculateCollateralBalance(msg.value, 0);
// We re-direct the deposit to Compound Protocol.
ICompProxy(compAddress).mint{value: msg.value}();
// We get the new balance total of Comp on our smart contract.
uint256 cETHNewBalance =
ICompProxy(compAddress).balanceOf(address(this));
// Connect the amount that belongs to user with his wallet address.
cETH[msg.sender] = cETHNewBalance.sub(cETHCurrentBalance);
// We replace the last balance with the new balance.
cETHCurrentBalance = cETHNewBalance;
}
function prepWithdraw(uint256 _amount) private {
// Calculate the portion of the withdraw.
uint256 withdrawPortion = _amount;
// Redeem and substract from CETH Balance of user.
cETH[msg.sender] = cETH[msg.sender].sub(withdrawPortion);
// Reduce total balance of CETH
cETHCurrentBalance = cETHCurrentBalance.sub(withdrawPortion);
// Send redeem request to COMP
ICompProxy(compAddress).redeem(_amount);
}
function withdrawCollateral(uint256 _amount) public {
// Requare that has made deposits he wants to withdraw & Requare that user is withdrawing less than locked up collateral.
require(
_amount <=
collateralBalance[msg.sender].sub(
collateralUsedEth[msg.sender].mul(10000).div(
10000 - collateralRequirementPercent
)
),
"Reason: Exeeds allowed"
);
// Calculate the portion of the withdraw.
uint256 withdrawpercent =
_amount.mul(1e18).div(collateralBalance[msg.sender]);
uint256 withdrawPortion =
cETH[msg.sender].mul(withdrawpercent).div(1e18);
prepWithdraw(withdrawPortion);
require(
address(this).balance >= _amount,
"Reason: Protocol out of ETH "
);
// Calculate the withdraw balance to avoid reentrancy attack.
calculateCollateralBalance(0, _amount);
// Return ETH to user.
payable(msg.sender).transfer(_amount);
// Emit an eventx
emit EthUncollaterased(msg.sender, _amount);
}
// ^^^^^^^ COLLATERAL DEPOSITS AND WITHDRAWS END HERE ^^^^^^^^^^
// ##### TOKEN BUYBACK AND BURN START HERE #####
// Contract owner can do a buyback and token Burn.
function buyBackAndBurn() external payable onlyOwner {
address[] memory path = new address[](2);
path[0] = uniswap.WETH();
path[1] = address(protocolToken);
uint256 ethBalance = address(this).balance;
// Calling UNISWAP to buy back Protocol Tokens
uniswap.swapExactETHForTokens{value: ethBalance}(
1,
path,
address(this),
block.timestamp
);
// Adding to the balance how much tokens have we burned.
tokenBurnBalance =
tokenBurnBalance +
protocolToken.balanceOf(address(this));
// Burning the Tokens.
protocolToken.burn(protocolToken.balanceOf(address(this)));
}
// ^^^^^^^ TOKEN BUYBACK AND BURN END HERE ^^^^^^^^^^
// Update contract address where the price feed is coming from.
// Most likely a temporary function and will be removed in the future.
function updateOracleAddress(address _address) public onlyOwner {
oracleAddress = _address;
}
}
| Contract owner can do a buyback and token Burn. Calling UNISWAP to buy back Protocol Tokens Adding to the balance how much tokens have we burned. Burning the Tokens. | function buyBackAndBurn() external payable onlyOwner {
address[] memory path = new address[](2);
path[0] = uniswap.WETH();
path[1] = address(protocolToken);
uint256 ethBalance = address(this).balance;
1,
path,
address(this),
block.timestamp
);
tokenBurnBalance =
tokenBurnBalance +
protocolToken.balanceOf(address(this));
protocolToken.burn(protocolToken.balanceOf(address(this)));
}
| 12,920,637 |
./full_match/56/0x7a6698c9eC149894C678B43cD370567220A19FC5/sources/contracts/L1/messaging/L1StandardBridge.sol | Performs the logic for deposits by storing the GCD and informing the L2 GCD Gateway of the deposit. _from Account to pull the deposit from on L1. _to Account to give the deposit to on L2. _l2Gas Gas limit required to complete the deposit on L2. _data Optional data to forward to L2. This data is provided solely as a convenience for external contracts. Aside from enforcing a maximum length, these contracts provide no guarantees about its content./ When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future withdrawals. The use of safeTransferFrom enables support of "broken tokens" which do not return a boolean value. slither-disable-next-line reentrancy-events, reentrancy-benign Construct calldata for finalizeDeposit call Send calldata into L2 slither-disable-next-line reentrancy-events slither-disable-next-line reentrancy-benign slither-disable-next-line reentrancy-events | function _initiateGCDDeposit(
address _from,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes memory _data
) internal {
IERC20(gcd).safeTransferFrom(_from, address(this), _amount);
bytes memory message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
address(0),
Lib_PredeployAddresses.OVM_GCD,
_from,
_to,
_amount,
_data
);
sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);
deposits[gcd][Lib_PredeployAddresses.OVM_GCD] =
deposits[gcd][Lib_PredeployAddresses.OVM_GCD] +
_amount;
emit GCDDepositInitiated(_from, _to, msg.value, _data);
}
| 3,242,107 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IAaveGovernanceV2} from "./interfaces/Aave/IAaveGovernanceV2.sol";
import {IGovernanceStrategy} from "./interfaces/Aave/IGovernanceStrategy.sol";
import "./interfaces/IAavePool.sol";
import "./interfaces/IWrapperToken.sol";
import "./interfaces/Aave/IStakedAave.sol";
import "./interfaces/IERC20Details.sol";
import "./interfaces/IBribeExecutor.sol";
import "./BribePoolBase.sol";
////////////////////////////////////////////////////////////////////////////////////////////
///
/// @title AavePool
/// @author [email protected]
/// @notice
///
////////////////////////////////////////////////////////////////////////////////////////////
contract AavePool is BribePoolBase, IAavePool, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
/// @dev share scale
uint256 private constant SHARE_SCALE = 1e12;
/// @dev maximum claim iterations
uint64 internal constant MAX_CLAIM_ITERATIONS = 10;
/// @dev fee precision
uint64 internal constant FEE_PRECISION = 10000;
/// @dev fee percentage share is 16%
uint128 internal constant FEE_PERCENTAGE = 1600;
/// @dev seconds per block
uint64 internal constant secondPerBlock = 13;
/// @dev aave governance
address public immutable aaveGovernance;
/// @dev bidders will bid with bidAsset e.g. usdc
IERC20 public immutable bidAsset;
/// @dev bribe token
IERC20 public immutable bribeToken;
/// @dev aave token
IERC20 public immutable aaveToken;
/// @dev stkAave token
IERC20 public immutable stkAaveToken;
/// @dev aave wrapper token
IWrapperToken public immutable wrapperAaveToken;
/// @dev stkAave wrapper token
IWrapperToken public immutable wrapperStkAaveToken;
/// @dev feeReceipient address to send received fees to
address public feeReceipient;
/// @dev pending rewards to be distributed
uint128 internal pendingRewardToBeDistributed;
/// @dev fees received
uint128 public feesReceived;
/// @dev asset index
AssetIndex public assetIndex;
/// @dev bribre reward config
BribeReward public bribeRewardConfig;
/// @dev bid id to bid information
mapping(uint256 => Bid) public bids;
/// @dev blocked proposals
mapping(uint256 => bool) public blockedProposals;
/// @dev proposal id to bid information
mapping(uint256 => uint256) internal bidIdToProposalId;
/// @dev user info
mapping(address => UserInfo) internal users;
constructor(
address bribeToken_,
address aaveToken_,
address stkAaveToken_,
address bidAsset_,
address aave_,
address feeReceipient_,
IWrapperToken wrapperAaveToken_,
IWrapperToken wrapperStkAaveToken_,
BribeReward memory rewardConfig_
) BribePoolBase() {
require(bribeToken_ != address(0), "BRIBE_TOKEN");
require(aaveToken_ != address(0), "AAVE_TOKEN");
require(stkAaveToken_ != address(0), "STKAAVE_TOKEN");
require(aave_ != address(0), "AAVE_GOVERNANCE");
require(address(bidAsset_) != address(0), "BID_ASSET");
require(feeReceipient_ != address(0), "FEE_RECEIPIENT");
require(address(wrapperAaveToken_) != address(0), "AAVE_WRAPPER");
require(address(wrapperStkAaveToken_) != address(0), "STK_WRAPPER");
bribeToken = IERC20(bribeToken_);
aaveToken = IERC20(aaveToken_);
stkAaveToken = IERC20(stkAaveToken_);
aaveGovernance = aave_;
bidAsset = IERC20(bidAsset_);
bribeRewardConfig = rewardConfig_;
feeReceipient = feeReceipient_;
// initialize wrapper tokens
wrapperAaveToken_.initialize(aaveToken_);
wrapperStkAaveToken_.initialize(stkAaveToken_);
wrapperAaveToken = wrapperAaveToken_;
wrapperStkAaveToken = wrapperStkAaveToken_;
}
/// @notice deposit
/// @param asset either Aave or stkAave
/// @param recipient address to mint the receipt tokens
/// @param amount amount of tokens to deposit
/// @param claim claim stk aave rewards from Aave
function deposit(
IERC20 asset,
address recipient,
uint128 amount,
bool claim
) external override whenNotPaused nonReentrant {
if (asset == aaveToken) {
_deposit(asset, wrapperAaveToken, recipient, amount, claim);
} else {
_deposit(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim);
}
}
/// @notice withdraw
/// @param asset either Aave or stkAave
/// @param recipient address to mint the receipt tokens
/// @param amount amount of tokens to deposit
/// @param claim claim stk aave rewards from Aave
function withdraw(
IERC20 asset,
address recipient,
uint128 amount,
bool claim
) external override nonReentrant {
if (asset == aaveToken) {
_withdraw(asset, wrapperAaveToken, recipient, amount, claim);
} else {
_withdraw(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim);
}
}
/// @dev vote to `proposalId` with `support` option
/// @param proposalId proposal id
function vote(uint256 proposalId) external nonReentrant {
Bid storage currentBid = bids[proposalId];
require(currentBid.endTime > 0, "INVALID_PROPOSAL");
require(currentBid.endTime < block.timestamp, "BID_ACTIVE");
distributeRewards(proposalId);
IAaveGovernanceV2(aaveGovernance).submitVote(proposalId, currentBid.support);
emit Vote(proposalId, msg.sender, currentBid.support, block.timestamp);
}
/// @dev place a bid after check AaveGovernance status
/// @param bidder bidder address
/// @param proposalId proposal id
/// @param amount amount of bid assets
/// @param support the suport for the proposal
function bid(
address bidder,
uint256 proposalId,
uint128 amount,
bool support
) external override whenNotPaused nonReentrant {
IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState(
proposalId
);
require(
state == IAaveGovernanceV2.ProposalState.Pending ||
state == IAaveGovernanceV2.ProposalState.Active,
"INVALID_PROPOSAL_STATE"
);
require(blockedProposals[proposalId] == false, "PROPOSAL_BLOCKED");
Bid storage currentBid = bids[proposalId];
address prevHighestBidder = currentBid.highestBidder;
uint128 currentHighestBid = currentBid.highestBid;
uint128 newHighestBid;
// new bid
if (prevHighestBidder == address(0)) {
uint64 endTime = uint64(_getAuctionExpiration(proposalId));
currentBid.endTime = endTime;
currentBid.totalVotes = votingPower(proposalId);
currentBid.proposalStartBlock = IAaveGovernanceV2(aaveGovernance)
.getProposalById(proposalId)
.startBlock;
}
require(currentBid.endTime > block.timestamp, "BID_ENDED");
require(currentBid.totalVotes > 0, "INVALID_VOTING_POWER");
// if bidder == currentHighestBidder increase the bid amount
if (prevHighestBidder == bidder) {
bidAsset.safeTransferFrom(msg.sender, address(this), amount);
newHighestBid = currentHighestBid + amount;
} else {
require(amount > currentHighestBid, "LOW_BID");
bidAsset.safeTransferFrom(msg.sender, address(this), amount);
// refund to previous highest bidder
if (prevHighestBidder != address(0)) {
pendingRewardToBeDistributed -= currentHighestBid;
bidAsset.safeTransfer(prevHighestBidder, currentHighestBid);
}
newHighestBid = amount;
}
// write the new bid info to storage
pendingRewardToBeDistributed += amount;
currentBid.highestBid = newHighestBid;
currentBid.support = support;
currentBid.highestBidder = bidder;
emit HighestBidIncreased(
proposalId,
prevHighestBidder,
bidder,
msg.sender,
newHighestBid,
support
);
}
/// @dev refund bid for a cancelled proposal ONLY if it was not voted on
/// @param proposalId proposal id
function refund(uint256 proposalId) external nonReentrant {
IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState(
proposalId
);
require(state == IAaveGovernanceV2.ProposalState.Canceled, "PROPOSAL_ACTIVE");
Bid storage currentBid = bids[proposalId];
uint128 highestBid = currentBid.highestBid;
address highestBidder = currentBid.highestBidder;
// we do not refund if no high bid or if the proposal has been voted on
if (highestBid == 0 || currentBid.voted) return;
// reset the bid proposal state
delete bids[proposalId];
// refund the bid money
pendingRewardToBeDistributed -= highestBid;
bidAsset.safeTransfer(highestBidder, highestBid);
emit Refund(proposalId, highestBidder, highestBid);
}
/// @dev distribute rewards for the proposal
/// @notice called in children's vote function (after bidding process ended)
/// @param proposalId id of proposal to distribute rewards fo
function distributeRewards(uint256 proposalId) public {
Bid storage currentBid = bids[proposalId];
// ensure that the bidding period has ended
require(block.timestamp > currentBid.endTime, "BID_ACTIVE");
if (currentBid.voted) return;
uint128 highestBid = currentBid.highestBid;
uint128 feeAmount = _calculateFeeAmount(highestBid);
// reduce pending reward
pendingRewardToBeDistributed -= highestBid;
assetIndex.bidIndex += (highestBid - feeAmount);
feesReceived += feeAmount;
currentBid.voted = true;
// rewrite the highest bid minus fee
// set and increase the bid id
bidIdToProposalId[assetIndex.bidId] = proposalId;
assetIndex.bidId += 1;
emit RewardDistributed(proposalId, highestBid);
}
/// @dev withdrawFees withdraw fees
/// Enables ONLY the fee receipient to withdraw the pool accrued fees
function withdrawFees() external override nonReentrant returns (uint256 feeAmount) {
require(msg.sender == feeReceipient, "ONLY_RECEIPIENT");
feeAmount = feesReceived;
if (feeAmount > 0) {
feesReceived = 0;
bidAsset.safeTransfer(feeReceipient, feeAmount);
}
emit WithdrawFees(address(this), feeAmount, block.timestamp);
}
/// @dev get reward amount for user specified by `user`
/// @param user address of user to check balance of
function rewardBalanceOf(address user)
external
view
returns (
uint256 totalPendingBidReward,
uint256 totalPendingStkAaveReward,
uint256 totalPendingBribeReward
)
{
uint256 userAaveBalance = wrapperAaveToken.balanceOf(user);
uint256 userStkAaveBalance = wrapperStkAaveToken.balanceOf(user);
uint256 pendingBribeReward = _userPendingBribeReward(
userAaveBalance + userStkAaveBalance,
users[user].bribeLastRewardPerShare,
_calculateBribeRewardPerShare(_calculateBribeRewardIndex())
);
uint256 pendingBidReward;
uint256 currentBidRewardCount = assetIndex.bidId;
if (userAaveBalance > 0) {
pendingBidReward += _calculateUserPendingBidRewards(
wrapperAaveToken,
user,
users[user].aaveLastBidId,
currentBidRewardCount
);
}
if (userStkAaveBalance > 0) {
pendingBidReward += _calculateUserPendingBidRewards(
wrapperStkAaveToken,
user,
users[user].stkAaveLastBidId,
currentBidRewardCount
);
}
totalPendingBidReward = users[user].totalPendingBidReward + pendingBidReward;
(uint128 rewardsToReceive, ) = _stkAaveRewardsToReceive();
totalPendingStkAaveReward =
users[user].totalPendingStkAaveReward +
_userPendingstkAaveRewards(
user,
users[user].stkAaveLastRewardPerShare,
_calculateStkAaveRewardPerShare(rewardsToReceive),
wrapperStkAaveToken
);
totalPendingBribeReward = users[user].totalPendingBribeReward + pendingBribeReward;
}
/// @dev claimReward for msg.sender
/// @param to address to send the rewards to
/// @param executor An external contract to call with
/// @param data data to call the executor contract
/// @param claim claim stk aave rewards from Aave
function claimReward(
address to,
IBribeExecutor executor,
bytes calldata data,
bool claim
) external whenNotPaused nonReentrant {
// accrue rewards for both stkAave and Aave token balances
_accrueRewards(msg.sender, claim);
UserInfo storage _currentUser = users[msg.sender];
uint128 pendingBid = _currentUser.totalPendingBidReward;
uint128 pendingStkAaveReward = _currentUser.totalPendingStkAaveReward;
uint128 pendingBribeReward = _currentUser.totalPendingBribeReward;
unchecked {
// reset the reward calculation
_currentUser.totalPendingBidReward = 0;
_currentUser.totalPendingStkAaveReward = 0;
// update lastStkAaveRewardBalance
assetIndex.lastStkAaveRewardBalance -= pendingStkAaveReward;
}
if (pendingBid > 0) {
bidAsset.safeTransfer(to, pendingBid);
}
if (pendingStkAaveReward > 0 && claim) {
// claim stk aave rewards
IStakedAave(address(stkAaveToken)).claimRewards(to, pendingStkAaveReward);
}
if (pendingBribeReward > 0 && bribeToken.balanceOf(address(this)) > pendingBribeReward) {
_currentUser.totalPendingBribeReward = 0;
if (address(executor) != address(0)) {
bribeToken.safeTransfer(address(executor), pendingBribeReward);
executor.execute(msg.sender, pendingBribeReward, data);
} else {
require(to != address(0), "INVALID_ADDRESS");
bribeToken.safeTransfer(to, pendingBribeReward);
}
}
emit RewardClaim(
msg.sender,
pendingBid,
pendingStkAaveReward,
pendingBribeReward,
block.timestamp
);
}
/// @dev block a proposalId from used in the pool
/// @param proposalId proposalId
function blockProposalId(uint256 proposalId) external onlyOwner {
require(blockedProposals[proposalId] == false, "PROPOSAL_INACTIVE");
Bid storage currentBid = bids[proposalId];
// check if the propoal has already been voted on
require(currentBid.voted == false, "BID_DISTRIBUTED");
blockedProposals[proposalId] = true;
uint128 highestBid = currentBid.highestBid;
// check if the proposalId has any bids
// if there is any current highest bidder
// and the reward has not been distributed refund the bidder
if (highestBid > 0) {
pendingRewardToBeDistributed -= highestBid;
address highestBidder = currentBid.highestBidder;
// reset the bids
delete bids[proposalId];
bidAsset.safeTransfer(highestBidder, highestBid);
}
emit BlockProposalId(proposalId, block.timestamp);
}
/// @dev unblock a proposalId from used in the pool
/// @param proposalId proposalId
function unblockProposalId(uint256 proposalId) external onlyOwner {
require(blockedProposals[proposalId] == true, "PROPOSAL_ACTIVE");
blockedProposals[proposalId] = false;
emit UnblockProposalId(proposalId, block.timestamp);
}
/// @dev returns the pool voting power for a proposal
/// @param proposalId proposalId to fetch pool voting power
function votingPower(uint256 proposalId) public view returns (uint256 power) {
IAaveGovernanceV2.ProposalWithoutVotes memory proposal = IAaveGovernanceV2(aaveGovernance)
.getProposalById(proposalId);
address governanceStrategy = IAaveGovernanceV2(aaveGovernance).getGovernanceStrategy();
power = IGovernanceStrategy(governanceStrategy).getVotingPowerAt(
address(this),
proposal.startBlock
);
}
/// @dev getPendingRewardToBeDistributed returns the pending reward to be distributed
/// minus fees
function getPendingRewardToBeDistributed() external view returns (uint256 pendingReward) {
pendingReward =
pendingRewardToBeDistributed -
_calculateFeeAmount(pendingRewardToBeDistributed);
}
/// @notice pause pool actions
function pause() external onlyOwner {
_pause();
}
/// @notice unpause pool actions
function unpause() external onlyOwner {
_unpause();
}
/// @notice setFeeRecipient
/// @param newReceipient new fee receipeitn
function setFeeRecipient(address newReceipient) external onlyOwner {
require(newReceipient != address(0), "INVALID_RECIPIENT");
feeReceipient = newReceipient;
emit UpdateFeeRecipient(address(this), newReceipient);
}
/// @notice setStartTimestamp
/// @param startTimestamp when to start distributing rewards
/// @param rewardPerSecond reward to distribute per second
function setStartTimestamp(uint64 startTimestamp, uint128 rewardPerSecond) external onlyOwner {
require(startTimestamp > block.timestamp, "INVALID_START_TIMESTAMP");
if (bribeRewardConfig.endTimestamp != 0) {
require(startTimestamp < bribeRewardConfig.endTimestamp, "HIGH_TIMESTAMP");
}
_updateBribeRewardIndex();
uint64 oldTimestamp = bribeRewardConfig.startTimestamp;
bribeRewardConfig.startTimestamp = startTimestamp;
_setRewardPerSecond(rewardPerSecond);
emit SetBribeRewardStartTimestamp(oldTimestamp, startTimestamp);
}
/// @notice setEndTimestamp
/// @param endTimestamp end of bribe rewards
function setEndTimestamp(uint64 endTimestamp) external onlyOwner {
require(endTimestamp > block.timestamp, "INVALID_END_TIMESTAMP");
require(endTimestamp > bribeRewardConfig.startTimestamp, "LOW_TIMESTAMP");
_updateBribeRewardIndex();
uint64 oldTimestamp = bribeRewardConfig.endTimestamp;
bribeRewardConfig.endTimestamp = endTimestamp;
emit SetBribeRewardEndTimestamp(oldTimestamp, endTimestamp);
}
/// @notice setEndTimestamp
/// @param rewardPerSecond amount of rewards to distribute per second
function setRewardPerSecond(uint128 rewardPerSecond) public onlyOwner {
_updateBribeRewardIndex();
_setRewardPerSecond(rewardPerSecond);
}
function _setRewardPerSecond(uint128 rewardPerSecond) internal {
require(rewardPerSecond > 0, "INVALID_REWARD_SECOND");
uint128 oldReward = bribeRewardConfig.rewardAmountDistributedPerSecond;
bribeRewardConfig.rewardAmountDistributedPerSecond = rewardPerSecond;
emit SetBribeRewardPerSecond(oldReward, rewardPerSecond);
}
/// @notice withdrawRemainingBribeReward
/// @dev there is a 30 days window period after endTimestamp where a user can claim
/// rewards before it can be reclaimed by Bribe
function withdrawRemainingBribeReward() external onlyOwner {
require(bribeRewardConfig.endTimestamp != 0, "INVALID_END_TIMESTAMP");
require(block.timestamp > bribeRewardConfig.endTimestamp + 30 days, "GRACE_PERIOD");
uint256 remaining = bribeToken.balanceOf(address(this));
bribeToken.safeTransfer(address(this), remaining);
emit WithdrawRemainingReward(remaining);
}
/// @dev _calculateFeeAmount calculate the fee percentage share
function _calculateFeeAmount(uint128 amount) internal pure returns (uint128 feeAmount) {
feeAmount = (amount * FEE_PERCENTAGE) / FEE_PRECISION;
}
struct NewUserRewardInfoLocalVars {
uint256 pendingBidReward;
uint256 pendingstkAaveReward;
uint256 pendingBribeReward;
uint256 newUserAaveBidId;
uint256 newUserStAaveBidId;
}
/// @dev _accrueRewards accrue rewards for an address
/// @param user address to accrue rewards for
/// @param claim claim pending stk aave rewards
function _accrueRewards(address user, bool claim) internal {
require(user != address(0), "INVALID_ADDRESS");
UserInfo storage _user = users[user];
NewUserRewardInfoLocalVars memory userRewardVars;
uint256 userAaveBalance = wrapperAaveToken.balanceOf(user);
uint256 userStkAaveBalance = wrapperStkAaveToken.balanceOf(user);
uint256 total = userAaveBalance + userStkAaveBalance;
// update bribe reward index
_updateBribeRewardIndex();
if (total > 0) {
// calculate updated bribe rewards
userRewardVars.pendingBribeReward = _userPendingBribeReward(
total,
_user.bribeLastRewardPerShare,
assetIndex.bribeRewardPerShare
);
}
if (userAaveBalance > 0) {
// calculate pendingBidRewards
uint256 reward;
(userRewardVars.newUserAaveBidId, reward) = _userPendingBidRewards(
assetIndex.bidIndex,
wrapperAaveToken,
user,
users[user].aaveLastBidId
);
userRewardVars.pendingBidReward += reward;
}
if (claim) {
_updateStkAaveStakeReward();
}
if (userStkAaveBalance > 0) {
// calculate pendingBidRewards
uint256 reward;
(userRewardVars.newUserStAaveBidId, reward) = _userPendingBidRewards(
assetIndex.bidIndex,
wrapperStkAaveToken,
user,
users[user].stkAaveLastBidId
);
userRewardVars.pendingBidReward += reward;
// distribute stkAaveTokenRewards to the user too
userRewardVars.pendingstkAaveReward = _userPendingstkAaveRewards(
user,
users[user].stkAaveLastRewardPerShare,
assetIndex.stkAaveRewardPerShare,
wrapperStkAaveToken
);
}
// write to storage
_user.totalPendingBribeReward += userRewardVars.pendingBribeReward.toUint128();
_user.totalPendingBidReward += userRewardVars.pendingBidReward.toUint128();
_user.totalPendingStkAaveReward += userRewardVars.pendingstkAaveReward.toUint128();
_user.stkAaveLastRewardPerShare = assetIndex.stkAaveRewardPerShare;
_user.bribeLastRewardPerShare = assetIndex.bribeRewardPerShare;
_user.aaveLastBidId = userRewardVars.newUserAaveBidId.toUint128();
_user.stkAaveLastBidId = userRewardVars.newUserStAaveBidId.toUint128();
emit RewardAccrue(
user,
userRewardVars.pendingBidReward,
userRewardVars.pendingstkAaveReward,
userRewardVars.pendingBribeReward,
block.timestamp
);
}
/// @dev deposit governance token
/// @param asset asset to withdraw
/// @param receiptToken asset wrapper token
/// @param recipient address to award the receipt tokens
/// @param amount amount to deposit
/// @param claim claim pending stk aave rewards
/// @notice emit {Deposit} event
function _deposit(
IERC20 asset,
IWrapperToken receiptToken,
address recipient,
uint128 amount,
bool claim
) internal {
require(amount > 0, "INVALID_AMOUNT");
// accrue user pending rewards
_accrueRewards(recipient, claim);
asset.safeTransferFrom(msg.sender, address(this), amount);
// performs check that recipient != address(0)
receiptToken.mint(recipient, amount);
emit Deposit(asset, recipient, amount, block.timestamp);
}
/// @dev withdraw governance token
/// @param asset asset to withdraw
/// @param receiptToken asset wrapper token
/// @param recipient address to award the receipt tokens
/// @param amount amount to withdraw
/// @param claim claim pending stk aave rewards
function _withdraw(
IERC20 asset,
IWrapperToken receiptToken,
address recipient,
uint128 amount,
bool claim
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(receiptToken.balanceOf(msg.sender) >= amount, "INVALID_BALANCE");
// claim pending bid rewards only
_accrueRewards(msg.sender, claim);
// burn tokens
receiptToken.burn(msg.sender, amount);
// send back tokens
asset.safeTransfer(recipient, amount);
emit Withdraw(asset, msg.sender, amount, block.timestamp);
}
/// @dev _calculateBribeRewardIndex
function _calculateBribeRewardIndex() internal view returns (uint256 amount) {
if (
bribeRewardConfig.startTimestamp == 0 ||
bribeRewardConfig.startTimestamp > block.timestamp
) return 0;
uint64 startTimestamp = (bribeRewardConfig.startTimestamp >
assetIndex.bribeLastRewardTimestamp)
? bribeRewardConfig.startTimestamp
: assetIndex.bribeLastRewardTimestamp;
uint256 endTimestamp;
if (bribeRewardConfig.endTimestamp == 0) {
endTimestamp = block.timestamp;
} else {
endTimestamp = block.timestamp > bribeRewardConfig.endTimestamp
? bribeRewardConfig.endTimestamp
: block.timestamp;
}
if (endTimestamp > startTimestamp) {
amount =
(endTimestamp - startTimestamp) *
bribeRewardConfig.rewardAmountDistributedPerSecond;
}
}
/// @dev _updateBribeRewardIndex
function _updateBribeRewardIndex() internal {
uint256 newRewardAmount = _calculateBribeRewardIndex();
assetIndex.bribeLastRewardTimestamp = block.timestamp.toUint64();
assetIndex.bribeRewardIndex += newRewardAmount.toUint128();
assetIndex.bribeRewardPerShare = _calculateBribeRewardPerShare(newRewardAmount).toUint128();
emit AssetReward(bribeToken, assetIndex.bribeRewardIndex, block.timestamp);
}
/// @dev _calculateBribeRewardPerShare
/// @param newRewardAmount additional reward
function _calculateBribeRewardPerShare(uint256 newRewardAmount)
internal
view
returns (uint256 newBribeRewardPerShare)
{
uint256 increaseSharePrice;
if (newRewardAmount > 0) {
increaseSharePrice = ((newRewardAmount * SHARE_SCALE) / _totalSupply());
}
newBribeRewardPerShare = assetIndex.bribeRewardPerShare + increaseSharePrice;
}
/// @dev _userPendingBribeReward
/// @param userBalance user aave + stkAave balance
/// @param userLastPricePerShare user last price per share
/// @param currentBribeRewardPerShare current reward per share
function _userPendingBribeReward(
uint256 userBalance,
uint256 userLastPricePerShare,
uint256 currentBribeRewardPerShare
) internal pure returns (uint256 pendingReward) {
if (userBalance > 0 && currentBribeRewardPerShare > 0) {
pendingReward = ((userBalance * (currentBribeRewardPerShare - userLastPricePerShare)) /
SHARE_SCALE).toUint128();
}
}
/// @dev _totalSupply current total supply of tokens
function _totalSupply() internal view returns (uint256) {
return wrapperAaveToken.totalSupply() + wrapperStkAaveToken.totalSupply();
}
/// @dev returns the user bid reward share
/// @param receiptToken wrapper token
/// @param user user
/// @param userLastBidId user last bid id
function _userPendingBidRewards(
uint128 currentBidIndex,
IWrapperToken receiptToken,
address user,
uint128 userLastBidId
) internal view returns (uint256 accrueBidId, uint256 totalPendingReward) {
if (currentBidIndex == 0) return (0, 0);
uint256 currentBidRewardCount = assetIndex.bidId;
if (userLastBidId == currentBidRewardCount) return (currentBidRewardCount, 0);
accrueBidId = (currentBidRewardCount - userLastBidId) <= MAX_CLAIM_ITERATIONS
? currentBidRewardCount
: userLastBidId + MAX_CLAIM_ITERATIONS;
totalPendingReward = _calculateUserPendingBidRewards(
receiptToken,
user,
userLastBidId,
accrueBidId
);
}
/// @dev _calculateUserPendingBidRewards
/// @param receiptToken wrapper token
/// @param user user
/// @param userLastBidId user last bid id
/// @param maxRewardId maximum bid id to accrue rewards to
function _calculateUserPendingBidRewards(
IWrapperToken receiptToken,
address user,
uint256 userLastBidId,
uint256 maxRewardId
) internal view returns (uint256 totalPendingReward) {
for (uint256 i = userLastBidId; i < maxRewardId; i++) {
uint256 proposalId = bidIdToProposalId[i];
Bid storage _bid = bids[proposalId];
uint128 highestBid = _bid.highestBid;
// only calculate if highest bid is available and it has been distributed
if (highestBid > 0 && _bid.voted) {
uint256 amount = receiptToken.getDepositAt(user, _bid.proposalStartBlock);
if (amount > 0) {
// subtract fee from highest bid
totalPendingReward +=
(amount * (highestBid - _calculateFeeAmount(highestBid))) /
_bid.totalVotes;
}
}
}
}
/// @dev update the stkAAve aave reward index
function _updateStkAaveStakeReward() internal {
(uint128 rewardsToReceive, uint256 newBalance) = _stkAaveRewardsToReceive();
if (rewardsToReceive == 0) return;
assetIndex.rewardIndex += rewardsToReceive;
assetIndex.stkAaveRewardPerShare = _calculateStkAaveRewardPerShare(rewardsToReceive);
assetIndex.lastStkAaveRewardBalance = newBalance;
emit AssetReward(aaveToken, assetIndex.rewardIndex, block.timestamp);
}
/// @dev _calculateStkAaveRewardPerShare
/// @param rewardsToReceive amount of aave rewards to receive
function _calculateStkAaveRewardPerShare(uint256 rewardsToReceive)
internal
view
returns (uint128 newRewardPerShare)
{
uint256 increaseRewardSharePrice;
if (rewardsToReceive > 0) {
increaseRewardSharePrice = ((rewardsToReceive * SHARE_SCALE) /
wrapperStkAaveToken.totalSupply());
}
newRewardPerShare = (assetIndex.stkAaveRewardPerShare + increaseRewardSharePrice)
.toUint128();
}
/// @dev _stkAaveRewardsToReceive
function _stkAaveRewardsToReceive()
internal
view
returns (uint128 rewardsToReceive, uint256 newBalance)
{
newBalance = IStakedAave(address(stkAaveToken)).getTotalRewardsBalance(address(this));
rewardsToReceive = newBalance.toUint128() - assetIndex.lastStkAaveRewardBalance.toUint128();
}
/// @dev get the user stkAave aave reward share
/// @param user user address
/// @param userLastPricePerShare userLastPricePerShare
/// @param currentStkAaveRewardPerShare the latest reward per share
/// @param receiptToken stak aave wrapper token
function _userPendingstkAaveRewards(
address user,
uint128 userLastPricePerShare,
uint128 currentStkAaveRewardPerShare,
IWrapperToken receiptToken
) internal view returns (uint256 pendingReward) {
uint256 userBalance = receiptToken.balanceOf(user);
if (userBalance > 0 && currentStkAaveRewardPerShare > 0) {
uint128 rewardDebt = ((userBalance * userLastPricePerShare) / SHARE_SCALE).toUint128();
pendingReward = (((userBalance * currentStkAaveRewardPerShare) / SHARE_SCALE) -
rewardDebt).toUint128();
}
}
/// @dev get auction expiration of `proposalId`
/// @param proposalId proposal id
function _getAuctionExpiration(uint256 proposalId) internal view returns (uint256) {
IAaveGovernanceV2.ProposalWithoutVotes memory proposal = IAaveGovernanceV2(aaveGovernance)
.getProposalById(proposalId);
return block.timestamp + (proposal.endBlock - block.number) * secondPerBlock - 1 hours;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
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));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
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));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^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() {
_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 making 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;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
import {IExecutorWithTimelock} from "./IExecutorWithTimelock.sol";
interface IAaveGovernanceV2 {
enum ProposalState {
Pending,
Canceled,
Active,
Failed,
Succeeded,
Queued,
Expired,
Executed
}
struct Vote {
bool support;
uint248 votingPower;
}
struct Proposal {
uint256 id;
address creator;
IExecutorWithTimelock executor;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
uint256 startBlock;
uint256 endBlock;
uint256 executionTime;
uint256 forVotes;
uint256 againstVotes;
bool executed;
bool canceled;
address strategy;
bytes32 ipfsHash;
mapping(address => Vote) votes;
}
struct ProposalWithoutVotes {
uint256 id;
address creator;
IExecutorWithTimelock executor;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
uint256 startBlock;
uint256 endBlock;
uint256 executionTime;
uint256 forVotes;
uint256 againstVotes;
bool executed;
bool canceled;
address strategy;
bytes32 ipfsHash;
}
/**
* @dev emitted when a new proposal is created
* @param id Id of the proposal
* @param creator address of the creator
* @param executor The ExecutorWithTimelock contract that will execute the proposal
* @param targets list of contracts called by proposal's associated transactions
* @param values list of value in wei for each propoposal's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
* @param startBlock block number when vote starts
* @param endBlock block number when vote ends
* @param strategy address of the governanceStrategy contract
* @param ipfsHash IPFS hash of the proposal
**/
event ProposalCreated(
uint256 id,
address indexed creator,
IExecutorWithTimelock indexed executor,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
bool[] withDelegatecalls,
uint256 startBlock,
uint256 endBlock,
address strategy,
bytes32 ipfsHash
);
/**
* @dev emitted when a proposal is canceled
* @param id Id of the proposal
**/
event ProposalCanceled(uint256 id);
/**
* @dev emitted when a proposal is queued
* @param id Id of the proposal
* @param executionTime time when proposal underlying transactions can be executed
* @param initiatorQueueing address of the initiator of the queuing transaction
**/
event ProposalQueued(uint256 id, uint256 executionTime, address indexed initiatorQueueing);
/**
* @dev emitted when a proposal is executed
* @param id Id of the proposal
* @param initiatorExecution address of the initiator of the execution transaction
**/
event ProposalExecuted(uint256 id, address indexed initiatorExecution);
/**
* @dev emitted when a vote is registered
* @param id Id of the proposal
* @param voter address of the voter
* @param support boolean, true = vote for, false = vote against
* @param votingPower Power of the voter/vote
**/
event VoteEmitted(uint256 id, address indexed voter, bool support, uint256 votingPower);
event GovernanceStrategyChanged(address indexed newStrategy, address indexed initiatorChange);
event VotingDelayChanged(uint256 newVotingDelay, address indexed initiatorChange);
event ExecutorAuthorized(address executor);
event ExecutorUnauthorized(address executor);
/**
* @dev Creates a Proposal (needs Proposition Power of creator > Threshold)
* @param executor The ExecutorWithTimelock contract that will execute the proposal
* @param targets list of contracts called by proposal's associated transactions
* @param values list of value in wei for each propoposal's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls if true, transaction delegatecalls the taget, else calls the target
* @param ipfsHash IPFS hash of the proposal
**/
function create(
IExecutorWithTimelock executor,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls,
bytes32 ipfsHash
) external returns (uint256);
/**
* @dev Cancels a Proposal,
* either at anytime by guardian
* or when proposal is Pending/Active and threshold no longer reached
* @param proposalId id of the proposal
**/
function cancel(uint256 proposalId) external;
/**
* @dev Queue the proposal (If Proposal Succeeded)
* @param proposalId id of the proposal to queue
**/
function queue(uint256 proposalId) external;
/**
* @dev Execute the proposal (If Proposal Queued)
* @param proposalId id of the proposal to execute
**/
function execute(uint256 proposalId) external payable;
/**
* @dev Function allowing msg.sender to vote for/against a proposal
* @param proposalId id of the proposal
* @param support boolean, true = vote for, false = vote against
**/
function submitVote(uint256 proposalId, bool support) external;
/**
* @dev Function to register the vote of user that has voted offchain via signature
* @param proposalId id of the proposal
* @param support boolean, true = vote for, false = vote against
* @param v v part of the voter signature
* @param r r part of the voter signature
* @param s s part of the voter signature
**/
function submitVoteBySignature(
uint256 proposalId,
bool support,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Set new GovernanceStrategy
* Note: owner should be a timelocked executor, so needs to make a proposal
* @param governanceStrategy new Address of the GovernanceStrategy contract
**/
function setGovernanceStrategy(address governanceStrategy) external;
/**
* @dev Set new Voting Delay (delay before a newly created proposal can be voted on)
* Note: owner should be a timelocked executor, so needs to make a proposal
* @param votingDelay new voting delay in seconds
**/
function setVotingDelay(uint256 votingDelay) external;
/**
* @dev Add new addresses to the list of authorized executors
* @param executors list of new addresses to be authorized executors
**/
function authorizeExecutors(address[] memory executors) external;
/**
* @dev Remove addresses to the list of authorized executors
* @param executors list of addresses to be removed as authorized executors
**/
function unauthorizeExecutors(address[] memory executors) external;
/**
* @dev Let the guardian abdicate from its priviledged rights
**/
function __abdicate() external;
/**
* @dev Getter of the current GovernanceStrategy address
* @return The address of the current GovernanceStrategy contracts
**/
function getGovernanceStrategy() external view returns (address);
/**
* @dev Getter of the current Voting Delay (delay before a created proposal can be voted on)
* Different from the voting duration
* @return The voting delay in seconds
**/
function getVotingDelay() external view returns (uint256);
/**
* @dev Returns whether an address is an authorized executor
* @param executor address to evaluate as authorized executor
* @return true if authorized
**/
function isExecutorAuthorized(address executor) external view returns (bool);
/**
* @dev Getter the address of the guardian, that can mainly cancel proposals
* @return The address of the guardian
**/
function getGuardian() external view returns (address);
/**
* @dev Getter of the proposal count (the current number of proposals ever created)
* @return the proposal count
**/
function getProposalsCount() external view returns (uint256);
/**
* @dev Getter of a proposal by id
* @param proposalId id of the proposal to get
* @return the proposal as ProposalWithoutVotes memory object
**/
function getProposalById(uint256 proposalId)
external
view
returns (ProposalWithoutVotes memory);
/**
* @dev Getter of the Vote of a voter about a proposal
* Note: Vote is a struct: ({bool support, uint248 votingPower})
* @param proposalId id of the proposal
* @param voter address of the voter
* @return The associated Vote memory object
**/
function getVoteOnProposal(uint256 proposalId, address voter)
external
view
returns (Vote memory);
/**
* @dev Get the current state of a proposal
* @param proposalId id of the proposal
* @return The current state if the proposal
**/
function getProposalState(uint256 proposalId) external view returns (ProposalState);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
interface IGovernanceStrategy {
/**
* @dev Returns the Proposition Power of a user at a specific block number.
* @param user Address of the user.
* @param blockNumber Blocknumber at which to fetch Proposition Power
* @return Power number
**/
function getPropositionPowerAt(address user, uint256 blockNumber)
external
view
returns (uint256);
/**
* @dev Returns the total supply of Outstanding Proposition Tokens
* @param blockNumber Blocknumber at which to evaluate
* @return total supply at blockNumber
**/
function getTotalPropositionSupplyAt(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of Outstanding Voting Tokens
* @param blockNumber Blocknumber at which to evaluate
* @return total supply at blockNumber
**/
function getTotalVotingSupplyAt(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the Vote Power of a user at a specific block number.
* @param user Address of the user.
* @param blockNumber Blocknumber at which to fetch Vote Power
* @return Vote number
**/
function getVotingPowerAt(address user, uint256 blockNumber) external view returns (uint256);
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAavePool {
struct AssetIndex {
// tracks the last stkAave aave reward balance
uint256 lastStkAaveRewardBalance;
// tracks the total Aave reward for stkAave holders
uint128 rewardIndex;
// bribe reward index;
uint128 bribeRewardIndex;
// bribe reward last timestamp
uint64 bribeLastRewardTimestamp;
// bid id
uint64 bidId;
// tracks the total bid reward
// share to be distributed
uint128 bidIndex;
// tracks the reward per share
uint128 bribeRewardPerShare;
// tracks the reward per share
uint128 stkAaveRewardPerShare;
}
struct BribeReward {
uint128 rewardAmountDistributedPerSecond;
uint64 startTimestamp;
uint64 endTimestamp;
}
struct UserInfo {
// stkaave reward index
uint128 stkAaveLastRewardPerShare;
// bribe reward index
uint128 bribeLastRewardPerShare;
// reward from the bids in the bribe pool
uint128 totalPendingBidReward;
// tracks aave reward from the stk aave pool
uint128 totalPendingStkAaveReward;
// tracks bribe distributed to the user
uint128 totalPendingBribeReward;
// tracks the last user bid id for aave deposit
uint128 aaveLastBidId;
// tracks the last user bid id for stkAave deposit
uint128 stkAaveLastBidId;
}
/// @dev proposal bid info
struct Bid {
uint256 totalVotes;
uint256 proposalStartBlock;
uint128 highestBid;
uint64 endTime;
bool support;
bool voted;
address highestBidder;
}
/// @dev emitted on deposit
event Deposit(IERC20 indexed token, address indexed user, uint256 amount, uint256 timestamp);
/// @dev emitted on user reward accrue
event AssetReward(IERC20 indexed asset, uint256 totalAmountAccrued, uint256 timestamp);
/// @dev emitted on user reward accrue
event RewardAccrue(
address indexed user,
uint256 pendingBidReward,
uint256 pendingStkAaveReward,
uint256 pendingBribeReward,
uint256 timestamp
);
event Withdraw(IERC20 indexed token, address indexed user, uint256 amount, uint256 timestamp);
event RewardClaim(
address indexed user,
uint256 pendingBid,
uint256 pendingReward,
uint256 pendingBribeReward,
uint256 timestamp
);
event RewardDistributed(uint256 proposalId, uint256 amount);
event HighestBidIncreased(
uint256 indexed proposalId,
address indexed prevHighestBidder,
address indexed highestBidder,
address sender,
uint256 highestBid,
bool support
);
event BlockProposalId(uint256 indexed proposalId, uint256 timestamp);
event UnblockProposalId(uint256 indexed proposalId, uint256 timestamp);
event UpdateDelayPeriod(uint256 delayperiod, uint256 timestamp);
/// @dev emitted on vote
event Vote(uint256 indexed proposalId, address user, bool support, uint256 timestamp);
/// @dev emitted on Refund
event Refund(uint256 indexed proposalId, address bidder, uint256 bidAmount);
/// @dev emitted on Unclaimed rewards
event UnclaimedRewards(address owner, uint256 amount);
/// @dev emitted on setEndTimestamp
event SetBribeRewardEndTimestamp(uint256 oldTimestamp, uint256 endTimestamp);
/// @dev emitted on setRewardPerSecond
event SetBribeRewardPerSecond(uint256 oldRewardPerSecond, uint256 newRewardPerSecond);
/// @dev emitted on withdrawRemainingReward
event WithdrawRemainingReward(uint256 amount);
/// @dev emmitted on setStartTimestamp
event SetBribeRewardStartTimestamp(uint256 oldTimestamp, uint256 endTimestamp);
/// @dev emitted on setFeeRecipient
event UpdateFeeRecipient(address sender, address receipient);
function deposit(
IERC20 asset,
address recipient,
uint128 amount,
bool claim
) external;
function withdraw(
IERC20 asset,
address recipient,
uint128 amount,
bool claim
) external;
function bid(
address bidder,
uint256 proposalId,
uint128 amount,
bool support
) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWrapperToken is IERC20Upgradeable {
function mint(address, uint256) external;
function burn(address, uint256) external;
function getAccountSnapshot(address user)
external
view
returns (uint256[] memory, uint256[] memory);
function getDepositAt(address user, uint256 blockNumber) external view returns (uint256 amount);
function initialize(address underlying_) external;
/// @dev emitted on update account snapshot
event UpdateSnapshot(
address indexed user,
uint256 oldValue,
uint256 newValue,
uint256 timestamp
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStakedAave is IERC20 {
function claimRewards(address to, uint256 amount) external;
function getTotalRewardsBalance(address staker) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IERC20Details {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IBribeExecutor {
function execute(
address user,
uint256 amount,
bytes calldata data
) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "./interfaces/Bribe/IBribeMultiAssetPool.sol";
import "./interfaces/IFeeDistributor.sol";
////////////////////////////////////////////////////////////////////////////////////////////
///
/// @title BribePoolBase
/// @author [email protected]
/// @notice
///
////////////////////////////////////////////////////////////////////////////////////////////
abstract contract BribePoolBase is IBribeMultiAssetPool, IFeeDistributor, Ownable, Multicall {
constructor() Ownable() {}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
// Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20Permit token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^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
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
import {IAaveGovernanceV2} from "./IAaveGovernanceV2.sol";
interface IExecutorWithTimelock {
/**
* @dev emitted when a new pending admin is set
* @param newPendingAdmin address of the new pending admin
**/
event NewPendingAdmin(address newPendingAdmin);
/**
* @dev emitted when a new admin is set
* @param newAdmin address of the new admin
**/
event NewAdmin(address newAdmin);
/**
* @dev emitted when a new delay (between queueing and execution) is set
* @param delay new delay
**/
event NewDelay(uint256 delay);
/**
* @dev emitted when a new (trans)action is Queued.
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
event QueuedAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall
);
/**
* @dev emitted when an action is Cancelled
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
event CancelledAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall
);
/**
* @dev emitted when an action is Cancelled
* @param actionHash hash of the action
* @param target address of the targeted contract
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
* @param resultData the actual callData used on the target
**/
event ExecutedAction(
bytes32 actionHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 executionTime,
bool withDelegatecall,
bytes resultData
);
/**
* @dev Getter of the current admin address (should be governance)
* @return The address of the current admin
**/
function getAdmin() external view returns (address);
/**
* @dev Getter of the current pending admin address
* @return The address of the pending admin
**/
function getPendingAdmin() external view returns (address);
/**
* @dev Getter of the delay between queuing and execution
* @return The delay in seconds
**/
function getDelay() external view returns (uint256);
/**
* @dev Returns whether an action (via actionHash) is queued
* @param actionHash hash of the action to be checked
* keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall))
* @return true if underlying action of actionHash is queued
**/
function isActionQueued(bytes32 actionHash) external view returns (bool);
/**
* @dev Checks whether a proposal is over its grace period
* @param governance Governance contract
* @param proposalId Id of the proposal against which to test
* @return true of proposal is over grace period
**/
function isProposalOverGracePeriod(IAaveGovernanceV2 governance, uint256 proposalId)
external
view
returns (bool);
/**
* @dev Getter of grace period constant
* @return grace period in seconds
**/
function GRACE_PERIOD() external view returns (uint256);
/**
* @dev Getter of minimum delay constant
* @return minimum delay in seconds
**/
function MINIMUM_DELAY() external view returns (uint256);
/**
* @dev Getter of maximum delay constant
* @return maximum delay in seconds
**/
function MAXIMUM_DELAY() external view returns (uint256);
/**
* @dev Function, called by Governance, that queue a transaction, returns action hash
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external returns (bytes32);
/**
* @dev Function, called by Governance, that cancels a transaction, returns the callData executed
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external payable returns (bytes memory);
/**
* @dev Function, called by Governance, that cancels a transaction, returns action hash
* @param target smart contract target
* @param value wei value of the transaction
* @param signature function signature of the transaction
* @param data function arguments of the transaction or callData if signature empty
* @param executionTime time at which to execute the transaction
* @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target
**/
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) external returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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
// OpenZeppelin Contracts v4.4.1 (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./Address.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract Multicall {
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), data[i]);
}
return results;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBribeMultiAssetPool {}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IFeeDistributor {
////
/// fee distribution interface to be implemented
/// by all pools so that they conform to the
/// fee Distributor implementation
///
event WithdrawFees(address indexed sender, uint256 feesReceived, uint256 timestamp);
function withdrawFees() external returns (uint256 feeAmount);
}
| SPDX-License-Identifier: MIT | interface IERC20Details {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
| 6,395,290 |
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Crowdsale.sol";
import "./KYC.sol";
contract MyTokenSale is Crowdsale {
KYC kyc;
constructor(
uint256 rate, // rate in TKNbits
address payable wallet,
IERC20 token,
KYC _kyc
) public Crowdsale(rate, wallet, token) {
kyc = _kyc;
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view override {
super._preValidatePurchase(beneficiary, weiAmount);
require(kyc.kycCompleted(msg.sender), "KYC not completed, purchase not allowed");
}
}
| Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. Example from CappedCrowdsale.sol's _preValidatePurchase method: super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= cap); beneficiary Address performing the token purchase weiAmount Value in wei involved in the purchase/ | function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view override {
super._preValidatePurchase(beneficiary, weiAmount);
require(kyc.kycCompleted(msg.sender), "KYC not completed, purchase not allowed");
}
| 15,843,214 |
./full_match/1/0x5349E94435Cc9Cab9FfB40A492DA46935052733A/sources/cache/solpp-generated-contracts/zksync/Plonk4VerifierWithAccessToDNext.sol | a^2 - b = 0 t.mul_assign(challenge1); b^2 - c = 0 ca - d = 0; | function rescue_custom_gate_linearization_contribution(
VerificationKey memory vk,
Proof memory proof,
PartialVerifierState memory state
) public view returns (PairingsBn254.G1Point memory result) {
PairingsBn254.Fr memory t;
PairingsBn254.Fr memory intermediate_result;
t = proof.state_polys_openings_at_z[0].copy();
t.mul_assign(t);
t.sub_assign(proof.state_polys_openings_at_z[1]);
t.mul_assign(state.alpha_values[1]);
intermediate_result.add_assign(t);
t = proof.state_polys_openings_at_z[1].copy();
t.mul_assign(t);
t.sub_assign(proof.state_polys_openings_at_z[2]);
t.mul_assign(state.alpha_values[1 + 1]);
intermediate_result.add_assign(t);
t = proof.state_polys_openings_at_z[2].copy();
t.mul_assign(proof.state_polys_openings_at_z[0]);
t.sub_assign(proof.state_polys_openings_at_z[3]);
t.mul_assign(state.alpha_values[1 + 2]);
intermediate_result.add_assign(t);
result = vk.gate_selectors_commitments[1].point_mul(intermediate_result);
}
| 3,023,103 |
./full_match/5/0x1BbE9C1eA7446Ac68dfF4Cb9044EF7aa4B73F3B1/sources/contracts/CantoLocker.sol | returns array of all TokenLocks for a certain token address lpToken token's address/ | function tokenLocksAll(address lpToken) external view returns (TokenLock[] memory) {
uint256 tokenLocksNr = tokenLocksByAddress[lpToken].length();
TokenLock[] memory tokenLocks = new TokenLock[](tokenLocksNr);
for (uint256 i; i < tokenLocksNr;) {
tokenLocks[i] = tokenLocksById[tokenLocksByAddress[lpToken].at(i)];
unchecked {
++i;
}
}
return tokenLocks;
}
| 1,896,283 |
./full_match/4/0x6e936fE9E2c386c6BaF77FA21093b91d3dC027f6/sources/500balles.sol | solhint-disable-line | function DAO() external view returns (address); | 788,174 |
./full_match/5/0x1cD3522515BA87e190fDa01A636e7F6D59601fFF/sources/contracts/ETH/PresaleV1.sol | To claim tokens after claiming starts/ | function claim() external whenNotPaused returns (bool) {
require(saleToken != address(0), "Sale token not added");
require(!isBlacklisted[_msgSender()], "This Address is Blacklisted");
if (whitelistClaimOnly) {
require(
isWhitelisted[_msgSender()],
"User not whitelisted for claim"
);
}
require(block.timestamp >= claimStart, "Claim has not started yet");
require(!hasClaimed[_msgSender()], "Already claimed");
hasClaimed[_msgSender()] = true;
uint256 amount = userDeposits[_msgSender()];
require(amount > 0, "Nothing to claim");
delete userDeposits[_msgSender()];
bool success = IERC20Upgradeable(saleToken).transfer(
_msgSender(),
amount
);
require(success, "Token transfer failed");
emit TokensClaimed(_msgSender(), amount, block.timestamp);
return true;
}
| 1,932,311 |
pragma solidity ^0.4.18;
pragma solidity ^0.4.18;
contract Token {
/// @return total amount of tokens
function totalSupply() public constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/*
This implements ONLY the standard functions and NOTHING else.
For a token like you would want to deploy in something like Mist, see HumanStandardToken.sol.
If you deploy this, you won't have anything useful.
Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
.*/
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
/*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.
In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.
.*/
contract HumanStandardToken is StandardToken {
//What is this function?
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
function HumanStandardToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title Token Swap Contract for Neverdie
/// @author Julia Altenried, Yuriy Kashnikov
contract TokenSwap is Ownable {
/* neverdie token contract address and its instance, can be set by owner only */
HumanStandardToken ndc;
/* neverdie token contract address and its instance, can be set by owner only */
HumanStandardToken tpt;
/* signer address, verified in 'swap' method, can be set by owner only */
address neverdieSigner;
/* minimal amount for swap, the amount passed to 'swap method can't be smaller
than this value, can be set by owner only */
uint256 minSwapAmount = 40;
event Swap(
address indexed to,
address indexed PTaddress,
uint256 rate,
uint256 amount,
uint256 ptAmount
);
event BuyNDC(
address indexed to,
uint256 NDCprice,
uint256 value,
uint256 amount
);
event BuyTPT(
address indexed to,
uint256 TPTprice,
uint256 value,
uint256 amount
);
/// @dev handy constructor to initialize TokenSwap with a set of proper parameters
/// NOTE: min swap amount is left with default value, set it manually if needed
/// @param _teleportContractAddress Teleport token address
/// @param _neverdieContractAddress Neverdie token address
/// @param _signer signer address, verified further in swap functions
function TokenSwap(address _teleportContractAddress, address _neverdieContractAddress, address _signer) public {
tpt = HumanStandardToken(_teleportContractAddress);
ndc = HumanStandardToken(_neverdieContractAddress);
neverdieSigner = _signer;
}
function setTeleportContractAddress(address _to) external onlyOwner {
tpt = HumanStandardToken(_to);
}
function setNeverdieContractAddress(address _to) external onlyOwner {
ndc = HumanStandardToken(_to);
}
function setNeverdieSignerAddress(address _to) external onlyOwner {
neverdieSigner = _to;
}
function setMinSwapAmount(uint256 _amount) external onlyOwner {
minSwapAmount = _amount;
}
/// @dev receiveApproval calls function encoded as extra data
/// @param _sender token sender
/// @param _value value allowed to be spent
/// @param _tokenContract callee, should be equal to neverdieContractAddress
/// @param _extraData this should be a well formed calldata with function signature preceding which is used to call, for example, 'swap' method
function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external {
require(_tokenContract == address(ndc));
assert(this.call(_extraData));
}
/// @dev One-way swapFor function, swaps NDC for purchasable token for a given spender
/// @param _spender account that wants to swap NDC for purchasable token
/// @param _rate current NDC to purchasable token rate, i.e. that the returned amount
/// of purchasable tokens equals to (_amount * _rate) / 1000
/// @param _PTaddress the address of the purchasable token
/// @param _amount amount of NDC being offered
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function swapFor(address _spender,
uint256 _rate,
address _PTaddress,
uint256 _amount,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) public {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie signer address
address signer = ecrecover(keccak256(_spender, _rate, _PTaddress, _amount, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
// Check if the amount of NDC is higher than the minimum amount
require(_amount >= minSwapAmount);
// Check that we hold enough tokens
HumanStandardToken ptoken = HumanStandardToken(_PTaddress);
uint256 ptAmount;
uint8 decimals = ptoken.decimals();
if (decimals <= 18) {
ptAmount = SafeMath.div(SafeMath.div(SafeMath.mul(_amount, _rate), 1000), 10**(uint256(18 - decimals)));
} else {
ptAmount = SafeMath.div(SafeMath.mul(SafeMath.mul(_amount, _rate), 10**(uint256(decimals - 18))), 1000);
}
assert(ndc.transferFrom(_spender, this, _amount) && ptoken.transfer(_spender, ptAmount));
// Emit Swap event
Swap(_spender, _PTaddress, _rate, _amount, ptAmount);
}
/// @dev One-way swap function, swaps NDC to purchasable tokens
/// @param _rate current NDC to purchasable token rate, i.e. that the returned amount of purchasable tokens equals to _amount * _rate
/// @param _PTaddress the address of the purchasable token
/// @param _amount amount of NDC being offered
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function swap(uint256 _rate,
address _PTaddress,
uint256 _amount,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) external {
swapFor(msg.sender, _rate, _PTaddress, _amount, _expiration, _v, _r, _s);
}
/// @dev buy NDC with ether
/// @param _NDCprice NDC price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyNDC(uint256 _NDCprice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s
) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_NDCprice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
uint256 a = SafeMath.div(msg.value, _NDCprice);
assert(ndc.transfer(msg.sender, a));
// Emit BuyNDC event
BuyNDC(msg.sender, _NDCprice, msg.value, a);
}
/// @dev buy TPT with ether
/// @param _TPTprice TPT price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyTPT(uint256 _TPTprice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s
) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_TPTprice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
uint256 a = SafeMath.div(msg.value, _TPTprice);
assert(tpt.transfer(msg.sender, a));
// Emit BuyNDC event
BuyTPT(msg.sender, _TPTprice, msg.value, a);
}
/// @dev fallback function to reject any ether coming directly to the contract
function () payable public {
revert();
}
/// @dev withdraw all ether
function withdrawEther() external onlyOwner {
owner.transfer(this.balance);
}
/// @dev withdraw token
/// @param _tokenContract any kind of ERC20 token to withdraw from
function withdraw(address _tokenContract) external onlyOwner {
ERC20 token = ERC20(_tokenContract);
uint256 balance = token.balanceOf(this);
assert(token.transfer(owner, balance));
}
/// @dev kill contract, but before transfer all TPT, NDC tokens and ether to owner
function kill() onlyOwner public {
uint256 allNDC = ndc.balanceOf(this);
uint256 allTPT = tpt.balanceOf(this);
assert(ndc.transfer(owner, allNDC) && tpt.transfer(owner, allTPT));
selfdestruct(owner);
}
} | buy TPT with ether _TPTprice TPT price in Wei _expiration expiration timestamp _v ECDCA signature _r ECDSA signature _s ECDSA signature Check if the signature did not expire yet by inspecting the timestamp Check if the signature is coming from the neverdie address Emit BuyNDC event | function buyTPT(uint256 _TPTprice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s
) payable external {
require(_expiration >= block.timestamp);
address signer = ecrecover(keccak256(_TPTprice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
uint256 a = SafeMath.div(msg.value, _TPTprice);
assert(tpt.transfer(msg.sender, a));
BuyTPT(msg.sender, _TPTprice, msg.value, a);
}
| 6,063,116 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12; // Certik DCK-01
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Refer to Pancake SmartChef Contract: https://bscscan.com/address/0xCc2D359c3a99d9cfe8e6F31230142efF1C828e6D#readContract
contract GameSlot is Ownable, ReentrancyGuard, IERC721Receiver {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
IBEP20 public nativeToken;
IBEP20 public gamePointToken;
// The address of the manager
address public SLOT_MANAGER;
// Whether it is initialized
bool public isInitialized;
// The reserved tokens in the slot
uint256 public reservedAmount;
uint256 public unlockLimit; // GSD-03
uint256 public constant MAX_PERFORMANCE_FEE = 5000; // 50%
uint256 public performanceFee = 200; // 2%
// Whether it is suspended
bool public suspended = false;
uint256 public tokenId;
address public ownerAccount;
address public admin;
IERC721 public NFT; // The NFT token address that each game provider should hold
// address public treasury;
address public treasury;
// Send funds to blacklisted addresses are not allowed
mapping(address => bool) public blacklistAddresses;
event AdminTokenRecovery(address indexed tokenRecovered, uint256 amount); // Certik GSD-01
event EmergencyWithdraw(address indexed user, uint256 amount);
event AddSlotEvent(uint256 indexed tokenId, address indexed gameAccount);
event StatusChanged(address indexed slotAddress, bool suspended);
event SlotUnlocked(address indexed user, address indexed gameAccount, uint256 amount);
event AdminUpdated(address indexed user, address indexed admin);
event Payout(address indexed user, address indexed receiver, uint256 amount);
event CashoutPoints(address indexed user, uint256 amount);
event AddToWhitelist(address indexed entry);
event RemoveFromWhitelist(address indexed entry);
event SetReservedAmount(uint256 amount);
event SetPerformanceFee(uint256 amount);
event SetUnlockLimitAmount(uint256 amount);
event SetTreasury(address indexed amount); // Certik
constructor(
address _NFT,
address _nativeToken,
address _gamePointToken,
uint256 _reservedAmount,
address _manager
) public {
require(_NFT != address(0), "_NFT is a zero address"); // Certik GSD-02
require(_nativeToken != address(0), "_nativeToken is a zero address");
require(_gamePointToken != address(0), "_gamePointToken is a zero address");
NFT = IERC721(_NFT);
// Set manager to SlotManager rather than factory
SLOT_MANAGER = _manager;
nativeToken = IBEP20(_nativeToken);
gamePointToken = IBEP20(_gamePointToken);
reservedAmount = _reservedAmount;
treasury = _manager;
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/*
* @notice Initialize the contract, owner may not be the msg.sender
* @param _tokenId: tokenId of the NFT
* @param _owner: The current owner of NFT
*/
function initialize(
uint256 _tokenId,
address _owner
) external {
require(!isInitialized, "Already initialized");
require(msg.sender == SLOT_MANAGER, "Not manager");
tokenId = _tokenId;
_add(_tokenId, _owner);
// Make this contract initialized
isInitialized = true;
emit AddSlotEvent(_tokenId, msg.sender);
}
/**
* Game provider to bid slot
* @param _owner is the NFT owner (Game provider)
* @param _tokenId is the token owned by owner and to be transffered into this slot
*/
function _add(uint256 _tokenId, address _owner) private nonReentrant {
require(NFT.ownerOf(_tokenId) != address(this), "Already owner");
NFT.safeTransferFrom(
_owner,
address(this),
_tokenId
);
// require(NFT.ownerOf(_tokenId) == address(this), "Not received"); // Certik GSD-09
ownerAccount = _owner;
// Admin account is set to same account of ownerAccount first
admin = _owner;
}
/**
* @notice This function is private and not privilege checking
* Safe token transfer function for nativeToken, just in case if rounding error causes pool to not have enough tokens.
*/
function safeTransfer(address _to, uint256 _amount) private {
uint256 bal = nativeToken.balanceOf(address(this));
if (_amount > bal) {
nativeToken.safeTransfer(_to, bal); // Certik GSD-07
} else {
nativeToken.safeTransfer(_to, _amount); // Certik GSD-07
}
}
/**
* @notice This function is private and not privilege checking
* Safe token transfer function for point token, just in case if rounding error causes pool to not have enough tokens.
*/
function safeTransferPoints(address _to, uint256 _amount) private {
uint256 bal = gamePointToken.balanceOf(address(this));
if (_amount > bal) {
gamePointToken.safeTransfer(_to, bal); // Certik GSD-07
} else {
gamePointToken.safeTransfer(_to, _amount); // Certik GSD-07
}
}
// Owner is the GameSlot, and triggered by Game Slot owner / admin
function payout(address _to, uint256 _amount) external nonReentrant {
require(_to != address(0), "Cannot send to 0 address");
require(_amount > 0, "Must more than 0");
require(!suspended, "Slot is suspended");
require(msg.sender == admin, "Only the game admin can payout");
require(_balance() > reservedAmount, "Balance must more than reserved");
require(_amount <= (_balance() - reservedAmount), "Exceeded max payout-able amount");
require(!blacklistAddresses[_to], "user is blacklisted");
uint256 currentPerformanceFee = _amount.mul(performanceFee).div(10000);
safeTransfer(treasury, currentPerformanceFee);
safeTransfer(_to, _amount.sub(currentPerformanceFee));
emit Payout(msg.sender, _to, _amount);
}
/**
* @notice Owner is the GameSlot, and triggered by Game Slot owner
* There is no theshold to cashout
*/
function cashoutPoints(uint256 _amount) external nonReentrant {
require(_amount > 0, "Must more than 0");
require(!suspended, "Slot is suspended");
require(msg.sender == admin || msg.sender == ownerAccount, "Only the game owner or admin can cashout");
require(_amount <= _balanceOfPoints(), "Exceeded max game points amount");
safeTransferPoints(ownerAccount, _amount);
emit CashoutPoints(msg.sender, _amount);
}
/**
* Unlock NFT and return the slot back
* Only return the current tokenId back to ownerAccount
*
* TODO: need more rules to unlock slot
*/
function unlock() external onlyOwner {
require(_balance() < unlockLimit, "Balance must be less than balance before unlock"); // Certik GSD-03
NFT.transferFrom(
address(this),
ownerAccount,
tokenId
);
isInitialized = false;
emit SlotUnlocked(msg.sender, ownerAccount, tokenId);
}
function addToBlacklist(address[] calldata entries) external onlyOwner {
for(uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), "NULL_ADDRESS");
blacklistAddresses[entry] = true;
emit AddToWhitelist(entry);
}
}
function removeFromBlacklist(address[] calldata entries) external onlyOwner {
for(uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), "NULL_ADDRESS");
blacklistAddresses[entry] = false;
emit RemoveFromWhitelist(entry);
}
}
/*
* @notice Withdraw staked tokens without caring other factor
* The funds will be sent to treasury, and the team need to manually refund back to users affected
*
* @dev TODO: Needs to be for emergency.
*/
function emergencyWithdraw() external onlyOwner {
uint256 balance = _balance();
nativeToken.safeTransfer(treasury, balance);
emit EmergencyWithdraw(msg.sender, balance);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(nativeToken), "Cannot be native token");
require(_tokenAddress != address(gamePointToken), "Cannot be point token");
IBEP20(_tokenAddress).safeTransfer(treasury, _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/**
* @notice Sets Reserved Amount of native token
* Can be zero only if the owner want to leave the slot
*
* @dev Only callable by the contract admin.
*/
function setAdmin(address _admin) external {
require(_admin != address(0), "Address cannot be 0");
require(msg.sender == ownerAccount, "Only the game owener can update admin");
admin = _admin;
emit AdminUpdated(msg.sender, _admin);
}
/**
* @notice Sets Reserved Amount of native token
* Can be zero only if the owner want to leave the slot
*
* @dev Only callable by the contract admin.
*/
function setReservedAmount(uint256 _reservedAmount) external onlyOwner {
reservedAmount = _reservedAmount;
emit SetReservedAmount(reservedAmount);
}
/**
* @notice Only if unlockLimit is set and the balance is less than unlockLimit
* Then it's able to unlock
*/
function setUnlockLimitAmount(uint256 _unlockLimit) external onlyOwner {
unlockLimit = _unlockLimit;
emit SetUnlockLimitAmount(_unlockLimit);
}
/**
* @notice Sets performance fee
* @dev Only callable by the contract admin.
*/
function setPerformanceFee(uint256 _performanceFee) external onlyOwner {
require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE");
performanceFee = _performanceFee;
emit SetPerformanceFee(performanceFee);
}
/**
* @notice Sets treasury address
* @dev Only callable by the contract owner.
*/
function setTreasury(address _treasury) external onlyOwner {
require(_treasury != address(0), "Cannot be zero address");
treasury = _treasury;
emit SetTreasury(treasury);
}
/**
* @notice Sets treasury address
* @dev Only callable by the contract owner.
*/
function flipSuspendState() external onlyOwner {
suspended = !suspended;
emit StatusChanged(msg.sender, suspended);
}
/** View functions */
function initialized() external view returns (bool) {
return isInitialized;
}
function isSuspended() external view returns (bool) {
return suspended;
}
function balanceOfPoints() external view returns (uint256) {
return _balanceOfPoints();
}
function _balanceOfPoints() private view returns (uint256) {
return gamePointToken.balanceOf(address(this));
}
function balance() external view returns (uint256) {
return _balance();
}
function _balance() private view returns (uint256) {
return nativeToken.balanceOf(address(this));
}
}
| Withdraw staked tokens without caring other factor The funds will be sent to treasury, and the team need to manually refund back to users affected TODO: Needs to be for emergency./ | function emergencyWithdraw() external onlyOwner {
uint256 balance = _balance();
nativeToken.safeTransfer(treasury, balance);
emit EmergencyWithdraw(msg.sender, balance);
}
| 929,688 |
./full_match/5/0xc11EB9B5E028F5Ddf3f1b390F6041CbF38feabf8/sources/contracts/BaseWallet.sol | ensure the request comes from the known entrypoint./ | function _requireFromEntryPoint() internal virtual view {
require(msg.sender == address(entryPoint()), "wallet: not from EntryPoint");
}
| 11,603,655 |
pragma solidity ^0.4.24;
// File: contracts/interface/DiviesInterface.sol
interface DiviesInterface {
function deposit() external payable;
}
// File: contracts/interface/F3DexternalSettingsInterface.sol
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
// File: contracts/interface/HourglassInterface.sol
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
// File: contracts/interface/JIincForwarderInterface.sol
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
// File: contracts/interface/PlayerBookInterface.sol
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
// File: contracts/interface/otherFoMo3D.sol
interface otherFoMo3D {
function potSwap() external payable;
}
// File: contracts/library/SafeMath.sol
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
// File: contracts/library/F3DKeysCalcLong.sol
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
// File: contracts/library/F3Ddatasets.sol
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys 小羊
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead, lead领导吗?
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran 这个开关值得研究下
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
// File: contracts/library/NameFilter.sol
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
// File: contracts/library/UintCompressor.sol
/**
* @title -UintCompressor- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ _ __ __ _ ____ ___ __ _ _ ____ ____ ____ ____ ____ __ ____
*===/ )( \ ( ) ( ( \(_ _)===/ __) / \ ( \/ )( _ \( _ \( __)/ ___)/ ___) / \ ( _ \===*
* ) \/ ( )( / / )( ( (__ ( O )/ \/ \ ) __/ ) / ) _) \___ \\___ \( O ) ) /
*===\____/ (__) \_)__) (__)====\___) \__/ \_)(_/(__) (__\_)(____)(____/(____/ \__/ (__\_)===*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
// File: contracts/F3Devents.sol
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
// File: contracts/modularLong.sol
contract modularLong is F3Devents {}
// File: contracts/FoMo3Dlong.sol
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
otherFoMo3D private otherF3D_;
//TODO:
DiviesInterface constant private Divies = DiviesInterface(0x6e6d9770e44f57db3bb94d18e3e7cc5ba7855f6d);
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xca255f23ba3fd322fb634d3783db90659a7a48ba);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x8727455a941d4f95e20a4c76ec3aef019fe73811);
F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x35d3f1c98d9fd8087e312e953f32233ace1996b6);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMoKiller long";
string constant public symbol = "FoMoKiller";
uint256 private rndExtra_ = 15 seconds; // length of the very first ICO
uint256 private rndGap_ = 1 hours; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 24 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA , Team的费用分配数据
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
address public ourTEAM = 0xf1E32a3EaA5D6c360AF6AA2c45a97e377Be183BD;
mapping (address => bool) public myFounder_;
mapping (address => uint256) public myFounder_PID;
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = 预言家
// 1 = 守卫
// 2 = 丘比特
// 3 = 长老
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(70,0);
fees_[1] = F3Ddatasets.TeamFee(60,0);
fees_[2] = F3Ddatasets.TeamFee(50,0);
fees_[3] = F3Ddatasets.TeamFee(40,0);
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(20,0);
potSplit_[1] = F3Ddatasets.PotSplit(30,0);
potSplit_[2] = F3Ddatasets.PotSplit(40,0);
potSplit_[3] = F3Ddatasets.PotSplit(50,0);
myFounder_[0xa78cd12e5f2daf88023f0bfe119eac8b3f3dbc93] = true;
myFounder_[0xfB31eb7B96e413BEbEe61F5E3880938b937c2Ef0] = true;
myFounder_[0xEa8A4f09C45967DFCFda180fA80ad44eefAb52bE] = true;
myFounder_[0xf1E32a3EaA5D6c360AF6AA2c45a97e377Be183BD] = true;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
// require (_addr == tx.origin);
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
*
*/
modifier onlyDevs() {
//TODO:
require(
msg.sender == 0xa78cd12e5f2daf88023f0bfe119eac8b3f3dbc93 ||
msg.sender == 0xfB31eb7B96e413BEbEe61F5E3880938b937c2Ef0 ||
msg.sender == 0xEa8A4f09C45967DFCFda180fA80ad44eefAb52bE ||
msg.sender == 0xf1E32a3EaA5D6c360AF6AA2c45a97e377Be183BD,
"only team just can activate"
);
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(40)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
// 不在这里reset,一轮游戏结束的时候再reset
// airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
if (myFounder_PID[plyr_[_pID].addr] > 0) {
plyrRnds_[_pID][_rID].keys = myFounder_PID[plyr_[_pID].addr].add(plyrRnds_[_pID][_rID].keys);
round_[_rID].keys = myFounder_PID[plyr_[_pID].addr].add(round_[_rID].keys);
myFounder_PID[plyr_[_pID].addr] = 0;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth 分钱
_eth = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(40)) / 100; //赢得奖金池里40%的奖金
uint256 _com = (_pot / 10); // _com获得10%的收益
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; //20%、30%、40%、50%
uint256 _p3d = 0;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
//结算收益
ourTEAM.transfer(_com);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// // community rewards
// if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
// {
// // This ensures Team Just cannot influence the outcome of FoMo3D with
// // bank migrations by breaking outgoing transactions.
// // Something we would never do. But that's not the point.
// // We spent 2000$ in eth re-deploying just to patch this, we hold the
// // highest belief that everything we create should be trustless.
// // Team JUST, The name you shouldn't have to trust.
// _p3d = _p3d.add(_com);
// _com = 0;
// }
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
airDropTracker_ = 0; //下一轮,空投数从0计数
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
//购买第1w、10w、100w、1000w、10000w只小羊的时候有奖励
if(airDropTracker_ == 10000 || airDropTracker_ == 100000 || airDropTracker_ == 1000000 || airDropTracker_ == 10000000 || airDropTracker_ == 100000000 || airDropTracker_ == 1000000000 )
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d mark by 33
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(uint256)
{
// pay 3% out to community rewards
uint256 _com = (_eth.mul(3) / 100);
ourTEAM.transfer(_com);
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
//修改分红比例,创世农民分红比例为20%
if(myFounder_[plyr_[_affID].addr]) {
_aff = _eth / 5;
}
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
}
return (_eth.sub(_com)).sub(_aff);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; //70%、60%、50%、40%
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
uint256 _pot = _eth.sub(_gen).sub(_air);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
onlyDevs()
public
{
// make sure that its been linked.
require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
onlyDevs()
public
{
// make sure that it HASNT yet been linked.
require(address(otherF3D_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherF3D_ = otherFoMo3D(_otherF3D);
}
function setOtherFounder(address _otherF3D, uint256 _values)
onlyDevs()
public
{
myFounder_[_otherF3D] = true;
myFounder_PID[_otherF3D] = _values.mul(1000000000000000000);
}
} | generates a random number between 0-99 and checks to see if thats resulted in an airdrop win return do we have a winner?/购买第1w、10w、100w、1000w、10000w只小羊的时候有奖励 | function airdrop()
private
view
returns(bool)
{
if(airDropTracker_ == 10000 || airDropTracker_ == 100000 || airDropTracker_ == 1000000 || airDropTracker_ == 10000000 || airDropTracker_ == 100000000 || airDropTracker_ == 1000000000 )
return(true);
else
return(false);
}
| 10,042,996 |
./full_match/43114/0xd2e517C452B34FF88b937aA714f7bd1F21103f2D/sources/contracts/MasterChef.sol | Add a new lp to the pool. Can only be called by the owner. | function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) {
require(_depositFeeBP <= 400, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accEskiPerShare : 0,
depositFeeBP : _depositFeeBP
}));
}
| 4,630,310 |
pragma solidity 0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
// input /root/code/solidity/xixoio-contracts/flat/TokenPool.sol
// flattened : Monday, 03-Dec-18 10:34:17 UTC
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
interface ITokenPool {
function balanceOf(uint128 id) public view returns (uint256);
function allocate(uint128 id, uint256 value) public;
function withdraw(uint128 id, address to, uint256 value) public;
function complete() public;
}
contract TokenPool is ITokenPool, Ownable {
using SafeMath for uint256;
IERC20 public token;
bool public completed = false;
mapping(uint128 => uint256) private balances;
uint256 public allocated = 0;
event FundsAllocated(uint128 indexed account, uint256 value);
event FundsWithdrawn(uint128 indexed account, address indexed to, uint256 value);
constructor(address tokenAddress) public {
token = IERC20(tokenAddress);
}
/**
* @return The balance of the account in pool
*/
function balanceOf(uint128 account) public view returns (uint256) {
return balances[account];
}
/**
* Token allocation function
* @dev should be called after every token deposit to allocate these token to the account
*/
function allocate(uint128 account, uint256 value) public onlyOwner {
require(!completed, "Pool is already completed");
assert(unallocated() >= value);
allocated = allocated.add(value);
balances[account] = balances[account].add(value);
emit FundsAllocated(account, value);
}
/**
* Allows withdrawal of tokens and dividends from temporal storage to the wallet
* @dev transfers corresponding amount of dividend in ETH
*/
function withdraw(uint128 account, address to, uint256 value) public onlyOwner {
balances[account] = balances[account].sub(value);
uint256 balance = address(this).balance;
uint256 dividend = balance.mul(value).div(allocated);
allocated = allocated.sub(value);
token.transfer(to, value);
if (dividend > 0) {
to.transfer(dividend);
}
emit FundsWithdrawn(account, to, value);
}
/**
* Concludes allocation of tokens and serves as a drain for unallocated tokens
*/
function complete() public onlyOwner {
completed = true;
token.transfer(msg.sender, unallocated());
}
/**
* Fallback function enabling deposit of dividends in ETH
* @dev dividend has to be deposited only after pool completion, as additional token
* allocations after the deposit would skew shares
*/
function () public payable {
require(completed, "Has to be completed first");
}
/**
* @return Amount of unallocated tokens in the pool
*/
function unallocated() internal view returns (uint256) {
return token.balanceOf(this).sub(allocated);
}
} | return Amount of unallocated tokens in the pool/ | function unallocated() internal view returns (uint256) {
return token.balanceOf(this).sub(allocated);
}
| 6,434,011 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {IVersionBeacon} from "./VersionBeacon.sol";
contract VersionTemplate is Initializable {
bytes32 private constant _BEACON_SLOT = bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1);
bytes32 private constant _VERSION_SLOT = bytes32(uint256(keccak256("eip1967.proxy.version")) - 1);
bytes32 private constant _ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);
event BeaconChanged(address previousBeacon, address newBeacon);
event VersionChanged(uint256 previousVersion, uint256 newVersion);
event AdminChanged(address previousAdmin, address newAdmin);
function initialize(bytes memory data) external virtual initializer {}
modifier onlyAdmin() {
require(msg.sender == _admin(), "VersionTemplate: only admin");
_;
}
// external functions
function changeBeacon(address newBeacon) external onlyAdmin {
emit BeaconChanged(_beacon(), newBeacon);
_setBeacon(newBeacon);
}
function changeBeaconAndCall(address newBeacon, bytes calldata data) external onlyAdmin {
emit BeaconChanged(_beacon(), newBeacon);
_setBeacon(newBeacon);
_delegateCall(data);
}
function changeVersion(uint256 newVersion) external onlyAdmin {
emit VersionChanged(_version(), newVersion);
_setVersion(newVersion);
}
function changeVersionAndCall(uint256 newVersion, bytes calldata data) external onlyAdmin {
emit VersionChanged(_version(), newVersion);
_setVersion(newVersion);
_delegateCall(data);
}
function changeAdmin(address newAdmin) external onlyAdmin {
require(newAdmin != address(0), "VersionTemplate: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
// internal setters
function _setBeacon(address beacon) private {
require(Address.isContract(beacon), "VersionTemplate: new beacon is not a contract");
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, beacon)
}
}
function _setVersion(uint256 version) private {
require(version <= IVersionBeacon(_beacon()).getLatestVersion(), "VersionTemplate: new version is not defined");
bytes32 slot = _VERSION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, version)
}
}
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
function _delegateCall(bytes memory data) private {
address implementation = _implementation();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = implementation.delegatecall(data);
require(success);
}
// internal getters
function _beacon() internal view returns (address beacon) {
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
beacon := sload(slot)
}
}
function _version() internal view returns (uint256 version) {
bytes32 slot = _VERSION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
version := sload(slot)
}
}
function _admin() internal view returns (address admin) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
admin := sload(slot)
}
}
// internal overrides
function _implementation() internal view returns (address implementation) {
return IVersionBeacon(_beacon()).getImplementation(_version());
}
}
| solhint-disable-next-line no-inline-assembly | function _setVersion(uint256 version) private {
require(version <= IVersionBeacon(_beacon()).getLatestVersion(), "VersionTemplate: new version is not defined");
bytes32 slot = _VERSION_SLOT;
assembly {
sstore(slot, version)
}
}
| 7,284,791 |
./full_match/11155111/0x1e7eE10b72628db353DeDDfd3A6EC8a2543BDF78/sources/src/SimpleStorage.sol | with view and pure, we cant modify our state with view , in this case valueWithDefaultNumber we can only view them and there is an execution cost when you run this type of function | function retrieveNumber() public view returns (uint256) {
return valueWithDefaultNumber;
}
| 3,792,697 |
./partial_match/42/0xc5D2E8F47fA2f993eEcEB4ee4b1bfFd0E1154A35/sources/PriceFeedEUR.sol | Converts stablecoin balance into collateral balance at current price _asset address to the collateral asset e.g. WETH _balance amount of stablecoin/ | function convertTo(address _asset, uint256 _balance) public override view returns (uint256) {
uint256 price = getAssetPrice(_asset);
uint256 price_accuracy = MathPow.pow(10, eurOracle.decimals());
return _balance.mul(price_accuracy).div(price);
}
| 8,934,297 |
pragma solidity 0.4.25;
/**
* @title SafeCompare
*/
library SafeCompare {
function stringCompare(string str1, string str2) internal pure returns(bool) {
return keccak256(abi.encodePacked(str1)) == keccak256(abi.encodePacked(str2));
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract UsdtERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns(uint256);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal {
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal {
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view {
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns(bool) {
return _role.bearer[_addr];
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether there is code in the target address
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address address to check
* @return whether there is code in the target address
*/
function isContract(address addr) internal view returns(bool) {
uint256 size;
assembly {
size: = extcodesize(addr)
}
return size > 0;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles
for Roles.Role;
mapping(string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view {
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns(bool) {
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal {
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal {
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role) {
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract PartnerAuthority is Ownable {
address public partner;
/**
* Event for setPartner logging
* @param oldPartner the old Partner
* @param newPartner the new Partner
*/
event SetPartner(address oldPartner, address newPartner);
/**
* @dev Throws if called by any account other than the owner or the Partner.
*/
modifier onlyOwnerOrPartner() {
require(msg.sender == owner || msg.sender == partner);
_;
}
/**
* @dev Throws if called by any account other than the Partner.
*/
modifier onlyPartner() {
require(msg.sender == partner);
_;
}
/**
* @dev setPartner, set the partner address.
*/
function setPartner(address _partner) public onlyOwner {
require(_partner != address(0));
emit SetPartner(partner, _partner);
partner = _partner;
}
/**
* @dev removePartner, remove partner address.
*/
function removePartner() public onlyOwner {
delete partner;
}
}
contract RBACOperator is Ownable, RBAC {
/**
* A constant role name for indicating operator.
*/
string public constant ROLE_OPERATOR = "operator";
address public partner;
/**
* Event for setPartner logging
* @param oldPartner the old Partner
* @param newPartner the new Partner
*/
event SetPartner(address oldPartner, address newPartner);
/**
* @dev Throws if called by any account other than the owner or the Partner.
*/
modifier onlyOwnerOrPartner() {
require(msg.sender == owner || msg.sender == partner);
_;
}
/**
* @dev Throws if called by any account other than the Partner.
*/
modifier onlyPartner() {
require(msg.sender == partner);
_;
}
/**
* @dev setPartner, set the partner address.
* @param _partner the new partner address.
*/
function setPartner(address _partner) public onlyOwner {
require(_partner != address(0));
emit SetPartner(partner, _partner);
partner = _partner;
}
/**
* @dev removePartner, remove partner address.
*/
function removePartner() public onlyOwner {
delete partner;
}
/**
* @dev the modifier to operate
*/
modifier hasOperationPermission() {
checkRole(msg.sender, ROLE_OPERATOR);
_;
}
/**
* @dev add a operator role to an address
* @param _operator address
*/
function addOperater(address _operator) public onlyOwnerOrPartner {
addRole(_operator, ROLE_OPERATOR);
}
/**
* @dev remove a operator role from an address
* @param _operator address
*/
function removeOperater(address _operator) public onlyOwnerOrPartner {
removeRole(_operator, ROLE_OPERATOR);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns(uint256);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function approve(address spender, uint256 value) public returns(bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract UsdtERC20 is UsdtERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title pledge pool base
* @dev a base tokenPool, any tokenPool for a specific token should inherit from this tokenPool.
*/
contract PledgePoolBase is RBACOperator {
using SafeMath for uint256;
using AddressUtils for address;
// Record pledge details.
mapping(uint256 => Escrow) internal escrows;
/**
* @dev Information structure of pledge.
*/
struct Escrow {
uint256 pledgeSum;
address payerAddress;
string tokenName;
}
// -----------------------------------------
// TokenPool external interface
// -----------------------------------------
/**
* @dev addRecord, interface to add record.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function addRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) public hasOperationPermission returns(bool) {
_preValidateAddRecord(_payerAddress, _pledgeSum, _pledgeId, _tokenName);
_processAddRecord(_payerAddress, _pledgeSum, _pledgeId, _tokenName);
return true;
}
/**
* @dev withdrawToken, withdraw pledge token.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function withdrawToken(uint256 _pledgeId, address _maker, uint256 _num) public hasOperationPermission returns(bool) {
_preValidateWithdraw(_maker, _num, _pledgeId);
_processWithdraw(_maker, _num, _pledgeId);
return true;
}
/**
* @dev refundTokens, interface to refund
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function refundTokens(uint256 _pledgeId, uint256 _returnSum, address _targetAddress) public hasOperationPermission returns(bool) {
_preValidateRefund(_returnSum, _targetAddress, _pledgeId);
_processRefund(_returnSum, _targetAddress, _pledgeId);
return true;
}
/**
* @dev getLedger, Query the pledge details of the pledge number in the pool.
* @param _pledgeId pledge contract index number.
*/
function getLedger(uint256 _pledgeId) public view returns(uint256 num, address payerAddress, string tokenName) {
require(_pledgeId > 0);
num = escrows[_pledgeId].pledgeSum;
payerAddress = escrows[_pledgeId].payerAddress;
tokenName = escrows[_pledgeId].tokenName;
}
// -----------------------------------------
// TokenPool internal interface (extensible)
// -----------------------------------------
/**
* @dev _preValidateAddRecord, Validation of an incoming AddRecord. Use require statemens to revert state when conditions are not met.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function _preValidateAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) view internal {
require(_pledgeSum > 0 && _pledgeId > 0
&& _payerAddress != address(0)
&& bytes(_tokenName).length > 0
&& address(msg.sender).isContract()
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processAddRecord, Executed when a AddRecord has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function _processAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) internal {
Escrow memory escrow = Escrow(_pledgeSum, _payerAddress, _tokenName);
escrows[_pledgeId] = escrow;
}
/**
* @dev _preValidateRefund, Validation of an incoming refund. Use require statemens to revert state when conditions are not met.
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function _preValidateRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) view internal {
require(_returnSum > 0 && _pledgeId > 0
&& _targetAddress != address(0)
&& address(msg.sender).isContract()
&& _returnSum <= escrows[_pledgeId].pledgeSum
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processRefund, Executed when a Refund has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function _processRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) internal {
escrows[_pledgeId].pledgeSum = escrows[_pledgeId].pledgeSum.sub(_returnSum);
}
/**
* @dev _preValidateWithdraw, Withdraw initiated parameter validation.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function _preValidateWithdraw(address _maker, uint256 _num, uint256 _pledgeId) view internal {
require(_num > 0 && _pledgeId > 0
&& _maker != address(0)
&& address(msg.sender).isContract()
&& _num <= escrows[_pledgeId].pledgeSum
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processWithdraw, Withdraw data update.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function _processWithdraw(address _maker, uint256 _num, uint256 _pledgeId) internal {
escrows[_pledgeId].pledgeSum = escrows[_pledgeId].pledgeSum.sub(_num);
}
}
/**
* @title OrderManageContract
* @dev Order process management contract.
*/
contract OrderManageContract is PartnerAuthority {
using SafeMath for uint256;
using SafeCompare for string;
/**
* @dev Status of current business execution contract.
*/
enum StatusChoices {
NO_LOAN,
REPAYMENT_WAITING,
REPAYMENT_ALL,
CLOSE_POSITION,
OVERDUE_STOP
}
string internal constant TOKEN_ETH = "ETH";
string internal constant TOKEN_USDT = "USDT";
address public maker;
address public taker;
address internal token20;
uint256 public toTime;
// the amount of the borrower’s final loan.
uint256 public outLoanSum;
uint256 public repaymentSum;
uint256 public lastRepaymentSum;
string public loanTokenName;
// Borrower's record of the pledge.
StatusChoices internal status;
// Record the amount of the borrower's offline transfer.
mapping(address => uint256) public ethAmount;
/**
* Event for takerOrder logging.
* @param taker address of investor.
* @param outLoanSum the amount of the borrower’s final loan.
*/
event TakerOrder(address indexed taker, uint256 outLoanSum);
/**
* Event for executeOrder logging.
* @param maker address of borrower.
* @param lastRepaymentSum current order repayment amount.
*/
event ExecuteOrder(address indexed maker, uint256 lastRepaymentSum);
/**
* Event for forceCloseOrder logging.
* @param toTime order repayment due date.
* @param transferSum balance under current contract.
*/
event ForceCloseOrder(uint256 indexed toTime, uint256 transferSum);
/**
* Event for WithdrawToken logging.
* @param taker address of investor.
* @param refundSum number of tokens withdrawn.
*/
event WithdrawToken(address indexed taker, uint256 refundSum);
function() external payable {
// Record basic information about the borrower's REPAYMENT ETH
ethAmount[msg.sender] = ethAmount[msg.sender].add(msg.value);
}
/**
* @dev Constructor initial contract configuration parameters
* @param _loanTokenAddress order type supported by the token.
*/
constructor(string _loanTokenName, address _loanTokenAddress, address _maker) public {
require(bytes(_loanTokenName).length > 0 && _maker != address(0));
if (!_loanTokenName.stringCompare(TOKEN_ETH)) {
require(_loanTokenAddress != address(0));
token20 = _loanTokenAddress;
}
toTime = now;
maker = _maker;
loanTokenName = _loanTokenName;
status = StatusChoices.NO_LOAN;
}
/**
* @dev Complete an order combination and issue the loan to the borrower.
* @param _taker address of investor.
* @param _toTime order repayment due date.
* @param _repaymentSum total amount of money that the borrower ultimately needs to return.
*/
function takerOrder(address _taker, uint32 _toTime, uint256 _repaymentSum) public onlyOwnerOrPartner {
require(_taker != address(0) && _toTime > 0 && now <= _toTime && _repaymentSum > 0 && status == StatusChoices.NO_LOAN);
taker = _taker;
toTime = _toTime;
repaymentSum = _repaymentSum;
// Transfer the token provided by the investor to the borrower's address
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(ethAmount[_taker] > 0 && address(this).balance > 0);
outLoanSum = address(this).balance;
maker.transfer(outLoanSum);
} else {
require(token20 != address(0) && ERC20(token20).balanceOf(address(this)) > 0);
outLoanSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(maker, outLoanSum));
}
// Update contract business execution status.
status = StatusChoices.REPAYMENT_WAITING;
emit TakerOrder(taker, outLoanSum);
}
/**
* @dev Only the full repayment will execute the contract agreement.
*/
function executeOrder() public onlyOwnerOrPartner {
require(now <= toTime && status == StatusChoices.REPAYMENT_WAITING);
// The borrower pays off the loan and performs two-way operation.
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(ethAmount[maker] >= repaymentSum && address(this).balance >= repaymentSum);
lastRepaymentSum = address(this).balance;
taker.transfer(repaymentSum);
} else {
require(ERC20(token20).balanceOf(address(this)) >= repaymentSum);
lastRepaymentSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(taker, repaymentSum));
}
PledgeContract(owner)._conclude();
status = StatusChoices.REPAYMENT_ALL;
emit ExecuteOrder(maker, lastRepaymentSum);
}
/**
* @dev Close position or due repayment operation.
*/
function forceCloseOrder() public onlyOwnerOrPartner {
require(status == StatusChoices.REPAYMENT_WAITING);
uint256 transferSum = 0;
if (now <= toTime) {
status = StatusChoices.CLOSE_POSITION;
} else {
status = StatusChoices.OVERDUE_STOP;
}
if(loanTokenName.stringCompare(TOKEN_ETH)){
if(ethAmount[maker] > 0 && address(this).balance > 0){
transferSum = address(this).balance;
maker.transfer(transferSum);
}
}else{
if(ERC20(token20).balanceOf(address(this)) > 0){
transferSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(maker, transferSum));
}
}
// Return pledge token.
PledgeContract(owner)._forceConclude(taker);
emit ForceCloseOrder(toTime, transferSum);
}
/**
* @dev Withdrawal of the token invested by the taker.
* @param _taker address of investor.
* @param _refundSum refundSum number of tokens withdrawn.
*/
function withdrawToken(address _taker, uint256 _refundSum) public onlyOwnerOrPartner {
require(status == StatusChoices.NO_LOAN);
require(_taker != address(0) && _refundSum > 0);
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(address(this).balance >= _refundSum && ethAmount[_taker] >= _refundSum);
_taker.transfer(_refundSum);
ethAmount[_taker] = ethAmount[_taker].sub(_refundSum);
} else {
require(ERC20(token20).balanceOf(address(this)) >= _refundSum);
require(safeErc20Transfer(_taker, _refundSum));
}
emit WithdrawToken(_taker, _refundSum);
}
/**
* @dev Since the implementation of usdt ERC20.sol transfer code does not design the return value,
* @dev which is different from most ERC20 token interfaces,most erc20 transfer token agreements return bool.
* @dev it is necessary to independently adapt the interface for usdt token in order to transfer successfully
* @dev if not, the transfer may fail.
*/
function safeErc20Transfer(address _toAddress,uint256 _transferSum) internal returns (bool) {
if(loanTokenName.stringCompare(TOKEN_USDT)){
UsdtERC20(token20).transfer(_toAddress, _transferSum);
}else{
require(ERC20(token20).transfer(_toAddress, _transferSum));
}
return true;
}
/**
* @dev Get current contract order status.
*/
function getPledgeStatus() public view returns(string pledgeStatus) {
if (status == StatusChoices.NO_LOAN) {
pledgeStatus = "NO_LOAN";
} else if (status == StatusChoices.REPAYMENT_WAITING) {
pledgeStatus = "REPAYMENT_WAITING";
} else if (status == StatusChoices.REPAYMENT_ALL) {
pledgeStatus = "REPAYMENT_ALL";
} else if (status == StatusChoices.CLOSE_POSITION) {
pledgeStatus = "CLOSE_POSITION";
} else {
pledgeStatus = "OVERDUE_STOP";
}
}
}
/**
* @title EscrowMaintainContract
* @dev Provides configuration and external interfaces.
*/
contract EscrowMaintainContract is PartnerAuthority {
address public pledgeFactory;
// map of token name to token pool address;
mapping(string => address) internal nameByPool;
// map of token name to erc20 token address;
mapping(string => address) internal nameByToken;
// -----------------------------------------
// External interface
// -----------------------------------------
/**
* @dev Create a pledge subcontract
* @param _pledgeId index number of the pledge contract.
*/
function createPledgeContract(uint256 _pledgeId) public onlyPartner returns(bool) {
require(_pledgeId > 0 && pledgeFactory!=address(0));
require(PledgeFactory(pledgeFactory).createPledgeContract(_pledgeId,partner));
return true;
}
/**
* @dev Batch create a pledge subcontract
* @param _pledgeIds index number of the pledge contract.
*/
function batchCreatePledgeContract(uint256[] _pledgeIds) public onlyPartner {
require(_pledgeIds.length > 0);
PledgeFactory(pledgeFactory).batchCreatePledgeContract(_pledgeIds,partner);
}
/**
* @dev Use the index to get the basic information of the corresponding pledge contract.
* @param _pledgeId index number of the pledge contract
*/
function getEscrowPledge(uint256 _pledgeId) public view returns(string tokenName, address pledgeContract) {
require(_pledgeId > 0);
(tokenName,pledgeContract) = PledgeFactory(pledgeFactory).getEscrowPledge(_pledgeId);
}
/**
* @dev setTokenPool, set the token pool contract address of a token name.
* @param _tokenName set token pool name.
* @param _address the token pool contract address.
*/
function setTokenPool(string _tokenName, address _address) public onlyOwner {
require(_address != address(0) && bytes(_tokenName).length > 0);
nameByPool[_tokenName] = _address;
}
/**
* @dev setToken, set the token contract address of a token name.
* @param _tokenName token name
* @param _address the ERC20 token contract address.
*/
function setToken(string _tokenName, address _address) public onlyOwner {
require(_address != address(0) && bytes(_tokenName).length > 0);
nameByToken[_tokenName] = _address;
}
/**
* @dev setPledgeFactory, Plant contract for configuration management pledge business.
* @param _factory pledge factory contract.
*/
function setPledgeFactory(address _factory) public onlyOwner {
require(_factory != address(0));
pledgeFactory = _factory;
}
/**
* @dev Checks whether the current token pool is supported.
* @param _tokenName token name
*/
function includeTokenPool(string _tokenName) view public returns(address) {
require(bytes(_tokenName).length > 0);
return nameByPool[_tokenName];
}
/**
* @dev Checks whether the current erc20 token is supported.
* @param _tokenName token name
*/
function includeToken(string _tokenName) view public returns(address) {
require(bytes(_tokenName).length > 0);
return nameByToken[_tokenName];
}
}
/**
* @title PledgeContract
* @dev Pledge process management contract
*/
contract PledgeContract is PartnerAuthority {
using SafeMath for uint256;
using SafeCompare for string;
/**
* @dev Type of execution state of the pledge contract(irreversible)
*/
enum StatusChoices {
NO_PLEDGE_INFO,
PLEDGE_CREATE_MATCHING,
PLEDGE_REFUND
}
string public pledgeTokenName;
uint256 public pledgeId;
address internal maker;
address internal token20;
address internal factory;
address internal escrowContract;
uint256 internal pledgeAccountSum;
// order contract address
address internal orderContract;
string internal loanTokenName;
StatusChoices internal status;
address internal tokenPoolAddress;
string internal constant TOKEN_ETH = "ETH";
string internal constant TOKEN_USDT = "USDT";
// ETH pledge account
mapping(address => uint256) internal verifyEthAccount;
/**
* Event for createOrderContract logging.
* @param newOrderContract management contract address.
*/
event CreateOrderContract(address newOrderContract);
/**
* Event for WithdrawToken logging.
* @param maker address of investor.
* @param pledgeTokenName token name.
* @param refundSum number of tokens withdrawn.
*/
event WithdrawToken(address indexed maker, string pledgeTokenName, uint256 refundSum);
/**
* Event for appendEscrow logging.
* @param maker address of borrower.
* @param appendSum append amount.
*/
event AppendEscrow(address indexed maker, uint256 appendSum);
/**
* @dev Constructor initial contract configuration parameters
*/
constructor(uint256 _pledgeId, address _factory , address _escrowContract) public {
require(_pledgeId > 0 && _factory != address(0) && _escrowContract != address(0));
pledgeId = _pledgeId;
factory = _factory;
status = StatusChoices.NO_PLEDGE_INFO;
escrowContract = _escrowContract;
}
// -----------------------------------------
// external interface
// -----------------------------------------
function() external payable {
require(status != StatusChoices.PLEDGE_REFUND);
// Identify the borrower.
if (maker != address(0)) {
require(address(msg.sender) == maker);
}
// Record basic information about the borrower's pledge ETH
verifyEthAccount[msg.sender] = verifyEthAccount[msg.sender].add(msg.value);
}
/**
* @dev Add the pledge information and transfer the pledged token into the corresponding currency pool.
* @param _pledgeTokenName maker pledge token name.
* @param _maker borrower address.
* @param _pledgeSum pledge amount.
* @param _loanTokenName pledge token type.
*/
function addRecord(string _pledgeTokenName, address _maker, uint256 _pledgeSum, string _loanTokenName) public onlyOwner {
require(_maker != address(0) && _pledgeSum > 0 && status != StatusChoices.PLEDGE_REFUND);
// Add the pledge information for the first time.
if (status == StatusChoices.NO_PLEDGE_INFO) {
// public data init.
maker = _maker;
pledgeTokenName = _pledgeTokenName;
tokenPoolAddress = checkedTokenPool(pledgeTokenName);
PledgeFactory(factory).updatePledgeType(pledgeId, pledgeTokenName);
// Assign rights to the operation of the contract pool
PledgeFactory(factory).tokenPoolOperater(tokenPoolAddress, address(this));
// Create order management contracts.
createOrderContract(_loanTokenName);
}
// Record information of each pledge.
pledgeAccountSum = pledgeAccountSum.add(_pledgeSum);
PledgePoolBase(tokenPoolAddress).addRecord(maker, pledgeAccountSum, pledgeId, pledgeTokenName);
// Transfer the pledge token to the appropriate token pool.
if (pledgeTokenName.stringCompare(TOKEN_ETH)) {
require(verifyEthAccount[maker] >= _pledgeSum);
tokenPoolAddress.transfer(_pledgeSum);
} else {
token20 = checkedToken(pledgeTokenName);
require(ERC20(token20).balanceOf(address(this)) >= _pledgeSum);
require(safeErc20Transfer(token20,tokenPoolAddress, _pledgeSum));
}
}
/**
* @dev Increase the number of pledged tokens.
* @param _appendSum append amount.
*/
function appendEscrow(uint256 _appendSum) public onlyOwner {
require(status == StatusChoices.PLEDGE_CREATE_MATCHING);
addRecord(pledgeTokenName, maker, _appendSum, loanTokenName);
emit AppendEscrow(maker, _appendSum);
}
/**
* @dev Withdraw pledge behavior.
* @param _maker borrower address.
*/
function withdrawToken(address _maker) public onlyOwner {
require(status != StatusChoices.PLEDGE_REFUND);
uint256 pledgeSum = 0;
// there are two types of retractions.
if (status == StatusChoices.NO_PLEDGE_INFO) {
pledgeSum = classifySquareUp(_maker);
} else {
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).withdrawToken(pledgeId, maker, pledgeAccountSum));
pledgeSum = pledgeAccountSum;
}
emit WithdrawToken(_maker, pledgeTokenName, pledgeSum);
}
/**
* @dev Executed in some extreme unforsee cases, to avoid eth locked.
* @param _tokenName recycle token type.
* @param _amount Number of eth to recycle.
*/
function recycle(string _tokenName, uint256 _amount) public onlyOwner {
require(status != StatusChoices.NO_PLEDGE_INFO && _amount>0);
if (_tokenName.stringCompare(TOKEN_ETH)) {
require(address(this).balance >= _amount);
owner.transfer(_amount);
} else {
address token = checkedToken(_tokenName);
require(ERC20(token).balanceOf(address(this)) >= _amount);
require(safeErc20Transfer(token,owner, _amount));
}
}
/**
* @dev Since the implementation of usdt ERC20.sol transfer code does not design the return value,
* @dev which is different from most ERC20 token interfaces,most erc20 transfer token agreements return bool.
* @dev it is necessary to independently adapt the interface for usdt token in order to transfer successfully
* @dev if not, the transfer may fail.
*/
function safeErc20Transfer(address _token20,address _toAddress,uint256 _transferSum) internal returns (bool) {
if(loanTokenName.stringCompare(TOKEN_USDT)){
UsdtERC20(_token20).transfer(_toAddress, _transferSum);
}else{
require(ERC20(_token20).transfer(_toAddress, _transferSum));
}
return true;
}
// -----------------------------------------
// internal interface
// -----------------------------------------
/**
* @dev Create an order process management contract for the match and repayment business.
* @param _loanTokenName expect loan token type.
*/
function createOrderContract(string _loanTokenName) internal {
require(bytes(_loanTokenName).length > 0);
status = StatusChoices.PLEDGE_CREATE_MATCHING;
address loanToken20 = checkedToken(_loanTokenName);
OrderManageContract newOrder = new OrderManageContract(_loanTokenName, loanToken20, maker);
setPartner(address(newOrder));
newOrder.setPartner(owner);
// update contract public data.
orderContract = newOrder;
loanTokenName = _loanTokenName;
emit CreateOrderContract(address(newOrder));
}
/**
* @dev classification withdraw.
* @dev Execute without changing the current contract data state.
* @param _maker borrower address.
*/
function classifySquareUp(address _maker) internal returns(uint256 sum) {
if (pledgeTokenName.stringCompare(TOKEN_ETH)) {
uint256 pledgeSum = verifyEthAccount[_maker];
require(pledgeSum > 0 && address(this).balance >= pledgeSum);
_maker.transfer(pledgeSum);
verifyEthAccount[_maker] = 0;
sum = pledgeSum;
} else {
uint256 balance = ERC20(token20).balanceOf(address(this));
require(balance > 0);
require(safeErc20Transfer(token20,_maker, balance));
sum = balance;
}
}
/**
* @dev Check wether the token is included for a token name.
* @param _tokenName token name.
*/
function checkedToken(string _tokenName) internal view returns(address) {
address tokenAddress = EscrowMaintainContract(escrowContract).includeToken(_tokenName);
require(tokenAddress != address(0));
return tokenAddress;
}
/**
* @dev Check wether the token pool is included for a token name.
* @param _tokenName pledge token name.
*/
function checkedTokenPool(string _tokenName) internal view returns(address) {
address tokenPool = EscrowMaintainContract(escrowContract).includeTokenPool(_tokenName);
require(tokenPool != address(0));
return tokenPool;
}
// -----------------------------------------
// business relationship interface
// (Only the order contract has authority to operate)
// -----------------------------------------
/**
* @dev Refund of the borrower’s pledge.
*/
function _conclude() public onlyPartner {
require(status == StatusChoices.PLEDGE_CREATE_MATCHING);
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).refundTokens(pledgeId, pledgeAccountSum, maker));
}
/**
* @dev Expired for repayment or close position.
* @param _taker address of investor.
*/
function _forceConclude(address _taker) public onlyPartner {
require(_taker != address(0) && status == StatusChoices.PLEDGE_CREATE_MATCHING);
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).refundTokens(pledgeId, pledgeAccountSum, _taker));
}
// -----------------------------------------
// query interface (use no gas)
// -----------------------------------------
/**
* @dev Get current contract order status.
* @return pledgeStatus state indicate.
*/
function getPledgeStatus() public view returns(string pledgeStatus) {
if (status == StatusChoices.NO_PLEDGE_INFO) {
pledgeStatus = "NO_PLEDGE_INFO";
} else if (status == StatusChoices.PLEDGE_CREATE_MATCHING) {
pledgeStatus = "PLEDGE_CREATE_MATCHING";
} else {
pledgeStatus = "PLEDGE_REFUND";
}
}
/**
* @dev get order contract address. use no gas.
*/
function getOrderContract() public view returns(address) {
return orderContract;
}
/**
* @dev Gets the total number of tokens pledged under the current contract.
*/
function getPledgeAccountSum() public view returns(uint256) {
return pledgeAccountSum;
}
/**
* @dev get current contract borrower address.
*/
function getMakerAddress() public view returns(address) {
return maker;
}
/**
* @dev get current contract pledge Id.
*/
function getPledgeId() external view returns(uint256) {
return pledgeId;
}
}
/**
* @title PledgeFactory
* @dev Pledge factory contract.
* @dev Specially provides the pledge guarantee creation and the statistics function.
*/
contract PledgeFactory is RBACOperator {
using AddressUtils for address;
// initial type of pledge contract.
string internal constant INIT_TOKEN_NAME = "UNKNOWN";
mapping(uint256 => EscrowPledge) internal pledgeEscrowById;
// pledge number unique screening.
mapping(uint256 => bool) internal isPledgeId;
/**
* @dev Pledge guarantee statistics.
*/
struct EscrowPledge {
address pledgeContract;
string tokenName;
}
/**
* Event for createOrderContract logging.
* @param pledgeId management contract id.
* @param newPledgeAddress pledge management contract address.
*/
event CreatePledgeContract(uint256 indexed pledgeId, address newPledgeAddress);
/**
* @dev Create a pledge subcontract
* @param _pledgeId index number of the pledge contract.
*/
function createPledgeContract(uint256 _pledgeId, address _escrowPartner) public onlyPartner returns(bool) {
require(_pledgeId > 0 && !isPledgeId[_pledgeId] && _escrowPartner!=address(0));
// Give the pledge contract the right to update statistics.
PledgeContract pledgeAddress = new PledgeContract(_pledgeId, address(this),partner);
pledgeAddress.transferOwnership(_escrowPartner);
addOperater(address(pledgeAddress));
// update pledge contract info
isPledgeId[_pledgeId] = true;
pledgeEscrowById[_pledgeId] = EscrowPledge(pledgeAddress, INIT_TOKEN_NAME);
emit CreatePledgeContract(_pledgeId, address(pledgeAddress));
return true;
}
/**
* @dev Batch create a pledge subcontract
* @param _pledgeIds index number of the pledge contract.
*/
function batchCreatePledgeContract(uint256[] _pledgeIds, address _escrowPartner) public onlyPartner {
require(_pledgeIds.length > 0 && _escrowPartner.isContract());
for (uint i = 0; i < _pledgeIds.length; i++) {
require(createPledgeContract(_pledgeIds[i],_escrowPartner));
}
}
/**
* @dev Use the index to get the basic information of the corresponding pledge contract.
* @param _pledgeId index number of the pledge contract
*/
function getEscrowPledge(uint256 _pledgeId) public view returns(string tokenName, address pledgeContract) {
require(_pledgeId > 0);
tokenName = pledgeEscrowById[_pledgeId].tokenName;
pledgeContract = pledgeEscrowById[_pledgeId].pledgeContract;
}
// -----------------------------------------
// Internal interface (Only the pledge contract has authority to operate)
// -----------------------------------------
/**
* @dev Configure permissions to operate on the token pool.
* @param _tokenPool token pool contract address.
* @param _pledge pledge contract address.
*/
function tokenPoolOperater(address _tokenPool, address _pledge) public hasOperationPermission {
require(_pledge != address(0) && address(msg.sender).isContract() && address(msg.sender) == _pledge);
PledgePoolBase(_tokenPool).addOperater(_pledge);
}
/**
* @dev Update the basic data of the pledge contract.
* @param _pledgeId index number of the pledge contract.
* @param _tokenName pledge contract supported token type.
*/
function updatePledgeType(uint256 _pledgeId, string _tokenName) public hasOperationPermission {
require(_pledgeId > 0 && bytes(_tokenName).length > 0 && address(msg.sender).isContract());
pledgeEscrowById[_pledgeId].tokenName = _tokenName;
}
} | Create an order process management contract for the match and repayment business. _loanTokenName expect loan token type./ update contract public data. | function createOrderContract(string _loanTokenName) internal {
require(bytes(_loanTokenName).length > 0);
status = StatusChoices.PLEDGE_CREATE_MATCHING;
address loanToken20 = checkedToken(_loanTokenName);
OrderManageContract newOrder = new OrderManageContract(_loanTokenName, loanToken20, maker);
setPartner(address(newOrder));
newOrder.setPartner(owner);
orderContract = newOrder;
loanTokenName = _loanTokenName;
emit CreateOrderContract(address(newOrder));
}
| 6,378,407 |
./partial_match/56/0x24c3BB296AcA3CC27A9747Af53a38940579EE74f/sources/XETIToken.sol | Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
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), "XETI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "XETI::delegateBySig: invalid nonce");
require(now <= expiry, "XETI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 11,193,596 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "./KeeperWhitelist.sol";
import "./PoolCreatorV1.sol";
abstract contract PoolCreatorV2 is PoolCreatorV1, KeeperWhitelist {
/**
* @notice Owner of version control.
*/
function owner() public view override(OwnableUpgradeable, PoolCreatorV1) returns (address) {
return OwnableUpgradeable.owner();
}
}
| Owner of version control./ | function owner() public view override(OwnableUpgradeable, PoolCreatorV1) returns (address) {
return OwnableUpgradeable.owner();
}
| 5,391,950 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
import "https://github.com/starkware-libs/veedo/blob/master/contracts/BeaconContract.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c4bb7b7bb9f09534bf010f6bf6f0d85bf2bf1caa/contracts/math/SafeMath.sol";
/**
* @title Randomness Game
* @notice Contract to play the game. Game requires
* two players to try to guess a random number between
* 0-255. Whoever is closest, wins the total price of entry
* of both players.
*/
contract RandomnessGame {
address veedoBeaconAddress;
address owner;
uint8 public guessOne; // Make private for end
uint8 public guessTwo; // Make private for end
uint public targetNumber; // Make private for end
bool hasFirstGuess = false;
bool hasSecondGuess = false;
address payable public playerOne; // Make private for end
address payable public playerTwo; // Make private for end
address public winningAddress;
bool public isGameActive = false;
bool public tieGame = false;
uint public coolDownTime; // Make private for end
uint public blockNow = block.number; // Delete. For testing only.
event addedPlayer(address _player);
event winningsDispersed(address _winner, uint _winnings);
// Modifier not needed after demo
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @notice Constructor function that will take the beacon address
* and call setBeaconContractAddress() to set it to the variable.
* It will also set the creator of the contract as the owner.
* @param _veedoBeaconAddress address of the VeeDo beacon that
* will provide randomness.
*/
constructor(address _veedoBeaconAddress) public {
setBeaconContractAddress(_veedoBeaconAddress);
owner = msg.sender; // delete after demo
}
/**
* @notice Fallback function that returns funds sent to
* it on accident.
*/
function () external payable {
msg.sender.transfer(msg.value);
}
/**
* @notice Function that resets the game by
* clearing all relevant variables.
*/
function resetGame() public /*private*/ onlyOwner() /*delete modifier*/ {
guessOne = 0;
guessTwo = 0;
targetNumber = 0;
hasFirstGuess = false;
hasSecondGuess = false;
playerOne = address(0);
playerTwo = address(0);
winningAddress = address(0);
isGameActive = false;
tieGame = false;
blockNow = block.number; // Delete. For testing only.
}
/**
* @notice Function called to play the game. Game requires
* two players to try to guess a random number between
* 0-255. Whoever is closest, wins the total price of entry
* of all players.
* @param _guess a uint8 guess to try to be the closest
* to a randomly generated number.
*/
function playGame(uint8 _guess) public payable {
// Verifying that 240 blocks has passed since
// the last randomly generated number.
require(
block.number > (coolDownTime + 240),
"Not enough time has passed to play again."
);
// Verify 0.1 ether have been sent.
// (0.1 ether for testing only,
// 0.02 ether will be the normal amount)
require(msg.value == 0.1 ether);
// Confirm the guess is valid (0-255)
require(_guess < 256);
// Submit guess as valid for second player
// if first player has guessed already.
if (hasFirstGuess == true) {
guessTwo = _guess;
playerTwo = msg.sender;
hasSecondGuess = true;
isGameActive = true;
emit addedPlayer(msg.sender);
// After both guesses have been
// submitted, calculate the target number.
targetNumber = getRandomNumber();
// If guess one has not been declared,
// set equal to function argument.
} else {
guessOne = _guess;
playerOne = msg.sender;
hasFirstGuess = true;
isGameActive = true;
emit addedPlayer(msg.sender);
}
// Compare the guesses to the
// target number, decide the winner
// and disperse the winnings.
if (
hasFirstGuess == true && hasSecondGuess == true
) {
if (
guessOne == guessTwo
) {
tieGame = true;
playerOne.transfer((address(this).balance) / 2);
playerTwo.transfer((address(this).balance) / 2);
} else if (
(guessOne < targetNumber) &&
(guessTwo < targetNumber)
) {
if (
(SafeMath.sub(targetNumber, guessOne)) <
(SafeMath.sub(targetNumber, guessTwo))
) {
awardWinner(playerOne);
} else if (
(SafeMath.sub(targetNumber, guessTwo)) <
(SafeMath.sub(targetNumber, guessOne))
) {
awardWinner(playerTwo);
}
} else if (
(guessOne > targetNumber) &&
(guessTwo > targetNumber)
) {
if (
(SafeMath.sub(guessOne, targetNumber)) <
(SafeMath.sub(guessTwo, targetNumber))
) {
awardWinner(playerOne);
} else if (
(SafeMath.sub(guessTwo, targetNumber)) <
(SafeMath.sub(guessOne, targetNumber))
) {
awardWinner(playerTwo);
}
} else if (
(guessOne > targetNumber) &&
(guessTwo < targetNumber)
) {
if (
(SafeMath.sub(guessOne, targetNumber)) <
(SafeMath.sub(targetNumber, guessTwo))
) {
awardWinner(playerOne);
} else if (
(SafeMath.sub(targetNumber, guessTwo)) <
(SafeMath.sub(guessOne, targetNumber))
) {
awardWinner(playerTwo);
}
} else if (
(guessOne < targetNumber) &&
(guessTwo > targetNumber)
) {
if (
(SafeMath.sub(targetNumber, guessOne)) <
(SafeMath.sub(guessTwo, targetNumber))
) {
awardWinner(playerOne);
} else if (
(SafeMath.sub(guessTwo, targetNumber)) <
(SafeMath.sub(targetNumber, guessOne))
) {
awardWinner(playerTwo);
}
}
// resetGame();
// Calling and setting the value of the latest
// block to provide a random number to begin
// a cool down period until the next pulse.
BeaconContract veedoBeacon = BeaconContract(veedoBeaconAddress);
(uint latestBlockNumber, bytes32 registeredRandomness) = veedoBeacon.getLatestRandomness();
coolDownTime = latestBlockNumber;
}
}
// @notice Function to withdraw funds in case game
// doesn't work as expected. Only for testing.
function withdrawFunds() public {
msg.sender.transfer(address(this).balance);
}
/*
* @notice Setter function that adds randomness beacon
* address to previously declared address variable
* @param _address address of the beacon that
* will provide randomness.
*/
function setBeaconContractAddress(address _address) private {
veedoBeaconAddress = _address;
}
/**
* @notice Function that sends out funds to
* winning address.
* @param _player address of the winning
* player to receive funds.
*/
function awardWinner(address payable _player) private {
emit winningsDispersed(_player, address(this).balance);
winningAddress = _player;
_player.transfer(address(this).balance);
}
/**
* @notice Function called to generate new randon number
* from beacon contract, that will then be converted
* into a uint8.
* @return uint the randomly generated number.
*/
function getRandomNumber() private view returns(uint) {
BeaconContract veedoBeacon = BeaconContract(veedoBeaconAddress);
(uint latestBlockNumber, bytes32 registeredRandomness) = veedoBeacon.getLatestRandomness();
uint randomNumber = uint(registeredRandomness);
randomNumber = uint8(randomNumber);
return randomNumber;
}
} | Fallback function that returns funds sent to it on accident./ | function () external payable {
msg.sender.transfer(msg.value);
}
| 6,481,576 |
./full_match/1/0x7d9CCd94ba18CdE4FBE93F918018B4A9FAa99893/sources/contracts/LiveMintArtist.sol | Returns A 2d Array Of Minted ArtistIDs/ | function readUnmintedTicketIDs(uint[] calldata ArtistIDs, uint Range) public view returns(uint[][] memory TokenIDs)
{
uint[][] memory _TokenIDs = new uint[][](ArtistIDs.length);
uint Index;
for(uint ArtistID; ArtistID < ArtistIDs.length; ArtistID++)
{
uint[] memory UnmintedArtistTokenIDs = new uint[](Range);
uint Counter;
for(uint TokenID; TokenID < Range; TokenID++)
{
bool TicketIDBurned;
if(
!MintedArtist[ArtistIDs[ArtistID]][TokenID]
&&
(
BrightListArtist[ArtistIDs[ArtistID]][TokenID] != address(0)
||
TicketIDBurned
)
)
{
UnmintedArtistTokenIDs[Counter] = TokenID;
Counter++;
}
}
uint[] memory FormattedUnMintedArtistIDs = new uint[](Counter);
uint Found;
for(uint x; x < Counter; x++)
{
if(UnmintedArtistTokenIDs[x] != 0 || (UnmintedArtistTokenIDs[x] == 0 && x == 0))
{
FormattedUnMintedArtistIDs[Found] = UnmintedArtistTokenIDs[x];
Found++;
}
}
_TokenIDs[Index] = FormattedUnMintedArtistIDs;
Index++;
}
return (_TokenIDs);
}
| 17,096,950 |
./partial_match/1/0x20C998410b16CeDbB5B4c96e06f3cAe347feC5cd/sources/FORT.sol | The ETH balance of the account is not enough to perform the operation./ There's no code at `target` (it is not a contract)./ A call to an address target failed. The target may have reverted./ | function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
if (!success) {
revert FailedInnerCall();
}
}
| 4,160,859 |
./full_match/11155111/0x36ffB4740650FdbD307F50bD7344B447e3FF66DD/sources/diamond/records/RecordFacet.sol | In this case, the downtime starts in justified time, but ends outside it In this case, the downtime starts before justified time, but ends inside it | function removeJustifiedTimes(
uint _recordStartDate,
uint _recordEndDate,
RecordLib.Period[] memory _justifiedPeriods)
internal pure
returns(uint calculatedDownTime){
calculatedDownTime = 0;
uint insideDownTime = 0;
for(uint i = 0; i < _justifiedPeriods.length; i++){
if(_justifiedPeriods[i].start <= _recordStartDate && _justifiedPeriods[i].end >= _recordEndDate){
}
else if(_justifiedPeriods[i].start <= _recordStartDate && _justifiedPeriods[i].end >= _recordStartDate && _justifiedPeriods[i].end <= _recordEndDate) {
_recordStartDate = _justifiedPeriods[i].end;
}
else if(_justifiedPeriods[i].start >= _recordStartDate && _justifiedPeriods[i].end >= _recordEndDate && _justifiedPeriods[i].start <= _recordEndDate) {
_recordEndDate = _justifiedPeriods[i].start;
}
else if(_justifiedPeriods[i].start >= _recordStartDate && _justifiedPeriods[i].end <= _recordEndDate) {
insideDownTime += _justifiedPeriods[i].end - _justifiedPeriods[i].start;
}
}
return _recordEndDate - _recordStartDate - insideDownTime;
}
| 3,831,032 |
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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, 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) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* 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);
uint256 c = a - b;
return c;
}
/**
* @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) {
// 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, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts 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) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts 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) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1;
// All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key : key, _value : value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1;
// All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
// Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value;
// All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId,) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mecanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: contracts/common/AccessControlMixin.sol
pragma solidity 0.6.6;
contract AccessControlMixin is AccessControl {
string private _revertMsg;
function _setupContractId(string memory contractId) internal {
_revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS"));
}
modifier only(bytes32 role) {
require(
hasRole(role, _msgSender()),
_revertMsg
);
_;
}
}
// File: contracts/common/Initializable.sol
pragma solidity 0.6.6;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/common/EIP712Base.sol
pragma solidity 0.6.6;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contractsa that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/common/NativeMetaTransaction.sol
pragma solidity 0.6.6;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce : nonces[userAddress],
from : userAddress,
functionSignature : functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
msg.sender,
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File: contracts/root/RootToken/IMintableERC721.sol
pragma solidity 0.6.6;
interface IMintableERC721 is IERC721 {
/**
* @notice called by predicate contract to mint tokens while withdrawing
* @dev Should be callable only by MintableERC721Predicate
* Make sure minting is done only by this function
* @param user user address for whom token is being minted
* @param tokenId tokenId being minted
*/
function mint(address user, uint256 tokenId) external;
/**
* @notice called by predicate contract to mint tokens while withdrawing with metadata from L2
* @dev Should be callable only by MintableERC721Predicate
* Make sure minting is only done either by this function/ 👆
* @param user user address for whom token is being minted
* @param tokenId tokenId being minted
* @param metaData Associated token metadata, to be decoded & set using `setTokenMetadata`
*
* Note : If you're interested in taking token metadata from L2 to L1 during exit, you must
* implement this method
*/
function mint(address user, uint256 tokenId, bytes calldata metaData) external;
/**
* @notice check if token already exists, return true if it does exist
* @dev this check will be used by the predicate to determine if the token needs to be minted or transfered
* @param tokenId tokenId being checked
*/
function exists(uint256 tokenId) external view returns (bool);
}
// File: contracts/common/ContextMixin.sol
pragma solidity 0.6.6;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
}
// File: contracts/root/RootToken/DummyMintableERC721.sol
pragma experimental ABIEncoderV2;
pragma solidity 0.6.6;
contract ArtvatarsMintableERC721 is
ERC721,
AccessControlMixin,
NativeMetaTransaction,
IMintableERC721,
ContextMixin
{
bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE");
mapping(uint256 => Artvatar) public tokenToArtvatar;
struct Attribute {
string title;
string name;
}
struct Artvatar {
uint256 id;
string series;
string title;
string description;
string image;
Attribute[] attributes;
bool metadataChanged;
}
constructor(string memory name_, string memory symbol_, address predicateProxy_)
public
ERC721(name_, symbol_)
{
_setupContractId("ArtvatarsMintableERC721");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PREDICATE_ROLE, _msgSender());
_setupRole(PREDICATE_ROLE, predicateProxy_);
_initializeEIP712(name_);
}
function _msgSender()
internal
override
view
returns (address payable sender)
{
return ContextMixin.msgSender();
}
/**
* @dev See {IMintableERC721-mint}.
*/
function mint(address user, uint256 tokenId) external override only(PREDICATE_ROLE) {
_mint(user, tokenId);
}
/**
* If you're attempting to bring metadata associated with token
* from L2 to L1, you must implement this method, to be invoked
* when minting token back on L1, during exit
*/
function setTokenMetadata(uint256 tokenId, bytes memory data) internal virtual {
// This function should decode metadata obtained from L2
// and attempt to set it for this `tokenId`
//
// Following is just a default implementation, feel
// free to define your own encoding/ decoding scheme
// for L2 -> L1 token metadata transfer
(Artvatar memory _artvatar, string memory uri) = abi.decode(data, (Artvatar, string));
Artvatar storage artvatar = tokenToArtvatar[tokenId];
Attribute[] memory _attributes = _artvatar.attributes;
artvatar.id = _artvatar.id;
artvatar.series = _artvatar.series;
artvatar.title = _artvatar.title;
artvatar.description = _artvatar.description;
artvatar.image = _artvatar.image;
for (uint256 i = 0; i < _attributes.length; i++) {
Attribute memory attribute = _attributes[i];
artvatar.attributes.push(attribute);
}
artvatar.metadataChanged = true;
_setTokenURI(tokenId, uri);
}
function getArtvatarByTokenId(uint256 _tokenId) public view returns (Artvatar memory artvatar) {
return tokenToArtvatar[_tokenId];
}
/**
* @dev See {IMintableERC721-mint}.
*
* If you're attempting to bring metadata associated with token
* from L2 to L1, you must implement this method
*/
function mint(address user, uint256 tokenId, bytes calldata metaData) external override only(PREDICATE_ROLE) {
_mint(user, tokenId);
setTokenMetadata(tokenId, metaData);
}
/**
* @dev See {IMintableERC721-exists}.
*/
function exists(uint256 tokenId) external view override returns (bool) {
return _exists(tokenId);
}
} | See {IERC721Enumerable-totalSupply}./ _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds | function totalSupply() public view override returns (uint256) {
return _tokenOwners.length();
}
| 1,139,837 |
pragma solidity 0.5.14;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IToken { // brief ERC-20 interface
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract LXCHAT is Ownable { // perma post with lexDAO legal engineers & apprentices
address public accessToken = 0xAF0348b2A3818BD6Bc1f12bd2a9f73F1B725448F;
address public leethToken = 0x4D9D9a22458dD84dB8B0D074470f5d9536116eC5;
IToken private token = IToken(accessToken);
IToken private leeth = IToken(leethToken);
uint256 public posts;
string public redemptionOffer;
mapping (uint256 => post) public postings;
event LexPosting(uint256 indexed index, string indexed details);
event Offering(string indexed details);
event Posting(uint256 indexed index, string indexed details);
event Redemption(string indexed details, string indexed redemptionOffer);
struct post {
address poster;
uint256 index;
string details;
string response;
}
// accessToken holder functions
function newPost(string memory details) public { // accessToken holder (>= 1) can always write to contract
require(token.balanceOf(_msgSender()) >= 1000000000000000000, "accessToken balance insufficient");
uint256 index = posts + 1;
posts = posts + 1;
postings[index] = post(
_msgSender(),
index,
details,
"");
emit Posting(index, details);
}
function redeemOffer(string memory details) public { // accessToken holder can deposit (1) to redeem current offer
token.transferFrom(_msgSender(), address(this), 1000000000000000000);
emit Redemption(details, redemptionOffer);
}
function updatePost(uint256 index, string memory details) public { // accessToken holder can always update posts
post storage p = postings[index];
require(_msgSender() == p.poster, "must be indexed poster");
p.details = details;
emit Posting(index, details);
}
// lexDAO functions
function lexPost(uint256 index, string memory details) public { // leethToken holder (5) can always write responses to posts
require(leeth.balanceOf(_msgSender()) >= 5000000000000000000, "leeth balance insufficient");
post storage p = postings[index];
p.response = details;
emit LexPosting(index, details);
}
function updateRedemptionOffer(string memory details) public onlyOwner { // owner can update redemption offer for accessToken
redemptionOffer = details;
emit Offering(details);
}
function withdraw() public onlyOwner { // owner can withdraw redeemed accessToken
token.transfer(_msgSender(), token.balanceOf(address(this)));
}
}
| accessToken holder (>= 1) can always write to contract | function newPost(string memory details) public { | 6,345,145 |
pragma solidity ^0.4.18;
/*
VERSION DATE: 04/06/2018
CREATED BY: CRYPTO SPORTZ
ENJOY YOUR TEAM AND SPORTS AND EMAIL US IF YOU HAVE ANY QUESTIONS
*/
contract ERC721Abstract
{
function implementsERC721() public pure returns (bool);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function totalSupply() public view returns (uint256 total);
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract ERC721 is ERC721Abstract
{
string constant public name = "CryptoSportZ";
string constant public symbol = "CSZ";
uint256 public totalSupply;
struct Token
{
uint256 price; // value of stake
uint256 option; // [payout]96[idGame]64[combination]32[dateBuy]0
}
mapping (uint256 => Token) tokens;
// A mapping from tokens IDs to the address that owns them. All tokens have some valid owner address
mapping (uint256 => address) public tokenIndexToOwner;
// A mapping from owner address to count of tokens that address owns.
mapping (address => uint256) ownershipTokenCount;
// A mapping from tokenIDs to an address that has been approved to call transferFrom().
// Each token can only have one approved address for transfer at any time.
// A zero value means no approval is outstanding.
mapping (uint256 => address) public tokenIndexToApproved;
function implementsERC721() public pure returns (bool)
{
return true;
}
function balanceOf(address _owner) public view returns (uint256 count)
{
return ownershipTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
// Marks an address as being approved for transferFrom(), overwriting any previous approval.
// Setting _approved to address(0) clears all transfer approval.
function _approve(uint256 _tokenId, address _approved) internal
{
tokenIndexToApproved[_tokenId] = _approved;
}
// Checks if a given address currently has transferApproval for a particular token.
// param _claimant the address we are confirming token is approved for.
// param _tokenId token id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToApproved[_tokenId] == _claimant;
}
function approve( address _to, uint256 _tokenId ) public
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
function transferFrom( address _from, address _to, uint256 _tokenId ) public
{
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
function _transfer(address _from, address _to, uint256 _tokenId) internal
{
ownershipTokenCount[_to]++;
tokenIndexToOwner[_tokenId] = _to;
if (_from != address(0))
{
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete tokenIndexToApproved[_tokenId];
Transfer(_from, _to, _tokenId);
}
}
function transfer(address _to, uint256 _tokenId) public
{
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
}
contract Owned
{
address private candidate;
address public owner;
mapping(address => bool) public admins;
function Owned() public
{
owner = msg.sender;
}
function changeOwner(address newOwner) public
{
require(msg.sender == owner);
candidate = newOwner;
}
function confirmOwner() public
{
require(candidate == msg.sender); // run by name=candidate
owner = candidate;
}
function addAdmin(address addr) external
{
require(msg.sender == owner);
admins[addr] = true;
}
function removeAdmin(address addr) external
{
require(msg.sender == owner);
admins[addr] = false;
}
}
contract Functional
{
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint)
{
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string)
{
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function strConcat(string _a, string _b, string _c) internal pure returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abc;
uint k = 0;
uint i;
bytes memory babc;
if (_ba.length==0)
{
abc = new string(_bc.length);
babc = bytes(abc);
}
else
{
abc = new string(_ba.length + _bb.length+ _bc.length);
babc = bytes(abc);
for (i = 0; i < _ba.length; i++) babc[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babc[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) babc[k++] = _bc[i];
return string(babc);
}
function timenow() public view returns(uint32) { return uint32(block.timestamp); }
}
contract CryptoSportZ is ERC721, Functional, Owned
{
uint256 public feeGame;
enum Status {
NOTFOUND, //0 game not created
PLAYING, //1 buying tickets
PROCESSING, //2 waiting for result
PAYING, //3 redeeming
CANCELING //4 canceling the game
}
struct Game {
string nameGame;
uint32 countCombinations;
uint32 dateStopBuy;
uint32 winCombination;
uint256 betsSumIn; // amount bets
uint256 feeValue; // amount fee
Status status; // status of game
bool isFreezing;
}
mapping (uint256 => Game) private game;
uint32 public countGames;
uint32 private constant shiftGame = 0;
uint32 private constant FEECONTRACT = 5;
struct Stake {
uint256 sum; // amount bets
uint32 count; // count bets
}
mapping(uint32 => mapping (uint32 => Stake)) public betsAll; // ID-game => combination => Stake
mapping(bytes32 => uint32) private queryRes; // ID-query => ID-game
event LogEvent(string _event, string nameGame, uint256 value);
event LogToken(string _event, address user, uint32 idGame, uint256 idToken, uint32 combination, uint256 amount);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(msg.sender == owner || admins[msg.sender]);
_;
}
function getPriceTicket() public view returns ( uint32 )
{
if ( timenow() >= 1531339200 ) return 8000; // after 11.07 20:00
if ( timenow() >= 1530993600 ) return 4000; // after 07.07 20:00
if ( timenow() >= 1530648000 ) return 2000; // after 03.06 20:00
if ( timenow() >= 1530302400 ) return 1000; // after 29.06 20:00
if ( timenow() >= 1529870400 ) return 500; // after 24.06 20:00
if ( timenow() >= 1529438400 ) return 400; // after 19.06 20:00
if ( timenow() >= 1529006400 ) return 300; // after 14.06 20:00
if ( timenow() >= 1528747200 ) return 200; // after 11.06 20:00
if ( timenow() >= 1528401600 ) return 100; // after 07.06 20:00
return 50;
}
function getGameByID(uint32 _id) public view returns (
string nameGame,
uint32 countCombinations,
uint32 dateStopBuy,
uint32 priceTicket,
uint32 winCombination,
uint32 betsCount,
uint256 betsSumIn,
uint256 feeValue,
Status status,
bool isFreezing
){
Game storage gm = game[_id];
nameGame = gm.nameGame;
countCombinations = gm.countCombinations;
dateStopBuy = gm.dateStopBuy;
priceTicket = getPriceTicket();
winCombination = gm.winCombination;
betsCount = getCountTokensByGame(_id);
betsSumIn = gm.betsSumIn;
if (betsSumIn==0) betsSumIn = getSumInByGame(_id);
feeValue = gm.feeValue;
status = gm.status;
if ( status == Status.PLAYING && timenow() > dateStopBuy ) status = Status.PROCESSING;
isFreezing = gm.isFreezing;
}
function getBetsMas(uint32 idGame) public view returns (uint32[33])
{
Game storage curGame = game[idGame];
uint32[33] memory res;
for(uint32 i=1;i<=curGame.countCombinations;i++) res[i] = betsAll[idGame][i].count;
return res;
}
function getCountTokensByGame(uint32 idGame) internal view returns (uint32)
{
Game storage curGame = game[idGame];
uint32 count = 0;
for(uint32 i=1;i<=curGame.countCombinations;i++) count += betsAll[idGame][i].count;
return count;
}
function getSumInByGame(uint32 idGame) internal view returns (uint256)
{
Game storage curGame = game[idGame];
uint256 sum = 0;
for(uint32 i=1;i<=curGame.countCombinations;i++) sum += betsAll[idGame][i].sum;
return sum;
}
function getTokenByID(uint256 _id) public view returns (
uint256 price,
uint256 payment,
uint32 combination,
uint32 dateBuy,
uint32 idGame,
address ownerToken,
bool payout
){
Token storage tkn = tokens[_id];
price = tkn.price;
uint256 packed = tkn.option;
payout = uint8((packed >> (12*8)) & 0xFF)==1?true:false;
idGame = uint32((packed >> (8*8)) & 0xFFFFFFFF);
combination = uint32((packed >> (4*8)) & 0xFFFFFFFF);
dateBuy = uint32(packed & 0xFFFFFFFF);
payment = 0;
Game storage curGame = game[idGame];
uint256 betsSumIn = curGame.betsSumIn;
if (betsSumIn==0) betsSumIn = getSumInByGame(idGame);
if (curGame.winCombination==combination) payment = betsSumIn / betsAll[idGame][ curGame.winCombination ].count;
if (curGame.status == Status.CANCELING) payment = tkn.price;
ownerToken = tokenIndexToOwner[_id];
}
function getUserTokens(address user, uint32 count) public view returns ( string res )
{
res="";
require(user!=0x0);
uint32 findCount=0;
for (uint256 i = totalSupply-1; i >= 0; i--)
{
if(i>totalSupply) break;
if (user == tokenIndexToOwner[i])
{
res = strConcat( res, ",", uint2str(i) );
findCount++;
if (count!=0 && findCount>=count) break;
}
}
}
function getUserTokensByGame(address user, uint32 idGame) public view returns ( string res )
{
res="";
require(user!=0x0);
for(uint256 i=0;i<totalSupply;i++)
{
if (user == tokenIndexToOwner[i])
{
uint256 packed = tokens[i].option;
uint32 idGameToken = uint32((packed >> (8*8)) & 0xFFFFFFFF);
if (idGameToken == idGame) res = strConcat( res, ",", uint2str(i) );
}
}
}
function getTokensByGame(uint32 idGame) public view returns (string res)
{
res="";
for(uint256 i=0;i<totalSupply;i++)
{
uint256 packed = tokens[i].option;
uint32 idGameToken = uint32((packed >> (8*8)) & 0xFFFFFFFF);
if (idGameToken == idGame) res = strConcat( res, ",", uint2str(i) );
}
}
function getStatGames() public view returns (
uint32 countAll,
uint32 countPlaying,
uint32 countProcessing,
string listPlaying,
string listProcessing
){
countAll = countGames;
countPlaying = 0;
countProcessing = 0;
listPlaying="";
listProcessing="";
uint32 curtime = timenow();
for(uint32 i=shiftGame; i<countAll+shiftGame; i++)
{
if (game[i].status!=Status.PLAYING) continue;
if (curtime < game[i].dateStopBuy) { countPlaying++; listPlaying = strConcat( listPlaying, ",", uint2str(i) ); }
if (curtime >= game[i].dateStopBuy) { countProcessing++; listProcessing = strConcat( listProcessing, ",", uint2str(i) ); }
}
}
function CryptoSportZ() public
{
}
function freezeGame(uint32 idGame, bool freeze) public onlyAdmin
{
Game storage curGame = game[idGame];
require( curGame.isFreezing != freeze );
curGame.isFreezing = freeze;
}
function addGame( string _nameGame ) onlyAdmin public
{
require( bytes(_nameGame).length > 2 );
Game memory _game;
_game.nameGame = _nameGame;
_game.countCombinations = 32;
_game.dateStopBuy = 1531666800;
_game.status = Status.PLAYING;
uint256 newGameId = countGames + shiftGame;
game[newGameId] = _game;
countGames++;
LogEvent( "AddGame", _nameGame, newGameId );
}
function () payable public { require (msg.value == 0x0); }
function buyToken(uint32 idGame, uint32 combination, address captainAddress) payable public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( timenow() < curGame.dateStopBuy );
require( combination > 0 && combination <= curGame.countCombinations );
require( curGame.isFreezing == false );
uint256 userStake = msg.value;
uint256 ticketPrice = uint256(getPriceTicket()) * 1 finney;
// check money for stake
require( userStake >= ticketPrice );
if ( userStake > ticketPrice )
{
uint256 change = userStake - ticketPrice;
userStake = userStake - change;
require( userStake == ticketPrice );
msg.sender.transfer(change);
}
uint256 feeValue = userStake * FEECONTRACT / 100; // fee for contract
if (captainAddress!=0x0 && captainAddress != msg.sender)
{
uint256 captainValue = feeValue * 20 / 100; // bonus for captain = 1%
feeValue = feeValue - captainValue;
captainAddress.transfer(captainValue);
}
userStake = userStake - feeValue;
curGame.feeValue = curGame.feeValue + feeValue;
betsAll[idGame][combination].sum += userStake;
betsAll[idGame][combination].count += 1;
uint256 packed;
packed = ( uint128(idGame) << 8*8 ) + ( uint128(combination) << 4*8 ) + uint128(block.timestamp);
Token memory _token = Token({
price: userStake,
option : packed
});
uint256 newTokenId = totalSupply++;
tokens[newTokenId] = _token;
_transfer(0x0, msg.sender, newTokenId);
LogToken( "Buy", msg.sender, idGame, newTokenId, combination, userStake);
}
// take win money or money for canceling game
function redeemToken(uint256 _tokenId) public
{
Token storage tkn = tokens[_tokenId];
uint256 packed = tkn.option;
bool payout = uint8((packed >> (12*8)) & 0xFF)==1?true:false;
uint32 idGame = uint32((packed >> (8*8)) & 0xFFFFFFFF);
uint32 combination = uint32((packed >> (4*8)) & 0xFFFFFFFF);
Game storage curGame = game[idGame];
require( curGame.status == Status.PAYING || curGame.status == Status.CANCELING);
require( msg.sender == tokenIndexToOwner[_tokenId] ); // only onwer`s token
require( payout == false ); // has not paid
require( combination == curGame.winCombination || curGame.status == Status.CANCELING );
uint256 sumPayment = 0;
if ( curGame.status == Status.CANCELING ) sumPayment = tkn.price;
if ( curGame.status == Status.PAYING ) sumPayment = curGame.betsSumIn / betsAll[idGame][curGame.winCombination].count;
payout = true;
packed += uint128(payout?1:0) << 12*8;
tkn.option = packed;
msg.sender.transfer(sumPayment);
LogToken( "Redeem", msg.sender, idGame, uint32(_tokenId), combination, sumPayment);
}
function cancelGame(uint32 idGame) public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
// only owner/admin or anybody after 60 days
require( msg.sender == owner || admins[msg.sender] || timenow() > curGame.dateStopBuy + 60 days );
curGame.status = Status.CANCELING;
// LogEvent( "CancelGame", curGame.nameGame, idGame );
takeFee(idGame);
}
function resolveGameByHand(uint32 idGame, uint32 combination) onlyAdmin public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( combination <= curGame.countCombinations );
require( combination != 0 );
require( timenow() > curGame.dateStopBuy + 2*60*60 );
curGame.winCombination = combination;
// LogEvent( "ResolveGameByHand", curGame.nameGame, curGame.winCombination );
checkWinNobody(idGame);
}
function checkWinNobody(uint32 idGame) internal
{
Game storage curGame = game[idGame];
curGame.status = Status.PAYING;
curGame.betsSumIn = getSumInByGame(idGame);
// nobody win = send all to feeGame
if ( betsAll[idGame][curGame.winCombination].count == 0 )
{
if (curGame.betsSumIn+curGame.feeValue!=0) feeGame = feeGame + curGame.betsSumIn + curGame.feeValue;
LogEvent( "NobodyWin", curGame.nameGame, curGame.betsSumIn+curGame.feeValue );
}
else
takeFee(idGame);
}
function takeFee(uint32 idGame) internal
{
Game storage curGame = game[idGame];
// take fee
if ( curGame.feeValue > 0 )
{
feeGame = feeGame + curGame.feeValue;
LogEvent( "TakeFee", curGame.nameGame, curGame.feeValue );
}
}
function withdraw() onlyOwner public
{
require( feeGame > 0 );
uint256 tmpFeeGame = feeGame;
feeGame = 0;
owner.transfer(tmpFeeGame);
// LogEvent( "Withdraw", "", tmpFeeGame);
}
} | check money for stake | function buyToken(uint32 idGame, uint32 combination, address captainAddress) payable public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( timenow() < curGame.dateStopBuy );
require( combination > 0 && combination <= curGame.countCombinations );
require( curGame.isFreezing == false );
uint256 userStake = msg.value;
uint256 ticketPrice = uint256(getPriceTicket()) * 1 finney;
require( userStake >= ticketPrice );
if ( userStake > ticketPrice )
{
uint256 change = userStake - ticketPrice;
userStake = userStake - change;
require( userStake == ticketPrice );
msg.sender.transfer(change);
}
if (captainAddress!=0x0 && captainAddress != msg.sender)
{
feeValue = feeValue - captainValue;
captainAddress.transfer(captainValue);
}
userStake = userStake - feeValue;
curGame.feeValue = curGame.feeValue + feeValue;
betsAll[idGame][combination].sum += userStake;
betsAll[idGame][combination].count += 1;
uint256 packed;
packed = ( uint128(idGame) << 8*8 ) + ( uint128(combination) << 4*8 ) + uint128(block.timestamp);
Token memory _token = Token({
price: userStake,
option : packed
});
uint256 newTokenId = totalSupply++;
tokens[newTokenId] = _token;
_transfer(0x0, msg.sender, newTokenId);
LogToken( "Buy", msg.sender, idGame, newTokenId, combination, userStake);
}
| 1,168,097 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./Storage.sol";
contract StorageFactory {
Storage[] public StorageArray; //create array (type) Storage.
function createStorageContract() public {
Storage Storage = new Storage(); //create Storage type object namely Storage
//then new Storage() contracts without any
StorageArray.push(Storage); //When createStorageContract runs it is added to the array
}
// } here we can deploy Storage.sol contract from this Factory.sol contract.
//call store and retrieve functions in the Storage.sol from Factory.sol
function sfStore(uint256 _StorageIndex, uint256 _StorageNumber) public {
//_StorageIndex allows to choose which Storage[] contract in the created list that we wanna interact with
//_StorageNumber to call on the store function in the Storage.sol
//this line has an explicit cast to the address type and initializes a new Storage object from the address
Storage(address(StorageArray[_StorageIndex])).store(_StorageNumber);
//this line simply gets the Storage object at the index _StorageIndex in the array StorageArray
//StorageArray[_StorageIndex].store(_StorageNumber);
}
function sfGet(uint256 _StorageIndex) public view returns (uint256) {
//this line has an explicit cast to the address type and initializes a new Storage object from the address
return Storage(address(StorageArray[_StorageIndex])).retrieve();
//this line simply gets the Storage object at the index _StorageIndex in the array StorageArray
//return StorageArray[_StorageIndex].retrieve();
}
}
| this line has an explicit cast to the address type and initializes a new Storage object from the addressthis line simply gets the Storage object at the index _StorageIndex in the array StorageArrayreturn StorageArray[_StorageIndex].retrieve(); | function sfGet(uint256 _StorageIndex) public view returns (uint256) {
return Storage(address(StorageArray[_StorageIndex])).retrieve();
}
| 1,012,102 |
./full_match/1/0x2C9f65BD1a501CB406584F5532cE57c28829B131/sources/src/periphery/CauldronFeeWithdrawer.sol | only transfer the required mim amount | function withdraw() external returns (uint256 amount) {
for (uint256 i = 0; i < cauldronInfos.length; i++) {
CauldronInfo memory info = cauldronInfos[i];
if (ICauldronV1(info.masterContract).feeTo() != address(this)) {
revert ErrInvalidFeeTo(info.masterContract);
}
ICauldronV1(info.cauldron).accrue();
uint256 feesEarned;
IBentoBoxV1 bentoBox = info.bentoBox;
if (info.version == 1) {
(, feesEarned) = ICauldronV1(info.cauldron).accrueInfo();
(, feesEarned, ) = ICauldronV2(info.cauldron).accrueInfo();
}
uint256 cauldronMimAmount = bentoBox.toAmount(mim, bentoBox.balanceOf(mim, info.cauldron), false);
if (feesEarned > cauldronMimAmount) {
uint256 diff = feesEarned - cauldronMimAmount;
mim.safeTransferFrom(mimProvider, address(bentoBox), diff);
bentoBox.deposit(mim, address(bentoBox), info.cauldron, diff, 0);
}
ICauldronV1(info.cauldron).withdrawFees();
if (feeToOverride != address(0)) {
info.bentoBox.transfer(mim, address(this), feeToOverride, bentoBox.toShare(mim, feesEarned, false));
}
}
amount = _withdrawAllMimFromBentoBoxes();
emit CauldronFeeWithdrawWithdrawerEvents.LogMimTotalWithdrawn(amount);
}
| 17,184,393 |
// SPDX-License-Identifier: MIT
pragma solidity 0.5.6;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./lib/Babylonian.sol";
import "./owner/Operator.sol";
import "./interfaces/IJUNAsset.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IBoardroom.sol";
import "./TreasuryStorage.sol";
import "./TreasuryUni.sol";
import "./interfaces/ITreasury.sol";
/**
* @title JUN Protocol Treasury contract
* @notice Monetary policy logic to adjust supplies of JUN
*/
contract TreasuryImpl is TreasuryStorage {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* =================== Events =================== */
event Initialized(address indexed executor, uint256 at);
event RedeemedJUNB(address indexed from, uint256 junAmount, uint256 junbAmount);
event BoughtJUNB(address indexed from, uint256 junAmount, uint256 junbAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event TeamFundFunded(uint256 timestamp, uint256 seigniorage);
event BuyBackFunded(uint256 timestamp, uint256 seigniorage);
event BuyBackBurnedJUN(uint256 timestamp, uint256 junAmount);
/* =================== Admin Functions =================== */
function _become(TreasuryUni uni) public {
require(msg.sender == uni.admin(), "admin can change brains");
uni._acceptImplementation();
}
/* =================== Modifier =================== */
function checkSameOriginReentranted() internal view returns (bool) {
return _status[block.number][tx.origin];
}
function checkSameSenderReentranted() internal view returns (bool) {
return _status[block.number][msg.sender];
}
modifier onlyOneBlock() {
require(!checkSameOriginReentranted(), "one block, one function");
require(!checkSameSenderReentranted(), "one block, one function");
_;
_status[block.number][tx.origin] = true;
_status[block.number][msg.sender] = true;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can");
_;
}
modifier checkCondition {
require(now >= startTime, "not started yet");
_;
}
modifier checkEpoch {
require(now >= nextRoundPoint(), "not opened yet");
_;
round = round.add(1);
roundSupplyContractionLeft = (getJUNPrice() >= junPriceOne) ? 0 : IERC20(jun).totalSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator {
require(
Operator(jun).operator() == address(this) &&
Operator(junb).operator() == address(this) &&
Operator(juns).operator() == address(this) &&
Operator(boardroom).operator() == address(this),
"need more permission"
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
function getStartTime() public view returns (uint256) {
return startTime;
}
// round
function nextRoundPoint() public view returns (uint256) {
return startTime.add(round.mul(PERIOD));
}
// oracle
function getJUNPrice() public view returns (uint256) {
return IOracle(junOracle).consult(jun, 1e18);
}
function getJUNUpdatedPrice() public view returns (uint256) {
return IOracle(junOracle).twap(jun, 1e18);
}
// budget
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableJUNLeft() public view returns (uint256 _burnableLeft) {
uint256 _junPrice = getJUNPrice();
if (_junPrice < junPriceOne) {
uint256 _junSupply = IERC20(jun).totalSupply();
uint256 _junbMaxSupply = _junSupply.mul(maxDeptRatioPercent).div(10000);
uint256 _junbSupply = IERC20(junb).totalSupply();
if (_junbMaxSupply > _junbSupply) {
uint256 _maxMintableJUNB = _junbMaxSupply.sub(_junbSupply);
uint256 _maxBurnableJUN = _maxMintableJUNB.mul(_junPrice).div(1e18);
_burnableLeft = Math.min(roundSupplyContractionLeft, _maxBurnableJUN);
}
}
}
function getRedeemableJUNB() public view returns (uint256 _redeemableJUNB) {
uint256 _junPrice = getJUNPrice();
if (_junPrice > junPriceOne) {
uint256 _totalJUN = IERC20(jun).balanceOf(address(this));
uint256 _rate = getJUNBPremiumRate();
if (_rate > 0) {
_redeemableJUNB = _totalJUN.mul(1e18).div(_rate);
}
}
}
function getJUNBDiscountRate() public view returns (uint256 _rate) {
uint256 _junPrice = getJUNPrice();
if (_junPrice < junPriceOne) {
_rate = junPriceOne;
}
}
function getJUNBPremiumRate() public view returns (uint256 _rate) {
uint256 _junPrice = getJUNPrice();
if (_junPrice >= junPriceOne) {
_rate = junPriceOne;
}
}
/* ========== GOVERNANCE ========== */
constructor() public {
admin = msg.sender;
}
function initialize (
address _jun,
address _junb,
address _juns,
uint256 _startTime
) external onlyAdmin {
require(initialized == false, "already initiallized");
jun = _jun;
junb = _junb;
juns = _juns;
startTime = _startTime;
junPriceOne = 10**18;
bootstrapRounds = 21; // 1 weeks (8 * 21 / 24)
bootstrapSupplyExpansionPercent = 300; // 3%
maxSupplyExpansionPercent = 300; // Upto 3% supply for expansion
maxSupplyExpansionPercentInDebtPhase = 300; // Upto 3% supply for expansion in debt phase (to pay debt faster)
junbDepletionFloorPercent = 10000; // 100% of JUNB supply for depletion floor
seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for boardroom
seigniorageExpansionRate = 3000; // (TWAP - 1) * 100% * 30%
maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn JUN and mint JUNB)
maxDeptRatioPercent = 3500; // Upto 35% supply of JUNB to purchase
allocateSeigniorageSalary = 50 ether;
redeemPenaltyRate = 0.9 ether; // 0.9, 10% penalty
mintingFactorForPayingDebt = 10000; // 100%
teamFund = msg.sender;
teamFundSharedPercent = 1000; // 10%
buyBackFund = msg.sender;
buyBackFundExpansionRate = 1000; // 10%
maxBuyBackFundExpansion = 300; // 3%
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(jun).balanceOf(address(this));
initialized = true;
emit Initialized(msg.sender, block.number);
}
function setBoardroom(address _boardroom) external onlyAdmin {
require(_boardroom != address(0), "zero");
boardroom = _boardroom;
}
function setJUNOracle(address _oracle) external onlyAdmin {
require(_oracle != address(0), "zero");
junOracle = _oracle;
}
function setRound(uint256 _round) external onlyAdmin {
round = _round;
}
function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent, uint256 _maxSupplyExpansionPercentInDebtPhase) external onlyAdmin {
require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%]
require(_maxSupplyExpansionPercentInDebtPhase >= 10 && _maxSupplyExpansionPercentInDebtPhase <= 1500, "_maxSupplyExpansionPercentInDebtPhase: out of range"); // [0.1%, 15%]
require(_maxSupplyExpansionPercent <= _maxSupplyExpansionPercentInDebtPhase, "_maxSupplyExpansionPercent is over _maxSupplyExpansionPercentInDebtPhase");
maxSupplyExpansionPercent = _maxSupplyExpansionPercent;
maxSupplyExpansionPercentInDebtPhase = _maxSupplyExpansionPercentInDebtPhase;
}
function setSeigniorageExpansionRate(uint256 _seigniorageExpansionRate) external onlyAdmin {
require(_seigniorageExpansionRate >= 0 && _seigniorageExpansionRate <= 20000, "out of range"); // [0%, 200%]
seigniorageExpansionRate = _seigniorageExpansionRate;
}
function setJUNBDepletionFloorPercent(uint256 _junbDepletionFloorPercent) external onlyAdmin {
require(_junbDepletionFloorPercent >= 500 && _junbDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%]
junbDepletionFloorPercent = _junbDepletionFloorPercent;
}
function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyAdmin {
require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%]
maxSupplyContractionPercent = _maxSupplyContractionPercent;
}
function setMaxDeptRatioPercent(uint256 _maxDeptRatioPercent) external onlyAdmin {
require(_maxDeptRatioPercent >= 1000 && _maxDeptRatioPercent <= 10000, "out of range"); // [10%, 100%]
maxDeptRatioPercent = _maxDeptRatioPercent;
}
function setTeamFund(address _teamFund) external onlyAdmin {
require(_teamFund != address(0), "zero");
teamFund = _teamFund;
}
function setTeamFundSharedPercent(uint256 _teamFundSharedPercent) external onlyAdmin {
require(_teamFundSharedPercent <= 3000, "out of range"); // <= 30%
teamFundSharedPercent = _teamFundSharedPercent;
}
function setBuyBackFund(address _buyBackFund) external onlyAdmin {
require(_buyBackFund != address(0), "zero");
buyBackFund = _buyBackFund;
}
function setBuyBackFundExpansionRate(uint256 _buyBackFundExpansionRate) external onlyAdmin {
require(_buyBackFundExpansionRate <= 10000 && _buyBackFundExpansionRate >= 0, "out of range"); // under 100%
buyBackFundExpansionRate = _buyBackFundExpansionRate;
}
function setMaxBuyBackFundExpansionRate(uint256 _maxBuyBackFundExpansion) external onlyAdmin {
require(_maxBuyBackFundExpansion <= 1000 && _maxBuyBackFundExpansion >= 0, "out of range"); // under 10%
maxBuyBackFundExpansion = _maxBuyBackFundExpansion;
}
function setAllocateSeigniorageSalary(uint256 _allocateSeigniorageSalary) external onlyAdmin {
require(_allocateSeigniorageSalary <= 100 ether, "Treasury: dont pay too much");
allocateSeigniorageSalary = _allocateSeigniorageSalary;
}
function setRedeemPenaltyRate(uint256 _redeemPenaltyRate) external onlyAdmin {
require(_redeemPenaltyRate <= 1 ether && _redeemPenaltyRate >= 0.9 ether, "out of range");
redeemPenaltyRate = _redeemPenaltyRate;
}
function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyAdmin {
require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%]
mintingFactorForPayingDebt = _mintingFactorForPayingDebt;
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateJUNPrice() internal {
IOracle(junOracle).update();
}
function buyJUNB(uint256 _junAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_junAmount > 0, "Treasury: cannot purchase junbs with zero amount");
uint256 junPrice = getJUNPrice();
require(junPrice == targetPrice, "Treasury: jun price moved");
require(
junPrice < junPriceOne, // price < $1
"Treasury: junPrice not eligible for junb purchase"
);
require(_junAmount <= roundSupplyContractionLeft, "Treasury: not enough junb left to purchase");
uint256 _rate = getJUNBDiscountRate();
require(_rate > 0, "Treasury: invalid junb rate");
uint256 _junbAmount = _junAmount.mul(_rate).div(1e18);
uint256 junSupply = IERC20(jun).totalSupply();
uint256 newJUNBSupply = IERC20(junb).totalSupply().add(_junbAmount);
require(newJUNBSupply <= junSupply.mul(maxDeptRatioPercent).div(10000), "over max debt ratio");
IJUNAsset(jun).burnFrom(msg.sender, _junAmount);
IJUNAsset(junb).mint(msg.sender, _junbAmount);
roundSupplyContractionLeft = roundSupplyContractionLeft.sub(_junAmount);
emit BoughtJUNB(msg.sender, _junAmount, _junbAmount);
}
function redeemJUNB(uint256 _junbAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_junbAmount > 0, "Treasury: cannot redeem junbs with zero amount");
uint256 junPrice = getJUNPrice();
require(junPrice == targetPrice, "Treasury: jun price moved");
uint256 _junAmount;
uint256 _rate;
if (junPrice >= junPriceOne) {
_rate = getJUNBPremiumRate();
require(_rate > 0, "Treasury: invalid junb rate");
_junAmount = _junbAmount.mul(_rate).div(1e18);
require(IERC20(jun).balanceOf(address(this)) >= _junAmount, "Treasury: treasury has no more budget");
seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _junAmount));
IJUNAsset(junb).burnFrom(msg.sender, _junbAmount);
IERC20(jun).safeTransfer(msg.sender, _junAmount);
}
else {
require(redeemPenaltyRate > 0, "Treasury: not allow");
_junAmount = _junbAmount.mul(redeemPenaltyRate).div(1e18);
IJUNAsset(junb).burnFrom(msg.sender, _junbAmount);
IJUNAsset(jun).mint(msg.sender, _junAmount);
}
emit RedeemedJUNB(msg.sender, _junAmount, _junbAmount);
}
function _sendToBoardRoom(uint256 _amount) internal {
IJUNAsset(jun).mint(address(this), _amount);
if (teamFundSharedPercent > 0) {
uint256 _teamFundSharedAmount = _amount.mul(teamFundSharedPercent).div(10000);
IERC20(jun).transfer(teamFund, _teamFundSharedAmount);
emit TeamFundFunded(now, _teamFundSharedAmount);
_amount = _amount.sub(_teamFundSharedAmount);
}
IERC20(jun).safeApprove(boardroom, 0);
IERC20(jun).safeApprove(boardroom, _amount);
IBoardroom(boardroom).allocateSeigniorage(_amount);
emit BoardroomFunded(now, _amount);
}
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator {
_updateJUNPrice();
previousRoundJUNPrice = getJUNPrice();
uint256 junSupply = IERC20(jun).totalSupply().sub(seigniorageSaved);
if (round < bootstrapRounds) {
_sendToBoardRoom(junSupply.mul(bootstrapSupplyExpansionPercent).div(10000));
} else {
if (previousRoundJUNPrice > junPriceOne) {
// Expansion (JUN Price > 1$): there is some seigniorage to be allocated
uint256 junbSupply = IERC20(junb).totalSupply();
uint256 _percentage = previousRoundJUNPrice.sub(junPriceOne).mul(seigniorageExpansionRate).div(10000);
uint256 _savedForJUNB;
uint256 _savedForBoardRoom;
if (seigniorageSaved >= junbSupply.mul(junbDepletionFloorPercent).div(10000)) {// saved enough to pay dept, mint as usual rate
uint256 _mse = maxSupplyExpansionPercent.mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
_savedForBoardRoom = junSupply.mul(_percentage).div(1e18);
} else {// have not saved enough to pay dept, mint more
uint256 _mse = maxSupplyExpansionPercentInDebtPhase.mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
uint256 _seigniorage = junSupply.mul(_percentage).div(1e18);
_savedForBoardRoom = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000);
_savedForJUNB = _seigniorage.sub(_savedForBoardRoom);
if (mintingFactorForPayingDebt > 0) {
_savedForJUNB = _savedForJUNB.mul(mintingFactorForPayingDebt).div(10000);
}
}
if (_savedForBoardRoom > 0) {
_sendToBoardRoom(_savedForBoardRoom);
}
if (_savedForJUNB > 0) {
seigniorageSaved = seigniorageSaved.add(_savedForJUNB);
IJUNAsset(jun).mint(address(this), _savedForJUNB);
emit TreasuryFunded(now, _savedForJUNB);
}
}
}
// buy-back fund mint
if (previousRoundJUNPrice > junPriceOne) {
uint256 _buyBackRate = previousRoundJUNPrice.sub(junPriceOne).mul(buyBackFundExpansionRate).div(10000);
uint256 _maxBuyBackRate = maxBuyBackFundExpansion.mul(1e14);
if (_buyBackRate > _maxBuyBackRate) {
_buyBackRate = _maxBuyBackRate;
}
uint256 _savedForBuyBackFund = junSupply.mul(_buyBackRate).div(1e18);
if (_savedForBuyBackFund > 0) {
IJUNAsset(jun).mint(address(buyBackFund), _savedForBuyBackFund);
emit BuyBackFunded(now, _savedForBuyBackFund);
}
}
if (allocateSeigniorageSalary > 0) {
IJUNAsset(jun).mint(address(msg.sender), allocateSeigniorageSalary);
}
}
function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyAdmin {
// do not allow to drain core tokens
require(address(_token) != address(jun), "jun");
require(address(_token) != address(junb), "junb");
require(address(_token) != address(juns), "juns");
_token.safeTransfer(_to, _amount);
}
function burnJUNFromBuyBackFund(uint256 _amount) external onlyAdmin {
require(_amount > 0, "Treasury: cannot burn jun with zero amount");
IJUNAsset(jun).burnFrom(address(buyBackFund), _amount);
burnJUNAmount = burnJUNAmount.add(_amount);
emit BuyBackBurnedJUN(now, _amount);
}
/* ========== BOARDROOM CONTROLLING FUNCTIONS ========== */
function boardroomSetLockUp(uint256 _withdrawLockupRounds, uint256 _rewardLockupRounds) external onlyAdmin {
IBoardroom(boardroom).setLockUp(_withdrawLockupRounds, _rewardLockupRounds);
}
function boardroomAllocateSeigniorage(uint256 amount) external onlyAdmin {
IBoardroom(boardroom).allocateSeigniorage(amount);
}
function boardroomGovernanceRecoverUnsupported(address _token, uint256 _amount, address _to) external onlyAdmin {
IBoardroom(boardroom).governanceRecoverUnsupported(_token, _amount, _to);
}
}
| =================== Events =================== / =================== Admin Functions =================== / | function _become(TreasuryUni uni) public {
require(msg.sender == uni.admin(), "admin can change brains");
uni._acceptImplementation();
}
| 14,081,943 |
// File: contracts/vaults/IStrategy.sol
pragma solidity 0.5.17;
interface istrategy59 { //inject NONSTANDARD NAMING
function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING
function WANT31() external view returns (address); //inject NONSTANDARD NAMING
function WITHDRAW24(address) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/IERC20.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface ierc2080 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/ITreasury.sol
pragma solidity 0.5.17;
interface itreasury2 { //inject NONSTANDARD NAMING
function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING
function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVault.sol
pragma solidity 0.5.17;
interface ivault53 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING
function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVaultRewards.sol
pragma solidity 0.5.17;
interface ivaultrewards63 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IController.sol
pragma solidity 0.5.17;
interface icontroller20 { //inject NONSTANDARD NAMING
function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING
function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING
function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING
function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING
function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING
external view returns (
uint256 vaultRewardPercentage,
uint256 hurdleAmount,
uint256 harvestPercentage
);
function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING
function EARN37(address, uint256) external; //inject NONSTANDARD NAMING
function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING
}
// File: contracts/ISwapRouter.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface swaprouter18 { //inject NONSTANDARD NAMING
function WETH90() external pure returns (address); //inject NONSTANDARD NAMING
function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// File: contracts/SafeMath.sol
pragma solidity 0.5.17;
// Note: This file has been modified to include the sqrt function for quadratic voting
library math29 { //inject NONSTANDARD NAMING
function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 n = x / 2;
uint256 lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint256(n);
}
}
library safemath85 { //inject NONSTANDARD NAMING
function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB75(a, b, "SafeMath: subtraction overflow");
}
function SUB75(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL41(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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, "SafeMath: multiplication overflow");
return c;
}
function DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV62(a, b, "SafeMath: division by zero");
}
function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD3(a, b, "SafeMath: modulo by zero");
}
function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/zeppelin/Address.sol
pragma solidity 0.5.17;
library address35 { //inject NONSTANDARD NAMING
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: contracts/zeppelin/SafeERC20.sol
pragma solidity 0.5.17;
library safeerc2099 { //inject NONSTANDARD NAMING
using safemath85 for uint256;
using address35 for address;
function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value));
}
function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value));
}
function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE58(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value));
}
function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/vaults/strategy/MStableStrategy.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface ibpt3 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING
function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
}
interface impool6 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
function EXIT39() external; //inject NONSTANDARD NAMING
}
interface imtagov79 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING
function WITHDRAW24() external; //inject NONSTANDARD NAMING
function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
}
contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING
using safeerc2099 for ierc2080;
using address35 for address;
using safemath85 for uint256;
uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING
uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING
uint256 public hurdleLastUpdateTime;
uint256 public harvestAmountThisEpoch;
uint256 public strategistCollectedFee;
uint256 public numPools = 1;
ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2);
ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C);
swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80);
imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF);
ierc2080 public want = usdc; // should be set only in constructor or hardcoded
icontroller20 public controller; // should be set only in constructor
address public strategist; // mutable, but only by strategist
// want must be equal to an underlying vault token (Eg. USDC)
constructor(icontroller20 _controller) public {
controller = _controller;
strategist = msg.sender;
}
function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "MstableStrategy";
}
function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
numPools = _numPools;
}
function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
for (uint i = 0; i < recipients.length; i++) {
require(
recipients[i] == address(musdcBpt) ||
recipients[i] == address(swapRouter) ||
recipients[i] == address(mPool) ||
recipients[i] == address(mtaGov),
"bad recipient"
);
uint256 allowance = isIncrease ? uint256(-1) : 0;
token.SAFEAPPROVE5(recipients[i], allowance);
}
}
// Assumed that caller checks against available funds in vault
function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING
uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this));
require(amount <= availFunds, "exceed contAllowance");
controller.EARN37(address(this), amount);
// deposit into musdcBpt
uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(bptTokenAmt);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING
// get balance in mPool
uint256 bptStakeAmt = mPool.BALANCEOF3(address(this));
// get usdc + musd amts in BPT, and total BPT
uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt));
uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74();
// convert musd to usdc
usdcAmt = usdcAmt.ADD14(
musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc)))
);
return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt);
}
function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING
(uint256 earnedAmt,) = mPool.EARNED23(address(this));
return earnedAmt.ADD14(mtaGov.EARNED23(address(this)));
}
function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING
ierc2080 erc20Token = ierc2080(token);
require(msg.sender == address(controller), "!controller");
erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this)));
}
function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert to desired amount
musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1));
// deposit whatever remaining bpt back into mPool
mPool.STAKE12(musdcBpt.BALANCEOF3(address(this)));
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount);
}
function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert reward to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
// convert bpt to want tokens
musdcBpt.EXITSWAPPOOLAMOUNTIN6(
address(want),
musdcBpt.BALANCEOF3(address(this)),
0
);
// exclude collected strategist fee
balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance);
}
function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING
if (claimMPool) mPool.CLAIMREWARD81();
if (claimGov) mtaGov.CLAIMREWARD81();
// convert 80% reward to want tokens
// in case swap fails, return
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
false
)
);
// to remove compiler warning
if (!success) return;
uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
uint256 vaultRewardPercentage;
uint256 hurdleAmount;
uint256 harvestPercentage;
uint256 epochTime;
(vaultRewardPercentage, hurdleAmount, harvestPercentage) =
controller.GETHARVESTINFO14(address(this), msg.sender);
// check if harvest amount has to be reset
if (hurdleLastUpdateTime < epochTime) {
// reset collected amount
harvestAmountThisEpoch = 0;
}
// update variables
hurdleLastUpdateTime = block.timestamp;
harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount);
// first, take harvester fee
uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43);
want.SAFETRANSFER62(msg.sender, harvestFee);
uint256 fee;
// then, if hurdle amount has been exceeded, take performance fee
if (harvestAmountThisEpoch >= hurdleAmount) {
fee = amount.MUL41(performance_fee63).DIV62(denom43);
strategistCollectedFee = strategistCollectedFee.ADD14(fee);
}
// do the subtraction of harvester and strategist fees
amount = amount.SUB75(harvestFee).SUB75(fee);
// calculate how much is to be re-invested
// fee = vault reward amount, reusing variable
fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43);
want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee);
controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee);
amount = amount.SUB75(fee);
// finally, use remaining want amount for reinvestment
amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(amount);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING
strategistCollectedFee = 0;
want.SAFETRANSFER62(strategist, strategistCollectedFee);
}
function EXITMGOV72() external { //inject NONSTANDARD NAMING
mtaGov.WITHDRAW24();
// convert to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
want.SAFETRANSFER62(
address(controller.REWARDS0(address(want))),
want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee)
);
}
function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING
uint256 swapAmt = mta.BALANCEOF3(address(this));
if (swapAmt == 0) return;
// do the exchange
address[] memory routeDetails = new address[](3);
routeDetails[0] = address(mta);
routeDetails[1] = swapRouter.WETH90();
routeDetails[2] = address(want);
swapRouter.SWAPEXACTTOKENSFORTOKENS91(
exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43),
0,
routeDetails,
address(this),
block.timestamp + 100
);
}
function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING
uint256 mtaBal = mta.BALANCEOF3(address(this));
if (mtaBal == 0) return;
if (mtaGov.BALANCEOF3(address(this)) == 0) {
// create lock with max time
mtaGov.CREATELOCK73(mtaBal, 1632580257);
} else {
// increase amount
mtaGov.INCREASELOCKAMOUNT91(mtaBal);
}
}
} | inject NONSTANDARD NAMING | function ALLOWANCE58(address owner, address spender) external view returns (uint256); | 1,825,042 |
// SPDX-License-Identifier: AGPL
// File: contracts/interfaces/IITR.sol
pragma solidity ^0.8.0;
interface IITR {
function claim(address to) external;
}
// File: contracts/interfaces/ISRC20.sol
pragma solidity ^0.8.0;
interface ISRC20 {
event RestrictionsAndRulesUpdated(address restrictions, address rules);
function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime,
bytes32 msgHash, bytes calldata signature) external returns (bool);
function transferTokenFrom(address from, address to, uint256 value, uint256 nonce,
uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool);
function getTransferNonce() external view returns (uint256);
function getTransferNonce(address account) external view returns (uint256);
function executeTransfer(address from, address to, uint256 value) external returns (bool);
function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool);
// ERC20 part-like interface
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 value) external returns (bool);
function decreaseAllowance(address spender, uint256 value) external returns (bool);
}
// File: contracts/interfaces/ITransferRules.sol
pragma solidity ^0.8.0;
interface ITransferRules {
function setSRC(address src20) external returns (bool);
function doTransfer(address from, address to, uint256 value) external returns (bool);
}
// File: contracts/interfaces/IChain.sol
pragma solidity ^0.8.0;
interface IChain {
function doValidate(address from, address to, uint256 value) external returns (address, address, uint256, bool, string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/restrictions/ChainRuleBase.sol
pragma solidity ^0.8.0;
abstract contract ChainRuleBase is Ownable {
address public _chainRuleAddr;
function clearChain() public onlyOwner() {
_setChain(address(0));
}
function setChain(address chainAddr) public onlyOwner() {
_setChain(chainAddr);
}
//---------------------------------------------------------------------------------
// internal section
//---------------------------------------------------------------------------------
function _doValidate(
address from,
address to,
uint256 value
)
internal
returns (
address _from,
address _to,
uint256 _value,
bool _success,
string memory _msg
)
{
(_from, _to, _value, _success, _msg) = _validate(from, to, value);
if (isChainExists() && _success) {
(_from, _to, _value, _success, _msg) = IChain(_chainRuleAddr).doValidate(msg.sender, to, value);
}
}
function isChainExists() internal view returns(bool) {
return (_chainRuleAddr != address(0) ? true : false);
}
function _setChain(address chainAddr) internal {
_chainRuleAddr = chainAddr;
}
function _validate(address from, address to, uint256 value) internal virtual returns (address, address, uint256, bool, string memory);
}
// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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) {
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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/restrictions/TransferRule.sol
pragma solidity ^0.8.0;
contract TransferRule is Ownable, ITransferRules, ChainRuleBase {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
address public _src20;
address public _doTransferCaller;
uint256 internal constant MULTIPLIER = 100000;
address public _tradedToken;
uint256 public _lockupDuration;
uint256 public _lockupFraction;
struct Item {
uint256 untilTime;
uint256 lockedAmount;
}
mapping(address => Item) restrictions;
EnumerableSet.AddressSet _exchangeDepositAddresses;
modifier onlyDoTransferCaller {
require(msg.sender == address(_doTransferCaller));
_;
}
//---------------------------------------------------------------------------------
// public section
//---------------------------------------------------------------------------------
/**
* @param tradedToken tradedToken
* @param lockupDuration duration in sec
* @param lockupFraction fraction in percent to lock. multiplied by MULTIPLIER
*/
constructor(
address tradedToken,
uint256 lockupDuration,
uint256 lockupFraction
)
{
_tradedToken = tradedToken;
_lockupDuration = lockupDuration;
_lockupFraction = lockupFraction;
}
function cleanSRC() public onlyOwner() {
_src20 = address(0);
_doTransferCaller = address(0);
//_setChain(address(0));
}
function addExchangeAddress(address addr) public onlyOwner() {
_exchangeDepositAddresses.add(addr);
}
function removeExchangeAddress(address addr) public onlyOwner() {
_exchangeDepositAddresses.remove(addr);
}
function viewExchangeAddresses() public view returns(address[] memory) {
uint256 len = _exchangeDepositAddresses.length();
address[] memory ret = new address[](len);
for (uint256 i =0; i < len; i++) {
ret[i] = _exchangeDepositAddresses.at(i);
}
return ret;
}
function addRestrictions(
address[] memory addressArray,
uint256[] memory amountArray,
uint256[] memory untilArray
) public onlyOwner {
uint l=addressArray.length;
for (uint i=0; i<l; i++) {
restrictions[ addressArray[i] ] = Item({
lockedAmount: amountArray[i],
untilTime: untilArray[i]
});
}
}
//---------------------------------------------------------------------------------
// external section
//---------------------------------------------------------------------------------
/**
* @dev Set for what contract this rules are.
*
* @param src20 - Address of src20 contract.
*/
function setSRC(address src20) override external returns (bool) {
require(_doTransferCaller == address(0), "external contract already set");
require(address(_src20) == address(0), "external contract already set");
require(src20 != address(0), "src20 can not be zero");
_doTransferCaller = _msgSender();
_src20 = src20;
return true;
}
/**
* @dev Do transfer and checks where funds should go.
* before executeTransfer contract will call chainValidate on chain if exists
*
* @param from The address to transfer from.
* @param to The address to send tokens to.
* @param value The amount of tokens to send.
*/
function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) {
bool success;
string memory errmsg;
(from, to, value, success, errmsg) = _doValidate(from, to, value);
require(success, (bytes(errmsg).length == 0) ? "chain validation failed" : errmsg);
// todo: need to check params after chains validation??
require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed");
if (
success && (to == _tradedToken)
) {
IITR(_tradedToken).claim(from);
}
return true;
}
//---------------------------------------------------------------------------------
// internal section
//---------------------------------------------------------------------------------
function _validate(address from, address to, uint256 value) internal virtual override returns (address _from, address _to, uint256 _value, bool _success, string memory _errmsg) {
(_from, _to, _value, _success, _errmsg) = (from, to, value, true, "");
require(
_exchangeDepositAddresses.contains(to) == false,
string(abi.encodePacked("Don't deposit directly to this exchange. Send to the address ITR.ETH first, to obtain the correct token in your wallet."))
);
uint256 balanceFrom = ISRC20(_src20).balanceOf(from);
if (restrictions[from].untilTime > block.timestamp) {
if (to == _tradedToken) {
_success = false;
_errmsg = "you recently claimed new tokens, please wait until duration has elapsed to claim again";
} else if ((restrictions[from].lockedAmount).add(value) > balanceFrom) {
_success = false;
_errmsg = "you recently claimed new tokens, please wait until duration has elapsed to transfer this many tokens";
}
}
if (
_success &&
(to == _tradedToken) &&
(restrictions[from].untilTime > block.timestamp)
) {
restrictions[from].untilTime = (block.timestamp).add(_lockupDuration);
restrictions[from].lockedAmount = (balanceFrom.sub(value)).mul(_lockupFraction).div(MULTIPLIER);
}
}
//---------------------------------------------------------------------------------
// private section
//---------------------------------------------------------------------------------
} | Return the entire set in an array WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block./ | function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
| 6,152,355 |
./partial_match/42/0xC049CA7bd2B415aA8973D73C2Ad54a677F595DF9/sources/DisposableGovernance.sol | function required for Iupgradable and IGovernance implementation / | function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
| 8,940,789 |
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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) {
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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: NekoZamurai.sol
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
pragma solidity ^0.8.0;
/*
╔═╗ ╔╗╔═══╗╔╗╔═╗╔═══╗ ╔════╗╔═══╗╔═╗╔═╗╔╗ ╔╗╔═══╗╔═══╗╔══╗
║║╚╗║║║╔══╝║║║╔╝║╔═╗║ ╚══╗ ║║╔═╗║║║╚╝║║║║ ║║║╔═╗║║╔═╗║╚╣╠╝
║╔╗╚╝║║╚══╗║╚╝╝ ║║ ║║ ╔╝╔╝║║ ║║║╔╗╔╗║║║ ║║║╚═╝║║║ ║║ ║║
║║╚╗║║║╔══╝║╔╗║ ║║ ║║ ╔╝╔╝ ║╚═╝║║║║║║║║║ ║║║╔╗╔╝║╚═╝║ ║║
║║ ║║║║╚══╗║║║╚╗║╚═╝║ ╔╝ ╚═╗║╔═╗║║║║║║║║╚═╝║║║║╚╗║╔═╗║╔╣╠╗
╚╝ ╚═╝╚═══╝╚╝╚═╝╚═══╝ ╚════╝╚╝ ╚╝╚╝╚╝╚╝╚═══╝╚╝╚═╝╚╝ ╚╝╚══╝
Contract made with ❤️ by NekoZamurai
Socials:
Opensea: TBA
Twitter: https://twitter.com/NekoZamuraiNFT
Website: https://nekozamurai.io/
*/
contract NekoZamurai is ERC721Enumerable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
using ECDSA for bytes32;
// Constant variables
// ------------------------------------------------------------------------
uint public constant publicSupply = 5217;
uint public constant presaleSupply = 2560;
uint public constant maxSupply = presaleSupply + publicSupply;
uint public constant cost = 0.14 ether;
uint public constant maxMintPerTx = 5;
// Mapping variables
// ------------------------------------------------------------------------
mapping(address => bool) public presalerList;
mapping(address => uint256) public presalerListPurchases;
mapping(address => uint256) public publicListPurchases;
// Public variables
// ------------------------------------------------------------------------
uint256 public publicAmountMinted;
uint256 public presalePurchaseLimit = 1;
uint256 public publicPurchaseLimit = 5;
uint256 public reservedAmountMinted;
// URI variables
// ------------------------------------------------------------------------
string private contractURI;
string private baseTokenURI = "";
// Deployer address
// ------------------------------------------------------------------------
address public constant creatorAddress = 0x8707db291A13d9585b9Bc8e2289F64EbB6f5B672;
address private signerAddress = 0x8707db291A13d9585b9Bc8e2289F64EbB6f5B672; // tbd
bool public saleLive;
bool public presaleLive;
bool public revealed = false;
bool public metadataLock;
// Constructor
// ------------------------------------------------------------------------
constructor(string memory unrevealedBaseURI) ERC721("NekoZamurai", "NEKO") {
setBaseURI(unrevealedBaseURI);
// setBaseURI("ipfs://QmXTsae772LDETthjkCNR4pPrEWShJ9UbuP7gCKWi26XV6/"); // testing purposes
}
modifier notLocked {
require(!metadataLock, "Contract metadata methods are locked");
_;
}
// Mint function
// ------------------------------------------------------------------------
function mintPublic(uint256 mintQuantity) external payable {
require(saleLive, "Sale closed");
require(!presaleLive, "Only available for presale");
require(totalSupply() < maxSupply, "Out of stock");
require(publicAmountMinted + mintQuantity <= publicSupply, "Out of public stock");
require(publicListPurchases[msg.sender] + mintQuantity <= publicPurchaseLimit, "Public mint limit exceeded");
require(mintQuantity <= maxMintPerTx, "Exceeded mint limit");
require(cost * mintQuantity <= msg.value, "Insufficient funds");
for(uint256 i = 1; i <= mintQuantity; i++) {
publicAmountMinted++;
publicListPurchases[msg.sender]++;
_safeMint(msg.sender, totalSupply() + 1);
}
}
// Presale mint function
// ------------------------------------------------------------------------
function mintPresale(uint256 mintQuantity) external payable {
uint256 callSupply = totalSupply();
require(!saleLive && presaleLive, "Presale closed");
require(presalerList[msg.sender], "Not on presale list");
require(callSupply < maxSupply, "Out of stock");
require(publicAmountMinted + mintQuantity <= publicSupply, "Out of public stock");
require(presalerListPurchases[msg.sender] + mintQuantity <= presalePurchaseLimit, "Presale mint limit exceeded");
require(cost * mintQuantity <= msg.value, "Insufficient funds");
presalerListPurchases[msg.sender] += mintQuantity;
publicAmountMinted += mintQuantity;
for (uint256 i = 0; i < mintQuantity; i++) {
_safeMint(msg.sender, callSupply + 1);
}
}
// Reserved mint function
// ------------------------------------------------------------------------
function mintReserved(uint256 mintQuantity) external onlyOwner {
require(saleLive, "Sale closed");
require(totalSupply() < maxSupply, "Out of stock");
require(reservedAmountMinted + mintQuantity <= presaleSupply, "Out of reserved stock");
for(uint256 i = 1; i <= mintQuantity; i++) {
reservedAmountMinted++;
_safeMint(msg.sender, totalSupply() + 1);
}
}
// Get cost amount
// ------------------------------------------------------------------------
function getCost(uint256 _count) public pure returns (uint256) {
return cost.mul(_count);
}
// Get hash transaction
// ------------------------------------------------------------------------
function hashTransaction(address sender, uint256 qty, string memory nonce) public pure returns(bytes32) {
bytes32 hash = keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(sender, qty, nonce)))
);
return hash;
}
// Get match from address signer
// ------------------------------------------------------------------------
function matchAddressSigner(bytes32 hash, bytes memory signature) private view returns(bool) {
return signerAddress == hash.recover(signature);
}
// Get total supply leftover amount
// ------------------------------------------------------------------------
function getUnsoldRemaining() external view returns (uint256) {
return maxSupply - totalSupply();
}
// Get contract URI
// ------------------------------------------------------------------------
function getContractURI() public view returns (string memory) {
return contractURI;
}
// Get base token URI
// ------------------------------------------------------------------------
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!revealed) {
return baseTokenURI;
}
return bytes(baseTokenURI).length > 0 ? string(abi.encodePacked(baseTokenURI, tokenId.toString(), ".json")): "";
}
// Owner functions
// Toggle reveal function (True by default)
// ------------------------------------------------------------------------
function reveal() public onlyOwner {
revealed = true;
}
// Togle lock metadata function (True by default)
// ------------------------------------------------------------------------
function lockMetadata() external onlyOwner {
metadataLock = true;
}
// Toggle presale (False by default)
// ------------------------------------------------------------------------
function togglePresale() external onlyOwner {
presaleLive = !presaleLive;
}
// Toggle sale (False by default)
// ------------------------------------------------------------------------
function toggleSale() external onlyOwner {
saleLive = !saleLive;
}
// Add address to presael list
// ------------------------------------------------------------------------
function addToPresaleList(address[] calldata entries) external onlyOwner {
for(uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), "Null address");
require(!presalerList[entry], "Duplicate entry");
presalerList[entry] = true;
}
}
// Remove address from presale list
// ------------------------------------------------------------------------
function removeFromPresaleList(address[] calldata entries) external onlyOwner {
for(uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), "Null address");
presalerList[entry] = false;
}
}
// Approve signer address
// ------------------------------------------------------------------------
function setSignerAddress(address addr) external onlyOwner {
signerAddress = addr;
}
// Set contract URI
// ------------------------------------------------------------------------
function setContractURI(string calldata URI) external onlyOwner notLocked {
contractURI = URI;
}
// Set base URI
// ------------------------------------------------------------------------
function setBaseURI(string memory baseURI) public onlyOwner notLocked {
baseTokenURI = baseURI;
}
// Withdrawal function
// ------------------------------------------------------------------------
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
} | Togle lock metadata function (True by default) ------------------------------------------------------------------------ | function lockMetadata() external onlyOwner {
metadataLock = true;
}
| 1,685,253 |
./partial_match/1/0xa6d85F3b3bE6Ff6DC52C3aaBe9A35d0ce252b79F/sources/src/OpStateBridge.sol | Sends the latest WorldID Identity Manager root to the IOpStack. Calls this method on the L1 Proxy contract to relay roots to the destination OP Stack chain The `encodeCall` function is strongly typed, so this checks that we are passing the correct data to the optimism bridge. Contract address on the OP Stack Chain | function propagateRoot() external {
uint256 latestRoot = IWorldIDIdentityManager(worldIDAddress).latestRoot();
bytes memory message = abi.encodeCall(IOpWorldID.receiveRoot, (latestRoot));
ICrossDomainMessenger(crossDomainMessengerAddress).sendMessage(
opWorldIDAddress,
message,
_gasLimitPropagateRoot
);
emit RootPropagated(latestRoot);
}
| 4,475,499 |
// This file is part of the Blockchain Data Trading Simulator
// https://gitlab.com/MatthiasLohr/bdtsim
//
// Copyright 2020 Matthias Lohr <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file originates from https://github.com/lEthDev/FairSwap
// Original authors: Stefan Dziembowski, Lisa Eckey, Sebastian Faust
//
// Modifications by Matthias Lohr <[email protected]> towards a reusable smart contract design
pragma solidity ^0.6.1;
contract FileSale {
enum Stage {created, initialized, accepted, keyRevealed, finished}
struct FileSaleSession {
Stage phase;
address payable sender;
address payable receiver;
uint depth;
uint length;
uint n;
uint timeout;
uint timeoutInterval;
uint price;
bytes32 keyCommit;
bytes32 ciphertextRoot;
bytes32 fileRoot;
bytes32 key;
}
mapping (bytes32 => FileSaleSession) sessions;
// function modifier to only allow calling the function in the right phase only from the correct party
modifier allowed(bytes32 sessionId, address p, Stage s) {
require(sessions[sessionId].phase == s);
require(now < sessions[sessionId].timeout);
require(msg.sender == p);
_;
}
// go to next phase
function nextStage(bytes32 sessionId) internal {
sessions[sessionId].phase = Stage(uint(sessions[sessionId].phase) + 1);
sessions[sessionId].timeout = now + sessions[sessionId].timeoutInterval;
}
// init transfer for session
function init(address payable receiver, uint depth, uint length, uint n, uint timeoutInterval, uint price, bytes32 keyCommit, bytes32 ciphertextRoot, bytes32 fileRoot) public {
bytes32 sessionId = keccak256(abi.encodePacked(msg.sender, receiver, fileRoot));
require(sessions[sessionId].phase == Stage.created || now > (sessions[sessionId].timeout + sessions[sessionId].timeoutInterval));
sessions[sessionId] = FileSaleSession(
Stage.initialized,
msg.sender,
receiver,
depth,
length,
n,
now + timeoutInterval,
timeoutInterval,
price,
keyCommit,
ciphertextRoot,
fileRoot,
0
);
}
// function accept
function accept(bytes32 sessionId) allowed(sessionId, sessions[sessionId].receiver, Stage.initialized) payable public {
require(msg.value >= sessions[sessionId].price);
nextStage(sessionId);
}
// function revealKey (key)
function revealKey(bytes32 sessionId, bytes32 _key) allowed(sessionId, sessions[sessionId].sender, Stage.accepted) public {
require(sessions[sessionId].keyCommit == keccak256(abi.encode(_key)));
sessions[sessionId].key = _key;
nextStage(sessionId);
}
function noComplain(bytes32 sessionId) allowed(sessionId, sessions[sessionId].receiver, Stage.keyRevealed) public {
sessions[sessionId].sender.transfer(sessions[sessionId].price);
delete sessions[sessionId];
}
// function complain about wrong hash of file
function complainAboutRoot(bytes32 sessionId, bytes32 _Zm, bytes32[] memory _proofZm) allowed(sessionId, sessions[sessionId].receiver, Stage.keyRevealed) public {
require (vrfy(sessionId, 2 * (sessions[sessionId].n - 1), _Zm, _proofZm));
require (cryptSmall(sessionId, 2 * (sessions[sessionId].n - 1), _Zm) != sessions[sessionId].fileRoot);
sessions[sessionId].receiver.transfer(sessions[sessionId].price);
delete sessions[sessionId];
}
// function complain about wrong hash of two inputs
function complainAboutLeaf(bytes32 sessionId, uint _indexOut, uint _indexIn, bytes32 _Zout, bytes32[] memory _Zin1,
bytes32[] memory _Zin2, bytes32[] memory _proofZout, bytes32[] memory _proofZin)
allowed(sessionId, sessions[sessionId].receiver, Stage.keyRevealed) public {
FileSaleSession memory session = sessions[sessionId];
require (vrfy(sessionId, _indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(sessionId, _indexOut, _Zout);
require (vrfy(sessionId, _indexIn, keccak256(abi.encode(_Zin1)), _proofZin));
require (_proofZin[session.depth - 1] == keccak256(abi.encodePacked(_Zin2)));
require (Xout != keccak256(abi.encode(cryptLarge(sessionId, _indexIn, _Zin1), cryptLarge(sessionId, _indexIn + 1, _Zin2))));
sessions[sessionId].receiver.transfer(session.price);
delete sessions[sessionId];
}
// function complain about wrong hash of two inputs
function complainAboutNode(bytes32 sessionId, uint _indexOut, uint _indexIn, bytes32 _Zout, bytes32 _Zin1, bytes32 _Zin2,
bytes32[] memory _proofZout, bytes32[] memory _proofZin)
allowed(sessionId, sessions[sessionId].receiver, Stage.keyRevealed) public {
require (vrfy(sessionId, _indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(sessionId, _indexOut, _Zout);
require (vrfy(sessionId, _indexIn, _Zin1, _proofZin));
uint depth = sessions[sessionId].depth;
require (_proofZin[depth - 1] == _Zin2);
require (Xout != keccak256(abi.encode(cryptSmall(sessionId, _indexIn, _Zin1), cryptSmall(sessionId, _indexIn+ 1, _Zin2))));
uint price = sessions[sessionId].price;
sessions[sessionId].receiver.transfer(price);
delete sessions[sessionId];
}
// refund function is called in case some party did not contribute in time
function refund(bytes32 sessionId) public {
require (now > sessions[sessionId].timeout);
if (sessions[sessionId].phase == Stage.accepted) {
sessions[sessionId].receiver.transfer(sessions[sessionId].price);
delete sessions[sessionId];
}
if (sessions[sessionId].phase >= Stage.keyRevealed) {
sessions[sessionId].sender.transfer(sessions[sessionId].price);
delete sessions[sessionId];
}
}
// function to both encrypt and decrypt text chunks with key k
function cryptLarge(bytes32 sessionId, uint _index, bytes32[] memory _ciphertext) public view returns (bytes32[] memory) {
_index = _index * sessions[sessionId].length;
for (uint i = 0; i < sessions[sessionId].length; i++){
_ciphertext[i] = keccak256(abi.encode(_index, sessions[sessionId].key)) ^ _ciphertext[i];
_index++;
}
return _ciphertext;
}
// function to decrypt hashes of the merkle tree
function cryptSmall(bytes32 sessionId, uint _index, bytes32 _ciphertext) public view returns (bytes32) {
return keccak256(abi.encode(sessions[sessionId].n + _index, sessions[sessionId].key)) ^ _ciphertext;
}
// function to verify Merkle Tree proofs
function vrfy(bytes32 sessionId, uint _index, bytes32 _value, bytes32[] memory _proof) public view returns (bool) {
require(_proof.length == sessions[sessionId].depth);
return true;
for (uint i = 0; i < sessions[sessionId].depth; i++) {
if ((_index & 1 << i) >>i == 1)
_value = keccak256(abi.encodePacked(_proof[sessions[sessionId].depth - i - 1], _value));
else
_value = keccak256(abi.encodePacked(_value, _proof[sessions[sessionId].depth - i - 1]));
}
return (_value == sessions[sessionId].ciphertextRoot);
}
}
| function complain about wrong hash of file | function complainAboutRoot(bytes32 sessionId, bytes32 _Zm, bytes32[] memory _proofZm) allowed(sessionId, sessions[sessionId].receiver, Stage.keyRevealed) public {
require (vrfy(sessionId, 2 * (sessions[sessionId].n - 1), _Zm, _proofZm));
require (cryptSmall(sessionId, 2 * (sessions[sessionId].n - 1), _Zm) != sessions[sessionId].fileRoot);
sessions[sessionId].receiver.transfer(sessions[sessionId].price);
delete sessions[sessionId];
}
| 14,123,628 |
/*
* This file is part of the contracts written for artèQ Investment Fund (https://github.com/billionbuild/arteq-contracts).
* Copyright (c) 2021 BillionBuild (2B) Team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GNU General Public License v3.0
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./ERC1155Supply.sol";
import "./IarteQTokens.sol";
import "./IarteQTaskFinalizer.sol";
/// @author Kam Amini <[email protected]> <[email protected]> <[email protected]> <[email protected]>
///
/// Reviewed and revised by: Masoud Khosravi <masoud_at_2b.team> <mkh_at_arteq.io>
/// Ali Jafari <ali_at_2b.team> <aj_at_arteq.io>
///
/// @title This contract keeps track of the tokens used in artèQ Investment
/// Fund ecosystem. It also contains the logic used for profit distribution.
///
/// @notice Use at your own risk
contract arteQTokens is ERC1155Supply, IarteQTokens {
/// The main artèQ token
uint256 public constant ARTEQ = 1;
/// The governance token of artèQ Investment Fund
uint256 public constant gARTEQ = 2;
// The mapping from token IDs to their respective Metadata URIs
mapping (uint256 => string) private _tokenMetadataURIs;
// The admin smart contract
address private _adminContract;
// Treasury account responsible for asset-token ratio appreciation.
address private _treasuryAccount;
// This can be a Uniswap V1/V2 exchange (pool) account created for ARTEQ token,
// or any other exchange account. Treasury contract uses these pools to buy
// back or sell tokens. In case of buy backs, the tokens must be delivered to
// treasury account from these contracts. Otherwise, the profit distribution
// logic doesn't get triggered.
address private _exchange1Account;
address private _exchange2Account;
address private _exchange3Account;
address private _exchange4Account;
address private _exchange5Account;
// All the profits accumulated since the deployment of the contract. This is
// used as a marker to facilitate the caluclation of every eligible account's
// share from the profits in a given time range.
uint256 private _allTimeProfit;
// The actual number of profit tokens transferred to accounts
uint256 private _profitTokensTransferredToAccounts;
// The percentage of the bought back tokens which is considered as profit for gARTEQ owners
// Default value is 20% and only admin contract can change that.
uint private _profitPercentage;
// In order to caluclate the share of each elgiible account from the profits,
// and more importantly, in order to do this efficiently (less gas usage),
// we need this mapping to remember the "all time profit" when an account
// is modified (receives tokens or sends tokens).
mapping (address => uint256) private _profitMarkers;
// A timestamp indicating when the ramp-up phase gets expired.
uint256 private _rampUpPhaseExpireTimestamp;
// Indicates until when the address cannot send any tokens
mapping (address => uint256) private _lockedUntilTimestamps;
/// Emitted when the admin contract is changed.
event AdminContractChanged(address newContract);
/// Emitted when the treasury account is changed.
event TreasuryAccountChanged(address newAccount);
/// Emitted when the exchange account is changed.
event Exchange1AccountChanged(address newAccount);
event Exchange2AccountChanged(address newAccount);
event Exchange3AccountChanged(address newAccount);
event Exchange4AccountChanged(address newAccount);
event Exchange5AccountChanged(address newAccount);
/// Emitted when the profit percentage is changed.
event ProfitPercentageChanged(uint newPercentage);
/// Emitted when a token distribution occurs during the ramp-up phase
event RampUpPhaseTokensDistributed(address to, uint256 amount, uint256 lockedUntilTimestamp);
/// Emitted when some buy back tokens are received by the treasury account.
event ProfitTokensCollected(uint256 amount);
/// Emitted when a share holder receives its tokens from the buy back profits.
event ProfitTokensDistributed(address to, uint256 amount);
// Emitted when profits are caluclated because of a manual buy back event
event ManualBuyBackWithdrawalFromTreasury(uint256 amount);
modifier adminApprovalRequired(uint256 adminTaskId) {
_;
// This must succeed otherwise the tx gets reverted
IarteQTaskFinalizer(_adminContract).finalizeTask(msg.sender, adminTaskId);
}
modifier validToken(uint256 tokenId) {
require(tokenId == ARTEQ || tokenId == gARTEQ, "arteQTokens: non-existing token");
_;
}
modifier onlyRampUpPhase() {
require(block.timestamp < _rampUpPhaseExpireTimestamp, "arteQTokens: ramp up phase is finished");
_;
}
constructor(address adminContract) {
_adminContract = adminContract;
/// Must be set later
_treasuryAccount = address(0);
/// Must be set later
_exchange1Account = address(0);
_exchange2Account = address(0);
_exchange3Account = address(0);
_exchange4Account = address(0);
_exchange5Account = address(0);
string memory arteQURI = "ipfs://QmfBtH8BSztaYn3QFnz2qvu2ehZgy8AZsNMJDkgr3pdqT8";
string memory gArteQURI = "ipfs://QmRAXmU9AymDgtphh37hqx5R2QXSS2ngchQRDFtg6XSD7w";
_tokenMetadataURIs[ARTEQ] = arteQURI;
emit URI(arteQURI, ARTEQ);
_tokenMetadataURIs[gARTEQ] = gArteQURI;
emit URI(gArteQURI, gARTEQ);
/// 10 billion
_initialMint(_adminContract, ARTEQ, 10 ** 10, "");
/// 1 million
_initialMint(_adminContract, gARTEQ, 10 ** 6, "");
/// Obviously, no profit at the time of deployment
_allTimeProfit = 0;
_profitPercentage = 20;
/// Tuesday, February 1, 2022 12:00:00 AM
_rampUpPhaseExpireTimestamp = 1643673600;
}
/// See {ERC1155-uri}
function uri(uint256 tokenId) external view virtual override validToken(tokenId) returns (string memory) {
return _tokenMetadataURIs[tokenId];
}
function setURI(
uint256 adminTaskId,
uint256 tokenId,
string memory newUri
) external adminApprovalRequired(adminTaskId) validToken(tokenId) {
_tokenMetadataURIs[tokenId] = newUri;
emit URI(newUri, tokenId);
}
/// Returns the set treasury account
/// @return The set treasury account
function getTreasuryAccount() external view returns (address) {
return _treasuryAccount;
}
/// Sets a new treasury account. Just after deployment, treasury account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new treasury address
function setTreasuryAccount(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for treasury account");
_treasuryAccount = newAccount;
emit TreasuryAccountChanged(newAccount);
}
/// Returns the 1st exchange account
/// @return The 1st exchnage account
function getExchange1Account() external view returns (address) {
return _exchange1Account;
}
/// Returns the 2nd exchange account
/// @return The 2nd exchnage account
function getExchange2Account() external view returns (address) {
return _exchange2Account;
}
/// Returns the 3rd exchange account
/// @return The 3rd exchnage account
function getExchange3Account() external view returns (address) {
return _exchange3Account;
}
/// Returns the 4th exchange account
/// @return The 4th exchnage account
function getExchange4Account() external view returns (address) {
return _exchange4Account;
}
/// Returns the 5th exchange account
/// @return The 5th exchnage account
function getExchange5Account() external view returns (address) {
return _exchange5Account;
}
/// Sets a new exchange account. Just after deployment, exchange account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new exchange address
function setExchange1Account(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for exchange account");
_exchange1Account = newAccount;
emit Exchange1AccountChanged(newAccount);
}
/// Sets a new exchange account. Just after deployment, exchange account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new exchange address
function setExchange2Account(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for exchange account");
_exchange2Account = newAccount;
emit Exchange2AccountChanged(newAccount);
}
/// Sets a new exchange account. Just after deployment, exchange account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new exchange address
function setExchange3Account(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for exchange account");
_exchange3Account = newAccount;
emit Exchange3AccountChanged(newAccount);
}
/// Sets a new exchange account. Just after deployment, exchange account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new exchange address
function setExchange4Account(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for exchange account");
_exchange4Account = newAccount;
emit Exchange4AccountChanged(newAccount);
}
/// Sets a new exchange account. Just after deployment, exchange account is set to zero address but once
/// set to a non-zero address, it cannot be changed back to zero address again.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newAccount new exchange address
function setExchange5Account(uint256 adminTaskId, address newAccount) external adminApprovalRequired(adminTaskId) {
require(newAccount != address(0), "arteQTokens: zero address for exchange account");
_exchange5Account = newAccount;
emit Exchange5AccountChanged(newAccount);
}
/// Returns the profit percentage
/// @return The set treasury account
function getProfitPercentage() external view returns (uint) {
return _profitPercentage;
}
/// Sets a new profit percentage. This is the percentage of bought-back tokens which is considered
/// as profit for gARTEQ owners. The value can be between 10% and 50%.
///
/// @param adminTaskId the task which must have been approved by multiple admins
/// @param newPercentage new exchange address
function setProfitPercentage(uint256 adminTaskId, uint newPercentage) external adminApprovalRequired(adminTaskId) {
require(newPercentage >= 10 && newPercentage <= 50, "arteQTokens: invalid value for profit percentage");
_profitPercentage = newPercentage;
emit ProfitPercentageChanged(newPercentage);
}
/// Transfer from admin contract
function transferFromAdminContract(
uint256 adminTaskId,
address to,
uint256 id,
uint256 amount
) external adminApprovalRequired(adminTaskId) {
_safeTransferFrom(_msgSender(), _adminContract, to, id, amount, "");
}
/// A token distribution mechanism, only valid in ramp-up phase, valid till the end of Jan 2022.
function rampUpPhaseDistributeToken(
uint256 adminTaskId,
address[] memory tos,
uint256[] memory amounts,
uint256[] memory lockedUntilTimestamps
) external adminApprovalRequired(adminTaskId) onlyRampUpPhase {
require(tos.length == amounts.length, "arteQTokens: inputs have incorrect lengths");
for (uint256 i = 0; i < tos.length; i++) {
require(tos[i] != _treasuryAccount, "arteQTokens: cannot transfer to treasury account");
require(tos[i] != _adminContract, "arteQTokens: cannot transfer to admin contract");
_safeTransferFrom(_msgSender(), _adminContract, tos[i], ARTEQ, amounts[i], "");
if (lockedUntilTimestamps[i] > 0) {
_lockedUntilTimestamps[tos[i]] = lockedUntilTimestamps[i];
}
emit RampUpPhaseTokensDistributed(tos[i], amounts[i], lockedUntilTimestamps[i]);
}
}
function balanceOf(address account, uint256 tokenId) public view virtual override validToken(tokenId) returns (uint256) {
if (tokenId == gARTEQ) {
return super.balanceOf(account, tokenId);
}
return super.balanceOf(account, tokenId) + _calcUnrealizedProfitTokens(account);
}
function allTimeProfit() external view returns (uint256) {
return _allTimeProfit;
}
function totalCirculatingGovernanceTokens() external view returns (uint256) {
return totalSupply(gARTEQ) - balanceOf(_adminContract, gARTEQ);
}
function profitTokensTransferredToAccounts() external view returns (uint256) {
return _profitTokensTransferredToAccounts;
}
function compatBalanceOf(address /* origin */, address account, uint256 tokenId) external view virtual override returns (uint256) {
return balanceOf(account, tokenId);
}
function compatTotalSupply(address /* origin */, uint256 tokenId) external view virtual override returns (uint256) {
return totalSupply(tokenId);
}
function compatTransfer(address origin, address to, uint256 tokenId, uint256 amount) external virtual override {
address from = origin;
_safeTransferFrom(origin, from, to, tokenId, amount, "");
}
function compatTransferFrom(address origin, address from, address to, uint256 tokenId, uint256 amount) external virtual override {
require(
from == origin || isApprovedForAll(from, origin),
"arteQTokens: caller is not owner nor approved "
);
_safeTransferFrom(origin, from, to, tokenId, amount, "");
}
function compatAllowance(address /* origin */, address account, address operator) external view virtual override returns (uint256) {
if (isApprovedForAll(account, operator)) {
return 2 ** 256 - 1;
}
return 0;
}
function compatApprove(address origin, address operator, uint256 amount) external virtual override {
_setApprovalForAll(origin, operator, amount > 0);
}
// If this contract gets a balance in some ERC20 contract after it's finished, then we can rescue it.
function rescueTokens(uint256 adminTaskId, IERC20 foreignToken, address to) external adminApprovalRequired(adminTaskId) {
foreignToken.transfer(to, foreignToken.balanceOf(address(this)));
}
// If this contract gets a balance in some ERC721 contract after it's finished, then we can rescue it.
function approveNFTRescue(uint256 adminTaskId, IERC721 foreignNFT, address to) external adminApprovalRequired(adminTaskId) {
foreignNFT.setApprovalForAll(to, true);
}
// In case of any manual buy back event which is not processed through DEX contracts, this function
// helps admins distribute the profits. This function must be called only when the bought back tokens
// have been successfully transferred to treasury account.
function processManualBuyBackEvent(uint256 adminTaskId, uint256 boughtBackTokensAmount) external adminApprovalRequired(adminTaskId) {
uint256 profit = (boughtBackTokensAmount * _profitPercentage) / 100;
if (profit > 0) {
_balances[ARTEQ][_treasuryAccount] -= profit;
emit ManualBuyBackWithdrawalFromTreasury(profit);
_allTimeProfit += profit;
emit ProfitTokensCollected(profit);
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 id,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
// We have to call the super function in order to have the total supply correct.
// It is actually needed by the first two _initialMint calls only. After that, it is
// a no-op function.
super._beforeTokenTransfer(operator, from, to, id, amounts, data);
// this is one of the two first _initialMint calls
if (from == address(0)) {
return;
}
// This is a buy-back callback from exchange account
if ((
from == _exchange1Account ||
from == _exchange2Account ||
from == _exchange3Account ||
from == _exchange4Account ||
from == _exchange5Account
) && to == _treasuryAccount) {
require(amounts.length == 2 && id == ARTEQ, "arteQTokens: invalid transfer from exchange");
uint256 profit = (amounts[0] * _profitPercentage) / 100;
amounts[1] = amounts[0] - profit;
if (profit > 0) {
_allTimeProfit += profit;
emit ProfitTokensCollected(profit);
}
return;
}
// Ensures that the locked accounts cannot send their ARTEQ tokens
if (id == ARTEQ) {
require(_lockedUntilTimestamps[from] == 0 || block.timestamp > _lockedUntilTimestamps[from], "arteQTokens: account cannot send tokens");
}
// Realize/Transfer the accumulated profit of 'from' account and make it spendable
if (from != _adminContract &&
from != _treasuryAccount &&
from != _exchange1Account &&
from != _exchange2Account &&
from != _exchange3Account &&
from != _exchange4Account &&
from != _exchange5Account) {
_realizeAccountProfitTokens(from);
}
// Realize/Transfer the accumulated profit of 'to' account and make it spendable
if (to != _adminContract &&
to != _treasuryAccount &&
to != _exchange1Account &&
to != _exchange2Account &&
to != _exchange3Account &&
to != _exchange4Account &&
to != _exchange5Account) {
_realizeAccountProfitTokens(to);
}
}
function _calcUnrealizedProfitTokens(address account) internal view returns (uint256) {
if (account == _adminContract ||
account == _treasuryAccount ||
account == _exchange1Account ||
account == _exchange2Account ||
account == _exchange3Account ||
account == _exchange4Account ||
account == _exchange5Account) {
return 0;
}
uint256 profitDifference = _allTimeProfit - _profitMarkers[account];
uint256 totalGovTokens = totalSupply(gARTEQ) - balanceOf(_adminContract, gARTEQ);
if (totalGovTokens == 0) {
return 0;
}
uint256 tokensToTransfer = (profitDifference * balanceOf(account, gARTEQ)) / totalGovTokens;
return tokensToTransfer;
}
// This function actually transfers the unrealized accumulated profit tokens of an account
// and make them spendable by that account. The balance should not differ after the
// trasnfer as the balance already includes the unrealized tokens.
function _realizeAccountProfitTokens(address account) internal {
bool updateProfitMarker = true;
// If 'account' has some governance tokens then calculate the accumulated profit since the last distribution
if (balanceOf(account, gARTEQ) > 0) {
uint256 tokensToTransfer = _calcUnrealizedProfitTokens(account);
// If the profit is too small and no token can be transferred, then don't update the profit marker and
// let the account wait for the next round of profit distribution
if (tokensToTransfer == 0) {
updateProfitMarker = false;
} else {
_balances[ARTEQ][account] += tokensToTransfer;
_profitTokensTransferredToAccounts += tokensToTransfer;
emit ProfitTokensDistributed(account, tokensToTransfer);
}
}
if (updateProfitMarker) {
_profitMarkers[account] = _allTimeProfit;
}
}
receive() external payable {
revert("arteQTokens: cannot accept ether");
}
fallback() external payable {
revert("arteQTokens: cannot accept ether");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/*
* This file is part of the contracts written for artèQ Investment Fund (https://github.com/billionbuild/arteq-contracts).
* Copyright (c) 2021 BillionBuild (2B) Team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GNU General Public License v3.0
// Based on OpenZeppelin Contracts v4.3.2 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity 0.8.0;
import "./ERC1155.sol";
/**
* @author Modified by Kam Amini <[email protected]> <[email protected]> <[email protected]>
*
* @notice Use at your own risk
*
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*
* Note: 2B has modified the original code to cover its needs as
* part of artèQ Investment Fund ecosystem
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 id,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, id, amounts, data);
if (from == address(0)) {
_totalSupply[id] += amounts[0];
}
if (to == address(0)) {
_totalSupply[id] -= amounts[0];
}
}
}
/*
* This file is part of the contracts written for artèQ Investment Fund (https://github.com/billionbuild/arteq-contracts).
* Copyright (c) 2021 BillionBuild (2B) Team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GNU General Public License v3.0
pragma solidity 0.8.0;
/// @author Kam Amini <[email protected]> <[email protected]> <[email protected]>
///
/// @title An interface which allows ERC-20 tokens to interact with the
/// main ERC-1155 contract
///
/// @notice Use at your own risk
interface IarteQTokens {
function compatBalanceOf(address origin, address account, uint256 tokenId) external view returns (uint256);
function compatTotalSupply(address origin, uint256 tokenId) external view returns (uint256);
function compatTransfer(address origin, address to, uint256 tokenId, uint256 amount) external;
function compatTransferFrom(address origin, address from, address to, uint256 tokenId, uint256 amount) external;
function compatAllowance(address origin, address account, address operator) external view returns (uint256);
function compatApprove(address origin, address operator, uint256 amount) external;
}
/*
* This file is part of the contracts written for artèQ Investment Fund (https://github.com/billionbuild/arteq-contracts).
* Copyright (c) 2021 BillionBuild (2B) Team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GNU General Public License v3.0
pragma solidity 0.8.0;
/// @author Kam Amini <[email protected]> <[email protected]> <[email protected]>
/// @title The interface for finalizing tasks. Mainly used by artèQ contracts to
/// perform administrative tasks in conjuction with admin contract.
interface IarteQTaskFinalizer {
event TaskFinalized(address finalizer, address origin, uint256 taskId);
function finalizeTask(address origin, uint256 taskId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/*
* This file is part of the contracts written for artèQ Investment Fund (https://github.com/billionbuild/arteq-contracts).
* Copyright (c) 2021 BillionBuild (2B) Team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GNU General Public License v3.0
// Based on OpenZeppelin Contracts v4.3.2 (token/ERC1155/ERC1155.sol)
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @author Modified by Kam Amini <[email protected]> <[email protected]> <[email protected]>
*
* @notice Use at your own risk
*
* Note: 2B has modified the original code to cover its needs as
* part of artèQ Investment Fund ecosystem
*/
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
// arteQ: we made this field public in order to distribute profits in the token contract
mapping(uint256 => mapping(address => uint256)) public _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev See {_setURI}.
*/
constructor() {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved "
);
_safeTransferFrom(_msgSender(), from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address /* from */,
address /* to */,
uint256[] memory /* ids */,
uint256[] memory /* amounts */,
bytes memory /* data */
) public virtual override {
revert("ERC1155: not implemented");
}
function _safeTransferFrom(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
// arteQ: we have to read the returned amount again as it can change in the function
uint256[] memory amounts = _asArray(amount, 2);
_beforeTokenTransfer(operator, from, to, id, amounts, data);
uint256 fromAmount = amounts[0];
uint256 toAmount = amounts[1];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= fromAmount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - fromAmount;
}
_balances[id][to] += toAmount;
emit TransferSingle(operator, from, to, id, amount);
}
function _initialMint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, id, _asArray(amount, 2), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
}
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function _beforeTokenTransfer(
address /* operator */,
address /* from */,
address /* to */,
uint256 /* id */,
uint256[] memory /* amounts */,
bytes memory /* data */
) internal virtual {}
function _asArray(uint256 element, uint len) private pure returns (uint256[] memory) {
if (len == 1) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
} else if (len == 2) {
uint256[] memory array = new uint256[](2);
array[0] = element;
array[1] = element;
return array;
}
revert("ERC1155: length must be 1 or 2");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
} | Returns the profit percentage return The set treasury account | function getProfitPercentage() external view returns (uint) {
return _profitPercentage;
}
| 11,994,052 |
./partial_match/1/0x12A73E14ef40DbD995baE85377961A1D2F1596be/sources/contracts/SphinxManager.sol | / Execute the `SET_STORAGE` actions if there are any. | function executeEntireUpgrade(
SphinxTarget[] memory _targets,
bytes32[][] memory _targetProofs,
RawSphinxAction[] memory _setStorageActions,
bytes32[][] memory _setStorageProofs
) external {
initiateUpgrade(_targets, _targetProofs);
if (_setStorageActions.length > 0) {
setStorage(_setStorageActions, _setStorageProofs);
}
finalizeUpgrade(_targets, _targetProofs);
}
| 9,336,512 |
./full_match/1/0x6f10040d6A4f2Ab8d9FDf641797a78dE08DDCe81/sources/src/Jackpot.sol | selects number which is saved by internal function, used to determine winner off-chain | function drawNumber(uint256 drawingId) external onlyRole(RAFFLER_ROLE) {
if (bytes(drawings[drawingId].ipfsHash).length == 0 || drawings[drawingId].vrfRequestId != 0) {
revert("Jackpot::setupDrawing: Drawing either not set up or already drawn");
}
uint256 requestId = VRF_COODINATOR.requestRandomWords(
keyHash, subscriptionId, requestConfirmations, callbackGasLimit, uint32(1)
);
DrawingData storage drawing = drawings[drawingId];
drawings[drawingId].vrfRequestId = requestId;
vrfRequests[requestId] = drawingId;
}
| 16,610,167 |
/**
*Submitted for verification at Etherscan.io on 2022-01-25
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2 (utils/Strings.sol)
/*
@contract BXToken
@description NFT Contract of bx.com.br
*/
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
function append(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
}
pragma solidity ^0.8.0;
/**
* @dev - name BX Contract
* - description BX Token used by our projects
* - author bx.com.br
* - url https://bx.com.br
*/
contract BXToken {
using Strings for uint256;
mapping (uint256 => address) private tokenOwner;
mapping (uint256 => uint256) public tokenToPrice;
mapping (uint256 => uint256) public tokenToBxId;
event Mint(address indexed from_, uint256 tokenId_, uint256 bxId_, string name_, string tokenURI_, uint256 price_);
event Transfer(address indexed from_, address indexed to_, uint256 tokenId_, uint256 bxId_, uint256 price_);
address payable owner;
string private _name;
string private _symbol;
string private _baseURI;
string private _baseURL;
struct NFT {
uint256 tokenId;
uint256 bxId;
string name;
string group;
string tokenURI;
}
NFT[] public _nfts;
constructor(string memory name_, string memory symbol_, string memory baseURI_, string memory baseURL_) {
owner = payable(msg.sender);
_name = name_;
_symbol = symbol_;
_baseURI = baseURI_;
_baseURL = baseURL_;
}
/**
* @dev Modifier only contract owner can call method.
*/
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
/**
* @dev Append two strings
*/
function append(string storage a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns owner of tokenId
*/
function ownerOf(uint256 tokenId_) public view virtual returns (address) {
return tokenOwner[tokenId_];
}
/**
* @dev Returns token URL in market using tokenID
*/
function getToken(uint256 tokenId_) public view virtual returns (uint256, string memory, string memory) {
NFT storage nft = _nfts[tokenId_];
return (nft.tokenId, nft.name, nft.tokenURI);
}
/**
* @dev Returns tokenURI using tokenID
*/
function tokenURI(uint256 tokenId_) public view virtual returns (string memory) {
NFT storage nft = _nfts[tokenId_];
return append(_baseURI, nft.tokenURI);
}
/**
* @dev Returns token URL in market using tokenID
*/
function tokenURL(uint256 tokenId_) public view virtual returns (string memory) {
NFT storage nft = _nfts[tokenId_];
return append(_baseURL, nft.tokenId.toString());
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _nfts.length;
}
/**
* @dev Set price to token. If price is zero, nft cannot be purchased
*/
function setTokenPrice(uint256 tokenId_, uint256 price_) external {
require(msg.sender == tokenOwner[tokenId_], 'Not owner of this token');
tokenToPrice[tokenId_] = price_;
}
/**
* @dev Returns token price
*/
function getTokenPrice(uint256 tokenId_) public view virtual returns (uint256) {
return tokenToPrice[tokenId_];
}
/**
* @dev Mint nft. If price is zero, nft cannot be purchased
*/
function mintNFT(address to_, string memory name_, string memory group_, string memory tokenURI_, uint256 bxId_, uint256 price_) external onlyOwner returns (uint256) {
require(owner == msg.sender); // Only the Owner can create nfts
uint256 nftId = totalSupply(); // NFT id
_nfts.push(NFT(nftId, bxId_, name_, group_, tokenURI_));
tokenOwner[nftId] = to_;
tokenToPrice[nftId] = price_;
tokenToBxId[nftId] = bxId_;
emit Mint(msg.sender, nftId, bxId_, name_, tokenURI_, price_);
return nftId;
}
/**
* @dev Buy nft. Pay nft price, transfer to seller, change of owner.
*/
function buy(uint256 tokenId_) external payable {
uint256 price = tokenToPrice[tokenId_];
string memory token_not_for_sale = Strings.append('This token is not for sale - ', Strings.toString(price));
require(price != 0, token_not_for_sale);
require(msg.value == price, 'Incorrect value');
address seller = tokenOwner[tokenId_];
require(seller != msg.sender, 'You already have this token');
payable(seller).transfer(msg.value);
tokenOwner[tokenId_] = msg.sender;
tokenToPrice[tokenId_] = 0; // not for sale for now
emit Transfer(seller, msg.sender, tokenId_, tokenToBxId[tokenId_], price);
}
} | Append two strings/ | function append(string storage a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
| 6,534,019 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
/**
* @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.
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract BlackList is Ownable {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external view returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
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);
}
contract USD0xComp is IERC20, BlackList {
mapping(address => uint256) private _balances;
mapping(address => uint256) private timeOf;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply= 0;
string private _name="USD0x COMPOUND";
string private _symbol="USD0x COMP";
uint interest_updated=0;
uint public time=0;
uint blockNumber=0;
uint public interest_rate=1700000000000000000;
uint public _updateReceiver = 1 minutes;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor() {
time = block.timestamp;
blockNumber = block.number;
uint initalSupply=10000*10**18;
_mint(msg.sender,initalSupply);
timeOf[msg.sender]=time;
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
function setReceiverTime(uint secs ) external onlyOwner{
_updateReceiver = secs;
}
function setInt(uint ints ) external onlyOwner{
interest_rate = ints;
}
function mkcalc(address src, address dst) internal {
uint tempTime = time;
if(block.number > blockNumber){
blockNumber = block.number;
tempTime = block.timestamp;
}
time=tempTime;
interest_updated = timeOf[src];
if(interest_updated <= 0){
interest_updated = time;
timeOf[src] = time;
}
uint diff = tempTime - interest_updated;
uint how_many_mins = uint(diff/60);
uint256 no_usdox = _balances[src];
if(no_usdox > 0 && how_many_mins > 0 ){
uint minseconds = how_many_mins * 60;
uint256 interestSoFar = uint((((no_usdox * interest_rate ) / 31536000) * minseconds) / 100000000000000000000 ) ;
if(interestSoFar > 0){
interest_updated += minseconds;
timeOf[src] = interest_updated;
_balances[src] += interestSoFar ;
_totalSupply += interestSoFar;
emit Transfer(address(0),src, interestSoFar);
}
}
//checking receiver side the receiver end
no_usdox=0;
no_usdox = _balances[dst];
if( no_usdox > 0){
interest_updated = timeOf[dst];
diff = tempTime - interest_updated;
if(diff > _updateReceiver ){
//do the calc
how_many_mins = uint(diff / 60);
uint minseconds = how_many_mins * 60;
uint256 interestSoFar = uint((((no_usdox * interest_rate ) / 31536000) * minseconds) / 100000000000000000000 ) ;
//uint256 interestSoFar = uint(no_usdox.mul( interest_rate ).div(31536000).mul(how_many_mins*60 ).div( 100000000000000000000 )) ;
if(interestSoFar > 0){
interest_updated += minseconds;
timeOf[dst] = interest_updated;
_balances[dst] += interestSoFar ;
_totalSupply += interestSoFar ;
emit Transfer(address(0), dst, interestSoFar);
}
}
}else{
timeOf[dst] =tempTime;
}
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function timeOfs(address account) public view virtual returns (uint256) {
return timeOf[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address dst, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, dst, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(!isBlackListed[msg.sender]);
mkcalc(sender, recipient);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function issue(uint256 amount) external onlyOwner{
_mint(msg.sender,amount);
}
function redeem( uint256 amount) external onlyOwner {
address account = msg.sender;
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | do the calcuint256 interestSoFar = uint(no_usdox.mul( interest_rate ).div(31536000).mul(how_many_mins60 ).div( 100000000000000000000 )) ; | function mkcalc(address src, address dst) internal {
uint tempTime = time;
if(block.number > blockNumber){
blockNumber = block.number;
tempTime = block.timestamp;
}
time=tempTime;
interest_updated = timeOf[src];
if(interest_updated <= 0){
interest_updated = time;
timeOf[src] = time;
}
uint diff = tempTime - interest_updated;
uint how_many_mins = uint(diff/60);
uint256 no_usdox = _balances[src];
if(no_usdox > 0 && how_many_mins > 0 ){
uint minseconds = how_many_mins * 60;
uint256 interestSoFar = uint((((no_usdox * interest_rate ) / 31536000) * minseconds) / 100000000000000000000 ) ;
if(interestSoFar > 0){
interest_updated += minseconds;
timeOf[src] = interest_updated;
_balances[src] += interestSoFar ;
_totalSupply += interestSoFar;
emit Transfer(address(0),src, interestSoFar);
}
}
no_usdox = _balances[dst];
if( no_usdox > 0){
interest_updated = timeOf[dst];
diff = tempTime - interest_updated;
if(diff > _updateReceiver ){
how_many_mins = uint(diff / 60);
uint minseconds = how_many_mins * 60;
uint256 interestSoFar = uint((((no_usdox * interest_rate ) / 31536000) * minseconds) / 100000000000000000000 ) ;
if(interestSoFar > 0){
interest_updated += minseconds;
timeOf[dst] = interest_updated;
_balances[dst] += interestSoFar ;
_totalSupply += interestSoFar ;
emit Transfer(address(0), dst, interestSoFar);
}
}
timeOf[dst] =tempTime;
}
}
| 14,471,113 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
// import "@openzeppelin/contracts/utils/Counters.sol";
// import { Base64 } from "base64-sol/base64.sol";
import { RxStructs } from "./libraries/RxStructs.sol";
import { TokenURIDescriptor } from "./libraries/TokenURIDescriptor.sol";
/// @title A NFT Prescription creator
/// @author Matias Parij (@7i7o)
/// @notice You can use this contract only as a MVP for minting Prescriptions
/// @dev Features such as workplaces for doctors or pharmacists are for future iterations
contract Rx is ERC721, ERC721URIStorage, ERC721Burnable, AccessControl {
/// @notice Role definition for Minter
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/// @notice Role definition for Minter
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @notice Role definition for Burner
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
/** Begin of State Variables & Events */
// uint8 internal constant MAX_KEY_LENGTH = 20;
// uint8 internal constant MAX_VALUE_LENGTH = 62;
uint8 internal constant RX_LINES = 12; // Has to be same value as in RxStructs !!!
bool private selfGrantAdmin = false;
/// @notice TokenId enumeration (start at '1').
uint256 private _tokenIdCounter;
/// @notice this mapping holds all the subjects registered in the contract
mapping ( address => RxStructs.Subject ) private subjects;
/// @notice this mapping holds all the doctors registered in the contract
mapping ( address => RxStructs.Doctor ) private doctors;
/// @notice this mapping holds all the pharmacists registered in the contract
mapping ( address => RxStructs.Pharmacist ) private pharmacists;
/// @notice this mapping holds all the prescriptions minted in the contract
mapping ( uint256 => RxStructs.RxData ) private rxs;
/// @notice Event to signal when a new Rx has been minted
/// @param sender address of the Doctor that minted the Rx
/// @param receiver address of the Subject that received the Rx minted
/// @param tokenId Id of the Token (Rx) that has been minted
event minted(address indexed sender, address indexed receiver, uint256 indexed tokenId);
/// @notice Event to signal when adding/replacing a Subject allowed to receive/hold NFT Prescriptions
/// @param sender is the address of the admin that set the Subject's data
/// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions)
/// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01)
/// @param _nameA is the subject's full name (uses 2 bytes32)
/// @param _nameB is the subject's full name (uses 2 bytes32)
/// @param _homeAddressA is the subject's legal home address (uses 2 bytes32)
/// @param _homeAddressB is the subject's legal home address (uses 2 bytes32)
event subjectDataSet(address indexed sender, address indexed _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB);
/// @notice Event to signal when adding/replacing a Doctor allowed to mint NFT Prescriptions
/// @param sender is the address of the admin that set the Doctor's data
/// @param _subjectId is the ethereum address for the doctor (same Id as the subject that holds this doctor's personal details)
/// @param _degree contains a string with the degree of the doctor
/// @param _license contains a string with the legal license of the doctor
event doctorDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license);
/// @notice Event to signal when adding/replacing a Pharmacist allowed to burn NFT Prescriptions
/// @param sender is the address of the admin that set the Pharmacist's data
/// @param _subjectId is the ethereum address for the pahrmacist (same Id as the subject that holds this pharmacist's personal details)
/// @param _degree contains a string with the degree of the pharmacist
/// @param _license contains a string with the legal license of the pharmacist
event pharmacistDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license);
/// @notice Event to signal a removed Subject
/// @param sender is the address of the admin that removed the Subject
/// @param _subjectId is the registered address of the subject removed
event subjectRemoved(address indexed sender, address indexed _subjectId);
/// @notice Event to signal a removed Doctor
/// @param sender is the address of the admin that removed the Doctor
/// @param _subjectId is the registered address of the doctor removed
event doctorRemoved(address indexed sender, address indexed _subjectId);
/// @notice Event to signal a removed Pharmacist
/// @param sender is the address of the admin that removed the Pharmacist
/// @param _subjectId is the registered address of the pharmacist removed
event pharmacistRemoved(address indexed sender, address indexed _subjectId);
/** End of State Variables & Events */
/// @notice constructor for NFT Prescriptions contract
/// @dev Using ERC721 default constructor with "Prescription" and "Rx" as Name and Symbol for the tokens
/// @dev We set up the contract creator (msg.sender) with the ADMIN_ROLE to manage all the other Roles
/// @dev We increment the counter in the constructor to start Ids in 1, keeping Id 0 (default for uints
/// in solidity) to signal that someone doesn't have any NFTs
constructor() ERC721("Rx", "Rx") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
grantRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
_setRoleAdmin(BURNER_ROLE, ADMIN_ROLE);
_tokenIdCounter = 1;
}
/// @dev function override required by solidity
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/** Begin of implementation of functions for final project */
/// @dev Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
function transferOwnership(address newOwner)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(DEFAULT_ADMIN_ROLE, newOwner);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Checks if _addr is a Subject
function isSubject(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& subjects[_addr].subjectId == _addr
);
}
/// @dev Checks if _addr is a registered doctor
function isDoctor(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& doctors[_addr].subjectId == _addr
);
}
/// @dev Checks if _addr is a registered pharmacist
function isPharmacist(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& pharmacists[_addr].subjectId == _addr
);
}
/// @notice function override to prohibit token transfers
function _transfer(address, address, uint256)
internal
view
override(ERC721)
{
require(msg.sender == address(0), "RX: Rxs are untransferables");
}
/// @notice Funtion to mint a Prescription. Should be called only by a Doctor (has MINTER_ROLE)
/// @param to The id of the subject (patient) recipient of the prescription
/// @param _keys Text lines with the 'title' of each content of the prescription (max 19 characters each)
/// @param _values Text lines with the 'content' of the prescription (max 61 characters each)
/// @dev Does NOT store a tokenURI. It stores Prescription data on contract (tokenURI is generated upon request)
function mint(address to, bytes32[RX_LINES] memory _keys, bytes32[2*RX_LINES] memory _values)
public
onlyRole(MINTER_ROLE)
{
require( isSubject(to), 'RX: Not a Subject');
require( (msg.sender != to) , 'RX: Cannot self-prescribe');
uint256 tokenId = _tokenIdCounter++;
super._safeMint(to, tokenId);
// Store prescription data in contract, leaving tokenURI empty, for it is generated on request (Uniswap V3 style!)
rxs[tokenId].date = block.timestamp;
rxs[tokenId].patient = getSubject(to); // Patient Info
rxs[tokenId].doctorSubject = getSubject(msg.sender); // Doctor (Subject) Info
rxs[tokenId].doctor = getDoctor(msg.sender); // Doctor Info
rxs[tokenId].keys = _keys; // Rx Keys
rxs[tokenId].values = _values; // Rx values
emit minted(msg.sender, to, tokenId);
}
/// @dev function override required by solidity
/// @notice function override to store burner data in the rx before burning
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
onlyRole(BURNER_ROLE)
{
// delete rxs[tokenId]; // Keep Rx Data to be able to view past (dispensed) Prescriptions
require(
getApproved(tokenId) == msg.sender ||
isApprovedForAll(ownerOf(tokenId), msg.sender),
"pharm not approved");
// We save the burner (pharmacist) data to the Rx
rxs[tokenId].pharmacistSubject = getSubject(msg.sender);
rxs[tokenId].pharmacist = getPharmacist(msg.sender);
super._burn(tokenId);
//TODO: Change prescription life cycle in 'Status' to keep prescription data without burning
}
/// @dev TokenURI generated on the fly from stored data (function override required by solidity)
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
// require(_exists(tokenId), "nonexistent token");
require(tokenId < _tokenIdCounter, "nonminted token"); // Also show TokenURI for 'dispensed' prescriptions
return TokenURIDescriptor.constructTokenURI(tokenId, name(), symbol(), rxs[tokenId]);
// TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist)
// TODO: Modify SVG when a prescription is 'dispensed'
}
/// @notice Function to get data for a specific tokenId. Only for Doctor, Patient or Pharmacist of the tokenId.
/// @param tokenId uint256 representing an existing tokenId
/// @return a RxData struct containing all the Rx Data
function getRx(uint256 tokenId)
public
view
returns (RxStructs.RxData memory)
{
return rxs[tokenId];
// TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist)
}
/// @notice Function to set selfGrantAdmin (only deployer of contract is allowed)
/// @param _selfAdmin bool to set state variable
function setSelfGrantAdmin(bool _selfAdmin)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
selfGrantAdmin = _selfAdmin;
}
/// @notice Function to set selfGrantAdmin (only deployer of contract is allowed)
/// @return bool with state variable
function getSelfGrantAdmin()
public
view
returns (bool)
{
return selfGrantAdmin;
}
/// @notice Function to add an admin account
/// @param to Address of the account to grant admin role
function addAdmin(address to)
public
{
if (!selfGrantAdmin) {
grantRole(ADMIN_ROLE, to);
} else {
// We skip role manager checks for the final project presentation
_grantRole(ADMIN_ROLE, to);
}
}
/// @notice Function to remove an admin account
/// @param to Address of the account to remove admin role
function removeAdmin(address to)
public
onlyRole(ADMIN_ROLE)
{
revokeRole(ADMIN_ROLE, to);
}
/// @notice Function to check if someone has admin role
/// @param to address to check for admin role privilege
/// @return true if @param to is an admin or false otherwise
function isAdmin(address to)
public
view
returns (bool)
{
return hasRole(ADMIN_ROLE, to);
}
/// @notice Function to retrieve a Subject
/// @param _subjectId the registered address of the subject to retrieve
/// @return an object with the Subject
function getSubject(address _subjectId)
public
view
returns (RxStructs.Subject memory)
{
return subjects[_subjectId];
}
/// @notice Function to retrieve a Doctor
/// @param _subjectId the registered address of the doctor to retrieve
/// @return an object with the Doctor
function getDoctor(address _subjectId)
public
view
returns (RxStructs.Doctor memory)
{
return doctors[_subjectId];
}
/// @notice Function to retrieve a Pharmacist
/// @param _subjectId the registered address of the pharmacist to retrieve
/// @return an object with the Pharmacist
function getPharmacist(address _subjectId)
public
view
returns (RxStructs.Pharmacist memory)
{
return pharmacists[_subjectId];
}
/// @notice Function to add/replace a Subject allowed to receive/hold NFT Prescriptions
/// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions)
/// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01)
/// @param _nameA is the subject's full name (uses 2 bytes32)
/// @param _nameB is the subject's full name (uses 2 bytes32)
/// @param _homeAddressA is the subject's legal home address (uses 2 bytes32)
/// @param _homeAddressB is the subject's legal home address (uses 2 bytes32)
/// @dev Only ADMIN_ROLE users are allowed to modify subjects
function setSubjectData(address _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB)
public
onlyRole(ADMIN_ROLE)
{
require ( _subjectId != address(0), 'RX: Cannot register 0x0 address');
// subjects[_subjectId] = RxStructs.Subject(_subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB);
subjects[_subjectId].subjectId = _subjectId;
subjects[_subjectId].birthDate = _birthDate;
subjects[_subjectId].nameA = _nameA;
subjects[_subjectId].nameB = _nameB;
subjects[_subjectId].homeAddressA = _homeAddressA;
subjects[_subjectId].homeAddressB = _homeAddressB;
emit subjectDataSet(msg.sender, _subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB);
}
/// @notice Function to add/replace a Doctor allowed to mint NFT Prescriptions
/// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this doctor's personal details)
/// @param _degree should contain the degree of the doctor
/// @param _license should contain the legal license of the doctor
/// @dev @param _workplaces is a feature for future implementations
function setDoctorData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
grantRole(MINTER_ROLE, _subjectId);
// doctors[_subjectId] = RxStructs.Doctor(_subjectId, _degree, _license);
doctors[_subjectId].subjectId = _subjectId;
doctors[_subjectId].degree = _degree;
doctors[_subjectId].license = _license;
emit doctorDataSet(msg.sender, _subjectId, _degree, _license);
}
/// @notice Function to add/replace a Pharmacist allowed to burn NFT Prescriptions
/// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this pharmacist's personal details)
/// @param _degree should contain the degree of the pharmacist
/// @param _license should contain the legal license of the pharmacist
/// @dev @param _workplaces is a feature for future implementations
function setPharmacistData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
grantRole(BURNER_ROLE, _subjectId);
// pharmacists[_subjectId] = RxStructs.Pharmacist(_subjectId, _degree, _license);
pharmacists[_subjectId].subjectId = _subjectId;
pharmacists[_subjectId].degree = _degree;
pharmacists[_subjectId].license = _license;
emit pharmacistDataSet(msg.sender, _subjectId, _degree, _license);
}
/// @notice Function to remove a registered Subject
/// @param _subjectId is the registered address of the subject to remove
/// @dev Only ADMIN_ROLE users are allowed to remove subjects
function removeSubject(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
require( !isDoctor(_subjectId), 'RX: Still a Doctor');
require( !isPharmacist(_subjectId), 'RX: Still a Pharmacist');
delete subjects[_subjectId];
emit subjectRemoved(msg.sender, _subjectId);
}
/// @notice Function to remove a registered Doctor
/// @param _subjectId is the registered address of the doctor to remove
/// @dev Only ADMIN_ROLE users are allowed to remove doctors
function removeDoctor(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isDoctor(_subjectId), 'RX: Not a Doctor'); // Also checks address!=0x0
revokeRole(MINTER_ROLE, _subjectId);
delete doctors[_subjectId];
emit doctorRemoved(msg.sender, _subjectId);
}
/// @notice Function to remove a registered Pharmacist
/// @param _subjectId is the registered address of the pharmacist to remove
/// @dev Only ADMIN_ROLE users are allowed to remove pharmacists
function removePharmacist(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isPharmacist(_subjectId), 'RX: Not a Pharmacist'); // Also checks address!=0x0
revokeRole(BURNER_ROLE, _subjectId);
delete pharmacists[_subjectId];
emit pharmacistRemoved(msg.sender, _subjectId);
}
} | Function to retrieve a Subject _subjectId the registered address of the subject to retrieve return an object with the Subject | function getSubject(address _subjectId)
public
view
returns (RxStructs.Subject memory)
{
return subjects[_subjectId];
}
| 13,112,974 |
./full_match/11155111/0xE1350B9B29658498fB22907cc93Bdbfb6e2F9E56/sources/contracts/gauges/StakelessGauge.sol | solhint-disable-next-line func-name-mixedcase Because we calculate the rate locally, this gauge cannot be used prior to the start of the first emission period | function __StakelessGauge_init(uint256 relativeWeightCap) internal {
require(_period == 0, "Already initialized");
uint256 rate = _tokenAdmin.rate();
require(rate != 0, "BalancerTokenAdmin not yet activated");
_rate = rate;
_period = _currentPeriod();
_startEpochTime = _tokenAdmin.startEpochTimeWrite();
_setRelativeWeightCap(relativeWeightCap);
}
| 3,841,641 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions". This adds two-phase
* ownership control to OpenZeppelin's Ownable class. In this model, the original owner
* designates a new owner but does not actually transfer ownership. The new owner then accepts
* ownership and completes the transfer.
*/
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
pendingOwner = address(0);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
pendingOwner = _newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title CarbonDollarStorage
* @notice Contains necessary storage contracts for CarbonDollar (FeeSheet and StablecoinWhitelist).
*/
contract CarbonDollarStorage is Ownable {
using SafeMath for uint256;
/**
Mappings
*/
/* fees for withdrawing to stablecoin, in tenths of a percent) */
mapping (address => uint256) public fees;
/** @dev Units for fees are always in a tenth of a percent */
uint256 public defaultFee;
/* is the token address referring to a stablecoin/whitelisted token? */
mapping (address => bool) public whitelist;
/**
Events
*/
event DefaultFeeChanged(uint256 oldFee, uint256 newFee);
event FeeChanged(address indexed stablecoin, uint256 oldFee, uint256 newFee);
event FeeRemoved(address indexed stablecoin, uint256 oldFee);
event StablecoinAdded(address indexed stablecoin);
event StablecoinRemoved(address indexed stablecoin);
/** @notice Sets the default fee for burning CarbonDollar into a whitelisted stablecoin.
@param _fee The default fee.
*/
function setDefaultFee(uint256 _fee) public onlyOwner {
uint256 oldFee = defaultFee;
defaultFee = _fee;
if (oldFee != defaultFee)
emit DefaultFeeChanged(oldFee, _fee);
}
/** @notice Set a fee for burning CarbonDollar into a stablecoin.
@param _stablecoin Address of a whitelisted stablecoin.
@param _fee the fee.
*/
function setFee(address _stablecoin, uint256 _fee) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = _fee;
if (oldFee != _fee)
emit FeeChanged(_stablecoin, oldFee, _fee);
}
/** @notice Remove the fee for burning CarbonDollar into a particular kind of stablecoin.
@param _stablecoin Address of stablecoin.
*/
function removeFee(address _stablecoin) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = 0;
if (oldFee != 0)
emit FeeRemoved(_stablecoin, oldFee);
}
/** @notice Add a token to the whitelist.
@param _stablecoin Address of the new stablecoin.
*/
function addStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = true;
emit StablecoinAdded(_stablecoin);
}
/** @notice Removes a token from the whitelist.
@param _stablecoin Address of the ex-stablecoin.
*/
function removeStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = false;
emit StablecoinRemoved(_stablecoin);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _stablecoin The stablecoin whose fee will be used.
*/
function computeStablecoinFee(uint256 _amount, address _stablecoin) public view returns (uint256) {
uint256 fee = fees[_stablecoin];
return computeFee(_amount, fee);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _fee The fee that will be charged, in tenths of a percent.
*/
function computeFee(uint256 _amount, uint256 _fee) public pure returns (uint256) {
return _amount.mul(_fee).div(1000);
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title PermissionedTokenStorage
* @notice a PermissionedTokenStorage is constructed by setting Regulator, BalanceSheet, and AllowanceSheet locations.
* Once the storages are set, they cannot be changed.
*/
contract PermissionedTokenStorage is Ownable {
using SafeMath for uint256;
/**
Storage
*/
mapping (address => mapping (address => uint256)) public allowances;
mapping (address => uint256) public balances;
uint256 public totalSupply;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = _value;
}
function addBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = _value;
}
function addTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.add(_value);
}
function subTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.sub(_value);
}
function setTotalSupply(uint256 _value) public onlyOwner {
totalSupply = _value;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Lockable
* @dev Base contract which allows children to lock certain methods from being called by clients.
* Locked methods are deemed unsafe by default, but must be implemented in children functionality to adhere by
* some inherited standard, for example.
*/
contract Lockable is Ownable {
// Events
event Unlocked();
event Locked();
// Fields
bool public isMethodEnabled = false;
// Modifiers
/**
* @dev Modifier that disables functions by default unless they are explicitly enabled
*/
modifier whenUnlocked() {
require(isMethodEnabled);
_;
}
// Methods
/**
* @dev called by the owner to enable method
*/
function unlock() onlyOwner public {
isMethodEnabled = true;
emit Unlocked();
}
/**
* @dev called by the owner to disable method, back to normal state
*/
function lock() onlyOwner public {
isMethodEnabled = false;
emit Locked();
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism. Identical to OpenZeppelin version
* except that it uses local Ownable contract
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/
contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
}
/**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/
contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
}
/**
* @title PermissionedToken
* @notice A permissioned token that enables transfers, withdrawals, and deposits to occur
* if and only if it is approved by an on-chain Regulator service. PermissionedToken is an
* ERC-20 smart contract representing ownership of securities and overrides the
* transfer, burn, and mint methods to check with the Regulator.
*/
contract PermissionedToken is ERC20, Pausable, Lockable {
using SafeMath for uint256;
/** Events */
event DestroyedBlacklistedTokens(address indexed account, uint256 amount);
event ApprovedBlacklistedAddressSpender(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 value);
event Burn(address indexed burner, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event ChangedRegulator(address indexed oldRegulator, address indexed newRegulator );
PermissionedTokenStorage public tokenStorage;
Regulator public regulator;
/**
* @dev create a new PermissionedToken with a brand new data storage
**/
constructor (address _regulator) public {
regulator = Regulator(_regulator);
tokenStorage = new PermissionedTokenStorage();
}
/** Modifiers **/
/** @notice Modifier that allows function access to be restricted based on
* whether the regulator allows the message sender to execute that function.
**/
modifier requiresPermission() {
require (regulator.hasUserPermission(msg.sender, msg.sig), "User does not have permission to execute function");
_;
}
/** @notice Modifier that checks whether or not a transferFrom operation can
* succeed with the given _from and _to address. See transferFrom()'s documentation for
* more details.
**/
modifier transferFromConditionsRequired(address _from, address _to) {
require(!regulator.isBlacklistedUser(_to), "Recipient cannot be blacklisted");
// If the origin user is blacklisted, the transaction can only succeed if
// the message sender is a user that has been approved to transfer
// blacklisted tokens out of this address.
bool is_origin_blacklisted = regulator.isBlacklistedUser(_from);
// Is the message sender a person with the ability to transfer tokens out of a blacklisted account?
bool sender_can_spend_from_blacklisted_address = regulator.isBlacklistSpender(msg.sender);
require(!is_origin_blacklisted || sender_can_spend_from_blacklisted_address, "Origin cannot be blacklisted if spender is not an approved blacklist spender");
_;
}
/** @notice Modifier that checks whether a user is blacklisted.
* @param _user The address of the user to check.
**/
modifier userBlacklisted(address _user) {
require(regulator.isBlacklistedUser(_user), "User must be blacklisted");
_;
}
/** @notice Modifier that checks whether a user is not blacklisted.
* @param _user The address of the user to check.
**/
modifier userNotBlacklisted(address _user) {
require(!regulator.isBlacklistedUser(_user), "User must not be blacklisted");
_;
}
/** Functions **/
/**
* @notice Allows user to mint if they have the appropriate permissions. User generally
* must have minting authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _to The address of the receiver
* @param _amount The number of tokens to mint
*/
function mint(address _to, uint256 _amount) public userNotBlacklisted(_to) requiresPermission whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice Remove CUSD from supply
* @param _amount The number of tokens to burn
* @return `true` if successful and `false` if unsuccessful
*/
function burn(uint256 _amount) userNotBlacklisted(msg.sender) public whenNotPaused {
_burn(msg.sender, _amount);
}
/**
* @notice Implements ERC-20 standard approve function. Locked or disabled by default to protect against
* double spend attacks. To modify allowances, clients should call safer increase/decreaseApproval methods.
* Upon construction, all calls to approve() will revert unless this contract owner explicitly unlocks approve()
*/
function approve(address _spender, uint256 _value)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused whenUnlocked returns (bool) {
tokenStorage.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_increaseApproval(_spender, _addedValue, msg.sender);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @notice decreaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using decreaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_decreaseApproval(_spender, _subtractedValue, msg.sender);
return true;
}
/**
* @notice Destroy the tokens owned by a blacklisted account. This function can generally
* only be called by a central authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _who Account to destroy tokens from. Must be a blacklisted account.
*/
function destroyBlacklistedTokens(address _who, uint256 _amount) public userBlacklisted(_who) whenNotPaused requiresPermission {
tokenStorage.subBalance(_who, _amount);
tokenStorage.subTotalSupply(_amount);
emit DestroyedBlacklistedTokens(_who, _amount);
}
/**
* @notice Allows a central authority to approve themselves as a spender on a blacklisted account.
* By default, the allowance is set to the balance of the blacklisted account, so that the
* authority has full control over the account balance.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _blacklistedAccount The blacklisted account.
*/
function approveBlacklistedAddressSpender(address _blacklistedAccount)
public userBlacklisted(_blacklistedAccount) whenNotPaused requiresPermission {
tokenStorage.setAllowance(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
emit ApprovedBlacklistedAddressSpender(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
}
/**
* @notice Initiates a "send" operation towards another user. See `transferFrom` for details.
* @param _to The address of the receiver. This user must not be blacklisted, or else the tranfer
* will fail.
* @param _amount The number of tokens to transfer
*
* @return `true` if successful
*/
function transfer(address _to, uint256 _amount) public userNotBlacklisted(_to) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_transfer(_to, msg.sender, _amount);
return true;
}
/**
* @notice Initiates a transfer operation between address `_from` and `_to`. Requires that the
* message sender is an approved spender on the _from account.
* @dev When implemented, it should use the transferFromConditionsRequired() modifier.
* @param _to The address of the recipient. This address must not be blacklisted.
* @param _from The address of the origin of funds. This address _could_ be blacklisted, because
* a regulator may want to transfer tokens out of a blacklisted account, for example.
* In order to do so, the regulator would have to add themselves as an approved spender
* on the account via `addBlacklistAddressSpender()`, and would then be able to transfer tokens out of it.
* @param _amount The number of tokens to transfer
* @return `true` if successful
*/
function transferFrom(address _from, address _to, uint256 _amount)
public whenNotPaused transferFromConditionsRequired(_from, _to) returns (bool) {
require(_amount <= allowance(_from, msg.sender),"not enough allowance to transfer");
_transfer(_to, _from, _amount);
tokenStorage.subAllowance(_from, msg.sender, _amount);
return true;
}
/**
*
* @dev Only the token owner can change its regulator
* @param _newRegulator the new Regulator for this token
*
*/
function setRegulator(address _newRegulator) public onlyOwner {
require(_newRegulator != address(regulator), "Must be a new regulator");
require(AddressUtils.isContract(_newRegulator), "Cannot set a regulator storage to a non-contract address");
address old = address(regulator);
regulator = Regulator(_newRegulator);
emit ChangedRegulator(old, _newRegulator);
}
/**
* @notice If a user is blacklisted, they will have the permission to
* execute this dummy function. This function effectively acts as a marker
* to indicate that a user is blacklisted. We include this function to be consistent with our
* invariant that every possible userPermission (listed in Regulator) enables access to a single
* PermissionedToken function. Thus, the 'BLACKLISTED' permission gives access to this function
* @return `true` if successful
*/
function blacklisted() public view requiresPermission returns (bool) {
return true;
}
/**
* ERC20 standard functions
*/
function allowance(address owner, address spender) public view returns (uint256) {
return tokenStorage.allowances(owner, spender);
}
function totalSupply() public view returns (uint256) {
return tokenStorage.totalSupply();
}
function balanceOf(address _addr) public view returns (uint256) {
return tokenStorage.balances(_addr);
}
/** Internal functions **/
function _decreaseApproval(address _spender, uint256 _subtractedValue, address _tokenHolder) internal {
uint256 oldValue = allowance(_tokenHolder, _spender);
if (_subtractedValue > oldValue) {
tokenStorage.setAllowance(_tokenHolder, _spender, 0);
} else {
tokenStorage.subAllowance(_tokenHolder, _spender, _subtractedValue);
}
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _increaseApproval(address _spender, uint256 _addedValue, address _tokenHolder) internal {
tokenStorage.addAllowance(_tokenHolder, _spender, _addedValue);
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _burn(address _tokensOf, uint256 _amount) internal {
require(_tokensOf != address(0),"burner address cannot be 0x0");
require(_amount <= balanceOf(_tokensOf),"not enough balance to burn");
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
tokenStorage.subBalance(_tokensOf, _amount);
tokenStorage.subTotalSupply(_amount);
emit Burn(_tokensOf, _amount);
emit Transfer(_tokensOf, address(0), _amount);
}
function _mint(address _to, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
tokenStorage.addTotalSupply(_amount);
tokenStorage.addBalance(_to, _amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function _transfer(address _to, address _from, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
require(_amount <= balanceOf(_from),"not enough balance to transfer");
tokenStorage.addBalance(_to, _amount);
tokenStorage.subBalance(_from, _amount);
emit Transfer(_from, _to, _amount);
}
}
/**
* @title WhitelistedToken
* @notice A WhitelistedToken can be converted into CUSD and vice versa. Converting a WT into a CUSD
* is the only way for a user to obtain CUSD. This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation.
*/
contract WhitelistedToken is PermissionedToken {
address public cusdAddress;
/**
Events
*/
event CUSDAddressChanged(address indexed oldCUSD, address indexed newCUSD);
event MintedToCUSD(address indexed user, uint256 amount);
event ConvertedToCUSD(address indexed user, uint256 amount);
/**
* @notice Constructor sets the regulator contract and the address of the
* CarbonUSD meta-token contract. The latter is necessary in order to make transactions
* with the CarbonDollar smart contract.
*/
constructor(address _regulator, address _cusd) public PermissionedToken(_regulator) {
// base class fields
regulator = Regulator(_regulator);
cusdAddress = _cusd;
}
/**
* @notice Mints CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _to The address of the receiver
* @param _amount The number of CarbonTokens to mint to user
*/
function mintCUSD(address _to, uint256 _amount) public requiresPermission whenNotPaused userNotBlacklisted(_to) {
return _mintCUSD(_to, _amount);
}
/**
* @notice Converts WT0 to CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _amount The number of Whitelisted tokens to convert
*/
function convertWT(uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(balanceOf(msg.sender) >= _amount, "Conversion amount should be less than balance");
_burn(msg.sender, _amount);
_mintCUSD(msg.sender, _amount);
emit ConvertedToCUSD(msg.sender, _amount);
}
/**
* @notice Change the cusd address.
* @param _cusd the cusd address.
*/
function setCUSDAddress(address _cusd) public onlyOwner {
require(_cusd != address(cusdAddress), "Must be a new cusd address");
require(AddressUtils.isContract(_cusd), "Must be an actual contract");
address oldCUSD = address(cusdAddress);
cusdAddress = _cusd;
emit CUSDAddressChanged(oldCUSD, _cusd);
}
function _mintCUSD(address _to, uint256 _amount) internal {
require(_to != cusdAddress, "Cannot mint to CarbonUSD contract"); // This is to prevent Carbon Labs from printing money out of thin air!
CarbonDollar(cusdAddress).mint(_to, _amount);
_mint(cusdAddress, _amount);
emit MintedToCUSD(_to, _amount);
}
}
/**
* @title CarbonDollar
* @notice The main functionality for the CarbonUSD metatoken. (CarbonUSD is just a proxy
* that implements this contract's functionality.) This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation. Every CarbonDollar token is backed by one
* whitelisted stablecoin credited to the balance of this contract address.
*/
contract CarbonDollar is PermissionedToken {
// Events
event ConvertedToWT(address indexed user, uint256 amount);
event BurnedCUSD(address indexed user, uint256 feedAmount, uint256 chargedFee);
/**
Modifiers
*/
modifier requiresWhitelistedToken() {
require(isWhitelisted(msg.sender), "Sender must be a whitelisted token contract");
_;
}
CarbonDollarStorage public tokenStorage_CD;
/** CONSTRUCTOR
* @dev Passes along arguments to base class.
*/
constructor(address _regulator) public PermissionedToken(_regulator) {
// base class override
regulator = Regulator(_regulator);
tokenStorage_CD = new CarbonDollarStorage();
}
/**
* @notice Add new stablecoin to whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function listToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.addStablecoin(_stablecoin);
}
/**
* @notice Remove existing stablecoin from whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function unlistToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.removeStablecoin(_stablecoin);
}
/**
* @notice Change fees associated with going from CarbonUSD to a particular stablecoin.
* @param stablecoin Address of the stablecoin contract.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setFee(address stablecoin, uint256 _newFee) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.setFee(stablecoin, _newFee);
}
/**
* @notice Remove fees associated with going from CarbonUSD to a particular stablecoin.
* The default fee still may apply.
* @param stablecoin Address of the stablecoin contract.
*/
function removeFee(address stablecoin) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.removeFee(stablecoin);
}
/**
* @notice Change the default fee associated with going from CarbonUSD to a WhitelistedToken.
* This fee amount is used if the fee for a WhitelistedToken is not specified.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setDefaultFee(uint256 _newFee) public onlyOwner whenNotPaused {
tokenStorage_CD.setDefaultFee(_newFee);
}
/**
* @notice Mints CUSD on behalf of a user. Note the use of the "requiresWhitelistedToken"
* modifier; this means that minting authority does not belong to any personal account;
* only whitelisted token contracts can call this function. The intended functionality is that the only
* way to mint CUSD is for the user to actually burn a whitelisted token to convert into CUSD
* @param _to User to send CUSD to
* @param _amount Amount of CarbonUSD to mint.
*/
function mint(address _to, uint256 _amount) public requiresWhitelistedToken whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice user can convert CarbonUSD umbrella token into a whitelisted stablecoin.
* @param stablecoin represents the type of coin the users wishes to receive for burning carbonUSD
* @param _amount Amount of CarbonUSD to convert.
* we credit the user's account at the sender address with the _amount minus the percentage fee we want to charge.
*/
function convertCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
WhitelistedToken whitelisted = WhitelistedToken(stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Send back WT0 to calling user, but with a fee reduction.
// Transfer this fee into the whitelisted token's CarbonDollar account (this contract's address)
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(msg.sender, _amount);
require(whitelisted.transfer(msg.sender, feedAmount));
whitelisted.burn(chargedFee);
_mint(address(this), chargedFee);
emit ConvertedToWT(msg.sender, _amount);
}
/**
* @notice burns CarbonDollar and an equal amount of whitelisted stablecoin from the CarbonDollar address
* @param stablecoin Represents the stablecoin whose fee will be charged.
* @param _amount Amount of CarbonUSD to burn.
*/
function burnCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
_burnCarbonDollar(msg.sender, stablecoin, _amount);
}
/**
* @notice release collected CUSD fees to owner
* @param _amount Amount of CUSD to release
* @return `true` if successful
*/
function releaseCarbonDollar(uint256 _amount) public onlyOwner returns (bool) {
require(_amount <= balanceOf(address(this)),"not enough balance to transfer");
tokenStorage.subBalance(address(this), _amount);
tokenStorage.addBalance(msg.sender, _amount);
emit Transfer(address(this), msg.sender, _amount);
return true;
}
/** Computes fee percentage associated with burning into a particular stablecoin.
* @param stablecoin The stablecoin whose fee will be charged. Precondition: is a whitelisted
* stablecoin.
* @return The fee that will be charged. If the stablecoin's fee is not set, the default
* fee is returned.
*/
function computeFeeRate(address stablecoin) public view returns (uint256 feeRate) {
if (getFee(stablecoin) > 0)
feeRate = getFee(stablecoin);
else
feeRate = getDefaultFee();
}
/**
* @notice Check if whitelisted token is whitelisted
* @return bool true if whitelisted, false if not
**/
function isWhitelisted(address _stablecoin) public view returns (bool) {
return tokenStorage_CD.whitelist(_stablecoin);
}
/**
* @notice Get the fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @param stablecoin The stablecoin whose fee is being checked.
* @return The fee associated with the stablecoin.
*/
function getFee(address stablecoin) public view returns (uint256) {
return tokenStorage_CD.fees(stablecoin);
}
/**
* @notice Get the default fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @return The default fee for stablecoin trades.
*/
function getDefaultFee() public view returns (uint256) {
return tokenStorage_CD.defaultFee();
}
function _burnCarbonDollar(address _tokensOf, address _stablecoin, uint256 _amount) internal {
require(isWhitelisted(_stablecoin), "Stablecoin must be whitelisted prior to burning");
WhitelistedToken whitelisted = WhitelistedToken(_stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Burn user's CUSD, but with a fee reduction.
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(_stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(_tokensOf, _amount);
whitelisted.burn(_amount);
_mint(address(this), chargedFee);
emit BurnedCUSD(_tokensOf, feedAmount, chargedFee); // Whitelisted trust account should send user feedAmount USD
}
}
/**
* @title MetaToken
* @notice Extends the CarbonDollar token by providing functionality for users to interact with
* the permissioned token contract without needing to pay gas fees. MetaToken will perform the
* exact same actions as a normal CarbonDollar, but first it will validate a signature of the
* hash of the parameters and ecrecover() a signature to prove the signer so everything is still
* cryptographically backed. Then, instead of doing actions on behalf of msg.sender,
* it will move the signer’s tokens. Finally, we can also wrap in a token reward to incentivise the relayer.
* @notice inspiration from @austingriffith and @PhABCD for leading the meta-transaction innovations
*/
contract MetaToken is CarbonDollar {
/**
* @dev create a new CarbonDollar with a brand new data storage
**/
constructor (address _regulator) CarbonDollar(_regulator) public {
}
/**
Storage
*/
mapping (address => uint256) public replayNonce;
/**
ERC20 Metadata
*/
string public constant name = "CUSD";
string public constant symbol = "CUSD";
uint8 public constant decimals = 18;
/** Functions **/
/**
* @dev Verify and broadcast an increaseApproval() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaIncreaseApproval(address _spender, uint256 _addedValue, bytes _signature, uint256 _nonce, uint256 _reward)
public userNotBlacklisted(_spender) whenNotPaused returns (bool) {
bytes32 metaHash = metaApproveHash(_spender, _addedValue, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( _reward <= balanceOf(signer),"not enough balance to reward relayer");
_increaseApproval(_spender, _addedValue, signer);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a transfer() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _to The address of the receiver. This user must not be blacklisted, or else the transfer
* will fail.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaTransfer(address _to, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public userNotBlacklisted(_to) whenNotPaused returns (bool) {
bytes32 metaHash = metaTransferHash(_to, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to transfer and reward relayer");
_transfer(_to, signer, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a burnCarbonDollar() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaBurnCarbonDollar(address _stablecoin, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public whenNotPaused returns (bool) {
bytes32 metaHash = metaBurnHash(_stablecoin, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to burn and reward relayer");
_burnCarbonDollar(signer, _stablecoin, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Return hash containing all of the information about the transfer() metatransaction
* @param _to The address of the transfer receiver
* @param _amount The number of tokens to transfer
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaTransferHash(address _to, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaTransfer", _to, _amount, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the increaseApproval() metatransaction
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaApproveHash(address _spender, uint256 _addedValue, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaIncreaseApproval", _spender, _addedValue, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the burnCarbonDollar() metatransaction
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to burn
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaBurnHash(address _stablecoin, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaBurnCarbonDollar", _stablecoin, _amount, _nonce, _reward));
}
/**
* @dev Recover signer of original metatransaction
* @param _hash derived bytes32 metatransaction signature, which should be the same as the parameter _signature
* @param _signature bytes metatransaction signature, the signature is generated using web3.eth.sign()
* @return address of hash signer
*/
function _getSigner(bytes32 _hash, bytes _signature) internal pure returns (address){
bytes32 r;
bytes32 s;
uint8 v;
if (_signature.length != 65) {
return address(0);
}
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return address(0);
} else {
return ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s);
}
}
} | Verify and broadcast an increaseApproval() signed metatransaction. The msg.sender or "relayer" will pay for the ETH gas fees since they are sending this transaction, and in exchange the "signer" will pay CUSD to the relayer. increaseApproval should be used instead of approve when the user's allowance is greater than 0. Using increaseApproval protects against potential double-spend attacks by moving the check of whether the user has spent their allowance to the time that the transaction is mined, removing the user's ability to double-spend _spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by. _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender _nonce to prevent replay attack of metatransactions _reward amount of CUSD to pay relayer in return `true` if successful/ | function metaIncreaseApproval(address _spender, uint256 _addedValue, bytes _signature, uint256 _nonce, uint256 _reward)
public userNotBlacklisted(_spender) whenNotPaused returns (bool) {
bytes32 metaHash = metaApproveHash(_spender, _addedValue, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( _reward <= balanceOf(signer),"not enough balance to reward relayer");
_increaseApproval(_spender, _addedValue, signer);
_transfer(msg.sender, signer, _reward);
return true;
}
| 1,020,313 |
./full_match/97/0x20610C85207106d89e43335Cf8DDd7C58D6a3b4c/sources/contracts/deps/OwnableUpgradeable.sol | Throws if the sender is not the owner./ require(owner() == _msgSender(), "Ownable: caller is not the owner"); | function _checkOwner() internal view virtual {
if(!(owner() == _msgSender())) revert Ownable__CallerIsNotTheOwner();
}
| 3,274,064 |
// File: contracts/spec_interfaces/IGuardiansRegistration.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @title Guardian registration contract interface
interface IGuardiansRegistration {
event GuardianRegistered(address indexed guardian);
event GuardianUnregistered(address indexed guardian);
event GuardianDataUpdated(address indexed guardian, bool isRegistered, bytes4 ip, address orbsAddr, string name, string website, uint256 registrationTime);
event GuardianMetadataChanged(address indexed guardian, string key, string newValue, string oldValue);
/*
* External methods
*/
/// Registers a new guardian
/// @dev called using the guardian's address that holds the guardian self-stake and used for delegation
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string, publishing a name and website provide information for delegators
function registerGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website) external;
/// Updates a registered guardian data
/// @dev may be called only by a registered guardian
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string, publishing a name and website provide information for delegators
function updateGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website) external;
/// Updates a registered guardian ip address
/// @dev may be called only by a registered guardian
/// @dev may be called with either the guardian address or the guardian's orbs address
/// @param ip is the guardian's node ipv4 address as a 32b number
function updateGuardianIp(bytes4 ip) external /* onlyWhenActive */;
/// Updates a guardian's metadata property
/// @dev called using the guardian's address
/// @dev any key may be updated to be used by Orbs platform and tools
/// @param key is the name of the property to update
/// @param value is the value of the property to update in a string format
function setMetadata(string calldata key, string calldata value) external;
/// Returns a guardian's metadata property
/// @dev a property that wasn't set returns an empty string
/// @param guardian is the guardian to query
/// @param key is the name of the metadata property to query
/// @return value is the value of the queried property in a string format
function getMetadata(address guardian, string calldata key) external view returns (string memory);
/// Unregisters a guardian
/// @dev may be called only by a registered guardian
/// @dev unregistering does not clear the guardian's metadata properties
function unregisterGuardian() external;
/// Returns a guardian's data
/// @param guardian is the guardian to query
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string
/// @param registrationTime is the timestamp of the guardian's registration
/// @param lastUpdateTime is the timestamp of the guardian's last update
function getGuardianData(address guardian) external view returns (bytes4 ip, address orbsAddr, string memory name, string memory website, uint registrationTime, uint lastUpdateTime);
/// Returns the Orbs addresses of a list of guardians
/// @dev an unregistered guardian returns address(0) Orbs address
/// @param guardianAddrs is a list of guardians' addresses to query
/// @return orbsAddrs is a list of the guardians' Orbs addresses
function getGuardiansOrbsAddress(address[] calldata guardianAddrs) external view returns (address[] memory orbsAddrs);
/// Returns a guardian's ip
/// @dev an unregistered guardian returns 0 ip address
/// @param guardian is the guardian to query
/// @return ip is the guardian's node ipv4 address as a 32b number
function getGuardianIp(address guardian) external view returns (bytes4 ip);
/// Returns the ip of a list of guardians
/// @dev an unregistered guardian returns 0 ip address
/// @param guardianAddrs is a list of guardians' addresses to query
/// @param ips is a list of the guardians' node ipv4 addresses as a 32b numbers
function getGuardianIps(address[] calldata guardianAddrs) external view returns (bytes4[] memory ips);
/// Checks if a guardian is registered
/// @param guardian is the guardian to query
/// @return registered is a bool indicating a guardian address is registered
function isRegistered(address guardian) external view returns (bool);
/// Translates a list guardians Orbs addresses to guardian addresses
/// @dev an Orbs address that does not correspond to any registered guardian returns address(0)
/// @param orbsAddrs is a list of the guardians' Orbs addresses to query
/// @return guardianAddrs is a list of guardians' addresses that matches the Orbs addresses
function getGuardianAddresses(address[] calldata orbsAddrs) external view returns (address[] memory guardianAddrs);
/// Resolves the guardian address for a guardian, given a Guardian/Orbs address
/// @dev revert if the address does not correspond to a registered guardian address or Orbs address
/// @dev designed to be used for contracts calls, validating a registered guardian
/// @dev should be used with caution when called by tools as the call may revert
/// @dev in case of a conflict matching both guardian and Orbs address, the Guardian address takes precedence
/// @param guardianOrOrbsAddress is the address to query representing a guardian address or Orbs address
/// @return guardianAddress is the guardian address that matches the queried address
function resolveGuardianAddress(address guardianOrOrbsAddress) external view returns (address guardianAddress);
/*
* Governance functions
*/
/// Migrates a list of guardians from a previous guardians registration contract
/// @dev governance function called only by the initialization admin
/// @dev reads the migrated guardians data by calling getGuardianData in the previous contract
/// @dev imports also the guardians' registration time and last update
/// @dev emits a GuardianDataUpdated for each guardian to allow tracking by tools
/// @param guardiansToMigrate is a list of guardians' addresses to migrate
/// @param previousContract is the previous registration contract address
function migrateGuardians(address[] calldata guardiansToMigrate, IGuardiansRegistration previousContract) external /* onlyInitializationAdmin */;
}
// File: contracts/spec_interfaces/IElections.sol
pragma solidity 0.6.12;
/// @title Elections contract interface
interface IElections {
// Election state change events
event StakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 effectiveStake);
event GuardianStatusUpdated(address indexed guardian, bool readyToSync, bool readyForCommittee);
// Vote out / Vote unready
event GuardianVotedUnready(address indexed guardian);
event VoteUnreadyCasted(address indexed voter, address indexed subject, uint256 expiration);
event GuardianVotedOut(address indexed guardian);
event VoteOutCasted(address indexed voter, address indexed subject);
/*
* External functions
*/
/// Notifies that the guardian is ready to sync with other nodes
/// @dev may be called with either the guardian address or the guardian's orbs address
/// @dev ready to sync state is not managed in the contract that only emits an event
/// @dev readyToSync clears the readyForCommittee state
function readyToSync() external;
/// Notifies that the guardian is ready to join the committee
/// @dev may be called with either the guardian address or the guardian's orbs address
/// @dev a qualified guardian calling readyForCommittee is added to the committee
function readyForCommittee() external;
/// Checks if a guardian is qualified to join the committee
/// @dev when true, calling readyForCommittee() will result in adding the guardian to the committee
/// @dev called periodically by guardians to check if they are qualified to join the committee
/// @param guardian is the guardian to check
/// @return canJoin indicating that the guardian can join the current committee
function canJoinCommittee(address guardian) external view returns (bool);
/// Returns an address effective stake
/// The effective stake is derived from a guardian delegate stake and selfs stake
/// @return effectiveStake is the guardian's effective stake
function getEffectiveStake(address guardian) external view returns (uint effectiveStake);
/// Returns the current committee along with the guardians' Orbs address and IP
/// @return committee is a list of the committee members' guardian addresses
/// @return weights is a list of the committee members' weight (effective stake)
/// @return orbsAddrs is a list of the committee members' orbs address
/// @return certification is a list of bool indicating the committee members certification
/// @return ips is a list of the committee members' ip
function getCommittee() external view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips);
// Vote-unready
/// Casts an unready vote on a subject guardian
/// @dev Called by a guardian as part of the automatic vote-unready flow
/// @dev The transaction may be sent from the guardian or orbs address.
/// @param subject is the subject guardian to vote out
/// @param voteExpiration is the expiration time of the vote unready to prevent counting of a vote that is already irrelevant.
function voteUnready(address subject, uint voteExpiration) external;
/// Returns the current vote unready vote for a voter and a subject pair
/// @param voter is the voting guardian address
/// @param subject is the subject guardian address
/// @return valid indicates whether there is a valid vote
/// @return expiration returns the votes expiration time
function getVoteUnreadyVote(address voter, address subject) external view returns (bool valid, uint256 expiration);
/// Returns the current vote-unready status of a subject guardian.
/// @dev the committee and certification data is used to check the certified and committee threshold
/// @param subject is the subject guardian address
/// @return committee is a list of the current committee members
/// @return weights is a list of the current committee members weight
/// @return certification is a list of bool indicating the committee members certification
/// @return votes is a list of bool indicating the members that votes the subject unready
/// @return subjectInCommittee indicates that the subject is in the committee
/// @return subjectInCertifiedCommittee indicates that the subject is in the certified committee
function getVoteUnreadyStatus(address subject) external view returns (
address[] memory committee,
uint256[] memory weights,
bool[] memory certification,
bool[] memory votes,
bool subjectInCommittee,
bool subjectInCertifiedCommittee
);
// Vote-out
/// Casts a voteOut vote by the sender to the given address
/// @dev the transaction is sent from the guardian address
/// @param subject is the subject guardian address
function voteOut(address subject) external;
/// Returns the subject address the addr has voted-out against
/// @param voter is the voting guardian address
/// @return subject is the subject the voter has voted out
function getVoteOutVote(address voter) external view returns (address);
/// Returns the governance voteOut status of a guardian.
/// @dev A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold
/// @param subject is the subject guardian address
/// @return votedOut indicates whether the subject was voted out
/// @return votedStake is the total stake voting against the subject
/// @return totalDelegatedStake is the total delegated stake
function getVoteOutStatus(address subject) external view returns (bool votedOut, uint votedStake, uint totalDelegatedStake);
/*
* Notification functions from other PoS contracts
*/
/// Notifies a delegated stake change event
/// @dev Called by: delegation contract
/// @param delegate is the delegate to update
/// @param selfDelegatedStake is the delegate self stake (0 if not self-delegating)
/// @param delegatedStake is the delegate delegated stake (0 if not self-delegating)
/// @param totalDelegatedStake is the total delegated stake
function delegatedStakeChange(address delegate, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationsContract onlyWhenActive */;
/// Notifies a new guardian was unregistered
/// @dev Called by: guardian registration contract
/// @dev when a guardian unregisters its status is updated to not ready to sync and is removed from the committee
/// @param guardian is the address of the guardian that unregistered
function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */;
/// Notifies on a guardian certification change
/// @dev Called by: guardian registration contract
/// @param guardian is the address of the guardian to update
/// @param isCertified indicates whether the guardian is certified
function guardianCertificationChanged(address guardian, bool isCertified) external /* onlyCertificationContract */;
/*
* Governance functions
*/
event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue);
event VoteOutPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue);
event VoteUnreadyPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue);
event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue);
/// Sets the minimum self stake requirement for the effective stake
/// @dev governance function called only by the functional manager
/// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000)
function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalManager */;
/// Returns the minimum self-stake required for the effective stake
/// @return minSelfStakePercentMille is the minimum self stake in percent-mille
function getMinSelfStakePercentMille() external view returns (uint32);
/// Sets the vote-out threshold
/// @dev governance function called only by the functional manager
/// @param voteOutPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000)
function setVoteOutPercentMilleThreshold(uint32 voteOutPercentMilleThreshold) external /* onlyFunctionalManager */;
/// Returns the vote-out threshold
/// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille
function getVoteOutPercentMilleThreshold() external view returns (uint32);
/// Sets the vote-unready threshold
/// @dev governance function called only by the functional manager
/// @param voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000)
function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager */;
/// Returns the vote-unready threshold
/// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille
function getVoteUnreadyPercentMilleThreshold() external view returns (uint32);
/// Returns the contract's settings
/// @return minSelfStakePercentMille is the minimum self stake in percent-mille
/// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille
/// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille
function getSettings() external view returns (
uint32 minSelfStakePercentMille,
uint32 voteUnreadyPercentMilleThreshold,
uint32 voteOutPercentMilleThreshold
);
/// Initializes the ready for committee notification for the committee guardians
/// @dev governance function called only by the initialization admin during migration
/// @dev identical behaviour as if each guardian sent readyForCommittee()
/// @param guardians a list of guardians addresses to update
function initReadyForCommittee(address[] calldata guardians) external /* onlyInitializationAdmin */;
}
// File: contracts/spec_interfaces/IManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract interface, used by the contracts registry to notify the contract on updates
interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ {
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external;
}
// File: contracts/spec_interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/// @title Contract registry contract interface
/// @dev The contract registry holds Orbs PoS contracts and managers lists
/// @dev The contract registry updates the managed contracts on changes in the contract list
/// @dev Governance functions restricted to managers access the registry to retrieve the manager address
/// @dev The contract registry represents the source of truth for Orbs Ethereum contracts
/// @dev By tracking the registry events or query before interaction, one can access the up to date contracts
interface IContractRegistry {
event ContractAddressUpdated(string contractName, address addr, bool managedContract);
event ManagerChanged(string role, address newManager);
event ContractRegistryUpdated(address newContractRegistry);
/*
* External functions
*/
/// Updates the contracts address and emits a corresponding event
/// @dev governance function called only by the migrationManager or registryAdmin
/// @param contractName is the contract name, used to identify it
/// @param addr is the contract updated address
/// @param managedContract indicates whether the contract is managed by the registry and notified on changes
function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */;
/// Returns the current address of the given contracts
/// @param contractName is the contract name, used to identify it
/// @return addr is the contract updated address
function getContract(string calldata contractName) external view returns (address);
/// Returns the list of contract addresses managed by the registry
/// @dev Managed contracts are updated on changes in the registry contracts addresses
/// @return addrs is the list of managed contracts
function getManagedContracts() external view returns (address[] memory);
/// Locks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
/// @dev When set all onlyWhenActive functions will revert
function lockContracts() external /* onlyAdminOrMigrationManager */;
/// Unlocks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
function unlockContracts() external /* onlyAdminOrMigrationManager */;
/// Updates a manager address and emits a corresponding event
/// @dev governance function called only by the registryAdmin
/// @dev the managers list is a flexible list of role to the manager's address
/// @param role is the managers' role name, for example "functionalManager"
/// @param manager is the manager updated address
function setManager(string calldata role, address manager) external /* onlyAdmin */;
/// Returns the current address of the given manager
/// @param role is the manager name, used to identify it
/// @return addr is the manager updated address
function getManager(string calldata role) external view returns (address);
/// Sets a new contract registry to migrate to
/// @dev governance function called only by the registryAdmin
/// @dev updates the registry address record in all the managed contracts
/// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts
/// @param newRegistry is the new registry contract
function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the previous contract registry address
/// @dev used when the setting the contract as a new registry to assure a valid registry
/// @return previousContractRegistry is the previous contract registry
function getPreviousContractRegistry() external view returns (address);
}
// File: contracts/spec_interfaces/IContractRegistryAccessor.sol
pragma solidity 0.6.12;
interface IContractRegistryAccessor {
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newRegistry is the new registry contract
function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the contract registry address
/// @return contractRegistry is the contract registry address
function getContractRegistry() external view returns (IContractRegistry contractRegistry);
function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */;
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/WithClaimableRegistryManagement.sol
pragma solidity 0.6.12;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract WithClaimableRegistryManagement is Context {
address private _registryAdmin;
address private _pendingRegistryAdmin;
event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin.
*/
constructor () internal {
address msgSender = _msgSender();
_registryAdmin = msgSender;
emit RegistryManagementTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current registryAdmin.
*/
function registryAdmin() public view returns (address) {
return _registryAdmin;
}
/**
* @dev Throws if called by any account other than the registryAdmin.
*/
modifier onlyRegistryAdmin() {
require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin");
_;
}
/**
* @dev Returns true if the caller is the current registryAdmin.
*/
function isRegistryAdmin() public view returns (bool) {
return _msgSender() == _registryAdmin;
}
/**
* @dev Leaves the contract without registryAdmin. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current registryAdmin.
*
* NOTE: Renouncing registryManagement will leave the contract without an registryAdmin,
* thereby removing any functionality that is only available to the registryAdmin.
*/
function renounceRegistryManagement() public onlyRegistryAdmin {
emit RegistryManagementTransferred(_registryAdmin, address(0));
_registryAdmin = address(0);
}
/**
* @dev Transfers registryManagement of the contract to a new account (`newManager`).
*/
function _transferRegistryManagement(address newRegistryAdmin) internal {
require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address");
emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin);
_registryAdmin = newRegistryAdmin;
}
/**
* @dev Modifier throws if called by any account other than the pendingManager.
*/
modifier onlyPendingRegistryAdmin() {
require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin");
_;
}
/**
* @dev Allows the current registryAdmin to set the pendingManager address.
* @param newRegistryAdmin The address to transfer registryManagement to.
*/
function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin {
_pendingRegistryAdmin = newRegistryAdmin;
}
/**
* @dev Allows the _pendingRegistryAdmin address to finalize the transfer.
*/
function claimRegistryManagement() external onlyPendingRegistryAdmin {
_transferRegistryManagement(_pendingRegistryAdmin);
_pendingRegistryAdmin = address(0);
}
/**
* @dev Returns the current pendingRegistryAdmin
*/
function pendingRegistryAdmin() public view returns (address) {
return _pendingRegistryAdmin;
}
}
// File: contracts/Initializable.sol
pragma solidity 0.6.12;
contract Initializable {
address private _initializationAdmin;
event InitializationComplete();
/// Constructor
/// Sets the initializationAdmin to the contract deployer
/// The initialization admin may call any manager only function until initializationComplete
constructor() public{
_initializationAdmin = msg.sender;
}
modifier onlyInitializationAdmin() {
require(msg.sender == initializationAdmin(), "sender is not the initialization admin");
_;
}
/*
* External functions
*/
/// Returns the initializationAdmin address
function initializationAdmin() public view returns (address) {
return _initializationAdmin;
}
/// Finalizes the initialization and revokes the initializationAdmin role
function initializationComplete() external onlyInitializationAdmin {
_initializationAdmin = address(0);
emit InitializationComplete();
}
/// Checks if the initialization was completed
function isInitializationComplete() public view returns (bool) {
return _initializationAdmin == address(0);
}
}
// File: contracts/ContractRegistryAccessor.sol
pragma solidity 0.6.12;
contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable {
IContractRegistry private contractRegistry;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) public {
require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0");
setContractRegistry(_contractRegistry);
_transferRegistryManagement(_registryAdmin);
}
modifier onlyAdmin {
require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)");
_;
}
modifier onlyMigrationManager {
require(isMigrationManager(), "sender is not the migration manager");
_;
}
modifier onlyFunctionalManager {
require(isFunctionalManager(), "sender is not the functional manager");
_;
}
/// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin
function isAdmin() internal view returns (bool) {
return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin();
}
/// Checks whether the caller is a specific manager role or and Admin
/// @dev queries the registry contract for the up to date manager assignment
function isManager(string memory role) internal view returns (bool) {
IContractRegistry _contractRegistry = contractRegistry;
return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender;
}
/// Checks whether the caller is the migration manager
function isMigrationManager() internal view returns (bool) {
return isManager('migrationManager');
}
/// Checks whether the caller is the functional manager
function isFunctionalManager() internal view returns (bool) {
return isManager('functionalManager');
}
/*
* Contract getters, return the address of a contract by calling the contract registry
*/
function getProtocolContract() internal view returns (address) {
return contractRegistry.getContract("protocol");
}
function getStakingRewardsContract() internal view returns (address) {
return contractRegistry.getContract("stakingRewards");
}
function getFeesAndBootstrapRewardsContract() internal view returns (address) {
return contractRegistry.getContract("feesAndBootstrapRewards");
}
function getCommitteeContract() internal view returns (address) {
return contractRegistry.getContract("committee");
}
function getElectionsContract() internal view returns (address) {
return contractRegistry.getContract("elections");
}
function getDelegationsContract() internal view returns (address) {
return contractRegistry.getContract("delegations");
}
function getGuardiansRegistrationContract() internal view returns (address) {
return contractRegistry.getContract("guardiansRegistration");
}
function getCertificationContract() internal view returns (address) {
return contractRegistry.getContract("certification");
}
function getStakingContract() internal view returns (address) {
return contractRegistry.getContract("staking");
}
function getSubscriptionsContract() internal view returns (address) {
return contractRegistry.getContract("subscriptions");
}
function getStakingRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("stakingRewardsWallet");
}
function getBootstrapRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("bootstrapRewardsWallet");
}
function getGeneralFeesWallet() internal view returns (address) {
return contractRegistry.getContract("generalFeesWallet");
}
function getCertifiedFeesWallet() internal view returns (address) {
return contractRegistry.getContract("certifiedFeesWallet");
}
function getStakingContractHandler() internal view returns (address) {
return contractRegistry.getContract("stakingContractHandler");
}
/*
* Governance functions
*/
event ContractRegistryAddressUpdated(address addr);
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newContractRegistry is the new registry contract
function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin {
require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry");
contractRegistry = newContractRegistry;
emit ContractRegistryAddressUpdated(address(newContractRegistry));
}
/// Returns the contract registry that the contract is set to use
/// @return contractRegistry is the registry contract address
function getContractRegistry() public override view returns (IContractRegistry) {
return contractRegistry;
}
function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin {
_transferRegistryManagement(_registryAdmin);
}
}
// File: contracts/spec_interfaces/ILockable.sol
pragma solidity 0.6.12;
/// @title lockable contract interface, allows to lock a contract
interface ILockable {
event Locked();
event Unlocked();
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external /* onlyMigrationManager */;
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external /* onlyMigrationManager */;
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() view external returns (bool);
}
// File: contracts/Lockable.sol
pragma solidity 0.6.12;
/// @title lockable contract
contract Lockable is ILockable, ContractRegistryAccessor {
bool public locked;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {}
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external override onlyMigrationManager {
locked = true;
emit Locked();
}
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external override onlyMigrationManager {
locked = false;
emit Unlocked();
}
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() external override view returns (bool) {
return locked;
}
modifier onlyWhenActive() {
require(!locked, "contract is locked for this operation");
_;
}
}
// File: contracts/ManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract
contract ManagedContract is IManagedContract, Lockable {
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {}
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() virtual override external {}
}
// File: contracts/GuardiansRegistration.sol
pragma solidity 0.6.12;
contract GuardiansRegistration is IGuardiansRegistration, ManagedContract {
struct Guardian {
address orbsAddr;
bytes4 ip;
uint32 registrationTime;
uint32 lastUpdateTime;
string name;
string website;
}
mapping(address => Guardian) guardians;
mapping(address => address) orbsAddressToGuardianAddress;
mapping(bytes4 => address) public ipToGuardian;
mapping(address => mapping(string => string)) guardianMetadata;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) ManagedContract(_contractRegistry, _registryAdmin) public {}
modifier onlyRegisteredGuardian {
require(isRegistered(msg.sender), "Guardian is not registered");
_;
}
/*
* External methods
*/
/// Registers a new guardian
/// @dev called using the guardian's address that holds the guardian self-stake and used for delegation
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string, publishing a name and website provide information for delegators
function registerGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website) external override onlyWhenActive {
require(!isRegistered(msg.sender), "registerGuardian: Guardian is already registered");
guardians[msg.sender].registrationTime = uint32(block.timestamp);
emit GuardianRegistered(msg.sender);
_updateGuardian(msg.sender, ip, orbsAddr, name, website);
}
/// Updates a registered guardian data
/// @dev may be called only by a registered guardian
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string, publishing a name and website provide information for delegators
function updateGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website) external override onlyRegisteredGuardian onlyWhenActive {
_updateGuardian(msg.sender, ip, orbsAddr, name, website);
}
/// Updates a registered guardian ip address
/// @dev may be called only by a registered guardian
/// @dev may be called with either the guardian address or the guardian's orbs address
/// @param ip is the guardian's node ipv4 address as a 32b number
function updateGuardianIp(bytes4 ip) external override onlyWhenActive {
address guardianAddr = resolveGuardianAddress(msg.sender);
Guardian memory data = guardians[guardianAddr];
_updateGuardian(guardianAddr, ip, data.orbsAddr, data.name, data.website);
}
/// Updates a guardian's metadata property
/// @dev called using the guardian's address
/// @dev any key may be updated to be used by Orbs platform and tools
/// @param key is the name of the property to update
/// @param value is the value of the property to update in a string format
function setMetadata(string calldata key, string calldata value) external override onlyRegisteredGuardian onlyWhenActive {
_setMetadata(msg.sender, key, value);
}
/// Returns a guardian's metadata property
/// @dev a property that wasn't set returns an empty string
/// @param guardian is the guardian to query
/// @param key is the name of the metadata property to query
/// @return value is the value of the queried property in a string format
function getMetadata(address guardian, string calldata key) external override view returns (string memory) {
return guardianMetadata[guardian][key];
}
/// Unregisters a guardian
/// @dev may be called only by a registered guardian
/// @dev unregistering does not clear the guardian's metadata properties
function unregisterGuardian() external override onlyRegisteredGuardian onlyWhenActive {
delete orbsAddressToGuardianAddress[guardians[msg.sender].orbsAddr];
delete ipToGuardian[guardians[msg.sender].ip];
Guardian memory guardian = guardians[msg.sender];
delete guardians[msg.sender];
electionsContract.guardianUnregistered(msg.sender);
emit GuardianDataUpdated(msg.sender, false, guardian.ip, guardian.orbsAddr, guardian.name, guardian.website, guardian.registrationTime);
emit GuardianUnregistered(msg.sender);
}
/// Returns a guardian's data
/// @param guardian is the guardian to query
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string
/// @param registrationTime is the timestamp of the guardian's registration
/// @param lastUpdateTime is the timestamp of the guardian's last update
function getGuardianData(address guardian) external override view returns (bytes4 ip, address orbsAddr, string memory name, string memory website, uint registrationTime, uint lastUpdateTime) {
Guardian memory v = guardians[guardian];
return (v.ip, v.orbsAddr, v.name, v.website, v.registrationTime, v.lastUpdateTime);
}
/// Returns the Orbs addresses of a list of guardians
/// @dev an unregistered guardian returns address(0) Orbs address
/// @param guardianAddrs is a list of guardians' addresses to query
/// @return orbsAddrs is a list of the guardians' Orbs addresses
function getGuardiansOrbsAddress(address[] calldata guardianAddrs) external override view returns (address[] memory orbsAddrs) {
orbsAddrs = new address[](guardianAddrs.length);
for (uint i = 0; i < guardianAddrs.length; i++) {
orbsAddrs[i] = guardians[guardianAddrs[i]].orbsAddr;
}
}
/// Returns a guardian's ip
/// @dev an unregistered guardian returns 0 ip address
/// @param guardian is the guardian to query
/// @return ip is the guardian's node ipv4 address as a 32b number
function getGuardianIp(address guardian) external override view returns (bytes4 ip) {
return guardians[guardian].ip;
}
/// Returns the ip of a list of guardians
/// @dev an unregistered guardian returns 0 ip address
/// @param guardianAddrs is a list of guardians' addresses to query
/// @return ips is a list of the guardians' node ipv4 addresses as a 32b numbers
function getGuardianIps(address[] calldata guardianAddrs) external override view returns (bytes4[] memory ips) {
ips = new bytes4[](guardianAddrs.length);
for (uint i = 0; i < guardianAddrs.length; i++) {
ips[i] = guardians[guardianAddrs[i]].ip;
}
}
/// Checks if a guardian is registered
/// @param guardian is the guardian to query
/// @return registered is a bool indicating a guardian address is registered
function isRegistered(address guardian) public override view returns (bool) {
return guardians[guardian].registrationTime != 0;
}
/// Translates a list guardians Orbs addresses to guardian addresses
/// @dev an Orbs address that does not correspond to any registered guardian returns address(0)
/// @param orbsAddrs is a list of the guardians' Orbs addresses to query
/// @return guardianAddrs is a list of guardians' addresses that matches the Orbs addresses
function getGuardianAddresses(address[] calldata orbsAddrs) external override view returns (address[] memory guardianAddrs) {
guardianAddrs = new address[](orbsAddrs.length);
for (uint i = 0; i < orbsAddrs.length; i++) {
guardianAddrs[i] = orbsAddressToGuardianAddress[orbsAddrs[i]];
}
}
/// Resolves the guardian address for a guardian, given a Guardian/Orbs address
/// @dev revert if the address does not correspond to a registered guardian address or Orbs address
/// @dev designed to be used for contracts calls, validating a registered guardian
/// @dev should be used with caution when called by tools as the call may revert
/// @dev in case of a conflict matching both guardian and Orbs address, the Guardian address takes precedence
/// @param guardianOrOrbsAddress is the address to query representing a guardian address or Orbs address
/// @return guardianAddress is the guardian address that matches the queried address
function resolveGuardianAddress(address guardianOrOrbsAddress) public override view returns (address guardianAddress) {
if (isRegistered(guardianOrOrbsAddress)) {
guardianAddress = guardianOrOrbsAddress;
} else {
guardianAddress = orbsAddressToGuardianAddress[guardianOrOrbsAddress];
}
require(guardianAddress != address(0), "Cannot resolve address");
}
/*
* Governance
*/
/// Migrates a list of guardians from a previous guardians registration contract
/// @dev governance function called only by the initialization admin
/// @dev reads the migrated guardians data by calling getGuardianData in the previous contract
/// @dev imports also the guardians' registration time and last update
/// @dev emits a GuardianDataUpdated for each guardian to allow tracking by tools
/// @param guardiansToMigrate is a list of guardians' addresses to migrate
/// @param previousContract is the previous registration contract address
function migrateGuardians(address[] calldata guardiansToMigrate, IGuardiansRegistration previousContract) external override onlyInitializationAdmin {
require(previousContract != IGuardiansRegistration(0), "previousContract must not be the zero address");
for (uint i = 0; i < guardiansToMigrate.length; i++) {
require(guardiansToMigrate[i] != address(0), "guardian must not be the zero address");
migrateGuardianData(previousContract, guardiansToMigrate[i]);
migrateGuardianMetadata(previousContract, guardiansToMigrate[i]);
}
}
/*
* Private methods
*/
/// Updates a registered guardian data
/// @dev used by external functions that register a guardian or update its data
/// @dev emits a GuardianDataUpdated event on any update to the registration
/// @param guardianAddr is the address of the guardian to update
/// @param ip is the guardian's node ipv4 address as a 32b number
/// @param orbsAddr is the guardian's Orbs node address
/// @param name is the guardian's name as a string
/// @param website is the guardian's website as a string, publishing a name and website provide information for delegators
function _updateGuardian(address guardianAddr, bytes4 ip, address orbsAddr, string memory name, string memory website) private {
require(orbsAddr != address(0), "orbs address must be non zero");
require(orbsAddr != guardianAddr, "orbs address must be different than the guardian address");
require(!isRegistered(orbsAddr), "orbs address must not be a guardian address of a registered guardian");
require(bytes(name).length != 0, "name must be given");
Guardian memory guardian = guardians[guardianAddr];
delete ipToGuardian[guardian.ip];
require(ipToGuardian[ip] == address(0), "ip is already in use");
ipToGuardian[ip] = guardianAddr;
delete orbsAddressToGuardianAddress[guardian.orbsAddr];
require(orbsAddressToGuardianAddress[orbsAddr] == address(0), "orbs address is already in use");
orbsAddressToGuardianAddress[orbsAddr] = guardianAddr;
guardian.orbsAddr = orbsAddr;
guardian.ip = ip;
guardian.name = name;
guardian.website = website;
guardian.lastUpdateTime = uint32(block.timestamp);
guardians[guardianAddr] = guardian;
emit GuardianDataUpdated(guardianAddr, true, ip, orbsAddr, name, website, guardian.registrationTime);
}
/// Updates a guardian's metadata property
/// @dev used by setMetadata and migration functions
/// @dev any key may be updated to be used by Orbs platform and tools
/// @param key is the name of the property to update
/// @param value is the value of the property to update in a string format
function _setMetadata(address guardian, string memory key, string memory value) private {
string memory oldValue = guardianMetadata[guardian][key];
guardianMetadata[guardian][key] = value;
emit GuardianMetadataChanged(guardian, key, value, oldValue);
}
/// Migrates a guardian data from a previous guardians registration contract
/// @dev used by migrateGuardians
/// @dev reads the migrated guardians data by calling getGuardianData in the previous contract
/// @dev imports also the guardians' registration time and last update
/// @dev emits a GuardianDataUpdated
/// @param previousContract is the previous registration contract address
/// @param guardianAddress is the address of the guardians to migrate
function migrateGuardianData(IGuardiansRegistration previousContract, address guardianAddress) private {
(bytes4 ip, address orbsAddr, string memory name, string memory website, uint registrationTime, uint lastUpdateTime) = previousContract.getGuardianData(guardianAddress);
guardians[guardianAddress] = Guardian({
orbsAddr: orbsAddr,
ip: ip,
name: name,
website: website,
registrationTime: uint32(registrationTime),
lastUpdateTime: uint32(lastUpdateTime)
});
orbsAddressToGuardianAddress[orbsAddr] = guardianAddress;
ipToGuardian[ip] = guardianAddress;
emit GuardianRegistered(guardianAddress);
emit GuardianDataUpdated(guardianAddress, true, ip, orbsAddr, name, website, registrationTime);
}
string public constant ID_FORM_URL_METADATA_KEY = "ID_FORM_URL";
/// Migrates a guardian metadata keys in use from a previous guardians registration contract
/// @dev the metadata used by the contract are hard-coded in the function
/// @dev used by migrateGuardians
/// @dev reads the migrated guardians metadata by calling getMetadata in the previous contract
/// @dev emits a GuardianMetadataChanged
/// @param previousContract is the previous registration contract address
/// @param guardianAddress is the address of the guardians to migrate
function migrateGuardianMetadata(IGuardiansRegistration previousContract, address guardianAddress) private {
string memory rewardsFreqMetadata = previousContract.getMetadata(guardianAddress, ID_FORM_URL_METADATA_KEY);
if (bytes(rewardsFreqMetadata).length > 0) {
_setMetadata(guardianAddress, ID_FORM_URL_METADATA_KEY, rewardsFreqMetadata);
}
}
/*
* Contracts topology / registry interface
*/
IElections electionsContract;
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external override {
electionsContract = IElections(getElectionsContract());
}
} | Resolves the guardian address for a guardian, given a Guardian/Orbs address revert if the address does not correspond to a registered guardian address or Orbs address designed to be used for contracts calls, validating a registered guardian should be used with caution when called by tools as the call may revert in case of a conflict matching both guardian and Orbs address, the Guardian address takes precedence guardianOrOrbsAddress is the address to query representing a guardian address or Orbs address return guardianAddress is the guardian address that matches the queried address | function resolveGuardianAddress(address guardianOrOrbsAddress) public override view returns (address guardianAddress) {
if (isRegistered(guardianOrOrbsAddress)) {
guardianAddress = guardianOrOrbsAddress;
guardianAddress = orbsAddressToGuardianAddress[guardianOrOrbsAddress];
}
require(guardianAddress != address(0), "Cannot resolve address");
}
| 14,439,152 |
./full_match/1/0x29E95a16C277b97d04DE93655CE7c08D1480d410/sources/src/HelloBridgeStore.sol | Updates totalCrossChainWithdrawals of a user from a source chain address_ The address to update chainID_ The source chainID of the withdrawal amount_ The amount of token withdrawn/ | function setTotalCrossChainWithdrawals(address address_, uint256 chainID_, uint256 amount_) external {
if (msg.sender != bridgeContract) {
revert ErrUnauthorized();
}
totalCrossChainWithdrawals[address_][chainID_] = amount_;
}
| 2,908,055 |
pragma solidity >=0.4.25 <0.9.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/PayFor.sol";
contract TestPayFor_00 {
PayFor pay = new PayFor();
function testHasCorrectOwner() public {
// Assert.equal(pay.isOwner(), true, "isOwner should return true");
// Assert.equal(pay.getNPayments(), 0, "no payments yet");
}
}
| Assert.equal(pay.isOwner(), true, "isOwner should return true"); Assert.equal(pay.getNPayments(), 0, "no payments yet"); | function testHasCorrectOwner() public {
}
| 1,008,585 |
/**
*Submitted for verification at Etherscan.io on 2021-11-28
*/
pragma solidity 0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected] solidity 0.8.4;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
'Ownable: new owner is the zero address'
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
pragma solidity 0.8.4; // CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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)
{
unchecked {
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)
{
unchecked {
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)
{
unchecked {
// 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)
{
unchecked {
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)
{
unchecked {
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) {
return a + b;
}
/**
* @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) {
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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
interface IReferral {
/**
* @dev Record referral.
*/
function recordReferral(address user, address referrer) external;
/**
* @dev Record referral share.
*/
function recordReferralShare(address referrer, uint256 share) external;
/**
* @dev Get the referrer address that referred the user.
*/
function getReferrer(address user) external view returns (address);
}
contract Nfts is Ownable {
using SafeMath for uint256;
uint256 public price = 10000000 gwei;
uint256 public priceStep = 10000000 gwei;
uint256 public maxSupply = 100;
uint256 public premint = 30;
uint256 public totalSupply = premint;
uint16 public refShare = 1000; // in basis points, so it's 10%
uint256 public startTime = 0;
IReferral public referralContract;
event Mint(
address indexed user,
uint256 fromId,
uint256 amount
);
event ReferralSharePaid(
address indexed user,
address indexed referrer,
uint256 shareAmount
);
function getNextPrice() internal returns (uint) {
return price + priceStep * (totalSupply - premint);
}
function mint(address _referrer) external payable {
require(block.timestamp >= startTime);
if (
msg.value > 0 &&
address(referralContract) != address(0) &&
_referrer != address(0) &&
_referrer != msg.sender
) {
referralContract.recordReferral(msg.sender, _referrer);
}
uint rest = msg.value;
uint currentPrice = getNextPrice();
uint prevTotalSupply = totalSupply;
while (currentPrice <= rest) {
require(this.totalSupply() < maxSupply, 'Sold out');
totalSupply++;
rest -= currentPrice;
currentPrice = getNextPrice();
}
uint256 amount = totalSupply - prevTotalSupply;
if (amount > 0) {
emit Mint(msg.sender, prevTotalSupply, amount);
}
payable(msg.sender).transfer(rest);
payReferral(msg.sender, msg.value - rest);
}
// Update the referral contract address by the owner
function setReferralAddress(IReferral _referralAddress) public onlyOwner {
referralContract = _referralAddress;
}
// Pay referral share to the referrer who referred this user.
function payReferral(address _to, uint256 _amount) internal {
if (address(referralContract) != address(0) && refShare > 0) {
address referrer = referralContract.getReferrer(_to);
uint256 shareAmount = _amount.mul(refShare).div(10000);
if (referrer != address(0) && shareAmount > 0) {
payable(referrer).transfer(shareAmount);
referralContract.recordReferralShare(referrer, shareAmount);
emit ReferralSharePaid(_to, referrer, shareAmount);
}
}
}
}
contract Referral is IReferral, Ownable {
mapping(address => bool) public operators;
mapping(address => address) public referrers; // user address => referrer address
mapping(address => uint256) public referralsCount; // referrer address => referrals count
mapping(address => uint256) public totalReferralShares; // referrer address => total referral commissions
event ReferralRecorded(address indexed user, address indexed referrer);
event ReferralShareRecorded(address indexed referrer, uint256 commission);
event OperatorUpdated(address indexed operator, bool indexed status);
modifier onlyOperator() {
require(operators[msg.sender], 'Operator: caller is not the operator');
_;
}
function recordReferral(address _user, address _referrer)
public
override
onlyOperator
{
if (
_user != address(0) &&
_referrer != address(0) &&
_user != _referrer &&
referrers[_user] == address(0)
) {
referrers[_user] = _referrer;
referralsCount[_referrer] += 1;
emit ReferralRecorded(_user, _referrer);
}
}
function recordReferralShare(address _referrer, uint256 _share)
public
override
onlyOperator
{
if (_referrer != address(0) && _share > 0) {
totalReferralShares[_referrer] += _share;
emit ReferralShareRecorded(_referrer, _share);
}
}
// Get the referrer address that referred the user
function getReferrer(address _user) public view override returns (address) {
return referrers[_user];
}
// Update the status of the operator
function updateOperator(address _operator, bool _status)
external
onlyOwner
{
operators[_operator] = _status;
emit OperatorUpdated(_operator, _status);
}
} | 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)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
| 10,889,105 |
/**
*Submitted for verification at Etherscan.io on 2020-10-07
*/
pragma solidity ^0.6.12;
/**
* @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);
}
interface IMerkleTreeTokensVerification {
function verify(
address _leaf,
bytes32 [] calldata proof,
uint256 [] calldata positions
)
external
view
returns (bool);
}
interface ITokensTypeStorage {
function isRegistred(address _address) external view returns(bool);
function getType(address _address) external view returns(bytes32);
function isPermittedAddress(address _address) external view returns(bool);
function owner() external view returns(address);
function addNewTokenType(address _token, string calldata _type) external;
function setTokenTypeAsOwner(address _token, string calldata _type) external;
}
// Contains view methods for exchange
// We have separated the methods for the fund and for the exchange because they contain different methods.
interface PoolPortalViewInterface {
function getDataForBuyingPool(IERC20 _poolToken, uint _type, uint256 _amount)
external
view
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
);
function getBacorConverterAddressByRelay(address relay)
external
view
returns(address converter);
function getBancorConnectorsAmountByRelayAmount
(
uint256 _amount,
IERC20 _relay
)
external view returns(uint256 bancorAmount, uint256 connectorAmount);
function getBancorConnectorsByRelay(address relay)
external
view
returns(address[] memory connectorsAddress);
function getBancorRatio(address _from, address _to, uint256 _amount)
external
view
returns(uint256);
function getUniswapConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
external
view
returns(uint256 ethAmount, uint256 ercAmount);
function getUniswapV2ConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
external
view
returns(
uint256 tokenAmountOne,
uint256 tokenAmountTwo,
address tokenAddressOne,
address tokenAddressTwo
);
function getBalancerConnectorsAmountByPoolAmount(
uint256 _amount,
address _pool
)
external
view
returns(
address[] memory tokens,
uint256[] memory tokensAmount
);
function getUniswapTokenAmountByETH(address _token, uint256 _amount)
external
view
returns(uint256);
function getTokenByUniswapExchange(address _exchange)
external
view
returns(address);
}
interface DefiPortalInterface {
function callPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
payable
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
function callNonPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
function getValue(
address _from,
address _to,
uint256 _amount
)
external
view
returns(uint256);
}
interface ExchangePortalInterface {
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
payable
returns (uint256);
function getValue(address _from, address _to, uint256 _amount) external view returns (uint256);
function getTotalValue(
address[] calldata _fromAddresses,
uint256[] calldata _amounts,
address _to
)
external
view
returns (uint256);
}
interface IOneSplitAudit {
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 disableFlags
) external payable;
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 featureFlags // See contants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
/*
Bancor Network interface
*/
interface BancorNetworkInterface {
function getReturnByPath(
IERC20[] calldata _path,
uint256 _amount)
external
view
returns (uint256, uint256);
function convert(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn
) external payable returns (uint256);
function claimAndConvert(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn
) external returns (uint256);
function convertFor(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn,
address _for
) external payable returns (uint256);
function claimAndConvertFor(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn,
address _for
) external returns (uint256);
function conversionPath(
IERC20 _sourceToken,
IERC20 _targetToken
) external view returns (address[] memory);
}
interface IGetBancorData {
function getBancorContractAddresByName(string calldata _name) external view returns (address result);
function getBancorRatioForAssets(IERC20 _from, IERC20 _to, uint256 _amount) external view returns(uint256 result);
function getBancorPathForAssets(IERC20 _from, IERC20 _to) external view returns(address[] memory);
}
/*
* This contract do swap for ERC20 via 1inch
Also this contract allow get ratio between crypto curency assets
Also get ratio for Bancor and Uniswap pools
*/
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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, 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) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* 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);
uint256 c = a - b;
return c;
}
/**
* @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) {
// 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, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts 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) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message 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, 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts 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) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ExchangePortal is ExchangePortalInterface, Ownable {
using SafeMath for uint256;
uint public version = 5;
// Contract for handle tokens types
ITokensTypeStorage public tokensTypes;
// Contract for merkle tree white list verification
IMerkleTreeTokensVerification public merkleTreeWhiteList;
// 1INCH
IOneSplitAudit public oneInch;
// 1 inch protocol for calldata
address public oneInchETH;
// BANCOR
IGetBancorData public bancorData;
// CoTrader portals
PoolPortalViewInterface public poolPortal;
DefiPortalInterface public defiPortal;
// 1 inch flags
// By default support Bancor + Uniswap + Uniswap v2
uint256 oneInchFlags = 570425349;
// Enum
// NOTE: You can add a new type at the end, but DO NOT CHANGE this order,
// because order has dependency in other contracts like ConvertPortal
enum ExchangeType { Paraswap, Bancor, OneInch, OneInchETH }
// This contract recognizes ETH by this address
IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Trade event
event Trade(
address trader,
address src,
uint256 srcAmount,
address dest,
uint256 destReceived,
uint8 exchangeType
);
// black list for non trade able tokens
mapping (address => bool) disabledTokens;
// Modifier to check that trading this token is not disabled
modifier tokenEnabled(IERC20 _token) {
require(!disabledTokens[address(_token)]);
_;
}
/**
* @dev contructor
*
* @param _defiPortal address of defiPortal contract
* @param _bancorData address of GetBancorData helper
* @param _poolPortal address of pool portal
* @param _oneInch address of 1inch OneSplitAudit contract
* @param _oneInchETH address of oneInch ETH contract
* @param _tokensTypes address of the ITokensTypeStorage
* @param _merkleTreeWhiteList address of the IMerkleTreeWhiteList
*/
constructor(
address _defiPortal,
address _bancorData,
address _poolPortal,
address _oneInch,
address _oneInchETH,
address _tokensTypes,
address _merkleTreeWhiteList
)
public
{
defiPortal = DefiPortalInterface(_defiPortal);
bancorData = IGetBancorData(_bancorData);
poolPortal = PoolPortalViewInterface(_poolPortal);
oneInch = IOneSplitAudit(_oneInch);
oneInchETH = _oneInchETH;
tokensTypes = ITokensTypeStorage(_tokensTypes);
merkleTreeWhiteList = IMerkleTreeTokensVerification(_merkleTreeWhiteList);
}
// EXCHANGE Functions
/**
* @dev Facilitates a trade for a SmartFund
*
* @param _source ERC20 token to convert from
* @param _sourceAmount Amount to convert from (in _source token)
* @param _destination ERC20 token to convert to
* @param _type The type of exchange to trade with
* @param _proof Merkle tree proof (if not used just set [])
* @param _positions Merkle tree positions (if not used just set [])
* @param _additionalData For additional data (if not used just set 0x0)
* @param _verifyDestanation For additional check if token in list or not
*
* @return receivedAmount The amount of _destination received from the trade
*/
function trade( //injected LOCKED ETHER
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
override
payable
tokenEnabled(_destination)
returns (uint256 receivedAmount)
{
// throw if destanation token not in white list
if(_verifyDestanation)
_verifyToken(address(_destination), _proof, _positions);
require(_source != _destination, "source can not be destination");
// check ETH payable case
if (_source == ETH_TOKEN_ADDRESS) {
require(msg.value == _sourceAmount);
} else {
require(msg.value == 0);
}
// SHOULD TRADE PARASWAP HERE
if (_type == uint(ExchangeType.Paraswap)) {
revert("PARASWAP not supported");
}
// SHOULD TRADE BANCOR HERE
else if (_type == uint(ExchangeType.Bancor)){
receivedAmount = _tradeViaBancorNewtork(
address(_source),
address(_destination),
_sourceAmount
);
}
// SHOULD TRADE 1INCH HERE
else if (_type == uint(ExchangeType.OneInch)){
receivedAmount = _tradeViaOneInch(
address(_source),
address(_destination),
_sourceAmount,
_additionalData
);
}
// SHOULD TRADE 1INCH ETH HERE
else if (_type == uint(ExchangeType.OneInchETH)){
receivedAmount = _tradeViaOneInchETH(
address(_source),
address(_destination),
_sourceAmount,
_additionalData
);
}
else {
// unknown exchange type
revert();
}
// Additional check
require(receivedAmount > 0, "received amount can not be zerro");
// Send destination
if (_destination == ETH_TOKEN_ADDRESS) {
(msg.sender).transfer(0);
} else {
// transfer tokens received to sender
_destination.transfer(msg.sender, receivedAmount);
}
// Send remains
_sendRemains(_source, msg.sender);
// Trigger event
emit Trade(
msg.sender,
address(_source),
_sourceAmount,
address(_destination),
receivedAmount,
uint8(_type)
);
}
// Facilitates for send source remains
function _sendRemains(IERC20 _source, address _receiver) private {
// After the trade, any _source that exchangePortal holds will be sent back to msg.sender
uint256 endAmount = (_source == ETH_TOKEN_ADDRESS)
? address(this).balance
: _source.balanceOf(address(this));
// Check if we hold a positive amount of _source
if (endAmount > 0) {
if (_source == ETH_TOKEN_ADDRESS) {
payable(_receiver).transfer(0);
} else {
_source.transfer(_receiver, endAmount);
}
}
}
// Facilitates for verify destanation token input (check if token in merkle list or not)
// revert transaction if token not in list
function _verifyToken(
address _destination,
bytes32 [] memory proof,
uint256 [] memory positions)
private
view
{
bool status = merkleTreeWhiteList.verify(_destination, proof, positions);
if(!status)
revert("Dest not in white list");
}
// Facilitates trade with 1inch
function _tradeViaOneInch(
address sourceToken,
address destinationToken,
uint256 sourceAmount,
bytes memory _additionalData
)
private
returns(uint256 destinationReceived)
{
(uint256 flags,
uint256[] memory _distribution) = abi.decode(_additionalData, (uint256, uint256[]));
if(IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
oneInch.swap.value(sourceAmount)(
IERC20(sourceToken),
IERC20(destinationToken),
sourceAmount,
1,
_distribution,
flags
);
} else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(oneInch));
oneInch.swap(
IERC20(sourceToken),
IERC20(destinationToken),
sourceAmount,
1,
_distribution,
flags
);
}
destinationReceived = tokenBalance(IERC20(destinationToken));
tokensTypes.addNewTokenType(destinationToken, "CRYPTOCURRENCY");
}
// Facilitates trade with 1inch ETH
// this protocol require calldata from 1inch api
function _tradeViaOneInchETH(
address sourceToken,
address destinationToken,
uint256 sourceAmount,
bytes memory _additionalData
)
private
returns(uint256 destinationReceived)
{
bool success;
// from ETH
if(IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
(success, ) = oneInchETH.call.value(sourceAmount)(
_additionalData
);
}
// from ERC20
else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(oneInchETH));
(success, ) = oneInchETH.call(
_additionalData
);
}
// check trade status
require(success, "Fail 1inch call");
// get received amount
destinationReceived = tokenBalance(IERC20(destinationToken));
// set token type
tokensTypes.addNewTokenType(destinationToken, "CRYPTOCURRENCY");
}
// Facilitates trade with Bancor
function _tradeViaBancorNewtork(
address sourceToken,
address destinationToken,
uint256 sourceAmount
)
private
returns(uint256 returnAmount)
{
// get latest bancor contracts
BancorNetworkInterface bancorNetwork = BancorNetworkInterface(
bancorData.getBancorContractAddresByName("BancorNetwork")
);
// Get Bancor tokens path
address[] memory path = bancorData.getBancorPathForAssets(IERC20(sourceToken), IERC20(destinationToken));
// Convert addresses to ERC20
IERC20[] memory pathInERC20 = new IERC20[](path.length);
for(uint i=0; i<path.length; i++){
pathInERC20[i] = IERC20(path[i]);
}
// trade
if (IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
returnAmount = bancorNetwork.convert.value(sourceAmount)(pathInERC20, sourceAmount, 1);
}
else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(bancorNetwork));
returnAmount = bancorNetwork.claimAndConvert(pathInERC20, sourceAmount, 1);
}
tokensTypes.addNewTokenType(destinationToken, "BANCOR_ASSET");
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
require(_source.transferFrom(msg.sender, address(this), _sourceAmount));
// reset previos approve because some tokens require allowance 0
_source.approve(_to, 0);
// approve
_source.approve(_to, _sourceAmount);
}
// VIEW Functions
function tokenBalance(IERC20 _token) private view returns (uint256) {
if (_token == ETH_TOKEN_ADDRESS)
return address(this).balance;
return _token.balanceOf(address(this));
}
/**
* @dev Gets the ratio by amount of token _from in token _to by totekn type
*
* @param _from Address of token we're converting from
* @param _to Address of token we're getting the value in
* @param _amount The amount of _from
*
* @return best price from 1inch for ERC20, or ratio for Uniswap and Bancor pools
*/
function getValue(address _from, address _to, uint256 _amount)
public
override
view
returns (uint256)
{
if(_amount > 0){
// get asset type
bytes32 assetType = tokensTypes.getType(_from);
// get value by asset type
if(assetType == bytes32("CRYPTOCURRENCY")){
return getValueViaDEXsAgregators(_from, _to, _amount);
}
else if (assetType == bytes32("BANCOR_ASSET")){
return getValueViaBancor(_from, _to, _amount);
}
else if (assetType == bytes32("UNISWAP_POOL")){
return getValueForUniswapPools(_from, _to, _amount);
}
else if (assetType == bytes32("UNISWAP_POOL_V2")){
return getValueForUniswapV2Pools(_from, _to, _amount);
}
else if (assetType == bytes32("BALANCER_POOL")){
return getValueForBalancerPool(_from, _to, _amount);
}
else{
// Unmarked type, try find value
return findValue(_from, _to, _amount);
}
}
else{
return 0;
}
}
/**
* @dev find the ratio by amount of token _from in token _to trying all available methods
*
* @param _from Address of token we're converting from
* @param _to Address of token we're getting the value in
* @param _amount The amount of _from
*
* @return best price from 1inch for ERC20, or ratio for Uniswap and Bancor pools
*/
function findValue(address _from, address _to, uint256 _amount) private view returns (uint256) {
if(_amount > 0){
// Check at first value from defi portal, maybe there are new defi protocols
// If defiValue return 0 continue check from another sources
uint256 defiValue = defiPortal.getValue(_from, _to, _amount);
if(defiValue > 0)
return defiValue;
// If 1inch return 0, check from Bancor network for ensure this is not a Bancor pool
uint256 oneInchResult = getValueViaDEXsAgregators(_from, _to, _amount);
if(oneInchResult > 0)
return oneInchResult;
// If Bancor return 0, check from Balancer network for ensure this is not Balancer asset
uint256 bancorResult = getValueViaBancor(_from, _to, _amount);
if(bancorResult > 0)
return bancorResult;
// If Balancer return 0, check from Uniswap pools for ensure this is not Uniswap pool
uint256 balancerResult = getValueForBalancerPool(_from, _to, _amount);
if(balancerResult > 0)
return balancerResult;
// If Uniswap return 0, check from Uniswap version 2 pools for ensure this is not Uniswap V2 pool
uint256 uniswapResult = getValueForUniswapPools(_from, _to, _amount);
if(uniswapResult > 0)
return uniswapResult;
// Uniswap V2 pools return 0 if these is not a Uniswap V2 pool
return getValueForUniswapV2Pools(_from, _to, _amount);
}
else{
return 0;
}
}
// helper for get value via 1inch
// in this interface can be added more DEXs aggregators
function getValueViaDEXsAgregators(
address _from,
address _to,
uint256 _amount
)
public view returns (uint256){
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get value via 1inch
if(_amount > 0){
// try get value from 1inch aggregator
return getValueViaOneInch(_from, _to, _amount);
}
else{
return 0;
}
}
// helper for get ratio between assets in 1inch aggregator
function getValueViaOneInch(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get rate
try oneInch.getExpectedReturn(
IERC20(_from),
IERC20(_to),
_amount,
10,
oneInchFlags)
returns(uint256 returnAmount, uint256[] memory distribution)
{
value = returnAmount;
}
catch{
value = 0;
}
}
// helper for get ratio between assets in Bancor network
function getValueViaBancor(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get rate
if(_amount > 0){
try poolPortal.getBancorRatio(_from, _to, _amount) returns(uint256 result){
value = result;
}catch{
value = 0;
}
}else{
return 0;
}
}
// helper for get value via Balancer
function getValueForBalancerPool(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// get value for each pool share
try poolPortal.getBalancerConnectorsAmountByPoolAmount(_amount, _from)
returns(
address[] memory tokens,
uint256[] memory tokensAmount
)
{
// convert and sum value via DEX aggregator
for(uint i = 0; i < tokens.length; i++){
value += getValueViaDEXsAgregators(tokens[i], _to, tokensAmount[i]);
}
}
catch{
value = 0;
}
}
// helper for get ratio between pools in Uniswap network
// _from - should be uniswap pool address
function getValueForUniswapPools(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256)
{
// get connectors amount
try poolPortal.getUniswapConnectorsAmountByPoolAmount(
_amount,
_from
) returns (uint256 ethAmount, uint256 ercAmount)
{
// get ERC amount in ETH
address token = poolPortal.getTokenByUniswapExchange(_from);
uint256 ercAmountInETH = getValueViaDEXsAgregators(token, address(ETH_TOKEN_ADDRESS), ercAmount);
// sum ETH with ERC amount in ETH
uint256 totalETH = ethAmount.add(ercAmountInETH);
// if _to == ETH no need additional convert, just return ETH amount
if(_to == address(ETH_TOKEN_ADDRESS)){
return totalETH;
}
// convert ETH into _to asset via 1inch
else{
return getValueViaDEXsAgregators(address(ETH_TOKEN_ADDRESS), _to, totalETH);
}
}catch{
return 0;
}
}
// helper for get ratio between pools in Uniswap network version 2
// _from - should be uniswap pool address
function getValueForUniswapV2Pools(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256)
{
// get connectors amount by pool share
try poolPortal.getUniswapV2ConnectorsAmountByPoolAmount(
_amount,
_from
) returns (
uint256 tokenAmountOne,
uint256 tokenAmountTwo,
address tokenAddressOne,
address tokenAddressTwo
)
{
// convert connectors amount via DEX aggregator
uint256 amountOne = getValueViaDEXsAgregators(tokenAddressOne, _to, tokenAmountOne);
uint256 amountTwo = getValueViaDEXsAgregators(tokenAddressTwo, _to, tokenAmountTwo);
// return value
return amountOne + amountTwo;
}catch{
return 0;
}
}
/**
* @dev Gets the total value of array of tokens and amounts
*
* @param _fromAddresses Addresses of all the tokens we're converting from
* @param _amounts The amounts of all the tokens
* @param _to The token who's value we're converting to
*
* @return The total value of _fromAddresses and _amounts in terms of _to
*/
function getTotalValue(
address[] calldata _fromAddresses,
uint256[] calldata _amounts,
address _to)
external
override
view
returns (uint256)
{
uint256 sum = 0;
for (uint256 i = 0; i < _fromAddresses.length; i++) {
sum = sum.add(getValue(_fromAddresses[i], _to, _amounts[i]));
}
return sum;
}
// SETTERS Functions
/**
* @dev Allows the owner to disable/enable the buying of a token
*
* @param _token Token address whos trading permission is to be set
* @param _enabled New token permission
*/
function setToken(address _token, bool _enabled) external onlyOwner {
disabledTokens[_token] = _enabled;
}
// owner can change oneInch
function setNewOneInch(address _oneInch) external onlyOwner {
oneInch = IOneSplitAudit(_oneInch);
}
// owner can change oneInch
function setNewOneInchETH(address _oneInchETH) external onlyOwner {
oneInchETH = _oneInchETH;
}
// owner can set new pool portal
function setNewPoolPortal(address _poolPortal) external onlyOwner {
poolPortal = PoolPortalViewInterface(_poolPortal);
}
// owner can set new defi portal
function setNewDefiPortal(address _defiPortal) external onlyOwner {
defiPortal = DefiPortalInterface(_defiPortal);
}
// owner of portal can update 1 incg DEXs sources
function setOneInchFlags(uint256 _oneInchFlags) external onlyOwner {
oneInchFlags = _oneInchFlags;
}
// owner of portal can change getBancorData helper, for case if Bancor do some major updates
function setNewGetBancorData(address _bancorData) external onlyOwner {
bancorData = IGetBancorData(_bancorData);
}
// fallback payable function to receive ether from other contract addresses
fallback() external payable {} //injected LOCKED ETHER
} | owner of portal can change getBancorData helper, for case if Bancor do some major updates | function setNewGetBancorData(address _bancorData) external onlyOwner {
bancorData = IGetBancorData(_bancorData);
}
| 887,761 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC20Permit/ERC20Permit.sol";
contract sOlympus is ERC20Permit, Ownable {
using SafeMath for uint256;
modifier onlyStakingContract() {
require(msg.sender == stakingContract);
_;
}
address public stakingContract;
address public initializer;
event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply);
event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index);
event LogStakingContractUpdated(address stakingContract);
struct Rebase {
uint256 epoch;
uint256 rebase; // 18 decimals
uint256 totalStakedBefore;
uint256 totalStakedAfter;
uint256 amountRebased;
uint256 index;
uint256 blockNumberOccured;
}
Rebase[] public rebases;
uint256 public INDEX;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
mapping(address => mapping(address => uint256)) private _allowedValue;
constructor() ERC20("Staked Olympus", "sOHM", 9) ERC20Permit() {
initializer = msg.sender;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
}
function initialize(address stakingContract_) external returns (bool) {
require(msg.sender == initializer);
require(stakingContract_ != address(0));
stakingContract = stakingContract_;
_gonBalances[stakingContract] = TOTAL_GONS;
emit Transfer(address(0x0), stakingContract, _totalSupply);
emit LogStakingContractUpdated(stakingContract_);
initializer = address(0);
return true;
}
function setIndex(uint256 _INDEX) external onlyOwner returns (bool) {
require(INDEX == 0);
INDEX = gonsForBalance(_INDEX);
return true;
}
/**
@notice increases sOHM supply to increase staking balances relative to profit_
@param profit_ uint256
@return uint256
*/
function rebase(uint256 profit_, uint256 epoch_) public onlyStakingContract returns (uint256) {
uint256 rebaseAmount;
uint256 circulatingSupply_ = circulatingSupply();
if (profit_ == 0) {
emit LogSupply(epoch_, block.timestamp, _totalSupply);
emit LogRebase(epoch_, 0, index());
return _totalSupply;
} else if (circulatingSupply_ > 0) {
rebaseAmount = profit_.mul(_totalSupply).div(circulatingSupply_);
} else {
rebaseAmount = profit_;
}
_totalSupply = _totalSupply.add(rebaseAmount);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
_storeRebase(circulatingSupply_, profit_, epoch_);
return _totalSupply;
}
/**
@notice emits event with data about rebase
@param previousCirculating_ uint
@param profit_ uint
@param epoch_ uint
@return bool
*/
function _storeRebase(
uint256 previousCirculating_,
uint256 profit_,
uint256 epoch_
) internal returns (bool) {
uint256 rebasePercent = profit_.mul(1e18).div(previousCirculating_);
rebases.push(
Rebase({
epoch: epoch_,
rebase: rebasePercent, // 18 decimals
totalStakedBefore: previousCirculating_,
totalStakedAfter: circulatingSupply(),
amountRebased: profit_,
index: index(),
blockNumberOccured: block.number
})
);
emit LogSupply(epoch_, block.timestamp, _totalSupply);
emit LogRebase(epoch_, rebasePercent, index());
return true;
}
function balanceOf(address who) public view override returns (uint256) {
return _gonBalances[who].div(_gonsPerFragment);
}
function gonsForBalance(uint256 amount) public view returns (uint256) {
return amount.mul(_gonsPerFragment);
}
function balanceForGons(uint256 gons) public view returns (uint256) {
return gons.div(_gonsPerFragment);
}
// Staking contract holds excess sOHM
function circulatingSupply() public view returns (uint256) {
return _totalSupply.sub(balanceOf(stakingContract));
}
function index() public view returns (uint256) {
return balanceForGons(INDEX);
}
function transfer(address to, uint256 value) public override returns (bool) {
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
function allowance(address owner_, address spender) public view override returns (uint256) {
return _allowedValue[owner_][spender];
}
function transferFrom(
address from,
address to,
uint256 value
) public override returns (bool) {
_allowedValue[from][msg.sender] = _allowedValue[from][msg.sender].sub(value);
emit Approval(from, msg.sender, _allowedValue[from][msg.sender]);
uint256 gonValue = gonsForBalance(value);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint256 value) public override returns (bool) {
_allowedValue[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
// What gets called in a permit
function _approve(
address owner,
address spender,
uint256 value
) internal virtual override {
_allowedValue[owner][spender] = value;
emit Approval(owner, spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
_allowedValue[msg.sender][spender] = _allowedValue[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedValue[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
uint256 oldValue = _allowedValue[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedValue[msg.sender][spender] = 0;
} else {
_allowedValue[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedValue[msg.sender][spender]);
return true;
}
}
| Staking contract holds excess sOHM | function circulatingSupply() public view returns (uint256) {
return _totalSupply.sub(balanceOf(stakingContract));
}
| 7,296,568 |
./full_match/5/0xF2B155cbbaa706fc6b277E0279a02193285Ce333/sources/project_/contracts/AttributeStore.sol | retrieves the voter's attributes set in the setAttribute call | function getAttribute(Data storage self, bytes32 _UUID, string _attrName)
public view returns (uint) {
bytes32 key = keccak256(_UUID, _attrName);
return self.store[key];
}
| 1,899,651 |
./partial_match/1/0xc3e4100A8d5e9F43cCdC50303e275d8726E83b96/sources/InsolventCErc20Delegate.sol | Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supply return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
| 2,721,926 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
library SafeMath {
/**
* @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) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* 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);
uint256 c = a - b;
return c;
}
/**
* @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) {
// 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, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts 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) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts 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) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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);
}
library Constants {
address constant CDP_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address constant PROXY_ACTIONS = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
address constant MCD_JOIN_ETH_A = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address constant MCD_JOIN_USDC_A = 0xA191e578a6736167326d05c119CE0c90849E84B7;
address constant MCD_JOIN_DAI = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address constant MCD_END = 0xaB14d3CE3F733CACB76eC2AbE7d2fcb00c99F3d5;
address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant UNISWAPV2_ROUTER2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
bytes32 constant USDC_A_ILK = bytes32("USDC-A");
bytes32 constant ETH_A_ILK = bytes32("ETH-A");
}
contract Migrations {
address public owner;
uint public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}
contract ShortDAIActions {
using SafeMath for uint256;
function _openUSDCACdp() internal returns (uint256) {
return
IDssCdpManager(Constants.CDP_MANAGER).open(
bytes32("USDC-A"),
address(this)
);
}
// Entry point for proxy contracts
function flashloanAndOpen(
address _osd,
address _solo,
address _curvePool,
uint256 _cdpId, // Set 0 for new vault
uint256 _initialMarginUSDC, // Initial USDC margin
uint256 _mintAmountDAI, // Amount of DAI to mint
uint256 _flashloanAmountWETH, // Amount of WETH to flashloan
address _vaultStats,
uint256 _daiUsdcRatio6
) external payable {
require(msg.value == 2, "!fee");
// Tries and get USDC from msg.sender to proxy
require(
IERC20(Constants.USDC).transferFrom(
msg.sender,
address(this),
_initialMarginUSDC
),
"initial-margin-transferFrom-failed"
);
uint256 cdpId = _cdpId;
// Opens a new USDC vault for the user if unspecified
if (cdpId == 0) {
cdpId = _openUSDCACdp();
}
// Allows LSD contract to manage vault on behalf of user
IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdpId, _osd, 1);
// Approve OpenShortDAI Contract to use USDC funds
require(
IERC20(Constants.USDC).approve(_osd, _initialMarginUSDC),
"initial-margin-approve-failed"
);
// Flashloan and shorts DAI
OpenShortDAI(_osd).flashloanAndOpen{value: msg.value}(
msg.sender,
_solo,
_curvePool,
cdpId,
_initialMarginUSDC,
_mintAmountDAI,
_flashloanAmountWETH
);
// Forbids LSD contract to manage vault on behalf of user
IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdpId, _osd, 0);
// Save stats
VaultStats(_vaultStats).setDaiUsdcRatio6(cdpId, _daiUsdcRatio6);
}
function flashloanAndClose(
address _csd,
address _solo,
address _curvePool,
uint256 _cdpId,
uint256 _ethUsdRatio18
) external payable {
require(msg.value == 2, "!fee");
IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(_cdpId, _csd, 1);
CloseShortDAI(_csd).flashloanAndClose{value: msg.value}(
msg.sender,
_solo,
_curvePool,
_cdpId,
_ethUsdRatio18
);
IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(_cdpId, _csd, 0);
IDssCdpManager(Constants.CDP_MANAGER).give(_cdpId, address(1));
}
function cdpAllow(
uint256 cdp,
address usr,
uint256 ok
) public {
IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdp, usr, ok);
}
}
contract VaultStats {
uint256 constant RAY = 10**27;
using SafeMath for uint256;
// CDP ID => DAI/USDC Ratio in 6 decimals
// i.e. What was DAI/USDC ratio when CDP was opened
mapping(uint256 => uint256) public daiUsdcRatio6;
//** View functions for stats ** //
function _getCdpSuppliedAndBorrowed(
address vat,
address usr,
address urn,
bytes32 ilk
) internal view returns (uint256, uint256) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(uint256 supplied, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = art.mul(rate).sub(dai);
uint256 wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
uint256 borrowed = wad.mul(RAY) < rad ? wad + 1 : wad;
// Note that supplied is in 18 decimals, so you'll need to convert it back
// i.e. supplied = supplied / 10 ** (18 - decimals)
return (supplied, borrowed);
}
// Get DAI borrow / supply stats
function getCdpStats(uint256 cdp)
public
view
returns (
uint256,
uint256,
uint256
)
{
address vat = IDssCdpManager(Constants.CDP_MANAGER).vat();
address urn = IDssCdpManager(Constants.CDP_MANAGER).urns(cdp);
bytes32 ilk = IDssCdpManager(Constants.CDP_MANAGER).ilks(cdp);
address usr = IDssCdpManager(Constants.CDP_MANAGER).owns(cdp);
(uint256 supplied, uint256 borrowed) = _getCdpSuppliedAndBorrowed(
vat,
usr,
urn,
ilk
);
uint256 ratio = daiUsdcRatio6[cdp];
// Note that supplied and borrowed are in 18 decimals
// while DAI USDC ratio is in 6 decimals
return (supplied, borrowed, ratio);
}
function setDaiUsdcRatio6(uint256 _cdp, uint256 _daiUsdcRatio6) public {
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address owner = manager.owns(_cdp);
require(
owner == msg.sender || manager.cdpCan(owner, _cdp, msg.sender) == 1,
"cdp-not-allowed"
);
daiUsdcRatio6[_cdp] = _daiUsdcRatio6;
}
}
interface ICurveFiCurve {
function get_virtual_price() external view returns (uint256 out);
function add_liquidity(uint256[2] calldata amounts, uint256 deadline)
external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 deadline
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
}
contract DydxFlashloanBase {
using SafeMath for uint256;
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(address _solo, address token)
internal
view
returns (uint256)
{
ISoloMargin solo = ISoloMargin(_solo);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found for provided token");
}
function _getRepaymentAmount() internal pure returns (uint256) {
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return 2;
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
interface ISoloMargin {
function getMarketTokenAddress(uint256 marketId)
external
view
returns (address);
function getNumMarkets() external view returns (uint256);
function operate(
Account.Info[] calldata accounts,
Actions.ActionArgs[] calldata actions
) external;
}
interface ICallee {
// ============ external Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info calldata accountInfo,
bytes calldata data
) external;
}
interface GemLike {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
}
interface GemJoinLike {
function dec() external returns (uint256);
function gem() external returns (address);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface VatLike {
function can(address, address) external view returns (uint256);
function ilks(bytes32)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function dai(address) external view returns (uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) external;
function hope(address) external;
function move(
address,
address,
uint256
) external;
}
interface JugLike {
function drip(bytes32) external returns (uint256);
function ilks(bytes32) external view returns (uint256, uint256);
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
contract DssActionsBase {
uint256 constant RAY = 10**27;
using SafeMath for uint256;
function _convertTo18(address gemJoin, uint256 amt)
internal
returns (uint256 wad)
{
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec()));
}
function _toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function _toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = wad.mul(10**27);
}
function _gemJoin_join(
address apt,
address urn,
uint256 wad,
bool transferFrom
) internal {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Tokens already in address(this)
// GemLike(GemJoinLike(apt).gem()).transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemLike(GemJoinLike(apt).gem()).approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function _daiJoin_join(
address apt,
address urn,
uint256 wad
) internal {
// Contract already has tokens
// Gets DAI from the user's wallet
// DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
function _getDrawDart(
address vat,
address jug,
address urn,
bytes32 ilk,
uint256 wad
) internal returns (int256 dart) {
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < wad.mul(RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = _toInt(wad.mul(RAY).sub(dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(
address vat,
uint256 dai,
address urn,
bytes32 ilk
) internal view returns (int256 dart) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = _toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -_toInt(art);
}
function _getWipeAllWad(
address vat,
address usr,
address urn,
bytes32 ilk
) internal view returns (uint256 wad) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = art.mul(rate).sub(dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = wad.mul(RAY) < rad ? wad + 1 : wad;
}
function _getSuppliedAndBorrow(address gemJoin, uint256 cdp)
internal
returns (uint256, uint256)
{
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address vat = manager.vat();
bytes32 ilk = manager.ilks(cdp);
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(uint256 supplied, uint256 art) = VatLike(vat).urns(
ilk,
manager.urns(cdp)
);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(manager.owns(cdp));
uint256 rad = art.mul(rate).sub(dai);
uint256 wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
uint256 borrowed = wad.mul(RAY) < rad ? wad + 1 : wad;
// Convert back to native units
supplied = supplied.div(10**(18 - GemJoinLike(gemJoin).dec()));
return (supplied, borrowed);
}
function _lockGemAndDraw(
address gemJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD
) internal {
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address urn = manager.urns(cdp);
address vat = manager.vat();
bytes32 ilk = manager.ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
_gemJoin_join(gemJoin, urn, wadC, true);
// Locks GEM amount into the CDP and generates debt
manager.frob(
cdp,
_toInt(_convertTo18(gemJoin, wadC)),
_getDrawDart(vat, Constants.MCD_JUG, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
manager.move(cdp, address(this), _toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (
VatLike(vat).can(address(this), address(Constants.MCD_JOIN_DAI)) ==
0
) {
VatLike(vat).hope(Constants.MCD_JOIN_DAI);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(Constants.MCD_JOIN_DAI).exit(address(this), wadD);
}
function _wipeAllAndFreeGem(
address gemJoin,
uint256 cdp,
uint256 amtC
) internal {
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address vat = manager.vat();
address urn = manager.urns(cdp);
bytes32 ilk = manager.ilks(cdp);
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Joins DAI amount into the vat
_daiJoin_join(
Constants.MCD_JOIN_DAI,
urn,
_getWipeAllWad(vat, urn, urn, ilk)
);
uint256 wadC = _convertTo18(gemJoin, amtC);
// Paybacks debt to the CDP and unlocks token amount from it
manager.frob(cdp, -_toInt(wadC), -int256(art));
// Moves the amount from the CDP urn to proxy's address
manager.flux(cdp, address(this), wadC);
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(address(this), amtC);
}
function _openLockGemAndDraw(
address gemJoin,
bytes32 ilk,
uint256 amtC,
uint256 wadD
) internal returns (uint256 cdp) {
cdp = IDssCdpManager(Constants.CDP_MANAGER).open(ilk, address(this));
_lockGemAndDraw(gemJoin, cdp, amtC, wadD);
}
}
interface IDSProxy {
function authority() external view returns (address);
function cache() external view returns (address);
function execute(address _target, bytes calldata _data)
external
payable
returns (bytes memory response);
function execute(bytes calldata _code, bytes calldata _data)
external
payable
returns (address target, bytes memory response);
function owner() external view returns (address);
function setAuthority(address authority_) external;
function setCache(address _cacheAddr) external returns (bool);
function setOwner(address owner_) external;
}
interface IDssCdpManager {
function cdpAllow(
uint256 cdp,
address usr,
uint256 ok
) external;
function cdpCan(
address,
uint256,
address
) external view returns (uint256);
function cdpi() external view returns (uint256);
function count(address) external view returns (uint256);
function enter(address src, uint256 cdp) external;
function first(address) external view returns (uint256);
function flux(
bytes32 ilk,
uint256 cdp,
address dst,
uint256 wad
) external;
function flux(
uint256 cdp,
address dst,
uint256 wad
) external;
function frob(
uint256 cdp,
int256 dink,
int256 dart
) external;
function give(uint256 cdp, address dst) external;
function ilks(uint256) external view returns (bytes32);
function last(address) external view returns (uint256);
function list(uint256) external view returns (uint256 prev, uint256 next);
function move(
uint256 cdp,
address dst,
uint256 rad
) external;
function open(bytes32 ilk, address usr) external returns (uint256);
function owns(uint256) external view returns (address);
function quit(uint256 cdp, address dst) external;
function shift(uint256 cdpSrc, uint256 cdpDst) external;
function urnAllow(address usr, uint256 ok) external;
function urnCan(address, address) external view returns (uint256);
function urns(uint256) external view returns (address);
function vat() external view returns (address);
}
interface IDssProxyActions {
function cdpAllow(
address manager,
uint256 cdp,
address usr,
uint256 ok
) external;
function daiJoin_join(
address apt,
address urn,
uint256 wad
) external;
function draw(
address manager,
address jug,
address daiJoin,
uint256 cdp,
uint256 wad
) external;
function enter(
address manager,
address src,
uint256 cdp
) external;
function ethJoin_join(address apt, address urn) external payable;
function exitETH(
address manager,
address ethJoin,
uint256 cdp,
uint256 wad
) external;
function exitGem(
address manager,
address gemJoin,
uint256 cdp,
uint256 amt
) external;
function flux(
address manager,
uint256 cdp,
address dst,
uint256 wad
) external;
function freeETH(
address manager,
address ethJoin,
uint256 cdp,
uint256 wad
) external;
function freeGem(
address manager,
address gemJoin,
uint256 cdp,
uint256 amt
) external;
function frob(
address manager,
uint256 cdp,
int256 dink,
int256 dart
) external;
function gemJoin_join(
address apt,
address urn,
uint256 amt,
bool transferFrom
) external;
function give(
address manager,
uint256 cdp,
address usr
) external;
function giveToProxy(
address proxyRegistry,
address manager,
uint256 cdp,
address dst
) external;
function hope(address obj, address usr) external;
function lockETH(
address manager,
address ethJoin,
uint256 cdp
) external payable;
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) external payable;
function lockGem(
address manager,
address gemJoin,
uint256 cdp,
uint256 amt,
bool transferFrom
) external;
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 amtC,
uint256 wadD,
bool transferFrom
) external;
function makeGemBag(address gemJoin) external returns (address bag);
function move(
address manager,
uint256 cdp,
address dst,
uint256 rad
) external;
function nope(address obj, address usr) external;
function open(
address manager,
bytes32 ilk,
address usr
) external returns (uint256 cdp);
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD
) external payable returns (uint256 cdp);
function openLockGNTAndDraw(
address manager,
address jug,
address gntJoin,
address daiJoin,
bytes32 ilk,
uint256 amtC,
uint256 wadD
) external returns (address bag, uint256 cdp);
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 amtC,
uint256 wadD,
bool transferFrom
) external returns (uint256 cdp);
function quit(
address manager,
uint256 cdp,
address dst
) external;
function safeLockETH(
address manager,
address ethJoin,
uint256 cdp,
address owner
) external payable;
function safeLockGem(
address manager,
address gemJoin,
uint256 cdp,
uint256 amt,
bool transferFrom,
address owner
) external;
function safeWipe(
address manager,
address daiJoin,
uint256 cdp,
uint256 wad,
address owner
) external;
function safeWipeAll(
address manager,
address daiJoin,
uint256 cdp,
address owner
) external;
function shift(
address manager,
uint256 cdpSrc,
uint256 cdpOrg
) external;
function transfer(
address gem,
address dst,
uint256 amt
) external;
function urnAllow(
address manager,
address usr,
uint256 ok
) external;
function wipe(
address manager,
address daiJoin,
uint256 cdp,
uint256 wad
) external;
function wipeAll(
address manager,
address daiJoin,
uint256 cdp
) external;
function wipeAllAndFreeETH(
address manager,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadC
) external;
function wipeAllAndFreeGem(
address manager,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 amtC
) external;
function wipeAndFreeETH(
address manager,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD
) external;
function wipeAndFreeGem(
address manager,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 amtC,
uint256 wadD
) external;
}
interface IGetCdps {
function getCdpsAsc(address manager, address guy)
external
view
returns (
uint256[] memory ids,
address[] memory urns,
bytes32[] memory ilks
);
function getCdpsDesc(address manager, address guy)
external
view
returns (
uint256[] memory ids,
address[] memory urns,
bytes32[] memory ilks
);
}
interface IProxyRegistry {
function build() external returns (address proxy);
function proxies(address) external view returns (address);
function build(address owner) external returns (address proxy);
}
interface IOneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
) external payable returns (uint256 returnAmount);
}
interface UniswapRouterV2 {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface UniswapPair {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestamp
);
}
interface WETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
}
contract CloseShortDAI is ICallee, DydxFlashloanBase, DssActionsBase {
struct CSDParams {
uint256 cdpId; // CdpId to close
address curvePool; // Which curve pool to use
uint256 mintAmountDAI; // Amount of DAI to mint
uint256 withdrawAmountUSDC; // Amount of USDC to withdraw from vault
uint256 flashloanAmountWETH; // Amount of WETH flashloaned
}
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
CSDParams memory csdp = abi.decode(data, (CSDParams));
// Step 1. Have Flashloaned WETH
// Open WETH CDP in Maker, then Mint out some DAI
uint256 wethCdp = _openLockGemAndDraw(
Constants.MCD_JOIN_ETH_A,
Constants.ETH_A_ILK,
csdp.flashloanAmountWETH,
csdp.mintAmountDAI
);
// Step 2.
// Use flashloaned DAI to repay entire vault and withdraw USDC
_wipeAllAndFreeGem(
Constants.MCD_JOIN_USDC_A,
csdp.cdpId,
csdp.withdrawAmountUSDC
);
// Step 3.
// Converts USDC to DAI on CurveFi (To repay loan)
// DAI = 0 index, USDC = 1 index
ICurveFiCurve curve = ICurveFiCurve(csdp.curvePool);
// Calculate amount of USDC needed to exchange to repay flashloaned DAI
// Allow max of 5% slippage (otherwise no profits lmao)
uint256 usdcBal = IERC20(Constants.USDC).balanceOf(address(this));
require(
IERC20(Constants.USDC).approve(address(curve), usdcBal),
"erc20-approve-curvepool-failed"
);
curve.exchange_underlying(int128(1), int128(0), usdcBal, 0);
// Step 4.
// Repay DAI loan back to WETH CDP and FREE WETH
_wipeAllAndFreeGem(
Constants.MCD_JOIN_ETH_A,
wethCdp,
csdp.flashloanAmountWETH
);
}
function flashloanAndClose(
address _sender,
address _solo,
address _curvePool,
uint256 _cdpId,
uint256 _ethUsdRatio18 // 1 ETH = <X> DAI?
) external payable {
require(msg.value == 2, "!fee");
ISoloMargin solo = ISoloMargin(_solo);
uint256 marketId = _getMarketIdFromTokenAddress(_solo, Constants.WETH);
// Supplied = How much we want to withdraw
// Borrowed = How much we want to loan
(
uint256 withdrawAmountUSDC,
uint256 mintAmountDAI
) = _getSuppliedAndBorrow(Constants.MCD_JOIN_USDC_A, _cdpId);
// Given, ETH price, calculate how much WETH we need to flashloan
// Dividing by 2 to gives us 200% col ratio
uint256 flashloanAmountWETH = mintAmountDAI.mul(1 ether).div(
_ethUsdRatio18.div(2)
);
require(
IERC20(Constants.WETH).balanceOf(_solo) >= flashloanAmountWETH,
"!weth-supply"
);
// Wrap ETH into WETH
WETH(Constants.WETH).deposit{value: msg.value}();
WETH(Constants.WETH).approve(_solo, flashloanAmountWETH.add(msg.value));
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, flashloanAmountWETH);
operations[1] = _getCallAction(
abi.encode(
CSDParams({
mintAmountDAI: mintAmountDAI,
withdrawAmountUSDC: withdrawAmountUSDC,
flashloanAmountWETH: flashloanAmountWETH,
cdpId: _cdpId,
curvePool: _curvePool
})
)
);
operations[2] = _getDepositAction(
marketId,
flashloanAmountWETH.add(msg.value)
);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
// Convert DAI leftovers to USDC
uint256 daiBal = IERC20(Constants.DAI).balanceOf(address(this));
require(
IERC20(Constants.DAI).approve(_curvePool, daiBal),
"erc20-approve-curvepool-failed"
);
ICurveFiCurve(_curvePool).exchange_underlying(
int128(0),
int128(1),
daiBal,
0
);
// Refund leftovers
IERC20(Constants.USDC).transfer(
_sender,
IERC20(Constants.USDC).balanceOf(address(this))
);
}
}
contract OpenShortDAI is ICallee, DydxFlashloanBase, DssActionsBase {
// LeveragedShortDAI Params
struct OSDParams {
uint256 cdpId; // CDP Id to leverage
uint256 mintAmountDAI; // Amount of DAI to mint
uint256 flashloanAmountWETH; // Amount of WETH flashloaned
address curvePool;
}
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
OSDParams memory osdp = abi.decode(data, (OSDParams));
// Step 1. Have Flashloaned WETH
// Open WETH CDP in Maker, then Mint out some DAI
uint256 wethCdp = _openLockGemAndDraw(
Constants.MCD_JOIN_ETH_A,
Constants.ETH_A_ILK,
osdp.flashloanAmountWETH,
osdp.mintAmountDAI
);
// Step 2.
// Converts Flashloaned DAI to USDC on CurveFi
// DAI = 0 index, USDC = 1 index
require(
IERC20(Constants.DAI).approve(osdp.curvePool, osdp.mintAmountDAI),
"!curvepool-approved"
);
ICurveFiCurve(osdp.curvePool).exchange_underlying(
int128(0),
int128(1),
osdp.mintAmountDAI,
0
);
// Step 3.
// Locks up USDC and borrow just enough DAI to repay WETH CDP
uint256 supplyAmount = IERC20(Constants.USDC).balanceOf(address(this));
_lockGemAndDraw(
Constants.MCD_JOIN_USDC_A,
osdp.cdpId,
supplyAmount,
osdp.mintAmountDAI
);
// Step 4.
// Repay DAI loan back to WETH CDP and FREE WETH
_wipeAllAndFreeGem(
Constants.MCD_JOIN_ETH_A,
wethCdp,
osdp.flashloanAmountWETH
);
}
function flashloanAndOpen(
address _sender,
address _solo,
address _curvePool,
uint256 _cdpId,
uint256 _initialMarginUSDC,
uint256 _mintAmountDAI,
uint256 _flashloanAmountWETH
) external payable {
require(msg.value == 2, "!fee");
require(
IERC20(Constants.WETH).balanceOf(_solo) >= _flashloanAmountWETH,
"!weth-supply"
);
// Gets USDC
require(
IERC20(Constants.USDC).transferFrom(
msg.sender,
address(this),
_initialMarginUSDC
),
"initial-margin-transferFrom-failed"
);
ISoloMargin solo = ISoloMargin(_solo);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(_solo, Constants.WETH);
// Wrap ETH into WETH
WETH(Constants.WETH).deposit{value: msg.value}();
WETH(Constants.WETH).approve(
_solo,
_flashloanAmountWETH.add(msg.value)
);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _flashloanAmountWETH);
operations[1] = _getCallAction(
// Encode OSDParams for callFunction
abi.encode(
OSDParams({
mintAmountDAI: _mintAmountDAI,
flashloanAmountWETH: _flashloanAmountWETH,
cdpId: _cdpId,
curvePool: _curvePool
})
)
);
operations[2] = _getDepositAction(
marketId,
_flashloanAmountWETH.add(msg.value)
);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
// Refund user any ERC20 leftover
IERC20(Constants.DAI).transfer(
_sender,
IERC20(Constants.DAI).balanceOf(address(this))
);
IERC20(Constants.USDC).transfer(
_sender,
IERC20(Constants.USDC).balanceOf(address(this))
);
}
}
| Gets USDC Get marketId from token address Wrap ETH into WETH 1. Withdraw $ 2. Call callFunction(...) 3. Deposit back $ Encode OSDParams for callFunction | function flashloanAndOpen(
address _sender,
address _solo,
address _curvePool,
uint256 _cdpId,
uint256 _initialMarginUSDC,
uint256 _mintAmountDAI,
uint256 _flashloanAmountWETH
) external payable {
require(msg.value == 2, "!fee");
require(
IERC20(Constants.WETH).balanceOf(_solo) >= _flashloanAmountWETH,
"!weth-supply"
);
require(
IERC20(Constants.USDC).transferFrom(
msg.sender,
address(this),
_initialMarginUSDC
),
"initial-margin-transferFrom-failed"
);
ISoloMargin solo = ISoloMargin(_solo);
uint256 marketId = _getMarketIdFromTokenAddress(_solo, Constants.WETH);
WETH(Constants.WETH).approve(
_solo,
_flashloanAmountWETH.add(msg.value)
);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _flashloanAmountWETH);
operations[1] = _getCallAction(
abi.encode(
OSDParams({
mintAmountDAI: _mintAmountDAI,
flashloanAmountWETH: _flashloanAmountWETH,
cdpId: _cdpId,
curvePool: _curvePool
})
)
);
operations[2] = _getDepositAction(
marketId,
_flashloanAmountWETH.add(msg.value)
);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
IERC20(Constants.DAI).transfer(
_sender,
IERC20(Constants.DAI).balanceOf(address(this))
);
IERC20(Constants.USDC).transfer(
_sender,
IERC20(Constants.USDC).balanceOf(address(this))
);
}
| 7,332,849 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract GQGalacticReserve is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Accrued token per share
uint256 public accTokenPerShare;
// The block number when REWARD distribution ends.
uint256 public endBlock;
// The block number when REWARD distribution starts.
uint256 public startBlock;
// The block number of the last pool update
uint256 public lastUpdateBlock;
// REWARD tokens created per block.
uint256 public rewardPerBlock;
// Lockup duration for deposit
uint256 public lockUpDuration;
// Withdraw fee in BP
uint256 public withdrawFee;
// The precision factor
uint256 public PRECISION_FACTOR;
// decimals places of the reward token
uint8 public rewardTokenDecimals;
// Withdraw fee destiny address
address public feeAddress;
// The reward token
IERC20 public rewardToken;
// The staked token
IERC20 public stakedToken;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // Staked tokens the user has provided
uint256 rewardDebt; // Reward debt
uint256 firstDeposit; // First deposit before withdraw
}
event AdminTokenRecovery(address tokenRecovered, uint256 amount);
event Deposit(address indexed user, uint256 amount);
event Claim(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewEndBlock(uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event RewardsStop(uint256 blockNumber);
event Withdraw(address indexed user, uint256 amount);
event NewLockUpDuration(uint256 lockUpDuration);
/*
* @notice Constructor of the contract
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
* @param _rewardPerBlock: reward per block (in rewardToken)
* @param _startBlock: start block
* @param _endBlock: end block
* @param _lockUpDuration: duration for the deposit
* @param _withdrawFee: fee for early withdraw
* @param _feeAddress: address where fees for early withdraw will be send
*/
constructor(
IERC20 _stakedToken,
IERC20 _rewardToken,
uint256 _startBlock,
uint256 _endBlock,
uint256 _lockUpDuration,
uint256 _withdrawFee,
address _feeAddress
) {
stakedToken = _stakedToken;
rewardToken = _rewardToken;
startBlock = _startBlock;
endBlock = _endBlock;
lockUpDuration = _lockUpDuration;
withdrawFee = _withdrawFee;
feeAddress = _feeAddress;
rewardTokenDecimals = IERC20Metadata(address(rewardToken)).decimals();
uint256 decimalsRewardToken = uint256(rewardTokenDecimals);
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken)));
// Set the lastRewardBlock as the startBlock
lastUpdateBlock = startBlock;
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to deposit (in stakedToken)
*/
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_updatePool();
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
if (pending > 0) {
_safeTokenTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
user.amount = user.amount.add(_amount);
stakedToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.firstDeposit = user.firstDeposit == 0
? block.timestamp
: user.firstDeposit;
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(
PRECISION_FACTOR
);
emit Deposit(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
require(_amount > 0, "Error: Invalid amount");
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "Amount to withdraw too high");
_updatePool();
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
uint256 _amountToSend = _amount;
if (block.timestamp < (user.firstDeposit + lockUpDuration)) {
uint256 _feeAmountToSend = _amountToSend.mul(withdrawFee).div(
10000
);
stakedToken.safeTransfer(address(feeAddress), _feeAmountToSend);
_amountToSend = _amountToSend - _feeAmountToSend;
}
stakedToken.safeTransfer(address(msg.sender), _amountToSend);
user.firstDeposit = user.firstDeposit == 0
? block.timestamp
: user.firstDeposit;
if (pending > 0) {
_safeTokenTransfer(msg.sender, pending);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(
PRECISION_FACTOR
);
emit Withdraw(msg.sender, _amount);
}
/*
* @notice Claim reward tokens
*/
function claim() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_updatePool();
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
if (pending > 0) {
_safeTokenTransfer(msg.sender, pending);
emit Claim(msg.sender, pending);
}
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(
PRECISION_FACTOR
);
}
/*
* @notice Withdraw staked tokens without caring about rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 _amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Avoid users send an amount with 0 tokens
if (_amountToTransfer > 0) {
if (block.timestamp < (user.firstDeposit + lockUpDuration)) {
uint256 _feeAmountToSend = _amountToTransfer
.mul(withdrawFee)
.div(10000);
stakedToken.safeTransfer(address(feeAddress), _feeAmountToSend);
_amountToTransfer = _amountToTransfer - _feeAmountToSend;
}
stakedToken.safeTransfer(address(msg.sender), _amountToTransfer);
}
emit EmergencyWithdraw(msg.sender, _amountToTransfer);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
require(
_tokenAddress != address(stakedToken),
"Cannot be staked token"
);
require(
_tokenAddress != address(rewardToken),
"Cannot be reward token"
);
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/*
* @notice Stop rewards
* @dev Only callable by owner
*/
function stopReward() external onlyOwner {
endBlock = block.number;
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(block.number < startBlock, "Pool has started");
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
/**
* @notice It allows the admin to update start and end blocks
* @dev This function is only callable by owner.
* @param _startBlock: the new start block
* @param _bonusEndBlock: the new end block
*/
function updateStartAndEndBlocks(
uint256 _startBlock,
uint256 _bonusEndBlock
) external onlyOwner {
require(block.number < startBlock, "Pool has started");
require(
_startBlock < _bonusEndBlock,
"New startBlock must be lower than new endBlock"
);
require(
block.number < _startBlock,
"New startBlock must be higher than current block"
);
startBlock = _startBlock;
endBlock = _bonusEndBlock;
// Set the lastRewardBlock as the startBlock
lastUpdateBlock = startBlock;
emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock);
}
/*
* @notice Sets the lock up duration
* @param _lockUpDuration: The lock up duration in seconds (block timestamp)
* @dev This function is only callable by owner.
*/
function setLockUpDuration(uint256 _lockUpDuration) external onlyOwner {
lockUpDuration = _lockUpDuration;
emit NewLockUpDuration(lockUpDuration);
}
/*
* @notice Sets start block of the pool given a block amount
* @param _blocks: block amount
* @dev This function is only callable by owner.
*/
function poolStartIn(uint256 _blocks) external onlyOwner {
poolSetStart(block.number.add(_blocks));
}
/*
* @notice Set the duration and start block of the pool
* @param _startBlock: start block
* @param _durationBlocks: duration block amount
* @dev This function is only callable by owner.
*/
function poolSetStartAndDuration(
uint256 _startBlock,
uint256 _durationBlocks
) external onlyOwner {
poolSetStart(_startBlock);
poolSetDuration(_durationBlocks);
}
/*
* @notice Withdraws the remaining funds
* @param _to The address where the funds will be sent
*/
function withdrawRemains(address _to) external onlyOwner {
require(block.number > endBlock, "Error: Pool not finished yet");
uint256 tokenBal = rewardToken.balanceOf(address(this));
require(tokenBal > 0, "Error: No remaining funds");
IERC20(rewardToken).safeTransfer(_to, tokenBal);
}
/*
* @notice Withdraws the remaining funds
* @param _to The address where the funds will be sent
*/
function depositRewardFunds(uint256 _amount) external onlyOwner {
IERC20(rewardToken).safeTransfer(address(this), _amount);
}
/*
* @notice Gets the reward per block for UI
* @return reward per block
*/
function rewardPerBlockUI() external view returns (uint256) {
return rewardPerBlock.div(10**uint256(rewardTokenDecimals));
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (block.number > lastUpdateBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(lastUpdateBlock, block.number);
uint256 tokenReward = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare = accTokenPerShare.add(
tokenReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)
);
return
user
.amount
.mul(adjustedTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
} else {
return
user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(
user.rewardDebt
);
}
}
/*
* @notice Sets start block of the pool
* @param _startBlock: start block
* @dev This function is only callable by owner.
*/
function poolSetStart(uint256 _startBlock) public onlyOwner {
require(block.number < startBlock, "Pool has started");
uint256 rewardDurationValue = rewardDuration();
startBlock = _startBlock;
endBlock = startBlock.add(rewardDurationValue);
lastUpdateBlock = startBlock;
emit NewStartAndEndBlocks(startBlock, endBlock);
}
/*
* @notice Set the duration of the pool
* @param _durationBlocks: duration block amount
* @dev This function is only callable by owner.
*/
function poolSetDuration(uint256 _durationBlocks) public onlyOwner {
require(block.number < startBlock, "Pool has started");
endBlock = startBlock.add(_durationBlocks);
poolCalcRewardPerBlock();
emit NewEndBlock(endBlock);
}
/*
* @notice Calculates the rewardPerBlock of the pool
* @dev This function is only callable by owner.
*/
function poolCalcRewardPerBlock() public onlyOwner {
uint256 rewardBal = rewardToken.balanceOf(address(this));
rewardPerBlock = rewardBal.div(rewardDuration());
}
/*
* @notice Gets the reward duration
* @return reward duration
*/
function rewardDuration() public view returns (uint256) {
return endBlock.sub(startBlock);
}
/*
* @notice SendPending tokens to claimer
* @param pending: amount to claim
*/
function _safeTokenTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBalance = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBalance) {
rewardToken.safeTransfer(_to, rewardTokenBalance);
} else {
rewardToken.safeTransfer(_to, _amount);
}
}
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= lastUpdateBlock) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply == 0) {
lastUpdateBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastUpdateBlock, block.number);
uint256 tokenReward = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(
tokenReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)
);
lastUpdateBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
* @return multiplier
*/
function _getMultiplier(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_to <= endBlock) {
return _to.sub(_from);
} else if (_from >= endBlock) {
return 0;
} else {
return endBlock.sub(_from);
}
}
}
| Calculates the rewardPerBlock of the pool This function is only callable by owner./ | function poolCalcRewardPerBlock() public onlyOwner {
uint256 rewardBal = rewardToken.balanceOf(address(this));
rewardPerBlock = rewardBal.div(rewardDuration());
}
| 5,473,686 |
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MIT
/**
* @title Genesis Voxmon Contract
*/
/*
██╗ ██╗ ██████╗ ██╗ ██╗███╗ ███╗ ██████╗ ███╗ ██╗
██║ ██║██╔═══██╗╚██╗██╔╝████╗ ████║██╔═══██╗████╗ ██║
██║ ██║██║ ██║ ╚███╔╝ ██╔████╔██║██║ ██║██╔██╗ ██║
╚██╗ ██╔╝██║ ██║ ██╔██╗ ██║╚██╔╝██║██║ ██║██║╚██╗██║
╚████╔╝ ╚██████╔╝██╔╝ ██╗██║ ╚═╝ ██║╚██████╔╝██║ ╚████║
╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
//
contract Genesis_Voxmon is ERC721, Ownable {
using Counters for Counters.Counter;
/*
* Global Data space
*/
// This is live supply for clarity because our re-roll mechanism causes one token to be burned
// and a new one to be generated. So some tokens may have a higher tokenId than 10,000
uint16 public constant MAX_SUPPLY = 10000;
Counters.Counter private _tokensMinted;
// count the number of rerolls so we can add to tokensMinted and get new global metadata ID during reroll
Counters.Counter private _tokensRerolled;
uint public constant MINT_COST = 70000000 gwei; // 0.07 ether
uint public constant REROLL_COST = 30000000 gwei; // 0.03 ether
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo public defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
// to avoid rarity sniping this will initially be a centralized domain
// and later updated to IPFS
string public __baseURI = "https://voxmon.io/token/";
// this will let us differentiate that a token has been locked for 3D art visually
string public __lockedBaseURI = "https://voxmon.io/locked/";
// time delay for public minting
// unix epoch time
uint256 public startingTime;
uint256 public artStartTime;
mapping (uint256 => address) internal tokenIdToOwner;
// As a reward to the early community, some members will get a number of free re-rolls
mapping (address => uint16) internal remainingRerolls;
// As a reward to the early community, some members will get free Voxmon
mapping (address => uint16) internal remainingPreReleaseMints;
// keep track of Voxmon which are currently undergoing transformation (staked)
mapping (uint256 => bool) internal tokenIdToFrozenForArt;
// since people can reroll their and we don't want to change the tokenId each time
// we need a mapping to know what metadata to pull from the global set
mapping (uint256 => uint256) internal tokenIdToMetadataId;
event artRequestedEvent(address indexed requestor, uint256 tokenId);
event rerollEvent(address indexed requestor, uint256 tokenId, uint256 newMetadataId);
event mintEvent(address indexed recipient, uint256 tokenId, uint256 metadataId);
// replace these test addresses with real addresses before mint
address[] votedWL = [
0x12C209cFb63bcaEe0E31b76a345FB01E25026c2b,
0x23b65a3239a08365C91f13D1ef7D339Ecd256b2F,
0x306bA4E024B9C36b225e7eb12a26dd80A4b49e77,
0x3Ec23503D26878F364aDD35651f81fe10450e33f,
0x3d8c9E263C24De09C7868E1ABA151cAEe3E77219,
0x4Ba73641d4FC515370A099D6346C295033553485,
0x4DCA116cF962e497BecAe7d441687320b6c66118,
0x50B0595CbA0A8a637E9C6c039b8327211721e686,
0x5161581E963A9463AFd483AcCC710541d5bEe6D0,
0x5A44e7863945A72c32C3C2288a955f4B5BE42F22,
0x5CeDFAE9629fdD41AE7dD25ff64656165526262A,
0x633e6a774F72AfBa0C06b4165EE8cbf18EA0FAe8,
0x6bcD919c30e9FDf3e2b6bB62630e2075185C77C1,
0x6ce3F8a0677D5F758977518f7873D60218C9d7Ef,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0x82b332fdd56d480a33B4Da58D83d5E0E432f1032,
0x83728593e7C362A995b4c51147afeCa5819bbdA1,
0x85eCCd73B4603a960ee84c1ce5bba45e189d2612,
0x87deEE357F9A188aEEbbd666AE11c15031A81cEc,
0x8C8f71d182d2F92794Ea2fCbF357814d09D222C3,
0x8e1ba6ABf60FB207A046B883B36797a9E8882F81,
0x8fC4EC6Aff0D79aCffdC6430987fc299D34959a3,
0x929D99600BB36DDE6385884b857C4B0F05AedE35,
0x94f36E68b33F5542deA92a7cF66478255a769652,
0x9680a866399A49e7E96ACdC3a4dfB8EF492eFE41,
0xA71C24E271394989D61Ac13749683d926A6AB81d,
0xB03BF3Ad1c850F815925767dF20c7e359cd3D033,
0xBDF5678D32631BDC09E412F1c317786e7C6BE5f1,
0xC23735de9dAC1116fb52745B48b8515Aa6955179,
0xF6bD73C1bF387568e2097A813Aa1e833Ca8e7e8C,
0xFC6dcAcA25362a7dD039932e151D21836b8CAB51,
0xa83b5371a3562DD31Fa28f90daE7acF4453Ae126,
0xaE416E324029AcB10367349234c13EDf44b0ddFD,
0xc2A77cdEd0bE8366c0972552B2B9ED9036cb666E,
0xcA7982f1A4d4439211221c3c4e2548298B3D7098,
0xdACc8Ab430B1249F1caa672b412Ac60AfcbFDf66,
0xe64B416c651A02f68566c7C2E38c19FaE820E105,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0xBe18dECE562dC6Ec1ff5d7eda7FdA4f755964481
];
address[] earlyDiscordWL = [
0xfB28A0B0BA53Ccc3F9945af7d7645F6503199e73,
0xFedeA86Ebec8DDE40a2ddD1d156350C62C6697E4,
0x5d6fd8a0D36Bb7E746b19cffBC856724952D1E6e,
0x15E7078D661CbdaC184B696AAC7F666D63490aF6,
0xE4330Acd7bB7777440a9250C7Cf65045052a6640,
0x6278E4FE0e4670eac88014D6326f079B4D02d73c,
0xFAd6EACaf5e3b8eC9E21397AA3b13aDaa138Cc80,
0x5586d438BE5920143c0f9B179835778fa81a544a,
0xcA7982f1A4d4439211221c3c4e2548298B3D7098,
0xdACc8Ab430B1249F1caa672b412Ac60AfcbFDf66,
0x82b332fdd56d480a33B4Da58D83d5E0E432f1032,
0x6bcD919c30e9FDf3e2b6bB62630e2075185C77C1,
0x4DCA116cF962e497BecAe7d441687320b6c66118,
0xaE416E324029AcB10367349234c13EDf44b0ddFD,
0xc2A77cdEd0bE8366c0972552B2B9ED9036cb666E,
0x23b65a3239a08365C91f13D1ef7D339Ecd256b2F,
0xE6E63B3225a3D4B2B6c13F0591DE9452C23242B8,
0xE90D7E0843410A0c4Ff24112D20e7883BF02839b,
0x9680a866399A49e7E96ACdC3a4dfB8EF492eFE41,
0xe64B416c651A02f68566c7C2E38c19FaE820E105,
0x83728593e7C362A995b4c51147afeCa5819bbdA1,
0x7b80B01E4a2b939E1E6AE0D51212b13062352Faa,
0x50B0595CbA0A8a637E9C6c039b8327211721e686,
0x31c979544BAfC22AFCe127FD708CD52838CFEB58,
0xE6ff1989f68b6Fd95b3B9f966d32c9E7d96e6255,
0x72C575aFa7878Bc25A3548E5dC9D1758DB74FD54,
0x5C95a4c6f66964DF324Cc95418f8cC9eD6D25D7c,
0xc96039D0f01724e9C98245ca4B65B235788Ca916,
0x44a3CCddccae339D05200a8f4347F83A58847E52,
0x6e65772Af2F0815b4676483f862e7C116feA195E,
0x4eee5183e2E4b670A7b5851F04255BfD8a4dB230,
0xa950319939098C67176FFEbE9F989aEF11a82DF4,
0x71A0496F59C0e2Bb91E48BEDD97dC233Fe76319F,
0x1B0767772dc52C0d4E031fF0e177cE9d32D25aDB,
0xa9f15D180FA3A8bFD15fbe4D5C956e005AF13D90
];
address[] foundingMemberWL = [
0x4f4EE78b653f0cd2df05a1Fb9c6c2cB2B632d7AA,
0x5CeDFAE9629fdD41AE7dD25ff64656165526262A,
0x0b83B35F90F46d3435D492D7189e179839743770,
0xF6bD73C1bF387568e2097A813Aa1e833Ca8e7e8C,
0x5A44e7863945A72c32C3C2288a955f4B5BE42F22,
0x3d8c9E263C24De09C7868E1ABA151cAEe3E77219,
0x7c4D0a5FC1AeA24d2Bd0285Dd37a352b6795b78B,
0xBe18dECE562dC6Ec1ff5d7eda7FdA4f755964481,
0x2f8c1346082Edcaf1f3B9310560B3D38CA225be8
];
constructor(address payable addr) ERC721("Genesis Voxmon", "VOXMN") {
// setup freebies for people who voted on site
for(uint i = 0; i < votedWL.length; i++) {
remainingRerolls[votedWL[i]] = 10;
}
// setup freebies for people who were active in discord
for(uint i = 0; i < earlyDiscordWL.length; i++) {
remainingRerolls[earlyDiscordWL[i]] = 10;
remainingPreReleaseMints[earlyDiscordWL[i]] = 1;
}
// setup freebies for people who were founding members
for(uint i = 0; i < foundingMemberWL.length; i++) {
remainingRerolls[foundingMemberWL[i]] = 25;
remainingPreReleaseMints[foundingMemberWL[i]] = 5;
}
// setup starting blocknumber (mint date)
// Friday Feb 4th 6pm pst
startingTime = 1644177600;
artStartTime = 1649228400;
// setup royalty address
defaultRoyaltyInfo = RoyaltyInfo(addr, 1000);
}
/*
* Priviledged functions
*/
// update the baseURI of all tokens
// initially to prevent rarity sniping all tokens metadata will come from a cnetralized domain
// and we'll upddate this to IPFS once the mint finishes
function setBaseURI(string calldata uri) external onlyOwner {
__baseURI = uri;
}
// upcate the locked baseURI just like the other one
function setLockedBaseURI(string calldata uri) external onlyOwner {
__lockedBaseURI = uri;
}
// allow us to change the mint date for testing and incase of error
function setStartingTime(uint256 newStartTime) external onlyOwner {
startingTime = newStartTime;
}
// allow us to change the mint date for testing and incase of error
function setArtStartingTime(uint256 newArtStartTime) external onlyOwner {
artStartTime = newArtStartTime;
}
// Withdraw funds in contract
function withdraw(uint _amount) external onlyOwner {
// for security, can only be sent to owner (or should we allow anyone to withdraw?)
address payable receiver = payable(owner());
receiver.transfer(_amount);
}
// value / 10000 (basis points)
function updateDefaultRoyalty(address newAddr, uint96 newPerc) external onlyOwner {
defaultRoyaltyInfo.receiver = newAddr;
defaultRoyaltyInfo.royaltyFraction = newPerc;
}
function updateRoyaltyInfoForToken(uint256 _tokenId, address _receiver, uint96 _amountBasis) external onlyOwner {
require(_amountBasis <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(_receiver != address(0), "ERC2981: invalid parameters");
_tokenRoyaltyInfo[_tokenId] = RoyaltyInfo(_receiver, _amountBasis);
}
/*
* Helper Functions
*/
function _baseURI() internal view virtual override returns (string memory) {
return __baseURI;
}
function _lockedBaseURI() internal view returns (string memory) {
return __lockedBaseURI;
}
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721) returns (bool) {
return ERC721.supportsInterface(interfaceId);
}
// see if minting is still possible
function _isTokenAvailable() internal view returns (bool) {
return _tokensMinted.current() < MAX_SUPPLY;
}
// used for royalty fraction
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/*
* Public View Function
*/
// concatenate the baseURI with the tokenId
function tokenURI(uint256 tokenId) public view virtual override returns(string memory) {
require(_exists(tokenId), "token does not exist");
if (tokenIdToFrozenForArt[tokenId]) {
string memory lockedBaseURI = _lockedBaseURI();
return bytes(lockedBaseURI).length > 0 ? string(abi.encodePacked(lockedBaseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : "";
}
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : "";
}
function getTotalMinted() external view returns (uint256) {
return _tokensMinted.current();
}
function getTotalRerolls() external view returns (uint256) {
return _tokensRerolled.current();
}
// tokenURIs increment with both mints and rerolls
// we use this function in our backend api to avoid trait sniping
function getTotalTokenURIs() external view returns (uint256) {
return _tokensRerolled.current() + _tokensMinted.current();
}
function tokenHasRequested3DArt(uint256 tokenId) external view returns (bool) {
return tokenIdToFrozenForArt[tokenId];
}
function getRemainingRerollsForAddress(address addr) external view returns (uint16) {
return remainingRerolls[addr];
}
function getRemainingPreReleaseMintsForAddress(address addr) external view returns (uint16) {
return remainingPreReleaseMints[addr];
}
function getMetadataIdForTokenId(uint256 tokenId) external view returns (uint256) {
return tokenIdToMetadataId[tokenId];
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = defaultRoyaltyInfo;
}
uint256 _royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, _royaltyAmount);
}
/*
* Public Functions
*/
// Used to request a 3D body for your voxmon
// Freezes transfers re-rolling a voxmon
function request3DArt(uint256 tokenId) external {
require(block.timestamp >= artStartTime, "you cannot freeze your Voxmon yet");
require(ownerOf(tokenId) == msg.sender, "you must own this token to request Art");
require(tokenIdToFrozenForArt[tokenId] == false, "art has already been requested for that Voxmon");
tokenIdToFrozenForArt[tokenId] = true;
emit artRequestedEvent(msg.sender, tokenId);
}
/*
* Payable Functions
*/
// Mint a Voxmon
// Cost is 0.07 ether
function mint(address recipient) payable public returns (uint256) {
require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one");
require(msg.value >= MINT_COST, "not enough ether, minting costs 0.07 ether");
require(block.timestamp >= startingTime, "public mint hasn\'t started yet");
_tokensMinted.increment();
uint256 newTokenId = _tokensMinted.current();
uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();
_mint(recipient, newTokenId);
tokenIdToMetadataId[newTokenId] = metadataId;
emit mintEvent(recipient, newTokenId, metadataId);
return newTokenId;
}
// Mint multiple Voxmon
// Cost is 0.07 ether per Voxmon
function mint(address recipient, uint256 numberToMint) payable public returns (uint256[] memory) {
require(numberToMint > 0);
require(numberToMint <= 10, "max 10 voxmons per transaction");
require(msg.value >= MINT_COST * numberToMint);
uint256[] memory tokenIdsMinted = new uint256[](numberToMint);
for(uint i = 0; i < numberToMint; i++) {
tokenIdsMinted[i] = mint(recipient);
}
return tokenIdsMinted;
}
// Mint a free Voxmon
function preReleaseMint(address recipient) public returns (uint256) {
require(remainingPreReleaseMints[msg.sender] > 0, "you have 0 remaining pre-release mints");
remainingPreReleaseMints[msg.sender] = remainingPreReleaseMints[msg.sender] - 1;
require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one");
_tokensMinted.increment();
uint256 newTokenId = _tokensMinted.current();
uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();
_mint(recipient, newTokenId);
tokenIdToMetadataId[newTokenId] = metadataId;
emit mintEvent(recipient, newTokenId, metadataId);
return newTokenId;
}
// Mint multiple free Voxmon
function preReleaseMint(address recipient, uint256 numberToMint) public returns (uint256[] memory) {
require(remainingPreReleaseMints[msg.sender] >= numberToMint, "You don\'t have enough remaining pre-release mints");
uint256[] memory tokenIdsMinted = new uint256[](numberToMint);
for(uint i = 0; i < numberToMint; i++) {
tokenIdsMinted[i] = preReleaseMint(recipient);
}
return tokenIdsMinted;
}
// Re-Roll a Voxmon
// Cost is 0.01 ether
function reroll(uint256 tokenId) payable public returns (uint256) {
require(ownerOf(tokenId) == msg.sender, "you must own this token to reroll");
require(msg.value >= REROLL_COST, "not enough ether, rerolling costs 0.03 ether");
require(tokenIdToFrozenForArt[tokenId] == false, "this token is frozen");
_tokensRerolled.increment();
uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current();
tokenIdToMetadataId[tokenId] = newMetadataId;
emit rerollEvent(msg.sender, tokenId, newMetadataId);
return newMetadataId;
}
// Re-Roll a Voxmon
// Cost is 0.01 ether
function freeReroll(uint256 tokenId) public returns (uint256) {
require(remainingRerolls[msg.sender] > 0, "you have 0 remaining free rerolls");
remainingRerolls[msg.sender] = remainingRerolls[msg.sender] - 1;
require(ownerOf(tokenId) == msg.sender, "you must own the token to reroll");
require(tokenIdToFrozenForArt[tokenId] == false, "this token is frozen");
_tokensRerolled.increment();
uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current();
tokenIdToMetadataId[tokenId] = newMetadataId;
emit rerollEvent(msg.sender, tokenId, newMetadataId);
return newMetadataId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | allow us to change the mint date for testing and incase of error | function setStartingTime(uint256 newStartTime) external onlyOwner {
startingTime = newStartTime;
}
| 6,156,508 |
./partial_match/1/0x154D245b552e18fE4B135cA7D6224199C3DEC6C9/sources/pussySixNine.sol | 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, "PussyMath: modulo by zero");
return a % b;
}
| 11,023,258 |
./partial_match/1/0xed8B26D99834540C5013701bB3715faFD39993Ba/sources/StabilityPool.sol | withdrawFromSP(): - Triggers a Prisma issuance, based on time passed since the last issuance. The Prisma issuance is shared between all depositors and front ends - Removes the deposit's front end tag if it is a full withdrawal - Sends all depositor's accumulated gains (Prisma, collateral) to depositor - Sends the tagged front end's accumulated Prisma gains to the tagged front end - Decreases deposit and tagged front end's stake, and takes new snapshots for each. If _amount > userDeposit, the user withdraws all of their compounded deposit./ | function withdrawFromSP(uint256 _amount) external {
uint256 initialDeposit = accountDeposits[msg.sender].amount;
uint128 depositTimestamp = accountDeposits[msg.sender].timestamp;
require(initialDeposit > 0, "StabilityPool: User must have a non-zero deposit");
require(depositTimestamp < block.timestamp, "!Deposit and withdraw same block");
_triggerRewardIssuance();
_accrueDepositorCollateralGain(msg.sender);
uint256 compoundedDebtDeposit = getCompoundedDebtDeposit(msg.sender);
uint256 debtToWithdraw = PrismaMath._min(_amount, compoundedDebtDeposit);
_accrueRewards(msg.sender);
if (debtToWithdraw > 0) {
debtToken.returnFromPool(address(this), msg.sender, debtToWithdraw);
_decreaseDebt(debtToWithdraw);
}
_updateSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
}
| 15,775,907 |
pragma solidity ^0.4.25;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract RepublicToken is PausableToken, BurnableToken {
string public constant name = "Republic Token";
string public constant symbol = "REN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
/// @notice The RepublicToken Constructor.
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
/* solium-disable error-reason */
require(amount > 0);
balances[owner] = balances[owner].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Transfer(owner, beneficiary, amount);
return true;
}
}
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = 0x0;
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping (address => Node) list;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].previous;
}
}
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RepublicToken.
RepublicToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RepublicToken contract.
constructor(
string _VERSION,
RepublicToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address _darknodeOwner,
uint256 _bond,
bytes _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner, bond), "bond transfer failed");
}
/// @notice Updates the bond of the darknode. If the bond is being
/// decreased, the difference is sent to the owner of this contract.
function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
darknodeRegistry[darknodeID].bond = bond;
if (previousBond > bond) {
require(ren.transfer(owner, previousBond - bond), "cannot transfer bond");
}
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOwner(address darknodeID) external view onlyOwner returns (address) {
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) {
return darknodeRegistry[darknodeID].publicKey;
}
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocknumber;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
address public slasher;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
address public nextSlasher;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RepublicToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// @notice Emitted when a darknode is registered.
/// @param _darknodeID The darknode ID that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(address _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeID The darknode ID that was deregistered.
event LogDarknodeDeregistered(address _darknodeID);
/// @notice Emitted when a refund has been made.
/// @param _owner The address that was refunded.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeOwnerRefunded(address _owner, uint256 _amount);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch();
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
/// @notice Only allow the owner that registered the darknode to pass.
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner");
_;
}
/// @notice Only allow unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "must be refunded or never registered");
_;
}
/// @notice Only allow refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "must be deregistered for at least one epoch");
_;
}
/// @notice Only allowed registered nodes without a pending deregistration to
/// deregister
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "must be deregisterable");
_;
}
/// @notice Only allow the Slasher contract.
modifier onlySlasher() {
require(slasher == msg.sender, "must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RepublicToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochInterval The minimum number of blocks between
/// epochs.
constructor(
string _VERSION,
RepublicToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochInterval
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochInterval;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocknumber: block.number
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
/// @notice Register a darknode and transfer the bond to this contract. The
/// caller must provide a public encryption key for the darknode as well as
/// a bond in REN. The bond must be provided as an ERC20 allowance. The dark
/// node will remain pending registration until the next epoch. Only after
/// this period can the darknode be deregistered. The caller of this method
/// will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
/// @param _bond The bond that will be paid. It must be greater than, or
/// equal to, the minimum bond.
function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) {
// REN allowance
require(_bond >= minimumBond, "insufficient bond");
// require(ren.allowance(msg.sender, address(this)) >= _bond);
require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed");
ren.transfer(address(store), _bond);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
_bond,
_publicKey,
currentEpoch.blocknumber + minimumEpochInterval,
0
);
numDarknodesNextEpoch += 1;
// Emit an event.
emit LogDarknodeRegistered(_darknodeID, _bond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method store.darknodeRegisteredAt(_darknodeID) must be
// the owner of this darknode.
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
// Emit an event
emit LogDarknodeDeregistered(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocknumber == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner, "not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(slasher, nextSlasher);
}
// Emit an event
emit LogNewEpoch();
}
/// @notice Allows the contract owner to transfer ownership of the
/// DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(address _slasher) external onlyOwner {
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's
/// bond and deregister it. The bond is distributed as follows:
/// 1/2 is kept by the guilty prover
/// 1/8 is rewarded to the first challenger
/// 1/8 is rewarded to the second challenger
/// 1/4 becomes unassigned
/// @param _prover The guilty prover whose bond is being slashed
/// @param _challenger1 The first of the two darknodes who submitted the challenge
/// @param _challenger2 The second of the two darknodes who submitted the challenge
function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
// Slash the bond of the failed prover in half
store.updateDarknodeBond(_prover, penalty);
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_prover)) {
store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
emit LogDarknodeDeregistered(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
ren.transfer(store.darknodeOwner(_challenger1), reward);
ren.transfer(store.darknodeOwner(_challenger2), reward);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
ren.transfer(darknodeOwner, amount);
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOwner(address _darknodeID) external view returns (address) {
return store.darknodeOwner(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID) external view returns (bytes) {
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch
function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == 0x0) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == 0x0) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/// @notice Implements safeTransfer, safeTransferFrom and
/// safeApprove for CompatibleERC20.
///
/// See https://github.com/ethereum/solidity/issues/4116
///
/// This library allows interacting with ERC20 tokens that implement any of
/// these interfaces:
///
/// (1) transfer returns true on success, false on failure
/// (2) transfer returns true on success, reverts on failure
/// (3) transfer returns nothing on success, reverts on failure
///
/// Additionally, safeTransferFromWithFees will return the final token
/// value received after accounting for token fees.
library CompatibleERC20Functions {
using SafeMath for uint256;
/// @notice Calls transfer on the token and reverts if the call fails.
function safeTransfer(address token, address to, uint256 amount) internal {
CompatibleERC20(token).transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
/// @notice Calls transferFrom on the token and reverts if the call fails.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
/// @notice Calls approve on the token and reverts if the call fails.
function safeApprove(address token, address spender, uint256 amount) internal {
CompatibleERC20(token).approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = CompatibleERC20(token).balanceOf(to);
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = CompatibleERC20(token).balanceOf(to);
return Math.min256(amount, balancesAfter.sub(balancesBefore));
}
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes.
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0x0, 0x0, 32)
// Load the return data into returnData
returnData := mload(0x0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/// @notice ERC20 interface which doesn't specify the return type for transfer,
/// transferFrom and approve.
interface CompatibleERC20 {
// Modified to not return boolean
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
// Not modifier
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @notice The DarknodeRewardVault contract is responsible for holding fees
/// for darknodes for settling orders. Fees can be withdrawn to the address of
/// the darknode's operator. Fees can be in ETH or in ERC20 tokens.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md
contract DarknodeRewardVault is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry;
mapping(address => mapping(address => uint256)) public darknodeBalances;
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The DarknodeRegistry contract that is used by
/// the vault to lookup Darknode owners.
constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Deposit fees into the vault for a Darknode. The Darknode
/// registration is not checked (to reduce gas fees); the caller must be
/// careful not to call this function for a Darknode that is not registered
/// otherwise any fees deposited to that Darknode can be withdrawn by a
/// malicious adversary (by registering the Darknode before the honest
/// party and claiming ownership).
///
/// @param _darknode The address of the Darknode that will receive the
/// fees.
/// @param _token The address of the ERC20 token being used to pay the fee.
/// A special address is used for Ether.
/// @param _value The amount of fees in the smallest unit of the token.
function deposit(address _darknode, ERC20 _token, uint256 _value) public payable {
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched ether value");
} else {
require(msg.value == 0, "unexpected ether value");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value);
}
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue);
}
/// @notice Withdraw fees earned by a Darknode. The fees will be sent to
/// the owner of the Darknode. If a Darknode is not registered the fees
/// cannot be withdrawn.
///
/// @param _darknode The address of the Darknode whose fees are being
/// withdrawn. The owner of this Darknode will receive the fees.
/// @param _token The address of the ERC20 token to withdraw.
function withdraw(address _darknode, ERC20 _token) public {
address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode));
require(darknodeOwner != 0x0, "invalid darknode owner");
uint256 value = darknodeBalances[_darknode][_token];
darknodeBalances[_darknode][_token] = 0;
if (address(_token) == ETHEREUM) {
darknodeOwner.transfer(value);
} else {
CompatibleERC20(_token).safeTransfer(darknodeOwner, value);
}
}
} | Burns a specific amount of tokens. _value The amount of token to be burned./ | function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
| 13,722 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* __ __ _
* | \/ | ___ _ __ ___| |_ ___ _ __
* | |\/| |/ _ \| '_ \/ __| __/ _ \ '__|
* | | | | (_) | | | \__ \ || __/ |
* |_|__|_|\___/|_| |_|___/\__\___|_|_ _
* / ___| __ _| |_ ___ ___| |__ (_) |__ | | ___ ___
* \___ \ / _` | __/ _ \/ __| '_ \| | '_ \| |/ _ \/ __|
* ___) | (_| | || (_) \__ \ | | | | |_) | | __/\__ \
* |____/ \__,_|\__\___/|___/_| |_|_|_.__/|_|\___||___/
*
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "./MerkleProof.sol";
/**
* @notice Original Satoshibles contract interface
*/
interface ISatoshible {
function ownerOf(
uint256 _tokenId
)
external
view
returns (address owner);
}
/**
* @title Monster Satoshibles
* @notice NFT of monsters that can be burned and combined into prime monsters!
* @author Aaron Hanson
*/
contract MonsterSatoshible is ERC721, ERC2981ContractWideRoyalties, Ownable {
/// The max token supply
uint256 public constant MAX_SUPPLY = 6666;
/// The presale portion of the max supply
uint256 public constant MAX_PRESALE_SUPPLY = 3333;
/// Mysterious constants 💀
uint256 constant DEATH = 0xDEAD;
uint256 constant LIFE = 0x024350AC;
uint256 constant ALPHA = LIFE % DEATH * 1000;
uint256 constant OMEGA = LIFE % DEATH + ALPHA;
/// Prime types
uint256 constant FRANKENSTEIN = 0;
uint256 constant WEREWOLF = 1;
uint256 constant VAMPIRE = 2;
uint256 constant ZOMBIE = 3;
uint256 constant INVALID = 4;
/// Number of prime parts
uint256 constant NUM_PARTS = 4;
/// Bitfield mask for prime part detection during prime minting
uint256 constant HAS_ALL_PARTS = 2 ** NUM_PARTS - 1;
/// Merkle root summarizing the presale whitelist
bytes32 public constant WHITELIST_MERKLE_ROOT =
0xdb6eea27a6a35a02d1928e9582f75c1e0a518ad5992b5cfee9cc0d86fb387b8d;
/// Additional team wallets (can withdraw)
address public constant TEAM_WALLET_A =
0xF746362D8162Eeb3624c17654FFAa6EB8bD71820;
address public constant TEAM_WALLET_B =
0x16659F9D2ab9565B0c07199687DE3634c0965391;
address public constant TEAM_WALLET_C =
0x7a73f770873761054ab7757E909ae48f771379D4;
address public constant TEAM_WALLET_D =
0xB7c7e3809591F720f3a75Fb3efa05E76E6B7B92A;
/// The maximum ERC-2981 royalties percentage
uint256 public constant MAX_ROYALTIES_PCT = 600;
/// Original Satoshibles contract instance
ISatoshible public immutable SATOSHIBLE_CONTRACT;
/// The max presale token ID
uint256 public immutable MAX_PRESALE_TOKEN_ID;
/// The current token supply
uint256 public totalSupply;
/// The current state of the sale
bool public saleIsActive;
/// Indicates if the public sale was opened manually
bool public publicSaleOpenedEarly;
/// The default and discount token prices in wei
uint256 public tokenPrice = 99900000000000000; // 0.0999 ether
uint256 public discountPrice = 66600000000000000; // 0.0666 ether
/// Tracks number of presale mints already used per address
mapping(address => uint256) public whitelistMintsUsed;
/// The current state of the laboratory
bool public laboratoryHasElectricity;
/// Merkle root summarizing all monster IDs and their prime parts
bytes32 public primePartsMerkleRoot;
/// The provenance URI
string public provenanceURI = "Not Yet Set";
/// When true, the provenanceURI can no longer be changed
bool public provenanceUriLocked;
/// The base URI
string public baseURI = "https://api.satoshibles.com/monsters/token/";
/// When true, the baseURI can no longer be changed
bool public baseUriLocked;
/// Use Counters for token IDs
using Counters for Counters.Counter;
/// Monster token ID counter
Counters.Counter monsterIds;
/// Prime token ID counter for each prime type
mapping(uint256 => Counters.Counter) primeIds;
/// Prime ID offsets for each prime type
mapping(uint256 => uint256) primeIdOffset;
/// Bitfields that track original Satoshibles already used for discounts
mapping(uint256 => uint256) satDiscountBitfields;
/// Bitfields that track original Satoshibles already used in lab
mapping(uint256 => uint256) satLabBitfields;
/**
* @notice Emitted when the saleIsActive flag changes
* @param isActive Indicates whether or not the sale is now active
*/
event SaleStateChanged(
bool indexed isActive
);
/**
* @notice Emitted when the public sale is opened early
*/
event PublicSaleOpenedEarly();
/**
* @notice Emitted when the laboratoryHasElectricity flag changes
* @param hasElectricity Indicates whether or not the laboratory is open
*/
event LaboratoryStateChanged(
bool indexed hasElectricity
);
/**
* @notice Emitted when a prime is created in the lab
* @param creator The account that created the prime
* @param primeId The ID of the prime created
* @param satId The Satoshible used as the 'key' to the lab
* @param monsterIdsBurned The IDs of the monsters burned
*/
event PrimeCreated(
address indexed creator,
uint256 indexed primeId,
uint256 indexed satId,
uint256[4] monsterIdsBurned
);
/**
* @notice Requires the specified Satoshible to be owned by msg.sender
* @param _satId Original Satoshible token ID
*/
modifier onlySatHolder(
uint256 _satId
) {
require(
SATOSHIBLE_CONTRACT.ownerOf(_satId) == _msgSender(),
"Sat not owned"
);
_;
}
/**
* @notice Requires msg.sender to be the owner or a team wallet
*/
modifier onlyTeam() {
require(
_msgSender() == TEAM_WALLET_A
|| _msgSender() == TEAM_WALLET_B
|| _msgSender() == TEAM_WALLET_C
|| _msgSender() == TEAM_WALLET_D
|| _msgSender() == owner(),
"Not owner or team address"
);
_;
}
/**
* @notice Boom... Let's go!
* @param _initialBatchCount Number of tokens to mint to msg.sender
* @param _immutableSatoshible Original Satoshible contract address
* @param _royaltiesPercentage Initial royalties percentage for ERC-2981
*/
constructor(
uint256 _initialBatchCount,
address _immutableSatoshible,
uint256 _royaltiesPercentage
)
ERC721("Monster Satoshibles", "MSBLS")
{
SATOSHIBLE_CONTRACT = ISatoshible(
_immutableSatoshible
);
require(
_royaltiesPercentage <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_msgSender(),
_royaltiesPercentage
);
_initializePrimeIdOffsets();
_initializeSatDiscountAvailability();
_initializeSatLabAvailability();
_mintTokens(_initialBatchCount);
require(
belowMaximum(_initialBatchCount, MAX_PRESALE_SUPPLY,
MAX_SUPPLY
) == true,
"Would exceed max supply"
);
unchecked {
MAX_PRESALE_TOKEN_ID = _initialBatchCount + MAX_PRESALE_SUPPLY;
}
}
/**
* @notice Mints monster tokens during presale, optionally with discounts
* @param _numberOfTokens Number of tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
* @param _whitelistedTokens Account's total number of whitelisted tokens
* @param _proof Merkle proof to be verified
*/
function mintTokensPresale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
external
payable
{
require(
publicSaleOpenedEarly == false,
"Presale has ended"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_PRESALE_TOKEN_ID
) == true,
"Would exceed presale size"
);
require(
belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens,
_whitelistedTokens
) == true,
"Would exceed whitelisted count"
);
require(
verifyWhitelisted(_msgSender(), _whitelistedTokens,
_proof
) == true,
"Invalid whitelist proof"
);
whitelistMintsUsed[_msgSender()] += _numberOfTokens;
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints monsters during public sale, optionally with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function mintTokensPublicSale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
external
payable
{
require(
publicSaleOpened() == true,
"Public sale has not started"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_SUPPLY
) == true,
"Not enough tokens left"
);
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints a prime token by burning two or more monster tokens
* @param _primeType Prime type to mint
* @param _satId Original Satoshible token ID to use as 'key' to the lab
* @param _monsterIds Array of monster token IDs to potentially be burned
* @param _monsterPrimeParts Array of bitfields of monsters' prime parts
* @param _proofs Array of merkle proofs to be verified
*/
function mintPrimeToken(
uint256 _primeType,
uint256 _satId,
uint256[] calldata _monsterIds,
uint256[] calldata _monsterPrimeParts,
bytes32[][] calldata _proofs
)
external
onlySatHolder(_satId)
{
require(
laboratoryHasElectricity == true,
"Prime laboratory not yet open"
);
require(
_primeType < INVALID,
"Invalid prime type"
);
require(
belowMaximum(
primeIdOffset[_primeType],
primeIds[_primeType].current() + 1,
primeIdOffset[_primeType + 1]
) == true,
"No more primes left of this type"
);
require(
satIsAvailableForLab(_satId) == true,
"Sat has already been used in lab"
);
// bitfield tracking aggregate parts across monsters
// (head = 1, eyes = 2, mouth = 4, body = 8)
uint256 combinedParts;
uint256[4] memory burnedIds;
unchecked {
uint256 burnedIndex;
for (uint256 i = 0; i < _monsterIds.length; i++) {
require(
verifyMonsterPrimeParts(
_monsterIds[i],
_monsterPrimeParts[i],
_proofs[i]
) == true,
"Invalid monster traits proof"
);
uint256 theseParts = _monsterPrimeParts[i]
>> (_primeType * NUM_PARTS) & HAS_ALL_PARTS;
if (combinedParts | theseParts != combinedParts) {
_burn(
_monsterIds[i]
);
burnedIds[burnedIndex++] = _monsterIds[i];
combinedParts |= theseParts;
if (combinedParts == HAS_ALL_PARTS) {
break;
}
}
}
}
require(
combinedParts == HAS_ALL_PARTS,
"Not enough parts for this prime"
);
_retireSatFromLab(_satId);
primeIds[_primeType].increment();
unchecked {
uint256 primeId = primeIdOffset[_primeType]
+ primeIds[_primeType].current();
totalSupply++;
_safeMint(
_msgSender(),
primeId
);
emit PrimeCreated(
_msgSender(),
primeId,
_satId,
burnedIds
);
}
}
/**
* @notice Activates or deactivates the sale
* @param _isActive Whether to activate or deactivate the sale
*/
function activateSale(
bool _isActive
)
external
onlyOwner
{
saleIsActive = _isActive;
emit SaleStateChanged(
_isActive
);
}
/**
* @notice Starts the public sale before MAX_PRESALE_TOKEN_ID is minted
*/
function openPublicSaleEarly()
external
onlyOwner
{
publicSaleOpenedEarly = true;
emit PublicSaleOpenedEarly();
}
/**
* @notice Modifies the prices in case of major ETH price changes
* @param _tokenPrice The new default token price
* @param _discountPrice The new discount token price
*/
function updateTokenPrices(
uint256 _tokenPrice,
uint256 _discountPrice
)
external
onlyOwner
{
require(
_tokenPrice >= _discountPrice,
"discountPrice cannot be larger"
);
require(
saleIsActive == false,
"Sale is active"
);
tokenPrice = _tokenPrice;
discountPrice = _discountPrice;
}
/**
* @notice Sets primePartsMerkleRoot summarizing all monster prime parts
* @param _merkleRoot The new merkle root
*/
function setPrimePartsMerkleRoot(
bytes32 _merkleRoot
)
external
onlyOwner
{
primePartsMerkleRoot = _merkleRoot;
}
/**
* @notice Turns the laboratory on or off
* @param _hasElectricity Whether to turn the laboratory on or off
*/
function electrifyLaboratory(
bool _hasElectricity
)
external
onlyOwner
{
laboratoryHasElectricity = _hasElectricity;
emit LaboratoryStateChanged(
_hasElectricity
);
}
/**
* @notice Mints the final prime token
*/
function mintFinalPrime()
external
onlyOwner
{
require(
_exists(OMEGA) == false,
"Final prime already exists"
);
unchecked {
totalSupply++;
}
_safeMint(
_msgSender(),
OMEGA
);
}
/**
* @notice Sets the provenance URI
* @param _newProvenanceURI The new provenance URI
*/
function setProvenanceURI(
string calldata _newProvenanceURI
)
external
onlyOwner
{
require(
provenanceUriLocked == false,
"Provenance URI has been locked"
);
provenanceURI = _newProvenanceURI;
}
/**
* @notice Prevents further changes to the provenance URI
*/
function lockProvenanceURI()
external
onlyOwner
{
provenanceUriLocked = true;
}
/**
* @notice Sets a new base URI
* @param _newBaseURI The new base URI
*/
function setBaseURI(
string calldata _newBaseURI
)
external
onlyOwner
{
require(
baseUriLocked == false,
"Base URI has been locked"
);
baseURI = _newBaseURI;
}
/**
* @notice Prevents further changes to the base URI
*/
function lockBaseURI()
external
onlyOwner
{
baseUriLocked = true;
}
/**
* @notice Withdraws sale proceeds
* @param _amount Amount to withdraw in wei
*/
function withdraw(
uint256 _amount
)
external
onlyTeam
{
payable(_msgSender()).transfer(
_amount
);
}
/**
* @notice Withdraws any other tokens
* @dev WARNING: Double check token is legit before calling this
* @param _token Contract address of token
* @param _to Address to which to withdraw
* @param _amount Amount to withdraw
* @param _hasVerifiedToken Must be true (sanity check)
*/
function withdrawOther(
address _token,
address _to,
uint256 _amount,
bool _hasVerifiedToken
)
external
onlyOwner
{
require(
_hasVerifiedToken == true,
"Need to verify token"
);
IERC20(_token).transfer(
_to,
_amount
);
}
/**
* @notice Sets token royalties (ERC-2981)
* @param _recipient Recipient of the royalties
* @param _value Royalty percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function setRoyalties(
address _recipient,
uint256 _value
)
external
onlyOwner
{
require(
_value <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_recipient,
_value
);
}
/**
* @notice Checks which Satoshibles can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForDiscountMint(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForDiscountMint(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks which Satoshibles can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForLab(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForLab(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks if a Satoshible can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can be used for a discounted mint
*/
function satIsAvailableForDiscountMint(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satDiscountBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Checks if a Satoshible can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can still be used to mint a prime
*/
function satIsAvailableForLab(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satLabBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Verifies a merkle proof for a monster ID and its prime parts
* @param _monsterId Monster token ID
* @param _monsterPrimeParts Bitfield of the monster's prime parts
* @param _proof Merkle proof be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyMonsterPrimeParts(
uint256 _monsterId,
uint256 _monsterPrimeParts,
bytes32[] calldata _proof
)
public
view
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_monsterId,
_monsterPrimeParts
)
);
isVerified = MerkleProof.verify(
_proof,
primePartsMerkleRoot,
node
);
}
/**
* @notice Gets total count of existing prime tokens for a prime type
* @param _primeType Prime type
* @return supply Count of existing prime tokens for this prime type
*/
function primeSupply(
uint256 _primeType
)
public
view
returns (uint256 supply)
{
supply = primeIds[_primeType].current();
}
/**
* @notice Gets total count of existing prime tokens
* @return supply Count of existing prime tokens
*/
function totalPrimeSupply()
public
view
returns (uint256 supply)
{
unchecked {
supply = primeSupply(FRANKENSTEIN)
+ primeSupply(WEREWOLF)
+ primeSupply(VAMPIRE)
+ primeSupply(ZOMBIE)
+ (_exists(OMEGA) ? 1 : 0);
}
}
/**
* @notice Gets total count of monsters burned
* @return burned Count of monsters burned
*/
function monstersBurned()
public
view
returns (uint256 burned)
{
unchecked {
burned = monsterIds.current() + totalPrimeSupply() - totalSupply;
}
}
/**
* @notice Gets state of public sale
* @return publicSaleIsOpen True if public sale phase has begun
*/
function publicSaleOpened()
public
view
returns (bool publicSaleIsOpen)
{
publicSaleIsOpen =
publicSaleOpenedEarly == true ||
monsterIds.current() >= MAX_PRESALE_TOKEN_ID;
}
/// @inheritdoc ERC165
function supportsInterface(
bytes4 _interfaceId
)
public
view
override (ERC721, ERC2981Base)
returns (bool doesSupportInterface)
{
doesSupportInterface = super.supportsInterface(_interfaceId);
}
/**
* @notice Verifies a merkle proof for an account's whitelisted tokens
* @param _account Account to verify
* @param _whitelistedTokens Number of whitelisted tokens for _account
* @param _proof Merkle proof to be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyWhitelisted(
address _account,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
public
pure
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_account,
_whitelistedTokens
)
);
isVerified = MerkleProof.verify(
_proof,
WHITELIST_MERKLE_ROOT,
node
);
}
/**
* @dev Base monster burning function
* @param _tokenId Monster token ID to burn
*/
function _burn(
uint256 _tokenId
)
internal
override
{
require(
_isApprovedOrOwner(_msgSender(), _tokenId) == true,
"not owner nor approved"
);
unchecked {
totalSupply -= 1;
}
super._burn(
_tokenId
);
}
/**
* @dev Base URI for computing tokenURI
* @return Base URI string
*/
function _baseURI()
internal
view
override
returns (string memory)
{
return baseURI;
}
/**
* @dev Base monster minting function, calculates price with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function _doMintTokens(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
private
{
require(
saleIsActive == true,
"Sale must be active"
);
require(
_numberOfTokens >= 1,
"Need at least 1 token"
);
require(
_numberOfTokens <= 50,
"Max 50 at a time"
);
require(
_satsForDiscount.length <= _numberOfTokens,
"Too many sats for discount"
);
unchecked {
uint256 discountIndex;
for (; discountIndex < _satsForDiscount.length; discountIndex++) {
_useSatForDiscountMint(_satsForDiscount[discountIndex]);
}
uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex)
+ discountPrice * discountIndex;
require(
totalPrice == msg.value,
"Ether amount not correct"
);
}
_mintTokens(
_numberOfTokens
);
}
/**
* @dev Base monster minting function.
* @param _numberOfTokens Number of monster tokens to mint
*/
function _mintTokens(
uint256 _numberOfTokens
)
private
{
unchecked {
totalSupply += _numberOfTokens;
for (uint256 i = 0; i < _numberOfTokens; i++) {
monsterIds.increment();
_safeMint(
_msgSender(),
monsterIds.current()
);
}
}
}
/**
* @dev Marks a Satoshible ID as having been used for a discounted mint
* @param _satId Satoshible ID that was used for a discounted mint
*/
function _useSatForDiscountMint(
uint256 _satId
)
private
onlySatHolder(_satId)
{
require(
satIsAvailableForDiscountMint(_satId) == true,
"Sat for discount already used"
);
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satDiscountBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Marks a Satoshible ID as having been used to mint a prime
* @param _satId Satoshible ID that was used to mint a prime
*/
function _retireSatFromLab(
uint256 _satId
)
private
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satLabBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Initializes prime token ID offsets
*/
function _initializePrimeIdOffsets()
private
{
unchecked {
primeIdOffset[FRANKENSTEIN] = ALPHA;
primeIdOffset[WEREWOLF] = ALPHA + 166;
primeIdOffset[VAMPIRE] = ALPHA + 332;
primeIdOffset[ZOMBIE] = ALPHA + 498;
primeIdOffset[INVALID] = ALPHA + 665;
}
}
/**
* @dev Initializes bitfields of Satoshibles available for discounted mints
*/
function _initializeSatDiscountAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satDiscountBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Initializes bitfields of Satoshibles available to mint primes
*/
function _initializeSatLabAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satLabBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Helper function used for token ID range checks when minting
* @param _currentValue Current token ID counter value
* @param _incrementValue Number of tokens to increment by
* @param _maximumValue Maximum token ID value allowed
* @return isBelowMaximum True if _maximumValue is not exceeded
*/
function belowMaximum(
uint256 _currentValue,
uint256 _incrementValue,
uint256 _maximumValue
)
private
pure
returns (bool isBelowMaximum)
{
unchecked {
isBelowMaximum = _currentValue + _incrementValue <= _maximumValue;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
)
internal
pure
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981Base.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// @dev This implementation has the same royalties for each and every tokens
abstract contract ERC2981ContractWideRoyalties is ERC2981Base {
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param _recipient recipient of the royalties
/// @param _value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(
address _recipient,
uint256 _value
)
internal
{
require(_value <= 10000, "ERC2981Royalties: Too high");
_royalties = RoyaltyInfo(_recipient, uint24(_value));
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(
uint256,
uint256 _value
)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (_value * royalties.amount) / 10000;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC2981Royalties.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
abstract contract ERC2981Base is ERC165, IERC2981Royalties {
struct RoyaltyInfo {
address recipient;
uint24 amount;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| Helper function used for token ID range checks when minting _currentValue Current token ID counter value _incrementValue Number of tokens to increment by _maximumValue Maximum token ID value allowed return isBelowMaximum True if _maximumValue is not exceeded/ | function belowMaximum(
uint256 _currentValue,
uint256 _incrementValue,
uint256 _maximumValue
)
private
pure
returns (bool isBelowMaximum)
{
unchecked {
isBelowMaximum = _currentValue + _incrementValue <= _maximumValue;
}
}
| 7,321,267 |
./full_match/4/0x7C383E9578da9f6068532bd0d4a2c1De34516B96/sources/contracts/Mainnet/V1_Vanilla/CryptographFactoryLogicV1.sol | Init function of the Cryptograph Factory Callable only once after deployment _officialPublisher The address that perpetual altruism will be using consistently through all deployments _targetVC The address of the proxied Version Control _targetAuctionHouse The address of the proxied Auction House _targetIndex The address of the proxied Index _targetCryLogicVersion The code index of TheCryptographLogicV1 in the version control _targetAuctionLogicVersion The code index of SingleAuctionLogicV1 in the version control _targetAuctionBidLogicVersion The code index of SingleAuctionBidLogicV1 in the version control _targetMintingAuctionLogicVersion The code index of MintingAuctionLogicV1 in the version control | function init(
address _officialPublisher,
address _targetVC,
address _targetAuctionHouse,
address _targetIndex,
uint256 _targetCryLogicVersion,
uint256 _targetAuctionLogicVersion,
uint256 _targetAuctionBidLogicVersion,
uint256 _targetMintingAuctionLogicVersion
) external {
unchecked {
require(!initialized, "The Cryptograph Factory has already been initialized");
initialized = true;
officialPublisher = _officialPublisher;
targetVC = _targetVC;
targetAuctionHouse = _targetAuctionHouse;
targetIndex = _targetIndex;
targetCryLogicVersion = _targetCryLogicVersion;
targetAuctionLogicVersion = _targetAuctionLogicVersion;
targetAuctionBidLogicVersion = _targetAuctionBidLogicVersion;
targetMintingAuctionLogicVersion = _targetMintingAuctionLogicVersion;
communityMintable = false;
}
}
| 13,351,165 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/.../Context.sol";
import "https://github.com/vigilance91/solidarity/contracts/accessControl/AccessControl.sol";
import "https://github.com/vigilance91/solidarity/libraries/bytes32/Bytes32Logic.sol";
import "https://github.com/vigilance91/solidarity/libraries/address/AddressConstraints.sol";
import "https://github.com/vigilance91/solidarity/libraries/address/addressToString.sol";
import "./iEIP1753.sol";
import "./eventsEIP1753.sol";
//import "https://github.com/vigilance91/solidarity/EIP/token/license/iEIP1753.sol";
//import "https://github.com/vigilance91/solidarity/EIP/token/license/eventsEIP1753.sol";
import "https://github.com/vigilance91/solidarity/contracts/token/StaticSupplyTokenABC.sol";
///
/// @title EIP-1753 License Library
/// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 2/4/2021, All Rights Reserved
/// @dev Ethereum Improvments Proposal: Smart Contract Interface for Licences[sic]: https://eips.ethereum.org/EIPS/eip-1753
///
library mixinEIP1753
{
using LogicConstraints for bool;
////using nowMath for uint;
////using BlockTime for uint;
using Bytes32Logic for bytes32;
using AddressConstraints for address;
using addressToString for address;
using stringUtilities for string;
//using bytes32Logic for bytes32;
using eventsEIP1753 for address;
using SafeMath for uint;
//using BlockTimeConstraints for uint;
//bytes32 private constant _HASH = keccak256(address(this).hexadecimal());
struct LicenseStorage{
address issuer; //address which issued the license
//hash of the issuer's address and the licensee/license owner's address (for verification of ownership)
bytes32 hash;
//note similarity with EIP-801 Carnary Standard
uint issuedBlock;
uint terminationBlock;
//
uint issuedTime;
uint terminationTime;
//
bool initalized;
}
function requireInitialized(
LicenseStorage storage self
)internal view
{
self.initalized.requireTrue(
//'not initialized'
);
}
function isValidIssuer(
LicenseStorage storage self,
address owner
)internal view returns(
bool
){
self.issuer.requireNotEqualAndNotNull(owner);
return self.issuer.hexadecimal().saltAndHash(
owner.hexadecimal()
).equal(self.hash);
}
function isValidTime(
LicenseStorage storage self,
uint time
)internal view returns(
bool
){
//if(time.greaterThan(self.issuedTime) &&
//time.lessThan(self.terminationTime)
//){
//return true;
//}
return false;
}
function isValidBlock(
LicenseStorage storage self,
uint blockNumber
)internal view returns(
bool
){
//if(blockNumber.greaterThan(self.issuedBlock) &&
//blockNumber.lessThan(self.terminationBlock)
//){
//return true;
//}
return false;
}
function isValid(
LicenseStorage storage self,
address owner
)internal returns(
bool
){
requireInitialized(self);
if(isValidIssuer(self, owner) &&
isValidTime(self, block.timestamp) &&
isValidBlock(self, block.number)
){
return true;
}
return false;
}
//function requireNotInitialized(
//LicenseStorage storage self
//)internal view
//{
//self.initalized.requireFalse('License already initialized');
//}
//function requireInitialized(
//LicenseStorage storage self
//)internal view
//{
//self.initalized.requireTrue('license is not initialized');
//}
//initialize License starting NOW for some duration into the future
function initialize(
LicenseStorage storage self,
address sender,
address licensee,
uint startTime,
uint expireTime
)internal //returns(
//LicenseStorage storage
//)
{
//requireNotInitialized(self);
//issuing authority can not issue licenses to themselves
//sender.requireNotNullAndNotEqual(
//licensee
//);
//startTime.requireGreaterThanZero();
//expireTime.requireGreaterThan(startTime);
self.issuer = sender;
self.hash = sender.hexadecimal().saltAndHash(
licensee.hexadecimal()
);
self.issuedTime = startTime;
uint duration = expireTime.sub(startTime);
//duration must be greater than the longest possible time to mine 1 block,
//otherwise this license would expire effective immediately and be pointless
//duration.requireGreaterThan(30);
self.terminationTime = expireTime;
//now must be less than the duration
self.terminationTime.requireNowLessThan();
self.issuedBlock = block.number;
//self.terminationBlock = block.number.add(
//estimateBlockNumber(
//expireTime
//15
//)
//);
//
//return self;
}
function initializeNow(
LicenseStorage storage self,
address sender,
address licensee,
uint duration
)internal //returns(
//LicenseStorage storage
//)
{
//sender.requireNotNullAndNotEqual(
//licensee
//);
//self.initalized.requireFalse();
//msg.sender.requireNotEqualAndNotNull(licensee);
////duration must be greater than the longest possible time to mine 1 block,
////otherwise this license would expire effective immediately and be pointless
//duration.requireGreaterThan(30);
self.issuer = sender;
self.hash = sender.hexadecimal().saltAndHash(
licensee.hexadecimal()
);
self.issuedTime = block.timestamp;
self.terminationTime = block.timestamp.add(duration);
//now must be less than the duration
self.terminationTime.requireNowLessThan();
self.issuedBlock = block.number;
//self.terminationBlock = block.number.add(
//estimateBlockNumber(
//now.add(duration)
//15
//)
//);
//
//return self;
}
function age(
LicenseStorage storage self
)internal view returns(
uint
){
//requireInitalized(self);
//if(!isValidTime(self, block.timestamp)){
//return 0;
//}
//return block.timestamp.sub(self.issuedTime);
}
function durationRemaining(
LicenseStorage storage self
)internal view returns(
uint
){
//requireInitalized(self);
//
//if(!isValidTime(self, block.timestamp)){
return 0;
//}
//return self.expireTime.sub(
//block.timestamp
//);
}
/// @return {uint} number of block mined/validated since the license was issued
function blockAge(
LicenseStorage storage self
)internal view returns(
uint
){
//requireInitalized(self);
//
//if(!isValidBlock(self, block.number)){
return 0;
//}
//return block.number.sub(self.issuedBlock);
}
/// @return {uint} number of blocks to mine/validate until this license is considered expired
function blocksRemaining(
LicenseStorage storage self
)internal view returns(
uint
){
//requireInitalized(self);
//
//if(!isValidBlock(self, block.number)){
return 0;
//}
//return self.terminationBlock.sub(block.number);
}
//
// @return {uint} the current license's average age based on the current block timestamp and number, adjusted for block rate to offset malicious attempts to modify block timestamps
//
//function blockAdjustedAge(
//uint
//){
//}
//function blockAdjustedDurationRemaining(
//uint
//){
//}
// extend duration of current license (if still valid) to the new timestamp `newExpireTime`
function renewTimestamp(
LicenseStorage storage self,
address sender,
address licensee,
uint newExpireTime
)internal //returns(
//LicenseStorage storage
//)
{
//only allow renewals from previous issuer
//self.issuer.requireEqual(sender);
//licensor can not be the licensee
//licensee.requireNotNullAndNotEqual(sender);
//duration.requireGreaterThan(30);
//isValid(self, licensee).requireTrue(
//'license is no longer valid'
//);
//
//newExpireTime.requireGreatThan(self.terminationTime);
uint duration = newExpireTime.sub(self.startTime);
//duration.requireGreaterThan(30);
self.terminationTime = newExpireTime;
self.terminationTime.requireNowLessThan();
//self.terminationBlock = estimateBlockNumber(
//newExpireTime
//15
//);
//
//return self;
}
//extend duration of current license (if still valid) by duration seconds beyond the previous termination
function renewDuration(
LicenseStorage storage self,
address sender,
address licensee,
uint duration
)internal //returns(
//LicenseStorage storage
//)
{
//only allow renewals from previous issuer
//self.issuer.requireNotNullAndEqual(sender);
//licensee.requireNotNullAndNotEqual(sender);
//duration.requireGreaterThan(30);
//isValid(self, licensee).requireTrue(
//'license no longer valid'
//);
//self.lastRenewalTime = block.timestamp;
//self.lastRenewalBlock = block.number;
self.terminationTime = self.terminationTime.add(duration);
self.terminationTime.requireNowLessThan();
//self.terminationBlock = estimateBlockNumber(
//self.terminationTime
//15
//);
//
//return self;
}
}
//library licenseHolders
//{
//mapping(address=>mixinEIP1753.LicenseStorage[]);
//}
//library secureLicenseHolders
//{
//mapping(bytes32=>mixinEIP1753.LicenseStorage[]);
//}
/*
library mixinLicenseHolders
{
//MAX_NAME_LENGTH =
//MAX_TOTAL_SUPPLY = ;
//struct LicenseHolderStorage{
//mixinEIP1753.LicenseStorage[] activeLicenses; ///licenses which a client has purchased and are currently valid
//mixinEIP1753.LicenseStorage[] expiredLicenses; ///licenses which a client has purchased but are no longer valid
//}
struct DataStorage{
//uint256 totalSupply;
//string name;
//string symbol;
//uint256 issuedAmount;
mapping(address=>LicenseHolderStorage) licenseHolders;
}
bytes32 private constant STORAGE_SLOT = keccak256('EIP-1753.mixin.storage');
function dataStore(
)internal pure returns(
DataStorage storage ret
){
bytes32 position = STORAGE_SLOT;
assembly {
ret_slot := position
}
}
function initialize(
address client
)internal
{
DataStorage storage ds = dataStore();
//ds.licenseHolders[client] = new mixinEIP1753.LicenseHolderStorage();
//ds.licenseHolders[client].activeLicenses = new mixinEIP1753.LicenseStorage[](0);
//ds.licenseHolders[client].expiredLicenses = new mixinEIP1753.LicenseStorage[](0);
}
}
*/
///
/// @dev EIP1753 shares similarities with both ERC-20 and EIP-801!
///
abstract contract EIP1753 is //iERC1753,
AccessControl,
StaticSupplyTokenABC
{
//using mixinEIP1753 for mixinEIP1753.LicenseStorage;
using eventsEIP1753 for address;
using eventsEIP1753AccessControl for address;
bytes32 public constant ROLE_ISSUING_AUTHORITY = keccak256('EIP-1753.ROLE_ISSUER');
bytes32 public constant ROLE_REVOKER = keccak256('EIP-1753.ROLE_REVOKER');
constructor(
string memory name,
string memory symbol,
uint256 totalSupply
)internal
AccessControl()
StaticSupplyTokenABC(name, symbol, totalSupply)
{
//address sender = _msgSender();
//mixinEIP1753.initialize(
//sender
//);
////_assignRoleAdmin(ROLE_ISSUER, DEFAULT_ADMIN_ROLE);
////_assignRoleAdmin(ROLE_REVOKER, DEFAULT_ADMIN_ROLE);
//_grantRole(ROLE_ISSUER, sender);
//_grantRole(ROLE_REVOKER, sender);
//
////_grantRole(ROLE_ISSUER, _this);
}
function _mutableLicenseStorage(
)private returns(
mixinEIP1753.LicenseStorage storage
){
return mixinEIP1753.dataStore(
//mixinEIP1753.STORAGE_SLOT
);
}
function _readOnlyLicenseStorage(
)private view returns(
mixinEIP1753.LicenseStorage storage
){
return mixinEIP1753.dataStore(
//mixinEIP1753.STORAGE_SLOT
);
}
//current circulating supply(licnese which have been issued)
//function circulatingSupply(
//)public view returns(
//uint256
//);
//totalSupply - issued
//function remainingSupply(
//)public view returns(
//uint256
//){
//}
//does client currently hold a valid license
function _hasValidLicense(
address client
)internal view returns(
bool
){
address sender = msg.sender;
//clients may only query their own license status
//issuing authorities may query whomever they wish
if(sender.notEquals(client)){
_requireLicensingAuthority(sender);
}
return _readOnlyLicenseStorage()[client].isValid();
}
//amount of seconds from now client has until their license is expired
//function durationRemaining(
//address client
//)public view returns(
//uint
//){
//return _readOnlyLicenseStorage()[client].durationRemaining();
//}
//does client have authority to issue/revoke licenses
function _hasAuthority(
address account
)internal view returns(
bool
){
account.requireNotNull();
return hasRole(ROLE_ISSUING_AUTHORITY, account); //|| hasRole(DEFAULT_ADMIN_ROLE, account);
}
function _isRevoker(
address account
)internal view returns(
bool
){
account.requireNotNull();
return hasRole(ROLE_REVOKER, account); // || hasRole(DEFAULT_ADMIN_ROLE, account);
}
//function hasAuthority(
//)external view returns(
//bool
//){
//return hasAuthority(msg.sender);
//}
function _requireLicensingAuthority(
address account
)internal view
{
_hasAuthority(account).requireTrue(
//''
);
}
//modifier _hasAuthority(
//address account
//){
//_requireLicensingAuthority(account);
//_;
//}
///
///mutable interface
///
//owner grants account elevated privellages (such as issuing and revoking licenses)
//issuing authorities can NOT themselves grant or revoke authority, that should be an owner/admin privellage ONLY
function _grantAuthority(
address issuer,
address account
)internal
{
account.requireNotNull();
issuer.requireNotNullAndNotEqual(account);
_hasAuthority(issuer).requireTrue(
//'invalid issuer'
);
_hasAuthority(account).requireFalse(
//'already has role'
);
grantRole(ROLE_ISSUING_AUTHORITY, account);
}
//revoke account's elevated privellages as an issuing authority
function _revokeAuthority(
address revoker,
address account
)internal
{
account.requireNotNull();
//_isRevoker(revoker).requireTrue(
//'invalid revoker'
//);
_hasAuthority(account).requireTrue(
//'address is not a revoker'
);
revokeRole(ROLE_ISSUING_AUTHORITY, account);
}
//an issuing authority issues client a license which is valid between the timestamp from, until the timestamp to
//from can be retroactive (in the past) but to MUST always be in the future
function _issue(
//address sender,
address client,
uint from,
uint to
)internal
{
client.requireNotNull();
address sender = msg.sender;
client.requireNotEqual(sender);
_requireLicensingAuthority(sender);
_mutableLicenseStorage()[client].initialize(
sender,
client,
from,
to
);
//sender.emitLicenseIssued(client);
}
function _revoke(
//address revoker,
address client
)internal
{
//can't revoke license from a null address
client.requireNotNull();
_requireLicensingAuthority(msg.sender);
_mutableLicenseStorage()[client].revoke();
//sender.emitLicenseRevoked(client);
}
///
///payable interface
///
//issuer purchases license (after recieving fee from client) which will then be issued to client by a specific date
function purchase(
uint validFrom,
uint validTo
)public payable virtual
{
//msg.sender.emitLicensePurchased(
//msg.sender
//);
}
//issuer purchases license (after recieving fee from client) then immediately issues license to client
function purchaseAndIssue(
uint validFrom,
uint validTo
)public payable virtual
{
}
function renewTime(
address client,
uint time
)public payable virtual
{
//mixinEIP1753.()[client].renewTime(
//);
}
function renewDuration(
address client,
uint duration
)public payable virtual
{
//mixinEIP1753.()[client].renewDuration(
//);
}
} | LicenseStorage storage)sender.requireNotNullAndNotEqual(licensee);self.initalized.requireFalse();msg.sender.requireNotEqualAndNotNull(licensee);duration.requireGreaterThan(30);now must be less than the durationself.terminationBlock = block.number.add(estimateBlockNumber(now.add(duration)15));return self; | function initializeNow(
LicenseStorage storage self,
address sender,
address licensee,
uint duration
{
self.issuer = sender;
self.hash = sender.hexadecimal().saltAndHash(
licensee.hexadecimal()
);
self.issuedTime = block.timestamp;
self.terminationTime = block.timestamp.add(duration);
self.terminationTime.requireNowLessThan();
self.issuedBlock = block.number;
}
| 12,953,615 |
./full_match/1/0x673003F86fFe32F7CaA3E5fcfDC711EBf8A64aeF/sources/src/membership/modules/StablecoinPurchaseModule.sol | Function to handle decimal precision variation between stablecoin implementations price The desired stablecoin price to be checked against ERC20 decimals() and formatted if needed stablecoin The stablecoin implementation to which to conform pad zeros to input quantity reduce price precision if remainder, round up as seller protection no remainder value lost, return trimmed price as is | function mintPriceToStablecoinAmount(uint256 price, address stablecoin) public view returns (uint256) {
uint256 stablecoinDecimals = IERC20Metadata(stablecoin).decimals();
if (stablecoinDecimals == decimals) {
return price;
return price * 10 ** (stablecoinDecimals - decimals);
uint256 precisionLoss = 10 ** (decimals - stablecoinDecimals);
uint256 trimmedPrice = price / precisionLoss;
if (price % precisionLoss > 0) {
return trimmedPrice + 1;
return trimmedPrice;
}
}
}
==========*/
| 3,159,217 |
/**
* Copyright (c) 2018-present, Leap DAO (leapdao.org)
*
* This source code is licensed under the Mozilla Public License, version 2,
* found in the LICENSE file in the root directory of this source tree.
*/
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./AdminableProxy.sol";
contract MinGov is Ownable {
uint256 public proposalTime;
uint256 public first;
uint256 public size;
struct Proposal {
address subject;
uint32 created;
bool canceled;
bytes msgData;
}
mapping(uint256 => Proposal) public proposals;
event NewProposal(uint256 indexed proposalId, address indexed subject, bytes msgData);
event Execution(uint256 indexed proposalId, address indexed subject, bytes msgData);
constructor(uint256 _proposalTime) public {
proposalTime = _proposalTime;
first = 1;
size = 0;
}
function propose(address _subject, bytes memory _msgData) onlyOwner() public {
require(size < 5);
proposals[first + size] = Proposal(_subject, uint32(now), false, _msgData);
emit NewProposal(first + size, _subject, _msgData);
size++;
}
function cancel(uint256 _proposalId) onlyOwner() public {
Proposal storage prop = proposals[_proposalId];
require(prop.created > 0);
require(prop.canceled == false);
prop.canceled = true;
}
function getSig(bytes _msgData) internal pure returns (bytes4) {
return bytes4(_msgData[3]) >> 24 | bytes4(_msgData[2]) >> 16 | bytes4(_msgData[1]) >> 8 | bytes4(_msgData[0]);
}
function finalize() public {
for (uint256 i = first; i < first + size; i++) {
Proposal memory prop = proposals[i];
if (prop.created + proposalTime <= now) {
if (!prop.canceled) {
bool rv;
if (
// changeAdmin(address)
getSig(prop.msgData) == 0x8f283970 ||
// upgradeTo(address)
getSig(prop.msgData) == 0x3659cfe6) {
// this changes proxy parameters
rv = prop.subject.call(prop.msgData);
// use this for 0.5
// (rv, ) = prop.subject.call(prop.msgData);
} else {
// this changes governance parameters to the implementation
rv = AdminableProxy(prop.subject).applyProposal(prop.msgData);
}
if (rv) {
emit Execution(i, prop.subject, prop.msgData);
}
}
delete proposals[i];
first++;
size--;
}
}
}
} | changeAdmin(address) upgradeTo(address) this changes proxy parameters use this for 0.5 (rv, ) = prop.subject.call(prop.msgData); this changes governance parameters to the implementation | function finalize() public {
for (uint256 i = first; i < first + size; i++) {
Proposal memory prop = proposals[i];
if (prop.created + proposalTime <= now) {
if (!prop.canceled) {
bool rv;
if (
getSig(prop.msgData) == 0x8f283970 ||
getSig(prop.msgData) == 0x3659cfe6) {
rv = prop.subject.call(prop.msgData);
rv = AdminableProxy(prop.subject).applyProposal(prop.msgData);
}
if (rv) {
emit Execution(i, prop.subject, prop.msgData);
}
}
delete proposals[i];
first++;
size--;
}
}
}
| 7,284,686 |
// SPDX-License-Identifier: MIT
// Amended by LeZig with RAWRRRR
/**
___..........__
_,...._ _."'_,.++8n.n8898n.`"._ _....._
.' `". _.'_.'" _.98n.68n. `"88n. `'. ," `.
/ . `. ,'. " -'" __.68`""'""=._`+8. `.' . `.
. ` . `. ,d86+889" 8"""+898n, j8 9 ," . \
: ' ., ,d"'" _..d88b..__ `"868' .' . ' :
: . . _ ,n8""88":8"888."8. " ' :
\ , ' , . .88" ,8P' ,d8. _ `"8n `+. `. . '
`. .. . d89' " _..n689+^'8n88n.._ `+ . ` . , ' ,'
`. . , ' 8' .d88+" j:""' `886n. b`. ' .' . ."
' , .j ,d'8. ` ."8.`. `. ':
. .' n8 ,_ .f A 6. ,.. `8b, '. .'_
.' _ ,88' :8"8 6'.d`i.`b. d8"8 688. ". `'
," .88 .d868 _ ,9:' `8.`8 "' ` _ 8+"" b `,
_. d8P d' .d :88. .8'`j ;+. " n888b 8 . ,88. .
` :68' ,8 88 `. ' : l ` .' `" jb .` 688b. ',
.' .688 6P 98 =+""`. ` ' ,-"`+"'+88b 'b. 8689 ` '
; .'"888 .8; ."+b. : `" ; .: "' ; ,n `8 q8, '88: \
. . 898 8: : `.`--"8. d8`--' ' .d' ;8 898 '
, 689 9: 8._ ,68 . . :89 ..n88+' 89 689,' ` .
: ,88' 88 `+88n - . . . " _. 6: `868 ' '
, ' .68h. 68 `" . . . . . . ,8' 8P' . .
. '88 'q. _.f . . . ' .._,. .8" .889 ,
.' `898 _8hnd8p' , . .. . . ._ `89,8P j"' _ `
\ ` .88, `q9868' ,9 .. . . . 8n .8 d8' +' n8. , '
,' ,+"88n `"8 .8' . .. . . `8688P" 9' ,d868' . .
. . `86b. " . . .. 68' _.698689; :
. ' ,889_.n8. , ` . .___ ___. .n" `86n8b._ `8988'b .,6
' q8689'`68. . ` `:. `.__,' .:' , + +88 `"688n `q8 q8. 88
, . ' " `+8 n . `:. .;' . ' . ,89 " `q, `8
. . , . + c , `:.,:" , " d8' d8. :
. ' 8n ` , . :: . ' " . .68h. .8'`8`. 6
, 8b.__. , .n8688b., . .;:._ .___nn898868n. n868b "` 8
`. `6889868n8898886888688898"' "+89n88898868868889' 688898b .8
: q68 `""+8688898P ` " ' . ` ' ' `+688988P" d8+8P' `. .d8
, 88b. `+88. ` ` ' .889"' ,.88' .,88
: '988b "88b.._ ,_ . n8p' .d8"' ' 689
'. "888n._, `"8"+88888n.8,88:`8 . _ .n88P' . ` ;88'
:8. "q888. . "+888P" "+888n,8n8'" . . ,d986
:.`8: `88986 `q8" , :688"
;. '8, "88b .d ' ,889'
:.. `6n '8988 b.89p
:. . '8. `88b 988'
:. . 8b `q8. ' . ' .d89 '
. . `8: `86n,. " . , , " ,98P ,
.. . '6n. +86b. . . _,.n88' .
. `"8b. 'q98n. , . _..n868688' .
' . . `"98. `8868. . _.n688868898p" d
. . '88. "688. q89888688868" ,86
mh '. . 88. `8898 " .889"' .988
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
interface IZodiacEnvelopes {
function _wallet_of_owner(address _owner)
external
view
returns (uint256[] memory);
function _is_gold(uint256 _token_id) external view returns (bool);
}
pragma solidity >=0.7.0 <0.9.0;
contract ZodiacTigers is ERC721Enumerable, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
// metadata values
string public _standard_base_uri;
// costs tiers
uint256 public _standard_cost = 0.06 ether;
uint256 public _discounted_cost = 0.02 ether;
mapping(uint256 => bool) public _was_gold_token_id_used;
// economics
Counters.Counter private _supply;
uint256 constant public _max_supply = 8888;
uint256 public _max_mint_amount_per_tx = 20;
uint256 public _tiger_reserve = 50;
// mint conditions
bool public _paused;
// interface to packet contract
IZodiacEnvelopes private _zodiac_envelopes_interface;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory standard_base_uri_,
address zodiac_envelopes_address_,
string memory name_,
string memory symbol_
) ERC721(name_, symbol_) {
_set_standard_base_uri(standard_base_uri_);
_zodiac_envelopes_interface = IZodiacEnvelopes(zodiac_envelopes_address_);
}
function _total_supply() public view returns (uint256) {
return _supply.current();
}
// to be accessed externally by a client wanting to know about the cost with its membership passes
function _get_mint_cost(address _to, uint256 _mint_amount) public view returns (uint256) {
// get the Zodiac envelopes tokens of the address
uint256[] memory _owned_token_ids = _zodiac_envelopes_interface._wallet_of_owner(_to);
// if there is no pass, we pay the full price
if(_owned_token_ids.length == 0){
return _mint_amount * _standard_cost;
}
// we have to iterate over all passes to make sure we don't skip a gold that wasn't still used
bool _found_red = false;
for (uint256 i = 0; i < _owned_token_ids.length; i++){
uint256 _current_token_id = _owned_token_ids[i];
if (_zodiac_envelopes_interface._is_gold(_current_token_id)){
// if it's not used yet, 1 free mint is given for this gold one and recorded
if (!_was_gold_token_id_used[_current_token_id]){
if (_mint_amount == 1) return 0;
else _mint_amount--;
}
}
else _found_red = true;
}
// it is sufficient to find 1 red to mint for the discounted cost all that wasn't free with gold
return _found_red ? _mint_amount * _discounted_cost : _mint_amount * _standard_cost;
}
function _get_record_mint_cost(address _to, uint256 _mint_amount) internal returns (uint256) {
// get the Zodiac envelopes tokens of the address
uint256[] memory _owned_token_ids = _zodiac_envelopes_interface._wallet_of_owner(_to);
// if there is no pass, we pay the full price
if(_owned_token_ids.length == 0){
return _mint_amount * _standard_cost;
}
// we have to iterate over all passes to make sure we don't skip a gold that wasn't still used
bool _found_red = false;
for (uint256 i = 0; i < _owned_token_ids.length; i++){
uint256 _current_token_id = _owned_token_ids[i];
if (_zodiac_envelopes_interface._is_gold(_current_token_id)){
// if it's not used yet, 1 free mint is given for this gold one and recorded
if (!_was_gold_token_id_used[_current_token_id]){
_was_gold_token_id_used[_current_token_id] = true;
if (_mint_amount == 1) return 0;
else _mint_amount--;
}
}
else _found_red = true;
}
// it is sufficient to find 1 red to mint for the discounted cost all that wasn't free with gold
return _found_red ? _mint_amount * _discounted_cost : _mint_amount * _standard_cost;
}
function _mint_loop(address _to, uint256 _mint_amount) internal {
for (uint256 i = 0; i < _mint_amount; i++) {
_supply.increment();
_safeMint(_to, _total_supply());
}
}
function _mint(uint256 _mint_amount) public payable {
require(_mint_amount > 0 && _mint_amount <= _max_mint_amount_per_tx, "Invalid mint amount");
require(_total_supply() + _mint_amount <= _max_supply, "Max supply exceeded");
require(!_paused, "Public sale has not started");
require(msg.sender == tx.origin, "Only EOA mint");
uint256 _mint_total_cost = _get_record_mint_cost(msg.sender, _mint_amount);
require(msg.value >= _mint_total_cost, "Insufficient value sent for minting");
_mint_loop(msg.sender, _mint_amount);
}
function _mint_reserved_tokens(uint256 _mint_amount) public onlyOwner {
require(_mint_amount > 0 && _mint_amount <= _tiger_reserve, "Team reserve down");
require(_total_supply() + _mint_amount <= _max_supply, "Max supply exceeded");
_mint_loop(msg.sender, _mint_amount);
_tiger_reserve -= _mint_amount;
}
function _wallet_of_owner(address _owner)
public
view
returns (uint256[] memory) {
uint256 _owner_token_count = balanceOf(_owner);
uint256[] memory _owned_token_ids = new uint256[](_owner_token_count);
for (uint256 i; i < _owner_token_count; i++) {
_owned_token_ids[i] = tokenOfOwnerByIndex(_owner, i);
}
return _owned_token_ids;
}
function tokenURI(uint256 _token_id)
public
view
virtual
override
returns (string memory)
{
require(_exists(_token_id), "ERC721Metadata: URI query for nonexistent token");
return bytes(_standard_base_uri).length > 0
? string(abi.encodePacked(_standard_base_uri, _token_id.toString(), ".json"))
: "";
}
function _was_gold_envelope_used(uint256 _token_id) public view returns (bool) {
require(_zodiac_envelopes_interface._is_gold(_token_id), "Token id is not a gold envelope");
return _was_gold_token_id_used[_token_id];
}
function _set_standard_base_uri(string memory standard_base_uri_) public onlyOwner {
_standard_base_uri = standard_base_uri_;
}
function _set_paused(bool _state) public onlyOwner {
_paused = _state;
}
function _set_max_mint_per_txn(uint256 max_mint_amount_per_tx_) public onlyOwner {
_max_mint_amount_per_tx = max_mint_amount_per_tx_;
}
function _set_discounted_cost(uint256 discounted_cost_) public onlyOwner {
_discounted_cost = discounted_cost_;
}
function _set_standard_cost(uint256 standard_cost_) public onlyOwner {
_standard_cost = standard_cost_;
}
function withdraw() public onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
___..........__
pragma solidity ^0.8.0;
}
| 5,881,102 |
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | Returns the downcasted uint88 from uint256, reverting on overflow (when the input is greater than largest uint88). Counterpart to Solidity's `uint88` operator. Requirements: - input must fit into 88 bits _Available since v4.7._/ | function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
| 8,818,473 |
./partial_match/3/0x7270187150D440643064aa9739239bA80CD8fE97/sources/contracts/ExampleToken.sol | Remove a ScalingFunds agent Only ScalingFunds agents can call this function/ | function removeScalingFundsAgent(address account)
external
onlyScalingFundsAgent
{
super.revokeRole(SCALINGFUNDS_AGENT, account);
}
| 5,051,813 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Fully commented standard ERC721 Distilled from OpenZeppelin Docs
Base for Building ERC721 by Martin McConnell
All the utility without the fluff.
*/
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
//@dev Emitted when `tokenId` token is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
//@dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
//@dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
//@dev Returns the number of tokens in ``owner``'s account.
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from,address to,uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
//@dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
interface IERC721Metadata is IERC721 {
//@dev Returns the token collection name.
function name() external view returns (string memory);
//@dev Returns the token collection symbol.
function symbol() external view returns (string memory);
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// ******************************************************************************************************************************
// ************************************************** Start of Main Contract ***************************************************
// ******************************************************************************************************************************
contract goldenEaglez is IERC721, Ownable {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// URI Root Location for Json Files
string private _baseURI;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// PandaBugz Specific Functionality
bool public mintActive;
bool private reentrancyLock;
uint256 public price;
uint256 public totalTokens = 10000;
uint256 public numberMinted;
uint256 private _maxMintsPerTxn;
uint256 public earlyMint;
mapping(address => bool) _whitelist;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor() {
_name = "Golden Eaglez Kartel";
_symbol = "GEK";
_baseURI = "https://herodev.mypinata.cloud/ipfs/QmUBv8AVVD3bh76J364ATqL22ZsuWmovuY2kSKEkCovGqd/";
price = 8 * (10 ** 16); // 0.08eth
_maxMintsPerTxn = 20;
earlyMint = 1500;
}
//@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == goldenEaglez.onERC721Received.selector;
}
function withdraw() external onlyOwner {
uint256 sendAmount = address(this).balance;
(bool success, ) = msg.sender.call{value: sendAmount}("");
require(success, "Transaction Unsuccessful");
}
function ownerMint(address _to, uint256 qty) external onlyOwner{
uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
numberMinted += qty;
for(uint256 i = 0; i < qty; i++) {
_safeMint(_to, mintSeedValue + i);
}
}
function mint(address _to, uint256 qty) external payable {
require(msg.value >= qty * price, "Mint: Insufficient Funds");
require(qty <= _maxMintsPerTxn, "Mint: Above Transaction Threshold!");
if (mintActive) {
require(qty < totalTokens - numberMinted, "Mint: Not enough NFTs remaining to fill order");
} else {
require(qty < earlyMint - numberMinted, "Mint: Not enough NFTs remaining to fill order");
require(_whitelist[_msgSender()]);
}
require(!reentrancyLock); //Lock up this whole function just in case
reentrancyLock = true;
uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
numberMinted += qty;
//Handle ETH transactions
uint256 cashIn = msg.value;
uint256 cashChange = cashIn - (qty * price);
//send tokens
for(uint256 i = 0; i < qty; i++) {
_safeMint(_to, mintSeedValue + i);
}
if (cashChange > 0){
(bool success, ) = msg.sender.call{value: cashChange}("");
require(success, "Mint: unable to send change to user");
}
reentrancyLock = false;
}
function burn(uint256 tokenID) external {
require(_msgSender() == ownerOf(tokenID));
_burn(tokenID);
}
//////////////////// Setters and Getters
function whiteList(address account) external onlyOwner {
_whitelist[account] = true;
}
function whiteListMany(address[] memory accounts) external onlyOwner {
for (uint256 i; i < accounts.length; i++) {
_whitelist[accounts[i]] = true;
}
}
function checkWhitelist(address testAddress) external view returns (bool) {
if (_whitelist[testAddress] == true) { return true; }
return false;
}
function setMaximumMintThreshold(uint256 maxMints) external onlyOwner {
_maxMintsPerTxn = maxMints;
}
function viewMaxMintThreshold() external view onlyOwner returns(uint256) {
return _maxMintsPerTxn;
}
function setBaseURI(string memory newURI) public onlyOwner {
_baseURI = newURI;
}
function setActive(bool setBoolValue) public onlyOwner {
mintActive = setBoolValue;
}
function setPrice(uint256 newPrice) public onlyOwner {
price = newPrice;
}
function setTotalTokens(uint256 numTokens) public onlyOwner {
totalTokens = numTokens;
}
function getBalance(address tokenAddress) view external returns (uint256) {
return _balances[tokenAddress];
}
// **************************************** Metadata Standard Functions **********
//@dev Returns the token collection name.
function name() external view returns (string memory){
return _name;
}
//@dev Returns the token collection symbol.
function symbol() external view returns (string memory){
return _symbol;
}
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
function tokenURI(uint256 tokenId) external view returns (string memory){ //Fill out file location here later
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory tokenuri = string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
return tokenuri;
}
// *******************************************************************************
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
// *********************** ERC721 Token Receiver **********************
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) {
//InterfaceID=0x150b7a02
return this.onERC721Received.selector;
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
receive() external payable {}
fallback() external payable {}
} | See {IERC165-supportsInterface}. Interfaces Supported by this Standard | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == goldenEaglez.onERC721Received.selector;
}
| 153,379 |
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/shared/MarketFees.sol | Returns the address of the registry allowing for royalty configuration overrides. return registry The address of the royalty registry contract./ | function getRoyaltyRegistry() external view returns (address registry) {
registry = address(royaltyRegistry);
}
| 8,357,253 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {ERC165Storage} from "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {IKODAV3} from "../core/IKODAV3.sol";
import {Konstants} from "../core/Konstants.sol";
import {IERC2981} from "../core/IERC2981.sol";
import {IKOAccessControlsLookup} from "../access/IKOAccessControlsLookup.sol";
import {ICollabRoyaltiesRegistry} from "./ICollabRoyaltiesRegistry.sol";
import {ICollabFundsHandler} from "./handlers/ICollabFundsHandler.sol";
contract CollabRoyaltiesRegistry is Pausable, Konstants, ERC165Storage, IERC2981, ICollabRoyaltiesRegistry {
// Admin Events
event KODASet(address koda);
event AccessControlsSet(address accessControls);
event RoyaltyAmountSet(uint256 royaltyAmount);
event EmergencyClearRoyalty(uint256 editionId);
event HandlerAdded(address handler);
event HandlerRemoved(address handler);
// Normal Events
event RoyaltyRecipientCreated(address creator, address handler, address deployedHandler, address[] recipients, uint256[] splits);
event RoyaltiesHandlerSetup(uint256 editionId, address deployedHandler);
event FutureRoyaltiesHandlerSetup(uint256 editionId, address deployedHandler);
IKODAV3 public koda;
IKOAccessControlsLookup public accessControls;
// @notice A controlled list of proxies which can be used byt eh KO protocol
mapping(address => bool) public isHandlerWhitelisted;
// @notice A list of initialised/deployed royalties recipients
mapping(address => bool) public deployedRoyaltiesHandlers;
/// @notice Funds handler to edition ID mapping - once set all funds are sent here on every sale, including EIP-2981 invocations
mapping(uint256 => address) public editionRoyaltiesHandlers;
/// @notice KO secondary sale royalty amount
uint256 public royaltyAmount = 12_50000; // 12.5% as represented in eip-2981
/// @notice precision 100.00000%
uint256 public modulo = 100_00000;
modifier onlyContractOrCreator(uint256 _editionId) {
require(
koda.getCreatorOfEdition(_editionId) == _msgSender() || accessControls.hasContractRole(_msgSender()),
"Caller not creator or contract"
);
_;
}
modifier onlyContractOrAdmin() {
require(
accessControls.hasAdminRole(_msgSender()) || accessControls.hasContractRole(_msgSender()),
"Caller not admin or contract"
);
_;
}
modifier onlyAdmin() {
require(accessControls.hasAdminRole(_msgSender()), "Caller not admin");
_;
}
constructor(IKOAccessControlsLookup _accessControls) {
accessControls = _accessControls;
// _INTERFACE_ID_ERC2981
_registerInterface(0x2a55205a);
}
/// @notice Set the IKODAV3 dependency - can't be passed to constructor due to circular dependency
function setKoda(IKODAV3 _koda)
external
onlyAdmin {
koda = _koda;
emit KODASet(address(koda));
}
/// @notice Set the IKOAccessControlsLookup dependency.
function setAccessControls(IKOAccessControlsLookup _accessControls)
external
onlyAdmin {
accessControls = _accessControls;
emit AccessControlsSet(address(accessControls));
}
/// @notice Admin setter for changing the default royalty amount
function setRoyaltyAmount(uint256 _amount)
external
onlyAdmin() {
require(_amount > 1, "Amount to low");
royaltyAmount = _amount;
emit RoyaltyAmountSet(royaltyAmount);
}
/// @notice Add a new cloneable funds handler
function addHandler(address _handler)
external
onlyAdmin() {
// Revert if handler already whitelisted
require(isHandlerWhitelisted[_handler] == false, "Handler already registered");
// whitelist handler
isHandlerWhitelisted[_handler] = true;
// Emit event
emit HandlerAdded(_handler);
}
/// @notice Remove a cloneable funds handler
function removeHandler(address _handler)
external
onlyAdmin() {
// remove handler from whitelist
isHandlerWhitelisted[_handler] = false;
// Emit event
emit HandlerRemoved(_handler);
}
////////////////////////////
/// Royalties setup logic //
////////////////////////////
/// @notice Sets up a royalties funds handler
/// @dev Can only be called once with the same args as this creates a new contract and we dont want to
/// override any currently deployed instance
/// @dev Can only be called by an approved artist
function createRoyaltiesRecipient(
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
)
external
override
whenNotPaused
returns (address deployedHandler) {
validateHandlerArgs(_handler, _recipients, _splits);
// Clone funds handler as Minimal deployedHandler with a deterministic address
deployedHandler = deployCloneableHandler(_handler, _recipients, _splits);
// Emit event
emit RoyaltyRecipientCreated(_msgSender(), _handler, deployedHandler, _recipients, _splits);
}
/// @notice Allows a deployed handler to be set against an edition
/// @dev Can be called by edition creator or another approved contract
/// @dev Can only be called once per edition
/// @dev Provided handler account must already be deployed
function useRoyaltiesRecipient(uint256 _editionId, address _deployedHandler)
external
override
whenNotPaused
onlyContractOrCreator(_editionId) {
// Ensure not already defined i.e. dont overwrite deployed contact
require(editionRoyaltiesHandlers[_editionId] == address(0), "Funds handler already registered");
// Ensure there actually was a registration
require(deployedRoyaltiesHandlers[_deployedHandler], "No deployed handler found");
// Register the deployed handler for the edition ID
editionRoyaltiesHandlers[_editionId] = _deployedHandler;
// Emit event
emit RoyaltiesHandlerSetup(_editionId, _deployedHandler);
}
/// @notice Allows an admin set a predetermined royalties recipient against an edition
/// @dev assumes the called has provided the correct args and a valid edition
function usePredeterminedRoyaltiesRecipient(
uint256 _editionId,
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
)
external
override
whenNotPaused
onlyContractOrAdmin {
// Ensure not already defined i.e. dont overwrite deployed contact
require(editionRoyaltiesHandlers[_editionId] == address(0), "Funds handler already registered");
// Determine salt
bytes32 salt = keccak256(abi.encode(_recipients, _splits));
address futureDeployedHandler = Clones.predictDeterministicAddress(_handler, salt);
// Register the same proxy for the new edition id
editionRoyaltiesHandlers[_editionId] = futureDeployedHandler;
// Emit event
emit FutureRoyaltiesHandlerSetup(_editionId, futureDeployedHandler);
}
function createAndUseRoyaltiesRecipient(
uint256 _editionId,
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
)
external
override
whenNotPaused
onlyContractOrAdmin
returns (address deployedHandler) {
validateHandlerArgs(_handler, _recipients, _splits);
// Confirm the handler has not already been created
address expectedAddress = Clones.predictDeterministicAddress(_handler, keccak256(abi.encode(_recipients, _splits)));
require(!deployedRoyaltiesHandlers[expectedAddress], "Already deployed the royalties handler");
// Clone funds handler as Minimal deployedHandler with a deterministic address
deployedHandler = deployCloneableHandler(_handler, _recipients, _splits);
// Emit event
emit RoyaltyRecipientCreated(_msgSender(), _handler, deployedHandler, _recipients, _splits);
// Register the deployed handler for the edition ID
editionRoyaltiesHandlers[_editionId] = deployedHandler;
// Emit event
emit RoyaltiesHandlerSetup(_editionId, deployedHandler);
}
function deployCloneableHandler(address _handler, address[] calldata _recipients, uint256[] calldata _splits)
internal
returns (address deployedHandler) {
// Confirm the handler has not already been created
address expectedAddress = Clones.predictDeterministicAddress(_handler, keccak256(abi.encode(_recipients, _splits)));
require(!deployedRoyaltiesHandlers[expectedAddress], "Already deployed the royalties handler");
// Clone funds handler as Minimal deployedHandler with a deterministic address
deployedHandler = Clones.cloneDeterministic(
_handler,
keccak256(abi.encode(_recipients, _splits))
);
// Initialize handler
ICollabFundsHandler(deployedHandler).init(_recipients, _splits);
// Verify that it was initialized properly
require(
ICollabFundsHandler(deployedHandler).totalRecipients() == _recipients.length,
"Funds handler created incorrectly"
);
// Record the deployed handler
deployedRoyaltiesHandlers[deployedHandler] = true;
}
function validateHandlerArgs(address _handler, address[] calldata _recipients, uint256[] calldata _splits)
internal view {
// Require more than 1 recipient
require(_recipients.length > 1, "Collab must have more than one funds recipient");
// Recipient and splits array lengths must match
require(_recipients.length == _splits.length, "Recipients and splits lengths must match");
// Ensure the handler is know and approved
require(isHandlerWhitelisted[_handler], "Handler is not whitelisted");
}
/// @notice Allows for the royalty creator to predetermine the recipient address for the funds to be sent to
/// @dev It does not deploy it, only allows to predetermine the address
function predictedRoyaltiesHandler(address _handler, address[] calldata _recipients, uint256[] calldata _splits)
public
override
view
returns (address) {
bytes32 salt = keccak256(abi.encode(_recipients, _splits));
return Clones.predictDeterministicAddress(_handler, salt);
}
/// @notice ability to clear royalty in an emergency situation - this would then default all royalties to the original creator
/// @dev Only callable from admin
function emergencyResetRoyaltiesHandler(uint256 _editionId) public onlyAdmin {
editionRoyaltiesHandlers[_editionId] = address(0);
emit EmergencyClearRoyalty(_editionId);
}
////////////////////
/// Query Methods //
////////////////////
/// @notice Is the given token part of an edition that has a collab royalties contract setup?
function hasRoyalties(uint256 _tokenId)
external
override
view returns (bool) {
// Get the associated edition id for the given token id
uint256 editionId = _editionFromTokenId(_tokenId);
// Get the proxy registered to the previous edition id
address proxy = editionRoyaltiesHandlers[editionId];
// Ensure there actually was a registration
return proxy != address(0);
}
/// @notice Get the proxy for a given edition's funds handler
function getRoyaltiesReceiver(uint256 _editionId)
external
override
view returns (address _receiver) {
_receiver = editionRoyaltiesHandlers[_editionId];
require(_receiver != address(0), "Edition not setup");
}
/// @notice Gets the funds handler proxy address and royalty amount for given edition id
function royaltyInfo(uint256 _editionId, uint256 _value)
external
override
view returns (address _receiver, uint256 _royaltyAmount) {
_receiver = editionRoyaltiesHandlers[_editionId];
require(_receiver != address(0), "Edition not setup");
_royaltyAmount = (_value / modulo) * royaltyAmount;
}
}
| Confirm the handler has not already been created Clone funds handler as Minimal deployedHandler with a deterministic address Emit event Register the deployed handler for the edition ID Emit event | function createAndUseRoyaltiesRecipient(
uint256 _editionId,
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
)
external
override
whenNotPaused
onlyContractOrAdmin
returns (address deployedHandler) {
validateHandlerArgs(_handler, _recipients, _splits);
address expectedAddress = Clones.predictDeterministicAddress(_handler, keccak256(abi.encode(_recipients, _splits)));
require(!deployedRoyaltiesHandlers[expectedAddress], "Already deployed the royalties handler");
deployedHandler = deployCloneableHandler(_handler, _recipients, _splits);
emit RoyaltyRecipientCreated(_msgSender(), _handler, deployedHandler, _recipients, _splits);
editionRoyaltiesHandlers[_editionId] = deployedHandler;
emit RoyaltiesHandlerSetup(_editionId, deployedHandler);
}
| 12,615,232 |
./full_match/137/0x52FB368692b6635104d6834D34EED024D4E6E94a/sources/contracts/WinPay.sol | `deal` version without `permit` functionality | function deal(
bytes32 provider,
bytes32 serviceId,
uint256 expiry,
address asset,
uint256 value
) external payable onlyLive {
_deal(provider, serviceId, expiry, asset, value, Permit.EIP2612Permit(address(0), 0, 0, bytes32(0), bytes32(0)));
}
| 3,777,082 |
// SPDX-License-Identifier: MIT
/**
* @authors: [@hbarcelos, @unknownunknown1]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.7.2;
import "@kleros/arbitrable-proxy-contracts/contracts/IDisputeResolver.sol";
import "@kleros/ethereum-libraries/contracts/CappedMath.sol";
import "./dependencies/IAMB.sol";
import "./ArbitrationProxyInterfaces.sol";
contract RealitioForeignArbitrationProxyWithAppeals is IForeignArbitrationProxy, IDisputeResolver {
using CappedMath for uint256;
/* Constants */
uint256 public constant NUMBER_OF_CHOICES_FOR_ARBITRATOR = (2**256) - 1; // The number of choices for the arbitrator.
uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
/* Storage */
enum Status {None, Requested, Created, Ruled, Failed}
struct Arbitration {
Status status; // Status of the arbitration.
address payable requester; // Address that made the arbitration request.
uint256 deposit; // The deposit paid by the requester at the time of the arbitration.
uint256 disputeID; // The ID of the dispute in arbitrator contract.
uint256 answer; // The answer given by the arbitrator shifted by -1 to match Realitio format.
Round[] rounds; // Tracks each appeal round of a dispute.
}
// Round struct stores the contributions made to particular answers.
struct Round {
mapping(uint256 => uint256) paidFees; // Tracks the fees paid in this round in the form paidFees[answer].
mapping(uint256 => bool) hasPaid; // True if the fees for this particular answer have been fully paid in the form hasPaid[answer].
mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each answer in the form contributions[address][answer].
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the answer that ultimately wins a dispute.
uint256[] fundedAnswers; // Stores the answer choices that are fully funded.
}
address public governor = msg.sender; // The contract governor. TRUSTED.
bool public initialized; // Whether the contract has been properly initialized or not.
IArbitrator public immutable arbitrator; // The address of the arbitrator. TRUSTED.
bytes public arbitratorExtraData; // The extra data used to raise a dispute in the arbitrator.
uint256 public metaEvidenceID; // The ID of the MetaEvidence for disputes.
IAMB public immutable amb; // ArbitraryMessageBridge contract address. TRUSTED.
address public homeProxy; // Address of the counter-party proxy on the Home Chain. TRUSTED.
uint256 public homeChainId; // The chain ID where the home proxy is deployed.
string public termsOfService; // The path for the Terms of Service for Kleros as an arbitrator for Realitio.
// Multipliers are in basis points.
uint64 private winnerMultiplier; // Multiplier for calculating the appeal fee that must be paid for the answer that was chosen by the arbitrator in the previous round.
uint64 private loserMultiplier; // Multiplier for calculating the appeal fee that must be paid for the answer that the arbitrator didn't rule for in the previous round.
mapping(uint256 => Arbitration) public arbitrations; // Maps arbitration ID to its data.
mapping(uint256 => uint256) public override externalIDtoLocalID; // Maps external dispute ids to local dispute(arbitration) ids.
/* Events */
/**
* @notice Should be emitted when the arbitration is requested.
* @param _questionID The ID of the question.
* @param _answer The answer provided by the requester.
* @param _requester The requester.
*/
event ArbitrationRequested(bytes32 indexed _questionID, bytes32 _answer, address indexed _requester);
/**
* @notice Should be emitted when the dispute is created.
* @param _questionID The ID of the question.
* @param _disputeID The ID of the dispute.
*/
event ArbitrationCreated(bytes32 indexed _questionID, uint256 indexed _disputeID);
/**
* @notice Should be emitted when the dispute could not be created.
* @dev This will happen if there is an increase in the arbitration fees
* between the time the arbitration is made and the time it is acknowledged.
* @param _questionID The ID of the question.
*/
event ArbitrationFailed(bytes32 indexed _questionID);
/**
* @notice Should be emitted when the arbitration is canceled by the Home Chain.
* @param _questionID The ID of the question.
*/
event ArbitrationCanceled(bytes32 indexed _questionID);
/* Modifiers */
modifier onlyArbitrator() {
require(msg.sender == address(arbitrator), "Only arbitrator allowed");
_;
}
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
modifier onlyHomeProxy() {
require(msg.sender == address(amb), "Only AMB allowed");
require(amb.messageSourceChainId() == bytes32(homeChainId), "Only home chain allowed");
require(amb.messageSender() == homeProxy, "Only home proxy allowed");
_;
}
modifier onlyIfInitialized() {
require(homeProxy != address(0), "Not initialized yet");
_;
}
/**
* @notice Creates an arbitration proxy on the foreign chain.
* @dev Contract will still require initialization before being usable.
* @param _amb ArbitraryMessageBridge contract address.
* @param _arbitrator Arbitrator contract address.
* @param _arbitratorExtraData The extra data used to raise a dispute in the arbitrator.
* @param _winnerMultiplier Multiplier for calculating the appeal cost of the winning answer.
* @param _loserMultiplier Multiplier for calculation the appeal cost of the losing answer.
*/
constructor(
IAMB _amb,
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
string memory _metaEvidence,
string memory _termsOfService,
uint64 _winnerMultiplier,
uint64 _loserMultiplier
) {
amb = _amb;
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
termsOfService = _termsOfService;
winnerMultiplier = _winnerMultiplier;
loserMultiplier = _loserMultiplier;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/* External and public */
/**
* @notice Changes the address of a new governor.
* @param _governor The address of the new governor.
*/
function changeGovernor(address _governor) external onlyGovernor {
governor = _governor;
}
/**
* @notice Sets the address of the arbitration proxy on the Home Chain.
* @param _homeProxy The address of the proxy.
* @param _homeChainId The chain ID where the home proxy is deployed.
*/
function setHomeProxy(address _homeProxy, uint256 _homeChainId) external onlyGovernor {
require(homeProxy == address(0), "Home proxy already set");
homeProxy = _homeProxy;
homeChainId = _homeChainId;
}
/**
* @notice Changes the proportion of appeal fees that must be added to appeal cost for the winning party.
* @param _winnerMultiplier The new winner multiplier value in basis points.
*/
function changeWinnerMultiplier(uint64 _winnerMultiplier) external onlyGovernor {
winnerMultiplier = _winnerMultiplier;
}
/**
* @notice Changes the proportion of appeal fees that must be added to appeal cost for the losing party.
* @param _loserMultiplier The new loser multiplier value in basis points.
*/
function changeLoserMultiplier(uint64 _loserMultiplier) external onlyGovernor {
loserMultiplier = _loserMultiplier;
}
/**
* @notice Changes the meta evidence used for disputes.
* @param _metaEvidence URI to the new meta evidence file.
*/
function changeMetaEvidence(string calldata _metaEvidence) external onlyGovernor {
metaEvidenceID += 1;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/**
* @notice Changes the terms of service for Realitio.
* @param _termsOfService URI to the new Terms of Service file.
*/
function changeTermsOfService(string calldata _termsOfService) external onlyGovernor {
termsOfService = _termsOfService;
}
// ************************ //
// * Realitio logic * //
// ************************ //
/**
* @notice Requests arbitration for a given question ID.
* @dev Can be executed only if the contract has been initialized.
* @param _questionID The ID of the question.
* @param _contestedAnswer The answer the requester deems to be incorrect.
*/
function requestArbitration(bytes32 _questionID, bytes32 _contestedAnswer) external payable onlyIfInitialized {
Arbitration storage arbitration = arbitrations[uint256(_questionID)];
require(arbitration.status == Status.None, "Arbitration already requested");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= arbitrationCost, "Deposit value too low");
arbitration.status = Status.Requested;
arbitration.requester = msg.sender;
arbitration.deposit = msg.value;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationRequest.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, _contestedAnswer, msg.sender);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationRequested(_questionID, _contestedAnswer, msg.sender);
}
/**
* @notice Creates a dispute for a given question ID.
* @param _questionID The ID of the question.
*/
function acknowledgeArbitration(bytes32 _questionID) external override onlyHomeProxy {
uint256 arbitrationID = uint256(_questionID);
Arbitration storage arbitration = arbitrations[arbitrationID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
if (arbitration.deposit >= arbitrationCost) {
try
arbitrator.createDispute{value: arbitrationCost}(NUMBER_OF_CHOICES_FOR_ARBITRATOR, arbitratorExtraData)
returns (uint256 disputeID) {
externalIDtoLocalID[disputeID] = arbitrationID;
// At this point, arbitration.deposit is guaranteed to be greater than or equal to the arbitration cost.
uint256 remainder = arbitration.deposit - arbitrationCost;
arbitration.status = Status.Created;
arbitration.deposit = 0;
arbitration.disputeID = disputeID;
arbitration.rounds.push();
if (remainder > 0) {
arbitration.requester.send(remainder);
}
emit ArbitrationCreated(_questionID, disputeID);
emit Dispute(arbitrator, disputeID, metaEvidenceID, arbitrationID);
} catch {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
} else {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
}
/**
* @notice Cancels the arbitration.
* @param _questionID The ID of the question.
*/
function cancelArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[uint256(_questionID)];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[uint256(_questionID)];
emit ArbitrationCanceled(_questionID);
}
/**
* @notice Cancels the arbitration in case the dispute could not be created.
* @param _questionID The ID of the question.
*/
function handleFailedDisputeCreation(bytes32 _questionID) external onlyIfInitialized {
Arbitration storage arbitration = arbitrations[uint256(_questionID)];
require(arbitration.status == Status.Failed, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[uint256(_questionID)];
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationFailure.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationCanceled(_questionID);
}
// ********************************* //
// * Appeals and arbitration * //
// ********************************* //
/**
* @notice Takes up to the total amount required to fund an answer. Reimburses the rest. Creates an appeal if at least two answers are funded.
* @param _arbitrationID The ID of the arbitration.
* @param _answer One of the possible rulings the arbitrator can give that the funder considers to be the correct answer to the question.
* @return Whether the answer was fully funded or not.
*/
function fundAppeal(uint256 _arbitrationID, uint256 _answer) external payable override returns (bool) {
Arbitration storage arbitration = arbitrations[_arbitrationID];
require(arbitration.status == Status.Created, "No dispute to appeal.");
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(arbitration.disputeID);
require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over.");
// Answer is equal to ruling - 1.
uint256 winner = arbitrator.currentRuling(arbitration.disputeID);
uint256 multiplier;
if (winner == _answer + 1) {
multiplier = winnerMultiplier;
} else {
require(
block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2,
"Appeal period is over for loser."
);
multiplier = loserMultiplier;
}
Round storage round = arbitration.rounds[arbitration.rounds.length - 1];
require(!round.hasPaid[_answer], "Appeal fee is already paid.");
uint256 appealCost = arbitrator.appealCost(arbitration.disputeID, arbitratorExtraData);
uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR);
// Take up to the amount necessary to fund the current round at the current costs.
uint256 contribution =
totalCost.subCap(round.paidFees[_answer]) > msg.value
? msg.value
: totalCost.subCap(round.paidFees[_answer]);
emit Contribution(_arbitrationID, arbitration.rounds.length - 1, _answer + 1, msg.sender, contribution);
round.contributions[msg.sender][_answer] += contribution;
round.paidFees[_answer] += contribution;
if (round.paidFees[_answer] >= totalCost) {
round.feeRewards += round.paidFees[_answer];
round.fundedAnswers.push(_answer);
round.hasPaid[_answer] = true;
emit RulingFunded(_arbitrationID, arbitration.rounds.length - 1, _answer + 1);
}
if (round.fundedAnswers.length > 1) {
// At least two sides are fully funded.
arbitration.rounds.push();
round.feeRewards = round.feeRewards.subCap(appealCost);
arbitrator.appeal{value: appealCost}(arbitration.disputeID, arbitratorExtraData);
}
msg.sender.transfer(msg.value.subCap(contribution)); // Sending extra value back to contributor.
return round.hasPaid[_answer];
}
/**
* @notice Sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. Reimburses contributions if there is no winner.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The address to send reward to.
* @param _round The round from which to withdraw.
* @param _answer The answer to query the reward from.
* @return reward The withdrawn amount.
*/
function withdrawFeesAndRewards(
uint256 _arbitrationID,
address payable _beneficiary,
uint256 _round,
uint256 _answer
) public override returns (uint256 reward) {
Arbitration storage arbitration = arbitrations[_arbitrationID];
Round storage round = arbitration.rounds[_round];
require(arbitration.status == Status.Ruled, "Dispute not resolved");
// Allow to reimburse if funding of the round was unsuccessful.
if (!round.hasPaid[_answer]) {
reward = round.contributions[_beneficiary][_answer];
} else if (!round.hasPaid[arbitration.answer]) {
// Reimburse unspent fees proportionally if the ultimate winner didn't pay appeal fees fully.
// Note that if only one side is funded it will become a winner and this part of the condition won't be reached.
reward = round.fundedAnswers.length > 1
? (round.contributions[_beneficiary][_answer] * round.feeRewards) /
(round.paidFees[round.fundedAnswers[0]] + round.paidFees[round.fundedAnswers[1]])
: 0;
} else if (arbitration.answer == _answer) {
// Reward the winner.
reward = round.paidFees[_answer] > 0
? (round.contributions[_beneficiary][_answer] * round.feeRewards) / round.paidFees[_answer]
: 0;
}
if (reward != 0) {
round.contributions[_beneficiary][_answer] = 0;
_beneficiary.transfer(reward);
emit Withdrawal(_arbitrationID, _round, _answer + 1, _beneficiary, reward);
}
}
/**
* @notice Allows to withdraw any reimbursable fees or rewards after the dispute gets solved for multiple ruling options (answers) at once.
* @dev This function is O(n) where n is the number of queried answers.
* @dev This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The address that made contributions.
* @param _round The round from which to withdraw.
* @param _contributedTo Answers that received contributions from contributor.
*/
function withdrawFeesAndRewardsForMultipleRulings(
uint256 _arbitrationID,
address payable _beneficiary,
uint256 _round,
uint256[] memory _contributedTo
) public override {
for (uint256 contributionNumber = 0; contributionNumber < _contributedTo.length; contributionNumber++) {
withdrawFeesAndRewards(_arbitrationID, _beneficiary, _round, _contributedTo[contributionNumber]);
}
}
/**
* @notice Allows to withdraw any rewards or reimbursable fees for multiple rulings options (answers) and for all rounds at once.
* @dev This function is O(n*m) where n is the total number of rounds and m is the number of queried answers.
* @dev This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The address that made contributions.
* @param _contributedTo Answers that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(
uint256 _arbitrationID,
address payable _beneficiary,
uint256[] memory _contributedTo
) external override {
for (uint256 roundNumber = 0; roundNumber < arbitrations[_arbitrationID].rounds.length; roundNumber++) {
withdrawFeesAndRewardsForMultipleRulings(_arbitrationID, _beneficiary, roundNumber, _contributedTo);
}
}
/**
* @notice Allows to submit evidence for a particular question.
* @param _arbitrationID The ID of the arbitration related to the question.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint256 _arbitrationID, string calldata _evidenceURI) external override {
Arbitration storage arbitration = arbitrations[_arbitrationID];
require(arbitration.status == Status.Created, "The status should be Created.");
if (bytes(_evidenceURI).length > 0) emit Evidence(arbitrator, _arbitrationID, msg.sender, _evidenceURI);
}
/**
* @notice Rules a specified dispute.
* @dev Note that 0 is reserved for "Unable/refused to arbitrate" and we shift it to `uint(-1)` which has a similar connotation in Realitio.
* @param _disputeID The ID of the dispute in the ERC792 arbitrator.
* @param _ruling The ruling given by the arbitrator.
*/
function rule(uint256 _disputeID, uint256 _ruling) external override onlyArbitrator {
uint256 arbitrationID = externalIDtoLocalID[_disputeID];
Arbitration storage arbitration = arbitrations[arbitrationID];
require(arbitration.status == Status.Created, "Invalid arbitration status");
uint256 finalRuling = _ruling;
// If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.
Round storage round = arbitration.rounds[arbitration.rounds.length - 1];
if (round.fundedAnswers.length == 1) finalRuling = round.fundedAnswers[0] + 1;
// Realitio ruling is shifted by 1 compared to Kleros.
arbitration.answer = finalRuling - 1;
arbitration.status = Status.Ruled;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationAnswer.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, bytes32(arbitrationID), bytes32(arbitration.answer));
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit Ruling(arbitrator, _disputeID, _ruling);
}
/* External Views */
/**
* @notice Returns stake multipliers.
* @return winner Winners stake multiplier.
* @return loser Losers stake multiplier.
* @return shared Multiplier when it's a tie. Is not used in this contract.
* @return divisor Multiplier divisor.
*/
function getMultipliers()
external
view
override
returns (
uint256 winner,
uint256 loser,
uint256 shared,
uint256 divisor
)
{
return (winnerMultiplier, loserMultiplier, 0, MULTIPLIER_DIVISOR);
}
/**
* @notice Returns number of possible ruling options. Valid rulings are [0, return value].
* @param _arbitrationID The ID of the arbitration.
* @return count The number of ruling options.
*/
function numberOfRulingOptions(uint256 _arbitrationID) external pure override returns (uint256) {
return NUMBER_OF_CHOICES_FOR_ARBITRATOR;
}
/**
* @notice Gets the fee to create a dispute.
* @return The fee to create a dispute.
*/
function getDisputeFee(bytes32 _questionID) external view override returns (uint256) {
return arbitrator.arbitrationCost(arbitratorExtraData);
}
/**
* @notice Gets the number of rounds of the specific question.
* @param _arbitrationID The ID of the arbitration.
* @return The number of rounds.
*/
function getNumberOfRounds(uint256 _arbitrationID) external view returns (uint256) {
return arbitrations[_arbitrationID].rounds.length;
}
/**
* @notice Gets the information of a round of a question.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @return paidFees The amount of fees paid for each fully funded answer.
* @return feeRewards The amount of fees that will be used as rewards.
* @return fundedAnswers IDs of fully funded answers.
*/
function getRoundInfo(uint256 _arbitrationID, uint256 _round)
external
view
returns (
uint256[] memory paidFees,
uint256 feeRewards,
uint256[] memory fundedAnswers
)
{
Round storage round = arbitrations[_arbitrationID].rounds[_round];
fundedAnswers = round.fundedAnswers;
paidFees = new uint256[](round.fundedAnswers.length);
for (uint256 i = 0; i < round.fundedAnswers.length; i++) {
paidFees[i] = round.paidFees[round.fundedAnswers[i]];
}
feeRewards = round.feeRewards;
}
/**
* @notice Gets the information of a round of a question for a specific answer choice.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @param _answer The answer choice to get funding status for.
* @return raised The amount paid for this answer.
* @return fullyFunded Whether the answer is fully funded or not.
*/
function getFundingStatus(
uint256 _arbitrationID,
uint256 _round,
uint256 _answer
) external view returns (uint256 raised, bool fullyFunded) {
Round storage round = arbitrations[_arbitrationID].rounds[_round];
raised = round.paidFees[_answer];
fullyFunded = round.hasPaid[_answer];
}
/**
* @notice Gets contributions to the answers that are fully funded.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @param _contributor The address whose contributions to query.
* @return fundedAnswers IDs of the answers that are fully funded.
* @return contributions The amount contributed to each funded answer by the contributor.
*/
function getContributionsToSuccessfulFundings(
uint256 _arbitrationID,
uint256 _round,
address _contributor
) external view returns (uint256[] memory fundedAnswers, uint256[] memory contributions) {
Round storage round = arbitrations[_arbitrationID].rounds[_round];
fundedAnswers = round.fundedAnswers;
contributions = new uint256[](round.fundedAnswers.length);
for (uint256 i = 0; i < contributions.length; i++) {
contributions[i] = round.contributions[_contributor][fundedAnswers[i]];
}
}
/**
* @notice Casts question ID into uint256 thus returning the related arbitration ID.
* @param _questionID The ID of the question.
* @return The ID of the arbitration.
*/
function questionIDToArbitrationID(bytes32 _questionID) external pure returns (uint256) {
return uint256(_questionID);
}
}
| Requests arbitration for a given question ID. Can be executed only if the contract has been initialized. _questionID The ID of the question. _contestedAnswer The answer the requester deems to be incorrect./ | function requestArbitration(bytes32 _questionID, bytes32 _contestedAnswer) external payable onlyIfInitialized {
Arbitration storage arbitration = arbitrations[uint256(_questionID)];
require(arbitration.status == Status.None, "Arbitration already requested");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= arbitrationCost, "Deposit value too low");
arbitration.status = Status.Requested;
arbitration.requester = msg.sender;
arbitration.deposit = msg.value;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationRequest.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, _contestedAnswer, msg.sender);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationRequested(_questionID, _contestedAnswer, msg.sender);
}
| 5,544,816 |
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_CrossDomainMessenger
*/
interface iOVM_CrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(bytes message);
event RelayedMessage(bytes32 msgHash);
event FailedRelayedMessage(bytes32 msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from
"../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol";
/**
* @title OVM_CrossDomainEnabled
* @dev Helper contract for contracts performing cross-domain communications
*
* Compiler used: defined by inheriting contract
* Runtime target: defined by inheriting contract
*/
contract OVM_CrossDomainEnabled {
/*************
* Variables *
*************/
// Messenger contract used to send and recieve messages from the other domain.
address public messenger;
/***************
* Constructor *
***************/
/**
* @param _messenger Address of the CrossDomainMessenger on the current layer.
*/
constructor(
address _messenger
) {
messenger = _messenger;
}
/**********************
* Function Modifiers *
**********************/
/**
* Enforces that the modified function is only callable by a specific cross-domain account.
* @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function.
*/
modifier onlyFromCrossDomainAccount(
address _sourceDomainAccount
) {
require(
msg.sender == address(getCrossDomainMessenger()),
"OVM_XCHAIN: messenger contract unauthenticated"
);
require(
getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,
"OVM_XCHAIN: wrong sender of cross-domain message"
);
_;
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the messenger, usually from storage. This function is exposed in case a child contract
* needs to override.
* @return The address of the cross-domain messenger contract which should be used.
*/
function getCrossDomainMessenger()
internal
virtual
returns (
iOVM_CrossDomainMessenger
)
{
return iOVM_CrossDomainMessenger(messenger);
}
/**
* Sends a message to an account on another domain
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
*/
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message
)
internal
{
getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol";
import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol";
import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol";
/* Library Imports */
import { ERC165Checker } from "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { IL2StandardERC20 } from "../../../libraries/standards/IL2StandardERC20.sol";
/**
* @title OVM_L2StandardBridge
* @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to
* enable ETH and ERC20 transitions between L1 and L2.
* This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard
* bridge.
* This contract also acts as a burner of the tokens intended for withdrawal, informing the L1
* bridge to release L1 funds.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled {
/********************************
* External Contract References *
********************************/
address public l1TokenBridge;
/***************
* Constructor *
***************/
/**
* @param _l2CrossDomainMessenger Cross-domain messenger used by this contract.
* @param _l1TokenBridge Address of the L1 bridge deployed to the main chain.
*/
constructor(
address _l2CrossDomainMessenger,
address _l1TokenBridge
)
OVM_CrossDomainEnabled(_l2CrossDomainMessenger)
{
l1TokenBridge = _l1TokenBridge;
}
/***************
* Withdrawing *
***************/
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
msg.sender,
_amount,
_l1Gas,
_data
);
}
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function withdrawTo(
address _l2Token,
address _to,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
_to,
_amount,
_l1Gas,
_data
);
}
/**
* @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway
* of the deposit.
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _from Account to pull the deposit from on L2.
* @param _to Account to give the withdrawal to on L1.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateWithdrawal(
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
internal
{
// When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2
// usage
IL2StandardERC20(_l2Token).burn(msg.sender, _amount);
// Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount)
address l1Token = IL2StandardERC20(_l2Token).l1Token();
bytes memory message;
if (_l2Token == Lib_PredeployAddresses.OVM_ETH) {
message = abi.encodeWithSelector(
iOVM_L1StandardBridge.finalizeETHWithdrawal.selector,
_from,
_to,
_amount,
_data
);
} else {
message = abi.encodeWithSelector(
iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,
l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
}
// Send message up to L1 bridge
sendCrossDomainMessage(
l1TokenBridge,
_l1Gas,
message
);
emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data);
}
/************************************
* Cross-chain Function: Depositing *
************************************/
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function finalizeDeposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
virtual
onlyFromCrossDomainAccount(l1TokenBridge)
{
// Check the target token is compliant and
// verify the deposited token on L1 matches the L2 deposited token representation here
if (
ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) &&
_l1Token == IL2StandardERC20(_l2Token).l1Token()
) {
// When a deposit is finalized, we credit the account on L2 with the same amount of
// tokens.
IL2StandardERC20(_l2Token).mint(_to, _amount);
emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);
} else {
// Either the L2 token which is being deposited-into disagrees about the correct address
// of its L1 token, or does not support the correct interface.
// This should only happen if there is a malicious L2 token, or if a user somehow
// specified the wrong L2 token address to deposit into.
// In either case, we stop the process here and construct a withdrawal
// message so that users can get their funds out in some cases.
// There is no way to prevent malicious token contracts altogether, but this does limit
// user error and mitigate some forms of malicious contract behavior.
bytes memory message = abi.encodeWithSelector(
iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,
_l1Token,
_l2Token,
_to, // switched the _to and _from here to bounce back the deposit to the sender
_from,
_amount,
_data
);
// Send message up to L1 bridge
sendCrossDomainMessage(
l1TokenBridge,
0,
message
);
emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
import "./iOVM_L1ERC20Bridge.sol";
/**
* @title iOVM_L1StandardBridge
*/
interface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge {
/**********
* Events *
**********/
event ETHDepositInitiated (
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
event ETHWithdrawalFinalized (
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev Deposit an amount of the ETH to the caller's balance on L2.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositETH (
uint32 _l2Gas,
bytes calldata _data
)
external
payable;
/**
* @dev Deposit an amount of ETH to a recipient's balance on L2.
* @param _to L2 address to credit the withdrawal to.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositETHTo (
address _to,
uint32 _l2Gas,
bytes calldata _data
)
external
payable;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the
* L1 ETH token. Since only the xDomainMessenger can call this function, it will never be called
* before the withdrawal is finalized.
* @param _from L2 address initiating the transfer.
* @param _to L1 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeETHWithdrawal (
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_L1ERC20Bridge
*/
interface iOVM_L1ERC20Bridge {
/**********
* Events *
**********/
event ERC20DepositInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event ERC20WithdrawalFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev deposit an amount of the ERC20 to the caller's balance on L2.
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _amount Amount of the ERC20 to deposit
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositERC20 (
address _l1Token,
address _l2Token,
uint _amount,
uint32 _l2Gas,
bytes calldata _data
)
external;
/**
* @dev deposit an amount of ERC20 to a recipient's balance on L2.
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _to L2 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositERC20To (
address _l1Token,
address _l2Token,
address _to,
uint _amount,
uint32 _l2Gas,
bytes calldata _data
)
external;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the
* L1 ERC20 token.
* This call will fail if the initialized withdrawal from L2 has not been finalized.
*
* @param _l1Token Address of L1 token to finalizeWithdrawal for.
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _from L2 address initiating the transfer.
* @param _to L1 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _data Data provided by the sender on L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeERC20Withdrawal (
address _l1Token,
address _l2Token,
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_L2ERC20Bridge
*/
interface iOVM_L2ERC20Bridge {
/**********
* Events *
**********/
event WithdrawalInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev initiate a withdraw of some tokens to the caller's account on L1
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function withdraw (
address _l2Token,
uint _amount,
uint32 _l1Gas,
bytes calldata _data
)
external;
/**
* @dev initiate a withdraw of some token to a recipient's account on L1.
* @param _l2Token Address of L2 token where withdrawal is initiated.
* @param _to L1 adress to credit the withdrawal to.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function withdrawTo (
address _l2Token,
address _to,
uint _amount,
uint32 _l1Gas,
bytes calldata _data
)
external;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this
* L2 token. This call will fail if it did not originate from a corresponding deposit in
* OVM_l1TokenGateway.
* @param _l1Token Address for the l1 token this is called with
* @param _l2Token Address for the l2 token this is called with
* @param _from Account to pull the deposit from on L2.
* @param _to Address to receive the withdrawal at
* @param _amount Amount of the token to withdraw
* @param _data Data provider by the sender on L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeDeposit (
address _l1Token,
address _l2Token,
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_PredeployAddresses
*/
library Lib_PredeployAddresses {
address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;
address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;
address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;
address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003;
address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005;
address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006;
// solhint-disable-next-line max-line-length
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;
// solhint-disable-next-line max-line-length
address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B;
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24;
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
interface IL2StandardERC20 is IERC20, IERC165 {
function l1Token() external returns (address);
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
event Mint(address indexed _account, uint256 _amount);
event Burn(address indexed _account, uint256 _amount);
}
// 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 Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { OVM_ETH } from "../predeploys/OVM_ETH.sol";
import { OVM_L2StandardBridge } from "../bridge/tokens/OVM_L2StandardBridge.sol";
/**
* @title OVM_SequencerFeeVault
* @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future
* but "good enough for now".
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_SequencerFeeVault {
/*************
* Constants *
*************/
// Minimum ETH balance that can be withdrawn in a single withdrawal.
uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether;
/*************
* Variables *
*************/
// Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth.
address public l1FeeWallet;
/***************
* Constructor *
***************/
/**
* @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn.
* Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during
* the genesis block. This is ONLY for testing purposes.
*/
constructor(
address _l1FeeWallet
) {
l1FeeWallet = _l1FeeWallet;
}
/********************
* Public Functions *
********************/
function withdraw()
public
{
uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this));
require(
balance >= MIN_WITHDRAWAL_AMOUNT,
// solhint-disable-next-line max-line-length
"OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount"
);
OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo(
Lib_PredeployAddresses.OVM_ETH,
l1FeeWallet,
balance,
0,
bytes("")
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { L2StandardERC20 } from "../../libraries/standards/L2StandardERC20.sol";
import { IWETH9 } from "../../libraries/standards/IWETH9.sol";
/**
* @title OVM_ETH
* @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that
* unlike on Layer 1, Layer 2 accounts do not have a balance field.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ETH is L2StandardERC20, IWETH9 {
/***************
* Constructor *
***************/
constructor()
L2StandardERC20(
Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
address(0),
"Ether",
"ETH"
)
{}
/******************************
* Custom WETH9 Functionality *
******************************/
fallback() external payable {
deposit();
}
/**
* Implements the WETH9 deposit() function as a no-op.
* WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant
* deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.
* This function allows developers to treat OVM_ETH as WETH without any modifications to their
* code.
*/
function deposit()
public
payable
override
{
// Calling deposit() with nonzero value will send the ETH to this contract address.
// Once received here, we transfer it back by sending to the msg.sender.
_transfer(address(this), msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
/**
* Implements the WETH9 withdraw() function as a no-op.
* WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant
* deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.
* This function allows developers to treat OVM_ETH as WETH without any modifications to their
* code.
* @param _wad Amount being withdrawn
*/
function withdraw(
uint256 _wad
)
external
override
{
// Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert,
// as in WETH9.
require(balanceOf(msg.sender) >= _wad);
// Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do
// anything else.
emit Withdrawal(msg.sender, _wad);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.8.0;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./IL2StandardERC20.sol";
contract L2StandardERC20 is IL2StandardERC20, ERC20 {
address public override l1Token;
address public l2Bridge;
/**
* @param _l2Bridge Address of the L2 standard bridge.
* @param _l1Token Address of the corresponding L1 token.
* @param _name ERC20 name.
* @param _symbol ERC20 symbol.
*/
constructor(
address _l2Bridge,
address _l1Token,
string memory _name,
string memory _symbol
)
ERC20(_name, _symbol) {
l1Token = _l1Token;
l2Bridge = _l2Bridge;
}
modifier onlyL2Bridge {
require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn");
_;
}
function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) {
bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector
^ IL2StandardERC20.mint.selector
^ IL2StandardERC20.burn.selector;
return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface;
}
function mint(address _to, uint256 _amount) public virtual override onlyL2Bridge {
_mint(_to, _amount);
emit Mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public virtual override onlyL2Bridge {
_burn(_from, _amount);
emit Burn(_from, _amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9. Also contains the non-ERC20 events
/// normally present in the WETH9 implementation.
interface IWETH9 is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// 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;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
//require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol";
import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol";
import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/* Library Imports */
import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title OVM_L1StandardBridge
* @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard
* tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits
* and listening to it for newly finalized withdrawals.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled {
using SafeMath for uint;
using SafeERC20 for IERC20;
/********************************
* External Contract References *
********************************/
address public l2TokenBridge;
// Maps L1 token to L2 token to balance of the L1 token deposited
mapping(address => mapping (address => uint256)) public deposits;
/***************
* Constructor *
***************/
// This contract lives behind a proxy, so the constructor parameters will go unused.
constructor()
OVM_CrossDomainEnabled(address(0))
{}
/******************
* Initialization *
******************/
/**
* @param _l1messenger L1 Messenger address being used for cross-chain communications.
* @param _l2TokenBridge L2 standard bridge address.
*/
function initialize(
address _l1messenger,
address _l2TokenBridge
)
public
{
require(messenger == address(0), "Contract has already been initialized.");
messenger = _l1messenger;
l2TokenBridge = _l2TokenBridge;
}
/**************
* Depositing *
**************/
/** @dev Modifier requiring sender to be EOA. This check could be bypassed by a malicious
* contract via initcode, but it takes care of the user error we want to avoid.
*/
modifier onlyEOA() {
// Used to stop deposits from contracts (avoid accidentally lost tokens)
require(!Address.isContract(msg.sender), "Account not EOA");
_;
}
/**
* @dev This function can be called with no data
* to deposit an amount of ETH to the caller's balance on L2.
* Since the receive function doesn't take data, a conservative
* default amount is forwarded to L2.
*/
receive()
external
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
1_300_000,
bytes("")
);
}
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function depositETH(
uint32 _l2Gas,
bytes calldata _data
)
external
override
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
_l2Gas,
_data
);
}
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function depositETHTo(
address _to,
uint32 _l2Gas,
bytes calldata _data
)
external
override
payable
{
_initiateETHDeposit(
msg.sender,
_to,
_l2Gas,
_data
);
}
/**
* @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of
* the deposit.
* @param _from Account to pull the deposit from on L1.
* @param _to Account to give the deposit to on L2.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateETHDeposit(
address _from,
address _to,
uint32 _l2Gas,
bytes memory _data
)
internal
{
// Construct calldata for finalizeDeposit call
bytes memory message =
abi.encodeWithSelector(
iOVM_L2ERC20Bridge.finalizeDeposit.selector,
address(0),
Lib_PredeployAddresses.OVM_ETH,
_from,
_to,
msg.value,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2TokenBridge,
_l2Gas,
message
);
emit ETHDepositInitiated(_from, _to, msg.value, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function depositERC20(
address _l1Token,
address _l2Token,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
external
override
virtual
onlyEOA()
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function depositERC20To(
address _l1Token,
address _l2Token,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data);
}
/**
* @dev Performs the logic for deposits by informing the L2 Deposited Token
* contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom)
*
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _from Account to pull the deposit from on L1
* @param _to Account to give the deposit to on L2
* @param _amount Amount of the ERC20 to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateERC20Deposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
internal
{
// When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future
// withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if
// _from is an EOA or address(0).
IERC20(_l1Token).safeTransferFrom(
_from,
address(this),
_amount
);
// Construct calldata for _l2Token.finalizeDeposit(_to, _amount)
bytes memory message = abi.encodeWithSelector(
iOVM_L2ERC20Bridge.finalizeDeposit.selector,
_l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2TokenBridge,
_l2Gas,
message
);
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount);
emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data);
}
/*************************
* Cross-chain Functions *
*************************/
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function finalizeETHWithdrawal(
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
onlyFromCrossDomainAccount(l2TokenBridge)
{
(bool success, ) = _to.call{value: _amount}(new bytes(0));
require(success, "TransferHelper::safeTransferETH: ETH transfer failed");
emit ETHWithdrawalFinalized(_from, _to, _amount, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function finalizeERC20Withdrawal(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
onlyFromCrossDomainAccount(l2TokenBridge)
{
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount);
// When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer
IERC20(_l1Token).safeTransfer(_to, _amount);
emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);
}
/*****************************
* Temporary - Migrating ETH *
*****************************/
/**
* @dev Adds ETH balance to the account. This is meant to allow for ETH
* to be migrated from an old gateway to a new gateway.
* NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the
* old contract
*/
function donateETH() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol";
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { OVM_ETH } from "../predeploys/OVM_ETH.sol";
/* External Imports */
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ECDSA } from "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title OVM_ECDSAContractAccount
* @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the
* ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by
* providing EIP155 formatted transaction encodings.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount {
/*************
* Libraries *
*************/
using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;
/*************
* Constants *
*************/
// TODO: should be the amount sufficient to cover the gas costs of all of the transactions up
// to and including the CALL/CREATE which forms the entrypoint of the transaction.
uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000;
/********************
* Public Functions *
********************/
/**
* No-op fallback mirrors behavior of calling an EOA on L1.
*/
fallback()
external
payable
{
return;
}
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(
bytes32 hash,
bytes memory signature
)
public
view
returns (
bytes4 magicValue
)
{
return ECDSA.recover(hash, signature) == address(this) ?
this.isValidSignature.selector :
bytes4(0);
}
/**
* Executes a signed transaction.
* @param _transaction Signed EIP155 transaction.
* @return Whether or not the call returned (rather than reverted).
* @return Data returned by the call.
*/
function execute(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
override
public
returns (
bool,
bytes memory
)
{
// Address of this contract within the ovm (ovmADDRESS) should be the same as the
// recovered address of the user who signed this message. This is how we manage to shim
// account abstraction even though the user isn't a contract.
require(
_transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(),
"Signature provided for EOA transaction execution is invalid."
);
require(
_transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(),
"Transaction signed with wrong chain ID"
);
// Need to make sure that the transaction nonce is right.
require(
_transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(),
"Transaction nonce does not match the expected nonce."
);
// TEMPORARY: Disable gas checks for mainnet.
// // Need to make sure that the gas is sufficient to execute the transaction.
// require(
// gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD),
// "Gas is not sufficient to execute the transaction."
// );
// Transfer fee to relayer.
require(
OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer(
Lib_PredeployAddresses.SEQUENCER_FEE_WALLET,
SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice)
),
"Fee was not transferred to relayer."
);
if (_transaction.isCreate) {
// TEMPORARY: Disable value transfer for contract creations.
require(
_transaction.value == 0,
"Value transfer in contract creation not supported."
);
(address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE(
_transaction.data
);
// Return true if the contract creation succeeded, false w/ revertdata otherwise.
if (created != address(0)) {
return (true, abi.encode(created));
} else {
return (false, revertdata);
}
} else {
// We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps
// the nonce of the calling account. Normally an EOA would bump the nonce for both
// cases, but since this is a contract we'd end up bumping the nonce twice.
Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE();
// NOTE: Upgrades are temporarily disabled because users can, in theory, modify their
// EOA so that they don't have to pay any fees to the sequencer. Function will remain
// disabled until a robust solution is in place.
require(
_transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(),
"Calls to self are disabled until upgradability is re-enabled."
);
return _transaction.to.call{value: _transaction.value}(_transaction.data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
/**
* @title iOVM_ECDSAContractAccount
*/
interface iOVM_ECDSAContractAccount {
/********************
* Public Functions *
********************/
function execute(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
external
returns (
bool,
bytes memory
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_EIP155Tx
* @dev A simple library for dealing with the transaction type defined by EIP155:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
*/
library Lib_EIP155Tx {
/***********
* Structs *
***********/
// Struct representing an EIP155 transaction. See EIP link above for more information.
struct EIP155Tx {
// These fields correspond to the actual RLP-encoded fields specified by EIP155.
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
uint8 v;
bytes32 r;
bytes32 s;
// Chain ID to associate this transaction with. Used all over the place, seemed easier to
// set this once when we create the transaction rather than providing it as an input to
// each function. I don't see a strong need to have a transaction with a mutable chain ID.
uint256 chainId;
// The ECDSA "recovery parameter," should always be 0 or 1. EIP155 specifies that:
// `v = {0,1} + CHAIN_ID * 2 + 35`
// Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for
// the recovery parameter:
// 1. `v = {0,1} + CHAIN_ID * 2 + 35`
// 2. `v = recovery_parameter + CHAIN_ID * 2 + 35`
// 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter`
// So we're left with the final formula:
// `recovery_parameter = v - CHAIN_ID * 2 - 35`
// NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we
// didn't use a uint8, then recovery_parameter would always be a negative number for chain
// IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support
// anything larger.
uint8 recoveryParam;
// Whether or not the transaction is a creation. Necessary because we can't make an address
// "nil". Using the zero address creates a potential conflict if the user did actually
// intend to send a transaction to the zero address.
bool isCreate;
}
// Lets us use nicer syntax.
using Lib_EIP155Tx for EIP155Tx;
/**********************
* Internal Functions *
**********************/
/**
* Decodes an EIP155 transaction and attaches a given Chain ID.
* Transaction *must* be RLP-encoded.
* @param _encoded RLP-encoded EIP155 transaction.
* @param _chainId Chain ID to assocaite with this transaction.
* @return Parsed transaction.
*/
function decode(
bytes memory _encoded,
uint256 _chainId
)
internal
pure
returns (
EIP155Tx memory
)
{
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded);
// Note formula above about how recoveryParam is computed.
uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6]));
uint8 recoveryParam = uint8(v - 2 * _chainId - 35);
// Recovery param being anything other than 0 or 1 indicates that we have the wrong chain
// ID.
require(
recoveryParam < 2,
"Lib_EIP155Tx: Transaction signed with wrong chain ID"
);
// Creations can be detected by looking at the byte length here.
bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0;
return EIP155Tx({
nonce: Lib_RLPReader.readUint256(decoded[0]),
gasPrice: Lib_RLPReader.readUint256(decoded[1]),
gasLimit: Lib_RLPReader.readUint256(decoded[2]),
to: Lib_RLPReader.readAddress(decoded[3]),
value: Lib_RLPReader.readUint256(decoded[4]),
data: Lib_RLPReader.readBytes(decoded[5]),
v: v,
r: Lib_RLPReader.readBytes32(decoded[7]),
s: Lib_RLPReader.readBytes32(decoded[8]),
chainId: _chainId,
recoveryParam: recoveryParam,
isCreate: isCreate
});
}
/**
* Encodes an EIP155 transaction into RLP.
* @param _transaction EIP155 transaction to encode.
* @param _includeSignature Whether or not to encode the signature.
* @return RLP-encoded transaction.
*/
function encode(
EIP155Tx memory _transaction,
bool _includeSignature
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](9);
raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce);
raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice);
raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit);
// We write the encoding of empty bytes when the transaction is a creation, *not* the zero
// address as one might assume.
if (_transaction.isCreate) {
raw[3] = Lib_RLPWriter.writeBytes("");
} else {
raw[3] = Lib_RLPWriter.writeAddress(_transaction.to);
}
raw[4] = Lib_RLPWriter.writeUint(_transaction.value);
raw[5] = Lib_RLPWriter.writeBytes(_transaction.data);
if (_includeSignature) {
raw[6] = Lib_RLPWriter.writeUint(_transaction.v);
raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r);
raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s);
} else {
// Chain ID *is* included in the unsigned transaction.
raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId);
raw[7] = Lib_RLPWriter.writeBytes("");
raw[8] = Lib_RLPWriter.writeBytes("");
}
return Lib_RLPWriter.writeList(raw);
}
/**
* Computes the hash of an EIP155 transaction. Assumes that you don't want to include the
* signature in this hash because that's a very uncommon usecase. If you really want to include
* the signature, just encode with the signature and take the hash yourself.
*/
function hash(
EIP155Tx memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(
_transaction.encode(false)
);
}
/**
* Computes the sender of an EIP155 transaction.
* @param _transaction EIP155 transaction to get a sender for.
* @return Address corresponding to the private key that signed this transaction.
*/
function sender(
EIP155Tx memory _transaction
)
internal
pure
returns (
address
)
{
return ecrecover(
_transaction.hash(),
_transaction.recoveryParam + 27,
_transaction.r,
_transaction.s
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol";
import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol";
/**
* @title Lib_ExecutionManagerWrapper
* @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the
* predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the
* user to trigger OVM opcodes by directly calling the OVM_ExecutionManger.
*
* Compiler used: solc
* Runtime target: OVM
*/
library Lib_ExecutionManagerWrapper {
/**********************
* Internal Functions *
**********************/
/**
* Performs a safe ovmCREATE call.
* @param _bytecode Code for the new contract.
* @return Address of the created contract.
*/
function ovmCREATE(
bytes memory _bytecode
)
internal
returns (
address,
bytes memory
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCREATE(bytes)",
_bytecode
)
);
return abi.decode(returndata, (address, bytes));
}
/**
* Performs a safe ovmGETNONCE call.
* @return Result of calling ovmGETNONCE.
*/
function ovmGETNONCE()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmGETNONCE()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmINCREMENTNONCE call.
*/
function ovmINCREMENTNONCE()
internal
{
_callWrapperContract(
abi.encodeWithSignature(
"ovmINCREMENTNONCE()"
)
);
}
/**
* Performs a safe ovmCREATEEOA call.
* @param _messageHash Message hash which was signed by EOA
* @param _v v value of signature (0 or 1)
* @param _r r value of signature
* @param _s s value of signature
*/
function ovmCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
_callWrapperContract(
abi.encodeWithSignature(
"ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)",
_messageHash,
_v,
_r,
_s
)
);
}
/**
* Calls the ovmL1TXORIGIN opcode.
* @return Address that sent this message from L1.
*/
function ovmL1TXORIGIN()
internal
returns (
address
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmL1TXORIGIN()"
)
);
return abi.decode(returndata, (address));
}
/**
* Calls the ovmCHAINID opcode.
* @return Chain ID of the current network.
*/
function ovmCHAINID()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCHAINID()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmADDRESS call.
* @return Result of calling ovmADDRESS.
*/
function ovmADDRESS()
internal
returns (
address
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
/**
* Calls the value-enabled ovmCALL opcode.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _value ETH value to pass with the call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
uint256 _value,
bytes memory _calldata
)
internal
returns (
bool,
bytes memory
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCALL(uint256,address,uint256,bytes)",
_gasLimit,
_address,
_value,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Calls the ovmBALANCE opcode.
* @param _address OVM account to query the balance of.
* @return Balance of the account.
*/
function ovmBALANCE(
address _address
)
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmBALANCE(address)",
_address
)
);
return abi.decode(returndata, (uint256));
}
/**
* Calls the ovmCALLVALUE opcode.
* @return Value of the current call frame.
*/
function ovmCALLVALUE()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCALLVALUE()"
)
);
return abi.decode(returndata, (uint256));
}
/*********************
* Private Functions *
*********************/
/**
* Performs an ovm interaction and the necessary safety checks.
* @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).
* @return Data sent back by the OVM_ExecutionManager.
*/
function _callWrapperContract(
bytes memory _calldata
)
private
returns (
bytes memory
)
{
(bool success, bytes memory returndata) =
Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata);
if (success == true) {
return returndata;
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_ErrorUtils
*/
library Lib_ErrorUtils {
/**********************
* Internal Functions *
**********************/
/**
* Encodes an error string into raw solidity-style revert data.
* (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))"))
* Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)
* #panic-via-assert-and-error-via-require
* @param _reason Reason for the reversion.
* @return Standard solidity revert data for the given reason.
*/
function encodeRevertString(
string memory _reason
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"Error(string)",
_reason
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
/**
* @title OVM_ProxyEOA
* @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation
* contract. In combination with the logic implemented in the ECDSA Contract Account, this enables
* a form of upgradable 'account abstraction' on layer 2.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ProxyEOA {
/**********
* Events *
**********/
event Upgraded(
address indexed implementation
);
/*************
* Constants *
*************/
// solhint-disable-next-line max-line-length
bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1);
/*********************
* Fallback Function *
*********************/
fallback()
external
payable
{
(bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data);
if (success) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
// WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA
// contracts. As a result, we must *not* perform any constructor logic. Use initialization
// functions if necessary.
/********************
* Public Functions *
********************/
/**
* Changes the implementation address.
* @param _implementation New implementation address.
*/
function upgrade(
address _implementation
)
external
{
require(
msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(),
"EOAs can only upgrade their own EOA implementation."
);
_setImplementation(_implementation);
emit Upgraded(_implementation);
}
/**
* Gets the address of the current implementation.
* @return Current implementation address.
*/
function getImplementation()
public
view
returns (
address
)
{
bytes32 addr32;
assembly {
addr32 := sload(IMPLEMENTATION_KEY)
}
address implementation = Lib_Bytes32Utils.toAddress(addr32);
if (implementation == address(0)) {
return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT;
} else {
return implementation;
}
}
/**********************
* Internal Functions *
**********************/
function _setImplementation(
address _implementation
)
internal
{
bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation);
assembly {
sstore(IMPLEMENTATION_KEY, addr32)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol";
/**
* @title OVM_SequencerEntrypoint
* @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by
* any account. It accepts a more efficient compressed calldata format, which it decompresses and
* encodes to the standard EIP155 transaction format.
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_SequencerEntrypoint {
/*************
* Libraries *
*************/
using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;
/*********************
* Fallback Function *
*********************/
/**
* Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed
* description of this transaction format:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
*/
fallback()
external
{
// We use this twice, so it's more gas efficient to store a copy of it (barely).
bytes memory encodedTx = msg.data;
// Decode the tx with the correct chain ID.
Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode(
encodedTx,
Lib_ExecutionManagerWrapper.ovmCHAINID()
);
// Value is computed on the fly. Keep it in the stack to save some gas.
address target = transaction.sender();
bool isEmptyContract;
assembly {
isEmptyContract := iszero(extcodesize(target))
}
// If the account is empty, deploy the default EOA to that address.
if (isEmptyContract) {
Lib_ExecutionManagerWrapper.ovmCREATEEOA(
transaction.hash(),
transaction.recoveryParam,
transaction.r,
transaction.s
);
}
// Forward the transaction over to the EOA.
(bool success, bytes memory returndata) = target.call(
abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction)
);
if (success) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol";
/**
* @title TestLib_EIP155Tx
*/
contract TestLib_EIP155Tx {
function decode(
bytes memory _encoded,
uint256 _chainId
)
public
pure
returns (
Lib_EIP155Tx.EIP155Tx memory
)
{
return Lib_EIP155Tx.decode(
_encoded,
_chainId
);
}
function encode(
Lib_EIP155Tx.EIP155Tx memory _transaction,
bool _includeSignature
)
public
pure
returns (
bytes memory
)
{
return Lib_EIP155Tx.encode(
_transaction,
_includeSignature
);
}
function hash(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
public
pure
returns (
bytes32
)
{
return Lib_EIP155Tx.hash(
_transaction
);
}
function sender(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
public
pure
returns (
address
)
{
return Lib_EIP155Tx.sender(
_transaction
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol";
/**
* @title TestLib_RLPWriter
*/
contract TestLib_RLPWriter {
function writeBytes(
bytes memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBytes(_in);
}
function writeList(
bytes[] memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeList(_in);
}
function writeString(
string memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeString(_in);
}
function writeAddress(
address _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeAddress(_in);
}
function writeUint(
uint256 _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeUint(_in);
}
function writeBool(
bool _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBool(_in);
}
function writeAddressWithTaintedMemory(
address _in
)
public
returns (
bytes memory _out
)
{
new TestERC20();
return Lib_RLPWriter.writeAddress(_in);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
// a test ERC20 token with an open mint function
contract TestERC20 {
using SafeMath for uint;
string public constant name = 'Test';
string public constant symbol = 'TST';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() {}
function mint(address to, uint256 value) public {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_BytesUtils } from "../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol";
/**
* @title TestLib_BytesUtils
*/
contract TestLib_BytesUtils {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
public
pure
returns (bytes memory)
{
return abi.encodePacked(
_preBytes,
_postBytes
);
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.slice(
_bytes,
_start,
_length
);
}
function toBytes32(
bytes memory _bytes
)
public
pure
returns (bytes32)
{
return Lib_BytesUtils.toBytes32(
_bytes
);
}
function toUint256(
bytes memory _bytes
)
public
pure
returns (uint256)
{
return Lib_BytesUtils.toUint256(
_bytes
);
}
function toNibbles(
bytes memory _bytes
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.toNibbles(
_bytes
);
}
function fromNibbles(
bytes memory _bytes
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.fromNibbles(
_bytes
);
}
function equal(
bytes memory _bytes,
bytes memory _other
)
public
pure
returns (bool)
{
return Lib_BytesUtils.equal(
_bytes,
_other
);
}
function sliceWithTaintedMemory(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
public
returns (bytes memory)
{
new TestERC20();
return Lib_BytesUtils.slice(
_bytes,
_start,
_length
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol";
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
* @dev The State Transitioner coordinates the execution of a state transition during the evaluation
* of a fraud proof. It feeds verified input to the Execution Manager's run(), and controls a
* State Manager (which is uniquely created for each fraud proof).
* Once a fraud proof has been initialized, this contract is provided with the pre-state root and
* verifies that the OVM storage slots committed to the State Mangager are contained in that state
* This contract controls the State Manager and Execution Manager, and uses them to calculate the
* post-state root by applying the transaction. The Fraud Verifier can then check for fraud by
* comparing the calculated post-state root with the proposed post-state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner
{
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_StateManager public ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase public phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/*************
* Constants *
*************/
// solhint-disable-next-line max-line-length
bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line max-line-length
bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory"))
.create(address(this));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
external
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
external
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
external
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _ethContractAddress Address of the corresponding contract on L1.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
(
ovmStateManager.hasAccount(_ovmContractAddress) == false
&& ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false
),
"Account state has already been proven."
);
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
);
if (exists == true) {
// Account exists, this was an inclusion proof.
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedAccount
);
address ethContractAddress = _ethContractAddress;
if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {
// Use a known empty contract to prevent an attack in which a user provides a
// contract address here and then later deploys code to it.
ethContractAddress = 0x0000000000000000000000000000000000000000;
} else {
// Otherwise, make sure that the code at the provided eth address matches the hash
// of the code stored on L2.
require(
Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,
// solhint-disable-next-line max-line-length
"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash."
);
}
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: account.nonce,
balance: account.balance,
storageRoot: account.storageRoot,
codeHash: account.codeHash,
ethAddress: ethContractAddress,
isFresh: false
})
);
} else {
// Account does not exist, this was an exclusion proof.
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);
bytes32 value;
if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {
// Storage trie was empty, so the user is always allowed to insert zero-byte values.
value = bytes32(0);
} else {
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedValue
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
storageRoot
);
if (exists == true) {
// Inclusion proof.
// Stored values are RLP encoded, with leading zeros removed.
value = Lib_BytesUtils.toBytes32PadLeft(
Lib_RLPReader.readBytes(encodedValue)
);
} else {
// Exclusion proof, can only be zero bytes.
value = bytes32(0);
}
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We require gas to complete the logic here in run() before/after execution,
// But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)
// This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first
// going into EM, then going into the code contract).
require(
// 1032/1000 = 1.032 = (64/63)^2 rounded up
gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000,
"Not enough gas to execute transaction deterministically."
);
iOVM_ExecutionManager ovmExecutionManager =
iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(address(ovmExecutionManager));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
// Prevent the Execution Manager from calling this SM again.
ovmStateManager.setExecutionManager(address(0));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before committing account states."
);
require (
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account state wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
// Emit an event to help clients figure out the proof ordering.
emit AccountCommitted(
_ovmContractAddress
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot value wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(value)
),
_storageTrieWitness,
account.storageRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
// Emit an event to help clients figure out the proof ordering.
emit ContractStorageCommitted(
_ovmContractAddress,
_key
);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
// solhint-disable-next-line max-line-length
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
// solhint-disable-next-line max-line-length
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
// solhint-disable-next-line max-line-length
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
// solhint-disable-next-line max-line-length
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
interface iOVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
enum MessageType {
ovmCALL,
ovmSTATICCALL,
ovmDELEGATECALL,
ovmCREATE,
ovmCREATE2
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
uint256 ovmCALLVALUE;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_OVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmCALLVALUE() external view returns (uint _callValue);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external
returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external
returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
// Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode.
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata)
external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external
returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/*********************
* ETH Value Opcodes *
*********************/
function ovmBALANCE(address _contract) external returns (uint256 _balance);
function ovmSELFBALANCE() external returns (uint256 _balance);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view
returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash)
external;
function testAndSetAccountLoaded(address _address) external
returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external
returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view
returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view
returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external
returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view
returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve("OVM_BondManager"))
.recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(
_name,
_address,
oldAddress
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) =
_walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes("");
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key
// meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path
// updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// solhint-disable-next-line max-line-length
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] =
_makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode =
_makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch =
_editBranchIndex(
newBranch,
branchKey,
_getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode =
_makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch =
_editBranchIndex(
newBranch,
branchKey,
_getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from
"../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/* Contract Imports */
import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol";
/**
* @title OVM_StateTransitionerFactory
* @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State
* Transitioner during the initialization of a fraud proof.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {
/***************
* Constructor *
***************/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateTransitioner
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
* @return New OVM_StateTransitioner instance.
*/
function create(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
override
public
returns (
iOVM_StateTransitioner
)
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"Create can only be done by the OVM_FraudVerifier."
);
return new OVM_StateTransitioner(
_libAddressManager,
_stateTransitionIndex,
_preStateRoot,
_transactionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view
returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from
"../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol";
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_FraudVerifier
* @dev The Fraud Verifier contract coordinates the entire fraud proof verification process.
* If the fraud proof was successful it prunes any state batches from State Commitment Chain
* which were published after the fraudulent state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier {
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
mapping (bytes32 => iOVM_StateTransitioner) internal transitioners;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/***************************************
* Public Functions: Transition Status *
***************************************/
/**
* Retrieves the state transitioner for a given root.
* @param _preStateRoot State root to query a transitioner for.
* @return _transitioner Corresponding state transitioner contract.
*/
function getStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
override
public
view
returns (
iOVM_StateTransitioner _transitioner
)
{
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
/****************************************
* Public Functions: Fraud Verification *
****************************************/
/**
* Begins the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _transaction OVM transaction claimed to be fraudulent.
* @param _txChainElement OVM transaction chain element.
* @param _transactionBatchHeader Batch header for the provided transaction.
* @param _transactionProof Inclusion proof for the provided transaction.
*/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _transactionProof
)
override
public
contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction))
{
bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction);
if (_hasStateTransitioner(_preStateRoot, _txHash)) {
return;
}
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain =
iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain"));
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmCanonicalTransactionChain.verifyTransaction(
_transaction,
_txChainElement,
_transactionBatchHeader,
_transactionProof
),
"Invalid transaction inclusion proof."
);
require (
// solhint-disable-next-line max-line-length
_preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index,
"Pre-state root global index must equal to the transaction root global index."
);
_deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index);
emit FraudProofInitialized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/**
* Finalizes the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _txHash The transaction for the state root
* @param _postStateRoot State root after the fraudulent transaction.
* @param _postStateRootBatchHeader Batch header for the provided post-state root.
* @param _postStateRootProof Inclusion proof for the provided post-state root.
*/
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof
)
override
public
contributesToFraudProof(_preStateRoot, _txHash)
{
iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash);
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
require(
transitioner.isComplete() == true,
"State transition process must be completed prior to finalization."
);
require (
// solhint-disable-next-line max-line-length
_postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1,
"Post-state root global index must equal to the pre state root global index plus one."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_postStateRoot,
_postStateRootBatchHeader,
_postStateRootProof
),
"Invalid post-state root inclusion proof."
);
// If the post state root did not match, then there was fraud and we should delete the batch
require(
_postStateRoot != transitioner.getPostStateRoot(),
"State transition has not been proven fraudulent."
);
_cancelStateTransition(_postStateRootBatchHeader, _preStateRoot);
// TEMPORARY: Remove the transitioner; for minnet.
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] =
iOVM_StateTransitioner(0x0000000000000000000000000000000000000000);
emit FraudProofFinalized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/************************************
* Internal Functions: Verification *
************************************/
/**
* Checks whether a transitioner already exists for a given pre-state root.
* @param _preStateRoot Pre-state root to check.
* @return _exists Whether or not we already have a transitioner for the root.
*/
function _hasStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
internal
view
returns (
bool _exists
)
{
return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0);
}
/**
* Deploys a new state transitioner.
* @param _preStateRoot Pre-state root to initialize the transitioner with.
* @param _txHash Hash of the transaction this transitioner will execute.
* @param _stateTransitionIndex Index of the transaction in the chain.
*/
function _deployTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash,
uint256 _stateTransitionIndex
)
internal
{
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] =
iOVM_StateTransitionerFactory(
resolve("OVM_StateTransitionerFactory")
).create(
address(libAddressManager),
_stateTransitionIndex,
_preStateRoot,
_txHash
);
}
/**
* Removes a state transition from the state commitment chain.
* @param _postStateRootBatchHeader Header for the post-state root.
* @param _preStateRoot Pre-state root hash.
*/
function _cancelStateTransition(
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
bytes32 _preStateRoot
)
internal
{
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager"));
// Delete the state batch.
ovmStateCommitmentChain.deleteStateBatch(
_postStateRootBatchHeader
);
// Get the timestamp and publisher for that block.
(uint256 timestamp, address publisher) =
abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));
// Slash the bonds at the bond manager.
ovmBondManager.finalize(
_preStateRoot,
publisher,
timestamp
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateCommitmentChain
*/
interface iOVM_StateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp()
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(
bytes32[] calldata _batch,
uint256 _shouldStartAtElement
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol";
/**
* @title iOVM_CanonicalTransactionChain
*/
interface iOVM_CanonicalTransactionChain {
/**********
* Events *
**********/
event TransactionEnqueued(
address _l1TxOrigin,
address _target,
uint256 _gasLimit,
bytes _data,
uint256 _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
external
view
returns (
uint40
);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_OVMCodec.QueueElement memory _element
);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
external
view
returns (
uint40
);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
external
view
returns (
uint40
);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
external
view
returns (
uint40
);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
external
view
returns (
uint40
);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
/**
* Appends a given number of queued transactions as a single batch.
* @param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 _numQueuedTransactions
)
external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
)
external;
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
external
view
returns (
bool
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_ChainStorageContainer
*/
interface iOVM_ChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata()
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length()
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_BondManager, Errors, ERC20 } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/**
* @title OVM_BondManager
* @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded
* Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a
* fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed,
* and the Verifier's gas costs are refunded.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver {
/****************************
* Constants and Parameters *
****************************/
/// The period to find the earliest fraud proof for a publisher
uint256 public constant multiFraudProofPeriod = 7 days;
/// The dispute period
uint256 public constant disputePeriodSeconds = 7 days;
/// The minimum collateral a sequencer must post
uint256 public constant requiredCollateral = 1 ether;
/*******************************************
* Contract Variables: Contract References *
*******************************************/
/// The bond token
ERC20 immutable public token;
/********************************************
* Contract Variables: Internal Accounting *
*******************************************/
/// The bonds posted by each proposer
mapping(address => Bond) public bonds;
/// For each pre-state root, there's an array of witnessProviders that must be rewarded
/// for posting witnesses
mapping(bytes32 => Rewards) public witnessProviders;
/***************
* Constructor *
***************/
/// Initializes with a ERC20 token to be used for the fidelity bonds
/// and with the Address Manager
constructor(
ERC20 _token,
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{
token = _token;
}
/********************
* Public Functions *
********************/
/// Adds `who` to the list of witnessProviders for the provided `preStateRoot`.
function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent)
override public {
// The sender must be the transitioner that corresponds to the claimed pre-state root
address transitioner =
address(iOVM_FraudVerifier(resolve("OVM_FraudVerifier"))
.getStateTransitioner(_preStateRoot, _txHash));
require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER);
witnessProviders[_preStateRoot].total += gasSpent;
witnessProviders[_preStateRoot].gasSpent[who] += gasSpent;
}
/// Slashes + distributes rewards or frees up the sequencer's bond, only called by
/// `FraudVerifier.finalizeFraudVerification`
function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public {
require(msg.sender == resolve("OVM_FraudVerifier"), Errors.ONLY_FRAUD_VERIFIER);
require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED);
// allow users to claim from that state root's
// pool of collateral (effectively slashing the sequencer)
witnessProviders[_preStateRoot].canClaim = true;
Bond storage bond = bonds[publisher];
if (bond.firstDisputeAt == 0) {
bond.firstDisputeAt = block.timestamp;
bond.earliestDisputedStateRoot = _preStateRoot;
bond.earliestTimestamp = timestamp;
} else if (
// only update the disputed state root for the publisher if it's within
// the dispute period _and_ if it's before the previous one
block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod &&
timestamp < bond.earliestTimestamp
) {
bond.earliestDisputedStateRoot = _preStateRoot;
bond.earliestTimestamp = timestamp;
}
// if the fraud proof's dispute period does not intersect with the
// withdrawal's timestamp, then the user should not be slashed
// e.g if a user at day 10 submits a withdrawal, and a fraud proof
// from day 1 gets published, the user won't be slashed since day 8 (1d + 7d)
// is before the user started their withdrawal. on the contrary, if the user
// had started their withdrawal at, say, day 6, they would be slashed
if (
bond.withdrawalTimestamp != 0 &&
uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds &&
bond.state == State.WITHDRAWING
) {
return;
}
// slash!
bond.state = State.NOT_COLLATERALIZED;
}
/// Sequencers call this function to post collateral which will be used for
/// the `appendBatch` call
function deposit() override public {
require(
token.transferFrom(msg.sender, address(this), requiredCollateral),
Errors.ERC20_ERR
);
// This cannot overflow
bonds[msg.sender].state = State.COLLATERALIZED;
}
/// Starts the withdrawal for a publisher
function startWithdrawal() override public {
Bond storage bond = bonds[msg.sender];
require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING);
require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE);
bond.state = State.WITHDRAWING;
bond.withdrawalTimestamp = uint32(block.timestamp);
}
/// Finalizes a pending withdrawal from a publisher
function finalizeWithdrawal() override public {
Bond storage bond = bonds[msg.sender];
require(
block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds,
Errors.TOO_EARLY
);
require(bond.state == State.WITHDRAWING, Errors.SLASHED);
// refunds!
bond.state = State.NOT_COLLATERALIZED;
bond.withdrawalTimestamp = 0;
require(
token.transfer(msg.sender, requiredCollateral),
Errors.ERC20_ERR
);
}
/// Claims the user's reward for the witnesses they provided for the earliest
/// disputed state root of the designated publisher
function claim(address who) override public {
Bond storage bond = bonds[who];
require(
block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod,
Errors.WAIT_FOR_DISPUTES
);
// reward the earliest state root for this publisher
bytes32 _preStateRoot = bond.earliestDisputedStateRoot;
Rewards storage rewards = witnessProviders[_preStateRoot];
// only allow claiming if fraud was proven in `finalize`
require(rewards.canClaim, Errors.CANNOT_CLAIM);
// proportional allocation - only reward 50% (rest gets locked in the
// contract forever
uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total);
// reset the user's spent gas so they cannot double claim
rewards.gasSpent[msg.sender] = 0;
// transfer
require(token.transfer(msg.sender, amount), Errors.ERC20_ERR);
}
/// Checks if the user is collateralized
function isCollateralized(address who) override public view returns (bool) {
return bonds[who].state == State.COLLATERALIZED;
}
/// Gets how many witnesses the user has provided for the state root
function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) {
return witnessProviders[preStateRoot].gasSpent[who];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { OVM_BondManager } from "./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol";
contract Mock_FraudVerifier {
OVM_BondManager bondManager;
mapping (bytes32 => address) transitioners;
function setBondManager(OVM_BondManager _bondManager) public {
bondManager = _bondManager;
}
function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public {
transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr;
}
function getStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
public
view
returns (
address
)
{
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public {
bondManager.finalize(_preStateRoot, publisher, timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol";
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/* External Imports */
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title OVM_StateCommitmentChain
* @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which
* Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC).
* Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique
* state root calculated off-chain by applying the canonical transactions one by one.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver {
/*************
* Constants *
*************/
uint256 public FRAUD_PROOF_WINDOW;
uint256 public SEQUENCER_PUBLISH_WINDOW;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager,
uint256 _fraudProofWindow,
uint256 _sequencerPublishWindow
)
Lib_AddressResolver(_libAddressManager)
{
FRAUD_PROOF_WINDOW = _fraudProofWindow;
SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-SCC-batches")
);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getTotalElements()
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements, ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getTotalBatches()
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().length();
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getLastSequencerTimestamp()
override
public
view
returns (
uint256 _lastSequencerTimestamp
)
{
(, uint40 lastSequencerTimestamp) = _getBatchExtraData();
return uint256(lastSequencerTimestamp);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function appendStateBatch(
bytes32[] memory _batch,
uint256 _shouldStartAtElement
)
override
public
{
// Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the
// publication of batches by some other user.
require(
_shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
// Proposers must have previously staked at the BondManager
require(
iOVM_BondManager(resolve("OVM_BondManager")).isCollateralized(msg.sender),
"Proposer does not have enough collateral posted"
);
require(
_batch.length > 0,
"Cannot submit an empty state batch."
);
require(
getTotalElements() + _batch.length <=
iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain"))
.getTotalElements(),
"Number of state roots cannot exceed the number of canonical transactions."
);
// Pass the block's timestamp and the publisher of the data
// to be used in the fraud proofs
_appendBatch(
_batch,
abi.encode(block.timestamp, msg.sender)
);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
override
public
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"State batches can only be deleted by the OVM_FraudVerifier."
);
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require(
insideFraudProofWindow(_batchHeader),
"State batches can only be deleted within the fraud proof window."
);
_deleteBatch(_batchHeader);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
override
public
view
returns (
bool
)
{
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require(
Lib_MerkleTree.verify(
_batchHeader.batchRoot,
_element,
_proof.index,
_proof.siblings,
_batchHeader.batchSize
),
"Invalid inclusion proof."
);
return true;
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
override
public
view
returns (
bool _inside
)
{
(uint256 timestamp,) = abi.decode(
_batchHeader.extraData,
(uint256, address)
);
require(
timestamp != 0,
"Batch header timestamp cannot be zero"
);
return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp;
}
/**********************
* Internal Functions *
**********************/
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Timestamp of the last batch submitted by the sequencer.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
// solhint-disable max-line-length
uint40 totalElements;
uint40 lastSequencerTimestamp;
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return (
totalElements,
lastSequencerTimestamp
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _lastSequencerTimestamp
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _lastSequencerTimestamp))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Appends a batch to the chain.
* @param _batch Elements within the batch.
* @param _extraData Any extra data to append to the batch.
*/
function _appendBatch(
bytes32[] memory _batch,
bytes memory _extraData
)
internal
{
address sequencer = resolve("OVM_Proposer");
(uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData();
if (msg.sender == sequencer) {
lastSequencerTimestamp = uint40(block.timestamp);
} else {
// We keep track of the last batch submitted by the sequencer so there's a window in
// which only the sequencer can publish state roots. A window like this just reduces
// the chance of "system breaking" state roots being published while we're still in
// testing mode. This window should be removed or significantly reduced in the future.
require(
lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp,
"Cannot publish state roots within the sequencer publication window."
);
}
// For efficiency reasons getMerkleRoot modifies the `_batch` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({
batchIndex: getTotalBatches(),
batchRoot: Lib_MerkleTree.getMerkleRoot(_batch),
batchSize: _batch.length,
prevTotalElements: totalElements,
extraData: _extraData
});
emit StateBatchAppended(
batchHeader.batchIndex,
batchHeader.batchRoot,
batchHeader.batchSize,
batchHeader.prevTotalElements,
batchHeader.extraData
);
batches().push(
Lib_OVMCodec.hashBatchHeader(batchHeader),
_makeBatchExtraData(
uint40(batchHeader.prevTotalElements + batchHeader.batchSize),
lastSequencerTimestamp
)
);
}
/**
* Removes a batch and all subsequent batches from the chain.
* @param _batchHeader Header of the batch to remove.
*/
function _deleteBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
{
require(
_batchHeader.batchIndex < batches().length(),
"Invalid batch index."
);
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
batches().deleteElementsAfterInclusive(
_batchHeader.batchIndex,
_makeBatchExtraData(
uint40(_batchHeader.prevTotalElements),
0
)
);
emit StateBatchDeleted(
_batchHeader.batchIndex,
_batchHeader.batchRoot
);
}
/**
* Checks that a batch header matches the stored hash for the given index.
* @param _batchHeader Batch header to validate.
* @return Whether or not the header matches the stored one.
*/
function _isValidBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
view
returns (
bool
)
{
return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(
bytes32[] memory _elements
)
internal
pure
returns (
bytes32
)
{
require(
_elements.length > 0,
"Lib_MerkleTree: Must provide at least one leaf hash."
);
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i) ];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling )
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
)
internal
pure
returns (
bool
)
{
require(
_totalLeaves > 0,
"Lib_MerkleTree: Total leaves must be greater than zero."
);
require(
_index < _totalLeaves,
"Lib_MerkleTree: Index out of bounds."
);
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(
abi.encodePacked(
_siblings[i],
computedRoot
)
);
} else {
computedRoot = keccak256(
abi.encodePacked(
computedRoot,
_siblings[i]
)
);
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(
uint256 _in
)
private
pure
returns (
uint256
)
{
require(
_in > 0,
"Lib_MerkleTree: Cannot compute ceil(log_2) of 0."
);
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (uint(1) << i) - 1 << i != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/**
* @title OVM_ChainStorageContainer
* @dev The Chain Storage Container provides its owner contract with read, write and delete
* functionality. This provides gas efficiency gains by enabling it to overwrite storage slots which
* can no longer be used in a fraud proof due to the fraud window having passed, and the associated
* chain state or transactions being finalized.
* Three distinct Chain Storage Containers will be deployed on Layer 1:
* 1. Stores transaction batches for the Canonical Transaction Chain
* 2. Stores queued transactions for the Canonical Transaction Chain
* 3. Stores chain state batches for the State Commitment Chain
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver {
/*************
* Libraries *
*************/
using Lib_Buffer for Lib_Buffer.Buffer;
/*************
* Variables *
*************/
string public owner;
Lib_Buffer.Buffer internal buffer;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _owner Name of the contract that owns this container (will be resolved later).
*/
constructor(
address _libAddressManager,
string memory _owner
)
Lib_AddressResolver(_libAddressManager)
{
owner = _owner;
}
/**********************
* Function Modifiers *
**********************/
modifier onlyOwner() {
require(
msg.sender == resolve(owner),
"OVM_ChainStorageContainer: Function can only be called by the owner."
);
_;
}
/********************
* Public Functions *
********************/
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
override
public
onlyOwner
{
return buffer.setExtraData(_globalMetadata);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function getGlobalMetadata()
override
public
view
returns (
bytes27
)
{
return buffer.getExtraData();
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function length()
override
public
view
returns (
uint256
)
{
return uint256(buffer.getLength());
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function push(
bytes32 _object
)
override
public
onlyOwner
{
buffer.push(_object);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
override
public
onlyOwner
{
buffer.push(_object, _globalMetadata);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function get(
uint256 _index
)
override
public
view
returns (
bytes32
)
{
return buffer.get(uint40(_index));
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function deleteElementsAfterInclusive(
uint256 _index
)
override
public
onlyOwner
{
buffer.deleteElementsAfterInclusive(
uint40(_index)
);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
override
public
onlyOwner
{
buffer.deleteElementsAfterInclusive(
uint40(_index),
_globalMetadata
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Buffer
* @dev This library implements a bytes32 storage array with some additional gas-optimized
* functionality. In particular, it encodes its length as a uint40, and tightly packs this with an
* overwritable "extra data" field so we can store more information with a single SSTORE.
*/
library Lib_Buffer {
/*************
* Libraries *
*************/
using Lib_Buffer for Buffer;
/***********
* Structs *
***********/
struct Buffer {
bytes32 context;
mapping (uint256 => bytes32) buf;
}
struct BufferContext {
// Stores the length of the array. Uint40 is way more elements than we'll ever reasonably
// need in an array and we get an extra 27 bytes of extra data to play with.
uint40 length;
// Arbitrary extra data that can be modified whenever the length is updated. Useful for
// squeezing out some gas optimizations.
bytes27 extraData;
}
/**********************
* Internal Functions *
**********************/
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
* @param _extraData Global extra data.
*/
function push(
Buffer storage _self,
bytes32 _value,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.buf[ctx.length] = _value;
// Bump the global index and insert our extra data, then save the context.
ctx.length++;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
*/
function push(
Buffer storage _self,
bytes32 _value
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.push(
_value,
ctx.extraData
);
}
/**
* Retrieves an element from the buffer.
* @param _self Buffer to access.
* @param _index Element index to retrieve.
* @return Value of the element at the given index.
*/
function get(
Buffer storage _self,
uint256 _index
)
internal
view
returns (
bytes32
)
{
BufferContext memory ctx = _self.getContext();
require(
_index < ctx.length,
"Index out of bounds."
);
return _self.buf[_index];
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
* @param _extraData Optional global extra data.
*/
function deleteElementsAfterInclusive(
Buffer storage _self,
uint40 _index,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
require(
_index < ctx.length,
"Index out of bounds."
);
// Set our length and extra data, save the context.
ctx.length = _index;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
*/
function deleteElementsAfterInclusive(
Buffer storage _self,
uint40 _index
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.deleteElementsAfterInclusive(
_index,
ctx.extraData
);
}
/**
* Retrieves the current global index.
* @param _self Buffer to access.
* @return Current global index.
*/
function getLength(
Buffer storage _self
)
internal
view
returns (
uint40
)
{
BufferContext memory ctx = _self.getContext();
return ctx.length;
}
/**
* Changes current global extra data.
* @param _self Buffer to access.
* @param _extraData New global extra data.
*/
function setExtraData(
Buffer storage _self,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Retrieves the current global extra data.
* @param _self Buffer to access.
* @return Current global extra data.
*/
function getExtraData(
Buffer storage _self
)
internal
view
returns (
bytes27
)
{
BufferContext memory ctx = _self.getContext();
return ctx.extraData;
}
/**
* Sets the current buffer context.
* @param _self Buffer to access.
* @param _ctx Current buffer context.
*/
function setContext(
Buffer storage _self,
BufferContext memory _ctx
)
internal
{
bytes32 context;
uint40 length = _ctx.length;
bytes27 extraData = _ctx.extraData;
assembly {
context := length
context := or(context, extraData)
}
if (_self.context != context) {
_self.context = context;
}
}
/**
* Retrieves the current buffer context.
* @param _self Buffer to access.
* @return Current buffer context.
*/
function getContext(
Buffer storage _self
)
internal
view
returns (
BufferContext memory
)
{
bytes32 context = _self.context;
uint40 length;
bytes27 extraData;
assembly {
// solhint-disable-next-line max-line-length
length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
// solhint-disable-next-line max-line-length
extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)
}
return BufferContext({
length: length,
extraData: extraData
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_Buffer } from "../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol";
/**
* @title TestLib_Buffer
*/
contract TestLib_Buffer {
using Lib_Buffer for Lib_Buffer.Buffer;
Lib_Buffer.Buffer internal buf;
function push(
bytes32 _value,
bytes27 _extraData
)
public
{
buf.push(
_value,
_extraData
);
}
function get(
uint256 _index
)
public
view
returns (
bytes32
)
{
return buf.get(_index);
}
function deleteElementsAfterInclusive(
uint40 _index
)
public
{
return buf.deleteElementsAfterInclusive(
_index
);
}
function deleteElementsAfterInclusive(
uint40 _index,
bytes27 _extraData
)
public
{
return buf.deleteElementsAfterInclusive(
_index,
_extraData
);
}
function getLength()
public
view
returns (
uint40
)
{
return buf.getLength();
}
function setExtraData(
bytes27 _extraData
)
public
{
return buf.setExtraData(
_extraData
);
}
function getExtraData()
public
view
returns (
bytes27
)
{
return buf.getExtraData();
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/* Contract Imports */
import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title OVM_CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
* If the Sequencer does not include an enqueued transaction within the 'force inclusion period',
* then any account may force it to be included by calling appendQueueBatch().
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 constant public MIN_ROLLUP_TX_GAS = 100000;
uint256 constant public MAX_ROLLUP_TX_SIZE = 50000;
uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32;
// Encoding-related (all in bytes)
uint256 constant internal BATCH_CONTEXT_SIZE = 16;
uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12;
uint256 constant internal BATCH_CONTEXT_START_POS = 15;
uint256 constant internal TX_DATA_HEADER_SIZE = 3;
uint256 constant internal BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public forceInclusionPeriodSeconds;
uint256 public forceInclusionPeriodBlocks;
uint256 public maxTransactionGasLimit;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _forceInclusionPeriodSeconds,
uint256 _forceInclusionPeriodBlocks,
uint256 _maxTransactionGasLimit
)
Lib_AddressResolver(_libAddressManager)
{
forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds;
forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks;
maxTransactionGasLimit = _maxTransactionGasLimit;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-batches")
);
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-queue")
);
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraData();
return nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
override
public
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
override
public
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
return _getQueueElement(
_index,
queue()
);
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
override
public
view
returns (
uint40
)
{
return getQueueLength() - getNextQueueIndex();
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
override
public
view
returns (
uint40
)
{
return _getQueueLength(
queue()
);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// We need to consume some amount of L1 gas in order to rate limit transactions going into
// L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the
// provided L1 gas.
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
"Insufficient gas for L2 rate limiting burn."
);
// Here we do some "dumb" work in order to burn gas, although we should probably replace
// this with something like minting gas token later on.
uint256 i;
while(startingGas - gasleft() < gasToConsume) {
i++;
}
bytes32 transactionHash = keccak256(
abi.encode(
msg.sender,
_target,
_gasLimit,
_data
)
);
bytes32 timestampAndBlockNumber;
assembly {
timestampAndBlockNumber := timestamp()
timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number()))
}
iOVM_ChainStorageContainer queueRef = queue();
queueRef.push(transactionHash);
queueRef.push(timestampAndBlockNumber);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueRef.length() / 2 - 1;
emit TransactionEnqueued(
msg.sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Appends a given number of queued transactions as a single batch.
* param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 // _numQueuedTransactions
)
override
public
pure
{
// TEMPORARY: Disable `appendQueueBatch` for minnet
revert("appendQueueBatch is currently disabled.");
// solhint-disable max-line-length
// _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements());
// require(
// _numQueuedTransactions > 0,
// "Must append more than zero transactions."
// );
// bytes32[] memory leaves = new bytes32[](_numQueuedTransactions);
// uint40 nextQueueIndex = getNextQueueIndex();
// for (uint256 i = 0; i < _numQueuedTransactions; i++) {
// if (msg.sender != resolve("OVM_Sequencer")) {
// Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex);
// require(
// el.timestamp + forceInclusionPeriodSeconds < block.timestamp,
// "Queue transactions cannot be submitted during the sequencer inclusion period."
// );
// }
// leaves[i] = _getQueueLeafHash(nextQueueIndex);
// nextQueueIndex++;
// }
// Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1);
// _appendBatch(
// Lib_MerkleTree.getMerkleRoot(leaves),
// _numQueuedTransactions,
// _numQueuedTransactions,
// lastElement.timestamp,
// lastElement.blockNumber
// );
// emit QueueBatchAppended(
// nextQueueIndex - _numQueuedTransactions,
// _numQueuedTransactions,
// getTotalElements()
// );
// solhint-enable max-line-length
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch()
override
public
{
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve("OVM_Sequencer"),
"Function can only be called by the Sequencer."
);
require(
numContexts > 0,
"Must provide at least one batch context."
);
require(
totalElementsToAppend > 0,
"Must append at least one element."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Take a reference to the queue and its length so we don't have to keep resolving it.
// Length isn't going to change during the course of execution, so it's fine to simply
// resolve this once at the start. Saves gas.
iOVM_ChainStorageContainer queueRef = queue();
uint40 queueLength = _getQueueLength(queueRef);
// Reserve some memory to save gas on hashing later on. This is a relatively safe estimate
// for the average transaction size that will prevent having to resize this chunk of memory
// later on. Saves gas.
bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2);
// Initialize the array of canonical chain leaves that we will append.
bytes32[] memory leaves = new bytes32[](totalElementsToAppend);
// Each leaf index corresponds to a tx, either sequenced or enqueued.
uint32 leafIndex = 0;
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// We will sequentially append leaves which are pointers to the queue.
// The initial queue index is what is currently in storage.
uint40 nextQueueIndex = getNextQueueIndex();
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
if (i == 0) {
// Execute a special check for the first batch.
_validateFirstBatchContext(nextContext);
}
// Execute this check on every single batch, including the first one.
_validateNextBatchContext(
curContext,
nextContext,
nextQueueIndex,
queueRef
);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) {
uint256 txDataLength;
assembly {
txDataLength := shr(232, calldataload(nextTransactionPtr))
}
require(
txDataLength <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
leaves[leafIndex] = _getSequencerLeafHash(
curContext,
nextTransactionPtr,
txDataLength,
hashMemory
);
nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength);
numSequencerTransactions++;
leafIndex++;
}
// Now process any subsequent queue transactions.
for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) {
require(
nextQueueIndex < queueLength,
"Not enough queued transactions to append."
);
leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex);
nextQueueIndex++;
leafIndex++;
}
}
_validateFinalBatchContext(
curContext,
nextQueueIndex,
queueLength,
queueRef
);
require(
msg.data.length == nextTransactionPtr,
"Not all sequencer transactions were processed."
);
require(
leafIndex == totalElementsToAppend,
"Actual transaction index does not match expected total elements to append."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(
nextQueueIndex - 1,
queueRef
);
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// For efficiency reasons getMerkleRoot modifies the `leaves` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
_appendBatch(
Lib_MerkleTree.getMerkleRoot(leaves),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
}
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
override
public
view
returns (
bool
)
{
if (_txChainElement.isSequenced == true) {
return _verifySequencerTransaction(
_transaction,
_txChainElement,
_batchHeader,
_inclusionProof
);
} else {
return _verifyQueueTransaction(
_transaction,
_txChainElement.queueIndex,
_batchHeader,
_inclusionProof
);
}
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))
}
// solhint-enable max-line-length
return (
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIndex Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIndex,
uint40 _timestamp,
uint40 _blockNumber
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIndex))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Retrieves the hash of a queue element.
* @param _index Index of the queue element to retrieve a hash for.
* @return Hash of the queue element.
*/
function _getQueueLeafHash(
uint256 _index
)
internal
pure
returns (
bytes32
)
{
return _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement({
isSequenced: false,
queueIndex: _index,
timestamp: 0,
blockNumber: 0,
txData: hex""
})
);
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function _getQueueElement(
uint256 _index,
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the actual desired queue index
// we need to multiply by 2.
uint40 trueIndex = uint40(_index * 2);
bytes32 transactionHash = _queueRef.get(trueIndex);
bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1);
uint40 elementTimestamp;
uint40 elementBlockNumber;
// solhint-disable max-line-length
assembly {
elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: elementTimestamp,
blockNumber: elementBlockNumber
});
}
/**
* Retrieves the length of the queue.
* @return Length of the queue.
*/
function _getQueueLength(
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
uint40
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2.
return uint40(_queueRef.length() / 2);
}
/**
* Retrieves the hash of a sequencer element.
* @param _context Batch context for the given element.
* @param _nextTransactionPtr Pointer to the next transaction in the calldata.
* @param _txDataLength Length of the transaction item.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
BatchContext memory _context,
uint256 _nextTransactionPtr,
uint256 _txDataLength,
bytes memory _hashMemory
)
internal
pure
returns (
bytes32
)
{
// Only allocate more memory if we didn't reserve enough to begin with.
if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) {
_hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength);
}
uint256 ctxTimestamp = _context.timestamp;
uint256 ctxBlockNumber = _context.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(_hashMemory, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength)
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength))
}
return leafHash;
}
/**
* Retrieves the hash of a sequencer element.
* @param _txChainElement The chain element which is hashed to calculate the leaf.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
Lib_OVMCodec.TransactionChainElement memory _txChainElement
)
internal
view
returns(
bytes32
)
{
bytes memory txData = _txChainElement.txData;
uint256 txDataLength = _txChainElement.txData.length;
bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength);
uint256 ctxTimestamp = _txChainElement.timestamp;
uint256 ctxBlockNumber = _txChainElement.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(chainElement, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength))
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength))
}
return leafHash;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
)
internal
{
iOVM_ChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
/**
* Checks that the first batch context in a sequencer submission is valid
* @param _firstContext The batch context to validate.
*/
function _validateFirstBatchContext(
BatchContext memory _firstContext
)
internal
view
{
// If there are existing elements, this batch must have the same context
// or a later timestamp and block number.
if (getTotalElements() > 0) {
(,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();
require(
_firstContext.blockNumber >= lastBlockNumber,
"Context block number is lower than last submitted."
);
require(
_firstContext.timestamp >= lastTimestamp,
"Context timestamp is lower than last submitted."
);
}
// Sequencer cannot submit contexts which are more than the force inclusion period old.
require(
_firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp,
"Context timestamp too far in the past."
);
require(
_firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number,
"Context block number too far in the past."
);
}
/**
* Checks that a given batch context has a time context which is below a given que element
* @param _context The batch context to validate has values lower.
* @param _queueIndex Index of the queue element we are validating came later than the context.
* @param _queueRef The storage container for the queue.
*/
function _validateContextBeforeEnqueue(
BatchContext memory _context,
uint40 _queueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement(
_queueIndex,
_queueRef
);
// If the force inclusion period has passed for an enqueued transaction, it MUST be the
// next chain element.
require(
block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds,
// solhint-disable-next-line max-line-length
"Previously enqueued batches have expired and must be appended before a new sequencer batch."
);
// Just like sequencer transaction times must be increasing relative to each other,
// We also require that they be increasing relative to any interspersed queue elements.
require(
_context.timestamp <= nextQueueElement.timestamp,
"Sequencer transaction timestamp exceeds that of next queue element."
);
require(
_context.blockNumber <= nextQueueElement.blockNumber,
"Sequencer transaction blockNumber exceeds that of next queue element."
);
}
/**
* Checks that a given batch context is valid based on its previous context, and the next queue
* elemtent.
* @param _prevContext The previously validated batch context.
* @param _nextContext The batch context to validate with this call.
* @param _nextQueueIndex Index of the next queue element to process for the _nextContext's
* subsequentQueueElements.
* @param _queueRef The storage container for the queue.
*/
function _validateNextBatchContext(
BatchContext memory _prevContext,
BatchContext memory _nextContext,
uint40 _nextQueueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// All sequencer transactions' times must be greater than or equal to the previous ones.
require(
_nextContext.timestamp >= _prevContext.timestamp,
"Context timestamp values must monotonically increase."
);
require(
_nextContext.blockNumber >= _prevContext.blockNumber,
"Context blockNumber values must monotonically increase."
);
// If there is going to be a queue element pulled in from this context:
if (_nextContext.numSubsequentQueueTransactions > 0) {
_validateContextBeforeEnqueue(
_nextContext,
_nextQueueIndex,
_queueRef
);
}
}
/**
* Checks that the final batch context in a sequencer submission is valid.
* @param _finalContext The batch context to validate.
* @param _queueLength The length of the queue at the start of the batchAppend call.
* @param _nextQueueIndex The next element in the queue that will be pulled into the CTC.
* @param _queueRef The storage container for the queue.
*/
function _validateFinalBatchContext(
BatchContext memory _finalContext,
uint40 _nextQueueIndex,
uint40 _queueLength,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// If the queue is not now empty, check the mononoticity of whatever the next batch that
// will come in is.
if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0)
{
_validateContextBeforeEnqueue(
_finalContext,
_nextQueueIndex,
_queueRef
);
}
// Batches cannot be added from the future, or subsequent enqueue() contexts would violate
// monotonicity.
require(_finalContext.timestamp <= block.timestamp,
"Context timestamp is from the future.");
require(_finalContext.blockNumber <= block.number,
"Context block number is from the future.");
}
/**
* Hashes a transaction chain element.
* @param _element Chain element to hash.
* @return Hash of the chain element.
*/
function _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement memory _element
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_element.isSequenced,
_element.queueIndex,
_element.timestamp,
_element.blockNumber,
_element.txData
)
);
}
/**
* Verifies a sequencer transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _txChainElement The chain element that the transaction is claimed to be a part of.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index.
* @return True if the transaction was included in the specified location, else false.
*/
function _verifySequencerTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
OVM_ExecutionManager ovmExecutionManager =
OVM_ExecutionManager(resolve("OVM_ExecutionManager"));
uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();
bytes32 leafHash = _getSequencerLeafHash(_txChainElement);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Sequencer transaction inclusion proof."
);
require(
_transaction.blockNumber == _txChainElement.blockNumber
&& _transaction.timestamp == _txChainElement.timestamp
&& _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress")
&& _transaction.gasLimit == gasLimit
&& _transaction.l1TxOrigin == address(0)
&& _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE
&& keccak256(_transaction.data) == keccak256(_txChainElement.txData),
"Invalid Sequencer transaction."
);
return true;
}
/**
* Verifies a queue transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _queueIndex The queueIndex of the queued transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to
* queue tx).
* @return True if the transaction was included in the specified location, else false.
*/
function _verifyQueueTransaction(
Lib_OVMCodec.Transaction memory _transaction,
uint256 _queueIndex,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
bytes32 leafHash = _getQueueLeafHash(_queueIndex);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Queue transaction inclusion proof."
);
bytes32 transactionHash = keccak256(
abi.encode(
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
)
);
Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);
require(
el.transactionHash == transactionHash
&& el.timestamp == _transaction.timestamp
&& el.blockNumber == _transaction.blockNumber,
"Invalid Queue transaction."
);
return true;
}
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function _verifyElement(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
require(
Lib_OVMCodec.hashBatchHeader(_batchHeader) ==
batches().get(uint32(_batchHeader.batchIndex)),
"Invalid batch header."
);
require(
Lib_MerkleTree.verify(
_batchHeader.batchRoot,
_element,
_proof.index,
_proof.siblings,
_batchHeader.batchSize
),
"Invalid inclusion proof."
);
return true;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Interface Imports */
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol";
/* Contract Imports */
import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title OVM_ExecutionManager
* @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed
* environment allowing us to execute OVM transactions deterministically on either Layer 1 or
* Layer 2.
* The EM's run() function is the first function called during the execution of any
* transaction on L2.
* For each context-dependent EVM operation the EM has a function which implements a corresponding
* OVM operation, which will read state from the State Manager contract.
* The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any
* context-dependent operations.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver {
/********************************
* External Contract References *
********************************/
iOVM_SafetyChecker internal ovmSafetyChecker;
iOVM_StateManager internal ovmStateManager;
/*******************************
* Execution Context Variables *
*******************************/
GasMeterConfig internal gasMeterConfig;
GlobalContext internal globalContext;
TransactionContext internal transactionContext;
MessageContext internal messageContext;
TransactionRecord internal transactionRecord;
MessageRecord internal messageRecord;
/**************************
* Gas Metering Constants *
**************************/
address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5;
uint256 constant NUISANCE_GAS_SLOAD = 20000;
uint256 constant NUISANCE_GAS_SSTORE = 20000;
uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000;
uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100;
uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000;
/**************************
* Native Value Constants *
**************************/
// Public so we can access and make assertions in integration tests.
uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000;
/**************************
* Default Context Values *
**************************/
uint256 constant DEFAULT_UINT256 =
0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d;
address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0;
/*************************************
* Container Contract Address Prefix *
*************************************/
/**
* @dev The Execution Manager and State Manager each have this 30 byte prefix,
* and are uncallable.
*/
address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager,
GasMeterConfig memory _gasMeterConfig,
GlobalContext memory _globalContext
)
Lib_AddressResolver(_libAddressManager)
{
ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker"));
gasMeterConfig = _gasMeterConfig;
globalContext = _globalContext;
_resetContext();
}
/**********************
* Function Modifiers *
**********************/
/**
* Applies dynamically-sized refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of the ovmOPCODE is fixed.
* @param _cost Desired gas cost for the function after the refund.
*/
modifier netGasCost(
uint256 _cost
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund everything *except* the specified cost.
if (_cost < gasUsed) {
transactionRecord.ovmGasRefund += gasUsed - _cost;
}
}
/**
* Applies a fixed-size gas refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered.
* @param _discount Amount of gas cost to refund for the ovmOPCODE.
*/
modifier fixedGasDiscount(
uint256 _discount
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund the specified _discount, unless this risks underflow.
if (_discount < gasUsed) {
transactionRecord.ovmGasRefund += _discount;
} else {
// refund all we can without risking underflow.
transactionRecord.ovmGasRefund += gasUsed;
}
}
/**
* Makes sure we're not inside a static context.
*/
modifier notStatic() {
if (messageContext.isStatic == true) {
_revertWithFlag(RevertFlag.STATIC_VIOLATION);
}
_;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
/**
* Starts the execution of a transaction via the OVM_ExecutionManager.
* @param _transaction Transaction data to be executed.
* @param _ovmStateManager iOVM_StateManager implementation providing account state.
*/
function run(
Lib_OVMCodec.Transaction memory _transaction,
address _ovmStateManager
)
override
external
returns (
bytes memory
)
{
// Make sure that run() is not re-enterable. This condition should always be satisfied
// Once run has been called once, due to the behavior of _isValidInput().
if (transactionContext.ovmNUMBER != DEFAULT_UINT256) {
return bytes("");
}
// Store our OVM_StateManager instance (significantly easier than attempting to pass the
// address around in calldata).
ovmStateManager = iOVM_StateManager(_ovmStateManager);
// Make sure this function can't be called by anyone except the owner of the
// OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because
// this would make the `run` itself invalid.
require(
// This method may return false during fraud proofs, but always returns true in
// L2 nodes' State Manager precompile.
ovmStateManager.isAuthenticated(msg.sender),
"Only authenticated addresses in ovmStateManager can call this function"
);
// Initialize the execution context, must be initialized before we perform any gas metering
// or we'll throw a nuisance gas error.
_initContext(_transaction);
// TEMPORARY: Gas metering is disabled for minnet.
// // Check whether we need to start a new epoch, do so if necessary.
// _checkNeedsNewEpoch(_transaction.timestamp);
// Make sure the transaction's gas limit is valid. We don't revert here because we reserve
// reverts for INVALID_STATE_ACCESS.
if (_isValidInput(_transaction) == false) {
_resetContext();
return bytes("");
}
// TEMPORARY: Gas metering is disabled for minnet.
// // Check gas right before the call to get total gas consumed by OVM transaction.
// uint256 gasProvided = gasleft();
// Run the transaction, make sure to meter the gas usage.
(, bytes memory returndata) = ovmCALL(
_transaction.gasLimit - gasMeterConfig.minTransactionGasLimit,
_transaction.entrypoint,
0,
_transaction.data
);
// TEMPORARY: Gas metering is disabled for minnet.
// // Update the cumulative gas based on the amount of gas used.
// uint256 gasUsed = gasProvided - gasleft();
// _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin);
// Wipe the execution context.
_resetContext();
return returndata;
}
/******************************
* Opcodes: Execution Context *
******************************/
/**
* @notice Overrides CALLER.
* @return _CALLER Address of the CALLER within the current message context.
*/
function ovmCALLER()
override
external
view
returns (
address _CALLER
)
{
return messageContext.ovmCALLER;
}
/**
* @notice Overrides ADDRESS.
* @return _ADDRESS Active ADDRESS within the current message context.
*/
function ovmADDRESS()
override
public
view
returns (
address _ADDRESS
)
{
return messageContext.ovmADDRESS;
}
/**
* @notice Overrides CALLVALUE.
* @return _CALLVALUE Value sent along with the call according to the current message context.
*/
function ovmCALLVALUE()
override
public
view
returns (
uint256 _CALLVALUE
)
{
return messageContext.ovmCALLVALUE;
}
/**
* @notice Overrides TIMESTAMP.
* @return _TIMESTAMP Value of the TIMESTAMP within the transaction context.
*/
function ovmTIMESTAMP()
override
external
view
returns (
uint256 _TIMESTAMP
)
{
return transactionContext.ovmTIMESTAMP;
}
/**
* @notice Overrides NUMBER.
* @return _NUMBER Value of the NUMBER within the transaction context.
*/
function ovmNUMBER()
override
external
view
returns (
uint256 _NUMBER
)
{
return transactionContext.ovmNUMBER;
}
/**
* @notice Overrides GASLIMIT.
* @return _GASLIMIT Value of the block's GASLIMIT within the transaction context.
*/
function ovmGASLIMIT()
override
external
view
returns (
uint256 _GASLIMIT
)
{
return transactionContext.ovmGASLIMIT;
}
/**
* @notice Overrides CHAINID.
* @return _CHAINID Value of the chain's CHAINID within the global context.
*/
function ovmCHAINID()
override
external
view
returns (
uint256 _CHAINID
)
{
return globalContext.ovmCHAINID;
}
/*********************************
* Opcodes: L2 Execution Context *
*********************************/
/**
* @notice Specifies from which source (Sequencer or Queue) this transaction originated from.
* @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context.
*/
function ovmL1QUEUEORIGIN()
override
external
view
returns (
Lib_OVMCodec.QueueOrigin _queueOrigin
)
{
return transactionContext.ovmL1QUEUEORIGIN;
}
/**
* @notice Specifies which L1 account, if any, sent this transaction by calling enqueue().
* @return _l1TxOrigin Address of the account which sent the tx into L2 from L1.
*/
function ovmL1TXORIGIN()
override
external
view
returns (
address _l1TxOrigin
)
{
return transactionContext.ovmL1TXORIGIN;
}
/********************
* Opcodes: Halting *
********************/
/**
* @notice Overrides REVERT.
* @param _data Bytes data to pass along with the REVERT.
*/
function ovmREVERT(
bytes memory _data
)
override
public
{
_revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data);
}
/******************************
* Opcodes: Contract Creation *
******************************/
/**
* @notice Overrides CREATE.
* @param _bytecode Code to be used to CREATE a new contract.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE(
bytes memory _bytecode
)
override
public
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE address.
address contractAddress = Lib_EthUtils.getAddressForCREATE(
creator,
_getAccountNonce(creator)
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE
);
}
/**
* @notice Overrides CREATE2.
* @param _bytecode Code to be used to CREATE2 a new contract.
* @param _salt Value used to determine the contract's address.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE2(
bytes memory _bytecode,
bytes32 _salt
)
override
external
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE2 address.
address contractAddress = Lib_EthUtils.getAddressForCREATE2(
creator,
_bytecode,
_salt
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE2
);
}
/*******************************
* Account Abstraction Opcodes *
******************************/
/**
* Retrieves the nonce of the current ovmADDRESS.
* @return _nonce Nonce of the current contract.
*/
function ovmGETNONCE()
override
external
returns (
uint256 _nonce
)
{
return _getAccountNonce(ovmADDRESS());
}
/**
* Bumps the nonce of the current ovmADDRESS by one.
*/
function ovmINCREMENTNONCE()
override
external
notStatic
{
address account = ovmADDRESS();
uint256 nonce = _getAccountNonce(account);
// Prevent overflow.
if (nonce + 1 > nonce) {
_setAccountNonce(account, nonce + 1);
}
}
/**
* Creates a new EOA contract account, for account abstraction.
* @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks
* because the contract we're creating is trusted (no need to do safety checking or to
* handle unexpected reverts). Doesn't need to return an address because the address is
* assumed to be the user's actual address.
* @param _messageHash Hash of a message signed by some user, for verification.
* @param _v Signature `v` parameter.
* @param _r Signature `r` parameter.
* @param _s Signature `s` parameter.
*/
function ovmCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
override
public
notStatic
{
// Recover the EOA address from the message hash and signature parameters. Since we do the
// hashing in advance, we don't have handle different message hashing schemes. Even if this
// function were to return the wrong address (rather than explicitly returning the zero
// address), the rest of the transaction would simply fail (since there's no EOA account to
// actually execute the transaction).
address eoa = ecrecover(
_messageHash,
_v + 27,
_r,
_s
);
// Invalid signature is a case we proactively handle with a revert. We could alternatively
// have this function return a `success` boolean, but this is just easier.
if (eoa == address(0)) {
ovmREVERT(bytes("Signature provided for EOA contract creation is invalid."));
}
// If the user already has an EOA account, then there's no need to perform this operation.
if (_hasEmptyAccount(eoa) == false) {
return;
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(eoa);
// Temporarily set the current address so it's easier to access on L2.
address prevADDRESS = messageContext.ovmADDRESS;
messageContext.ovmADDRESS = eoa;
// Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following
// "magic" prefix to deploy an exact copy of the code:
// PUSH1 0x0D # size of this prefix in bytes
// CODESIZE
// SUB # subtract prefix size from codesize
// DUP1
// PUSH1 0x0D
// PUSH1 0x00
// CODECOPY # copy everything after prefix into memory at pos 0
// PUSH1 0x00
// RETURN # return the copied code
address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked(
hex"600D380380600D6000396000f3",
ovmEXTCODECOPY(
Lib_PredeployAddresses.PROXY_EOA,
0,
ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA)
)
));
// Reset the address now that we're done deploying.
messageContext.ovmADDRESS = prevADDRESS;
// Commit the account with its final values.
_commitPendingAccount(
eoa,
address(proxyEOA),
keccak256(Lib_EthUtils.getCode(address(proxyEOA)))
);
_setAccountNonce(eoa, 0);
}
/*********************************
* Opcodes: Contract Interaction *
*********************************/
/**
* @notice Overrides CALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _value ETH value to pass with the call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
uint256 _value,
bytes memory _calldata
)
override
public
fixedGasDiscount(100000)
returns (
bool _success,
bytes memory _returndata
)
{
// CALL updates the CALLER and ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.ovmCALLVALUE = _value;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmCALL
);
}
/**
* @notice Overrides STATICCALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmSTATICCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(80000)
returns (
bool _success,
bytes memory _returndata
)
{
// STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static,
// valueless context.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.isStatic = true;
nextMessageContext.ovmCALLVALUE = 0;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmSTATICCALL
);
}
/**
* @notice Overrides DELEGATECALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmDELEGATECALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(40000)
returns (
bool _success,
bytes memory _returndata
)
{
// DELEGATECALL does not change anything about the message context.
MessageContext memory nextMessageContext = messageContext;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmDELEGATECALL
);
}
/**
* @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards
* compatibility.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
returns(
bool _success,
bytes memory _returndata
)
{
// Legacy ovmCALL assumed always-0 value.
return ovmCALL(
_gasLimit,
_address,
0,
_calldata
);
}
/************************************
* Opcodes: Contract Storage Access *
************************************/
/**
* @notice Overrides SLOAD.
* @param _key 32 byte key of the storage slot to load.
* @return _value 32 byte value of the requested storage slot.
*/
function ovmSLOAD(
bytes32 _key
)
override
external
netGasCost(40000)
returns (
bytes32 _value
)
{
// We always SLOAD from the storage of ADDRESS.
address contractAddress = ovmADDRESS();
return _getContractStorage(
contractAddress,
_key
);
}
/**
* @notice Overrides SSTORE.
* @param _key 32 byte key of the storage slot to set.
* @param _value 32 byte value for the storage slot.
*/
function ovmSSTORE(
bytes32 _key,
bytes32 _value
)
override
external
notStatic
netGasCost(60000)
{
// We always SSTORE to the storage of ADDRESS.
address contractAddress = ovmADDRESS();
_putContractStorage(
contractAddress,
_key,
_value
);
}
/*********************************
* Opcodes: Contract Code Access *
*********************************/
/**
* @notice Overrides EXTCODECOPY.
* @param _contract Address of the contract to copy code from.
* @param _offset Offset in bytes from the start of contract code to copy beyond.
* @param _length Total number of bytes to copy from the contract's code.
* @return _code Bytes of code copied from the requested contract.
*/
function ovmEXTCODECOPY(
address _contract,
uint256 _offset,
uint256 _length
)
override
public
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_getAccountEthAddress(_contract),
_offset,
_length
);
}
/**
* @notice Overrides EXTCODESIZE.
* @param _contract Address of the contract to query the size of.
* @return _EXTCODESIZE Size of the requested contract in bytes.
*/
function ovmEXTCODESIZE(
address _contract
)
override
public
returns (
uint256 _EXTCODESIZE
)
{
return Lib_EthUtils.getCodeSize(
_getAccountEthAddress(_contract)
);
}
/**
* @notice Overrides EXTCODEHASH.
* @param _contract Address of the contract to query the hash of.
* @return _EXTCODEHASH Hash of the requested contract.
*/
function ovmEXTCODEHASH(
address _contract
)
override
external
returns (
bytes32 _EXTCODEHASH
)
{
return Lib_EthUtils.getCodeHash(
_getAccountEthAddress(_contract)
);
}
/***************************************
* Public Functions: ETH Value Opcodes *
***************************************/
/**
* @notice Overrides BALANCE.
* NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...).
* @param _contract Address of the contract to query the OVM_ETH balance of.
* @return _BALANCE OVM_ETH balance of the requested contract.
*/
function ovmBALANCE(
address _contract
)
override
public
returns (
uint256 _BALANCE
)
{
// Easiest way to get the balance is query OVM_ETH as normal.
bytes memory balanceOfCalldata = abi.encodeWithSignature(
"balanceOf(address)",
_contract
);
// Static call because this should be a read-only query.
(bool success, bytes memory returndata) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.OVM_ETH,
balanceOfCalldata
);
// All balanceOf queries should successfully return a uint, otherwise this must be an OOG.
if (!success || returndata.length != 32) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// Return the decoded balance.
return abi.decode(returndata, (uint256));
}
/**
* @notice Overrides SELFBALANCE.
* @return _BALANCE OVM_ETH balance of the requesting contract.
*/
function ovmSELFBALANCE()
override
external
returns (
uint256 _BALANCE
)
{
return ovmBALANCE(ovmADDRESS());
}
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit()
external
view
override
returns (
uint256 _maxTransactionGasLimit
)
{
return gasMeterConfig.maxTransactionGasLimit;
}
/********************************************
* Public Functions: Deployment Whitelisting *
********************************************/
/**
* Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2,
* and reverts if not.
* @param _deployerAddress Address attempting to deploy a contract.
*/
function _checkDeployerAllowed(
address _deployerAddress
)
internal
{
// From an OVM semantics perspective, this will appear identical to
// the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to.
(bool success, bytes memory data) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.DEPLOYER_WHITELIST,
abi.encodeWithSelector(
OVM_DeployerWhitelist.isDeployerAllowed.selector,
_deployerAddress
)
);
bool isAllowed = abi.decode(data, (bool));
if (!isAllowed || !success) {
_revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED);
}
}
/********************************************
* Internal Functions: Contract Interaction *
********************************************/
/**
* Creates a new contract and associates it with some contract address.
* @param _contractAddress Address to associate the created contract with.
* @param _bytecode Bytecode to be used to create the contract.
* @return Final OVM contract address.
* @return Revertdata, if and only if the creation threw an exception.
*/
function _createContract(
address _contractAddress,
bytes memory _bytecode,
MessageType _messageType
)
internal
returns (
address,
bytes memory
)
{
// We always update the nonce of the creating account, even if the creation fails.
_setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1);
// We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point
// to the contract's associated address and CALLER to point to the previous ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = messageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _contractAddress;
// Run the common logic which occurs between call-type and create-type messages,
// passing in the creation bytecode and `true` to trigger create-specific logic.
(bool success, bytes memory data) = _handleExternalMessage(
nextMessageContext,
gasleft(),
_contractAddress,
_bytecode,
_messageType
);
// Yellow paper requires that address returned is zero if the contract deployment fails.
return (
success ? _contractAddress : address(0),
data
);
}
/**
* Calls the deployed contract associated with a given address.
* @param _nextMessageContext Message context to be used for the call.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _contract OVM address to be called.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function _callContract(
MessageContext memory _nextMessageContext,
uint256 _gasLimit,
address _contract,
bytes memory _calldata,
MessageType _messageType
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
// We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2
// geth. So, we block calls to these addresses since they are not safe to run as an OVM
// contract itself.
if (
(uint256(_contract) &
uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000))
== uint256(CONTAINER_CONTRACT_PREFIX)
) {
// solhint-disable-next-line max-line-length
// EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604
return (true, hex'');
}
// Both 0x0000... and the EVM precompiles have the same address on L1 and L2 -->
// no trie lookup needed.
address codeContractAddress =
uint(_contract) < 100
? _contract
: _getAccountEthAddress(_contract);
return _handleExternalMessage(
_nextMessageContext,
_gasLimit,
codeContractAddress,
_calldata,
_messageType
);
}
/**
* Handles all interactions which involve the execution manager calling out to untrusted code
* (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas
* refunds, nuisance gas, and flagged reversions.
*
* @param _nextMessageContext Message context to be used for the external message.
* @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is
* overwritten in some cases to avoid stack-too-deep.
* @param _contract OVM address being called or deployed to
* @param _data Data for the message (either calldata or creation code)
* @param _messageType What type of ovmOPCODE this message corresponds to.
* @return Whether or not the message (either a call or deployment) succeeded.
* @return Data returned by the message.
*/
function _handleExternalMessage(
MessageContext memory _nextMessageContext,
// NOTE: this argument is overwritten in some cases to avoid stack-too-deep.
uint256 _gasLimit,
address _contract,
bytes memory _data,
MessageType _messageType
)
internal
returns (
bool,
bytes memory
)
{
uint256 messageValue = _nextMessageContext.ovmCALLVALUE;
// If there is value in this message, we need to transfer the ETH over before switching
// contexts.
if (
messageValue > 0
&& _isValueType(_messageType)
) {
// Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to
// revert" if we don't have enough gas to transfer the ETH.
// Similar to dynamic gas cost of value exceeding gas here:
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273
if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) {
return (false, hex"");
}
// If there *is* enough gas to transfer ETH, then we need to make sure this amount of
// gas is reserved (i.e. not given to the _contract.call below) to guarantee that
// _handleExternalMessage can't run out of gas. In particular, in the event that
// the call fails, we will need to transfer the ETH back to the sender.
// Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS
// guarantees that the second _attemptForcedEthTransfer below, if needed, always has
// enough gas to succeed.
_gasLimit = Math.min(
_gasLimit,
gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check.
);
// Now transfer the value of the call.
// The target is interpreted to be the next message's ovmADDRESS account.
bool transferredOvmEth = _attemptForcedEthTransfer(
_nextMessageContext.ovmADDRESS,
messageValue
);
// If the ETH transfer fails (should only be possible in the case of insufficient
// balance), then treat this as a revert. This mirrors EVM behavior, see
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298
if (!transferredOvmEth) {
return (false, hex"");
}
}
// We need to switch over to our next message context for the duration of this call.
MessageContext memory prevMessageContext = messageContext;
_switchMessageContext(prevMessageContext, _nextMessageContext);
// Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs
// expensive by touching a lot of different accounts or storage slots. Since most contracts
// only use a few storage slots during any given transaction, this shouldn't be a limiting
// factor.
uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft;
uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit);
messageRecord.nuisanceGasLeft = nuisanceGasLimit;
// Make the call and make sure to pass in the gas limit. Another instance of hidden
// complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert
// behavior can be controlled. In particular, we enforce that flags are passed through
// revert data as to retrieve execution metadata that would normally be reverted out of
// existence.
bool success;
bytes memory returndata;
if (_isCreateType(_messageType)) {
// safeCREATE() is a function which replicates a CREATE message, but uses return values
// Which match that of CALL (i.e. bool, bytes). This allows many security checks to be
// to be shared between untrusted call and create call frames.
(success, returndata) = address(this).call{gas: _gasLimit}(
abi.encodeWithSelector(
this.safeCREATE.selector,
_data,
_contract
)
);
} else {
(success, returndata) = _contract.call{gas: _gasLimit}(_data);
}
// If the message threw an exception, its value should be returned back to the sender.
// So, we force it back, BEFORE returning the messageContext to the previous addresses.
// This operation is part of the reason we "reserved the intrinsic gas" above.
if (
messageValue > 0
&& _isValueType(_messageType)
&& !success
) {
bool transferredOvmEth = _attemptForcedEthTransfer(
prevMessageContext.ovmADDRESS,
messageValue
);
// Since we transferred it in above and the call reverted, the transfer back should
// always pass. This code path should NEVER be triggered since we sent `messageValue`
// worth of OVM_ETH into the target and reserved sufficient gas to execute the transfer,
// but in case there is some edge case which has been missed, we revert the entire frame
// (and its parent) to make sure the ETH gets sent back.
if (!transferredOvmEth) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
}
// Switch back to the original message context now that we're out of the call and all
// OVM_ETH is in the right place.
_switchMessageContext(_nextMessageContext, prevMessageContext);
// Assuming there were no reverts, the message record should be accurate here. We'll update
// this value in the case of a revert.
uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft;
// Reverts at this point are completely OK, but we need to make a few updates based on the
// information passed through the revert.
if (success == false) {
(
RevertFlag flag,
uint256 nuisanceGasLeftPostRevert,
uint256 ovmGasRefund,
bytes memory returndataFromFlag
) = _decodeRevertData(returndata);
// INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the
// parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must
// halt any further transaction execution that could impact the execution result.
if (flag == RevertFlag.INVALID_STATE_ACCESS) {
_revertWithFlag(flag);
}
// INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't
// dependent on the input state, so we can just handle them like standard reverts.
// Our only change here is to record the gas refund reported by the call (enforced by
// safety checking).
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
|| flag == RevertFlag.STATIC_VIOLATION
|| flag == RevertFlag.CREATOR_NOT_ALLOWED
) {
transactionRecord.ovmGasRefund = ovmGasRefund;
}
// INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the
// flag, *not* the full encoded flag. Additionally, we surface custom error messages
// to developers in the case of unsafe creations for improved devex.
// All other revert types return no data.
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
) {
returndata = returndataFromFlag;
} else {
returndata = hex'';
}
// Reverts mean we need to use up whatever "nuisance gas" was used by the call.
// EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message
// to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they
// run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags
// will simply pass up the remaining nuisance gas.
nuisanceGasLeft = nuisanceGasLeftPostRevert;
}
// We need to reset the nuisance gas back to its original value minus the amount used here.
messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft);
return (
success,
returndata
);
}
/**
* Handles the creation-specific safety measures required for OVM contract deployment.
* This function sanitizes the return types for creation messages to match calls (bool, bytes),
* by being an external function which the EM can call, that mimics the success/fail case of the
* CREATE.
* This allows for consistent handling of both types of messages in _handleExternalMessage().
* Having this step occur as a separate call frame also allows us to easily revert the
* contract deployment in the event that the code is unsafe.
*
* @param _creationCode Code to pass into CREATE for deployment.
* @param _address OVM address being deployed to.
*/
function safeCREATE(
bytes memory _creationCode,
address _address
)
external
{
// The only way this should callable is from within _createContract(),
// and it should DEFINITELY not be callable by a non-EM code contract.
if (msg.sender != address(this)) {
return;
}
// Check that there is not already code at this address.
if (_hasEmptyAccount(_address) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.CREATE_COLLISION
);
}
// Check the creation bytecode against the OVM_SafetyChecker.
if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?")
);
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(_address);
// Actually execute the EVM create message.
// NOTE: The inline assembly below means we can NOT make any evm calls between here and then
address ethAddress = Lib_EthUtils.createContract(_creationCode);
if (ethAddress == address(0)) {
// If the creation fails, the EVM lets us grab its revert data. This may contain a
// revert flag to be used above in _handleExternalMessage, so we pass the revert data
// back up unmodified.
assembly {
returndatacopy(0,0,returndatasize())
revert(0, returndatasize())
}
}
// Again simply checking that the deployed code is safe too. Contracts can generate
// arbitrary deployment code, so there's no easy way to analyze this beforehand.
bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress);
if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) {
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.")
);
}
// Contract creation didn't need to be reverted and the bytecode is safe. We finish up by
// associating the desired address with the newly created contract's code hash and address.
_commitPendingAccount(
_address,
ethAddress,
Lib_EthUtils.getCodeHash(ethAddress)
);
}
/******************************************
* Internal Functions: Value Manipulation *
******************************************/
/**
* Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to
* force movement of OVM_ETH in correspondence with ETH's native value functionality.
* WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage
* at the time of the call.
* NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...).
* @param _to Amount of OVM_ETH to be sent.
* @param _value Amount of OVM_ETH to send.
* @return _success Whether or not the transfer worked.
*/
function _attemptForcedEthTransfer(
address _to,
uint256 _value
)
internal
returns(
bool _success
)
{
bytes memory transferCalldata = abi.encodeWithSignature(
"transfer(address,uint256)",
_to,
_value
);
// OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return
// type is a boolean. However, the implementation always returns true if it does not revert
// Thus, success of the call frame is sufficient to infer success of the transfer itself.
(bool success, ) = ovmCALL(
gasleft(),
Lib_PredeployAddresses.OVM_ETH,
0,
transferCalldata
);
return success;
}
/******************************************
* Internal Functions: State Manipulation *
******************************************/
/**
* Checks whether an account exists within the OVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account exists.
*/
function _hasAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return ovmStateManager.hasAccount(_address);
}
/**
* Checks whether a known empty account exists within the OVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account empty exists.
*/
function _hasEmptyAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return ovmStateManager.hasEmptyAccount(_address);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function _setAccountNonce(
address _address,
uint256 _nonce
)
internal
{
_checkAccountChange(_address);
ovmStateManager.setAccountNonce(_address, _nonce);
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return _nonce Nonce of the account.
*/
function _getAccountNonce(
address _address
)
internal
returns (
uint256 _nonce
)
{
_checkAccountLoad(_address);
return ovmStateManager.getAccountNonce(_address);
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return _ethAddress Corresponding Ethereum address.
*/
function _getAccountEthAddress(
address _address
)
internal
returns (
address _ethAddress
)
{
_checkAccountLoad(_address);
return ovmStateManager.getAccountEthAddress(_address);
}
/**
* Creates the default account object for the given address.
* @param _address Address of the account create.
*/
function _initPendingAccount(
address _address
)
internal
{
// Although it seems like `_checkAccountChange` would be more appropriate here, we don't
// actually consider an account "changed" until it's inserted into the state (in this case
// by `_commitPendingAccount`).
_checkAccountLoad(_address);
ovmStateManager.initPendingAccount(_address);
}
/**
* Stores additional relevant data for a new account, thereby "committing" it to the state.
* This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract
* creation.
* @param _address Address of the account to commit.
* @param _ethAddress Address of the associated deployed contract.
* @param _codeHash Hash of the code stored at the address.
*/
function _commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
internal
{
_checkAccountChange(_address);
ovmStateManager.commitPendingAccount(
_address,
_ethAddress,
_codeHash
);
}
/**
* Retrieves the value of a storage slot.
* @param _contract Address of the contract to query.
* @param _key 32 byte key of the storage slot.
* @return _value 32 byte storage slot value.
*/
function _getContractStorage(
address _contract,
bytes32 _key
)
internal
returns (
bytes32 _value
)
{
_checkContractStorageLoad(_contract, _key);
return ovmStateManager.getContractStorage(_contract, _key);
}
/**
* Sets the value of a storage slot.
* @param _contract Address of the contract to modify.
* @param _key 32 byte key of the storage slot.
* @param _value 32 byte storage slot value.
*/
function _putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
internal
{
// We don't set storage if the value didn't change. Although this acts as a convenient
// optimization, it's also necessary to avoid the case in which a contract with no storage
// attempts to store the value "0" at any key. Putting this value (and therefore requiring
// that the value be committed into the storage trie after execution) would incorrectly
// modify the storage root.
if (_getContractStorage(_contract, _key) == _value) {
return;
}
_checkContractStorageChange(_contract, _key);
ovmStateManager.putContractStorage(_contract, _key, _value);
}
/**
* Validation whenever a contract needs to be loaded. Checks that the account exists, charges
* nuisance gas if the account hasn't been loaded before.
* @param _address Address of the account to load.
*/
function _checkAccountLoad(
address _address
)
internal
{
// See `_checkContractStorageLoad` for more information.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// See `_checkContractStorageLoad` for more information.
if (ovmStateManager.hasAccount(_address) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the account has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that an account is loaded.
(
bool _wasAccountAlreadyLoaded
) = ovmStateManager.testAndSetAccountLoaded(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyLoaded == false) {
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a contract needs to be changed. Checks that the account exists, charges
* nuisance gas if the account hasn't been changed before.
* @param _address Address of the account to change.
*/
function _checkAccountChange(
address _address
)
internal
{
// Start by checking for a load as we only want to charge nuisance gas proportional to
// contract size once.
_checkAccountLoad(_address);
// Check whether the account has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that an account is changed.
(
bool _wasAccountAlreadyChanged
) = ovmStateManager.testAndSetAccountChanged(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyChanged == false) {
ovmStateManager.incrementTotalUncommittedAccounts();
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a slot needs to be loaded. Checks that the account exists, charges
* nuisance gas if the slot hasn't been loaded before.
* @param _contract Address of the account to load from.
* @param _key 32 byte key to load.
*/
function _checkContractStorageLoad(
address _contract,
bytes32 _key
)
internal
{
// Another case of hidden complexity. If we didn't enforce this requirement, then a
// contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail
// on L1 but not on L2. A contract could use this behavior to prevent the
// OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS
// allows us to also charge for the full message nuisance gas, because you deserve that for
// trying to break the contract in this way.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// We need to make sure that the transaction isn't trying to access storage that hasn't
// been provided to the OVM_StateManager. We'll immediately abort if this is the case.
// We know that we have enough gas to do this check because of the above test.
if (ovmStateManager.hasContractStorage(_contract, _key) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the slot has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that a slot is loaded.
(
bool _wasContractStorageAlreadyLoaded
) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key);
// If we hadn't already loaded the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyLoaded == false) {
_useNuisanceGas(NUISANCE_GAS_SLOAD);
}
}
/**
* Validation whenever a slot needs to be changed. Checks that the account exists, charges
* nuisance gas if the slot hasn't been changed before.
* @param _contract Address of the account to change.
* @param _key 32 byte key to change.
*/
function _checkContractStorageChange(
address _contract,
bytes32 _key
)
internal
{
// Start by checking for load to make sure we have the storage slot and that we charge the
// "nuisance gas" necessary to prove the storage slot state.
_checkContractStorageLoad(_contract, _key);
// Check whether the slot has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that a slot is changed.
(
bool _wasContractStorageAlreadyChanged
) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key);
// If we hadn't already changed the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyChanged == false) {
// Changing a storage slot means that we're also going to have to change the
// corresponding account, so do an account change check.
_checkAccountChange(_contract);
ovmStateManager.incrementTotalUncommittedContractStorage();
_useNuisanceGas(NUISANCE_GAS_SSTORE);
}
}
/************************************
* Internal Functions: Revert Logic *
************************************/
/**
* Simple encoding for revert data.
* @param _flag Flag to revert with.
* @param _data Additional user-provided revert data.
* @return _revertdata Encoded revert data.
*/
function _encodeRevertData(
RevertFlag _flag,
bytes memory _data
)
internal
view
returns (
bytes memory _revertdata
)
{
// Out of gas and create exceptions will fundamentally return no data, so simulating it
// shouldn't either.
if (
_flag == RevertFlag.OUT_OF_GAS
) {
return bytes("");
}
// INVALID_STATE_ACCESS doesn't need to return any data other than the flag.
if (_flag == RevertFlag.INVALID_STATE_ACCESS) {
return abi.encode(
_flag,
0,
0,
bytes("")
);
}
// Just ABI encode the rest of the parameters.
return abi.encode(
_flag,
messageRecord.nuisanceGasLeft,
transactionRecord.ovmGasRefund,
_data
);
}
/**
* Simple decoding for revert data.
* @param _revertdata Revert data to decode.
* @return _flag Flag used to revert.
* @return _nuisanceGasLeft Amount of nuisance gas unused by the message.
* @return _ovmGasRefund Amount of gas refunded during the message.
* @return _data Additional user-provided revert data.
*/
function _decodeRevertData(
bytes memory _revertdata
)
internal
pure
returns (
RevertFlag _flag,
uint256 _nuisanceGasLeft,
uint256 _ovmGasRefund,
bytes memory _data
)
{
// A length of zero means the call ran out of gas, just return empty data.
if (_revertdata.length == 0) {
return (
RevertFlag.OUT_OF_GAS,
0,
0,
bytes("")
);
}
// ABI decode the incoming data.
return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes));
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
* @param _data Additional user-provided data.
*/
function _revertWithFlag(
RevertFlag _flag,
bytes memory _data
)
internal
view
{
bytes memory revertdata = _encodeRevertData(
_flag,
_data
);
assembly {
revert(add(revertdata, 0x20), mload(revertdata))
}
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
*/
function _revertWithFlag(
RevertFlag _flag
)
internal
{
_revertWithFlag(_flag, bytes(""));
}
/******************************************
* Internal Functions: Nuisance Gas Logic *
******************************************/
/**
* Computes the nuisance gas limit from the gas limit.
* @dev This function is currently using a naive implementation whereby the nuisance gas limit
* is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that
* this implementation is perfectly fine, but we may change this formula later.
* @param _gasLimit Gas limit to compute from.
* @return _nuisanceGasLimit Computed nuisance gas limit.
*/
function _getNuisanceGasLimit(
uint256 _gasLimit
)
internal
view
returns (
uint256 _nuisanceGasLimit
)
{
return _gasLimit < gasleft() ? _gasLimit : gasleft();
}
/**
* Uses a certain amount of nuisance gas.
* @param _amount Amount of nuisance gas to use.
*/
function _useNuisanceGas(
uint256 _amount
)
internal
{
// Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas
// refund to be given at the end of the transaction.
if (messageRecord.nuisanceGasLeft < _amount) {
_revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS);
}
messageRecord.nuisanceGasLeft -= _amount;
}
/************************************
* Internal Functions: Gas Metering *
************************************/
/**
* Checks whether a transaction needs to start a new epoch and does so if necessary.
* @param _timestamp Transaction timestamp.
*/
function _checkNeedsNewEpoch(
uint256 _timestamp
)
internal
{
if (
_timestamp >= (
_getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP)
+ gasMeterConfig.secondsPerEpoch
)
) {
_putGasMetadata(
GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP,
_timestamp
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS
)
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS
)
);
}
}
/**
* Validates the input values of a transaction.
* @return _valid Whether or not the transaction data is valid.
*/
function _isValidInput(
Lib_OVMCodec.Transaction memory _transaction
)
view
internal
returns (
bool
)
{
// Prevent reentrancy to run():
// This check prevents calling run with the default ovmNumber.
// Combined with the first check in run():
// if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; }
// It should be impossible to re-enter since run() returns before any other call frames are
// created. Since this value is already being written to storage, we save much gas compared
// to using the standard nonReentrant pattern.
if (_transaction.blockNumber == DEFAULT_UINT256) {
return false;
}
if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) {
return false;
}
return true;
}
/**
* Validates the gas limit for a given transaction.
* @param _gasLimit Gas limit provided by the transaction.
* param _queueOrigin Queue from which the transaction originated.
* @return _valid Whether or not the gas limit is valid.
*/
function _isValidGasLimit(
uint256 _gasLimit,
Lib_OVMCodec.QueueOrigin // _queueOrigin
)
view
internal
returns (
bool _valid
)
{
// Always have to be below the maximum gas limit.
if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) {
return false;
}
// Always have to be above the minimum gas limit.
if (_gasLimit < gasMeterConfig.minTransactionGasLimit) {
return false;
}
// TEMPORARY: Gas metering is disabled for minnet.
return true;
// GasMetadataKey cumulativeGasKey;
// GasMetadataKey prevEpochGasKey;
// if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS;
// } else {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS;
// }
// return (
// (
// _getGasMetadata(cumulativeGasKey)
// - _getGasMetadata(prevEpochGasKey)
// + _gasLimit
// ) < gasMeterConfig.maxGasPerQueuePerEpoch
// );
}
/**
* Updates the cumulative gas after a transaction.
* @param _gasUsed Gas used by the transaction.
* @param _queueOrigin Queue from which the transaction originated.
*/
function _updateCumulativeGas(
uint256 _gasUsed,
Lib_OVMCodec.QueueOrigin _queueOrigin
)
internal
{
GasMetadataKey cumulativeGasKey;
if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
} else {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
}
_putGasMetadata(
cumulativeGasKey,
(
_getGasMetadata(cumulativeGasKey)
+ gasMeterConfig.minTransactionGasLimit
+ _gasUsed
- transactionRecord.ovmGasRefund
)
);
}
/**
* Retrieves the value of a gas metadata key.
* @param _key Gas metadata key to retrieve.
* @return _value Value stored at the given key.
*/
function _getGasMetadata(
GasMetadataKey _key
)
internal
returns (
uint256 _value
)
{
return uint256(_getContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key))
));
}
/**
* Sets the value of a gas metadata key.
* @param _key Gas metadata key to set.
* @param _value Value to store at the given key.
*/
function _putGasMetadata(
GasMetadataKey _key,
uint256 _value
)
internal
{
_putContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key)),
bytes32(uint256(_value))
);
}
/*****************************************
* Internal Functions: Execution Context *
*****************************************/
/**
* Swaps over to a new message context.
* @param _prevMessageContext Context we're switching from.
* @param _nextMessageContext Context we're switching to.
*/
function _switchMessageContext(
MessageContext memory _prevMessageContext,
MessageContext memory _nextMessageContext
)
internal
{
// These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that
// the current storage value for the messageContext MUST equal the _prevMessageContext
// argument, or an SSTORE might be erroneously skipped.
if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) {
messageContext.ovmCALLER = _nextMessageContext.ovmCALLER;
}
if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) {
messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS;
}
if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) {
messageContext.isStatic = _nextMessageContext.isStatic;
}
if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) {
messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE;
}
}
/**
* Initializes the execution context.
* @param _transaction OVM transaction being executed.
*/
function _initContext(
Lib_OVMCodec.Transaction memory _transaction
)
internal
{
transactionContext.ovmTIMESTAMP = _transaction.timestamp;
transactionContext.ovmNUMBER = _transaction.blockNumber;
transactionContext.ovmTXGASLIMIT = _transaction.gasLimit;
transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin;
transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin;
transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch;
messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit);
}
/**
* Resets the transaction and message context.
*/
function _resetContext()
internal
{
transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS;
transactionContext.ovmTIMESTAMP = DEFAULT_UINT256;
transactionContext.ovmNUMBER = DEFAULT_UINT256;
transactionContext.ovmGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE;
transactionRecord.ovmGasRefund = DEFAULT_UINT256;
messageContext.ovmCALLER = DEFAULT_ADDRESS;
messageContext.ovmADDRESS = DEFAULT_ADDRESS;
messageContext.isStatic = false;
messageRecord.nuisanceGasLeft = DEFAULT_UINT256;
// Reset the ovmStateManager.
ovmStateManager = iOVM_StateManager(address(0));
}
/******************************************
* Internal Functions: Message Typechecks *
******************************************/
/**
* Returns whether or not the given message type is a CREATE-type.
* @param _messageType the message type in question.
*/
function _isCreateType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
return (
_messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/**
* Returns whether or not the given message type (potentially) requires the transfer of ETH
* value along with the message.
* @param _messageType the message type in question.
*/
function _isValueType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
// ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value.
return (
_messageType == MessageType.ovmCALL
|| _messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/*****************************
* L2-only Helper Functions *
*****************************/
/**
* Unreachable helper function for simulating eth_calls with an OVM message context.
* This function will throw an exception in all cases other than when used as a custom
* entrypoint in L2 Geth to simulate eth_call.
* @param _transaction the message transaction to simulate.
* @param _from the OVM account the simulated call should be from.
* @param _value the amount of ETH value to send.
* @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state.
*/
function simulateMessage(
Lib_OVMCodec.Transaction memory _transaction,
address _from,
uint256 _value,
iOVM_StateManager _ovmStateManager
)
external
returns (
bytes memory
)
{
// Prevent this call from having any effect unless in a custom-set VM frame
require(msg.sender == address(0));
// Initialize the EM's internal state, ignoring nuisance gas.
ovmStateManager = _ovmStateManager;
_initContext(_transaction);
messageRecord.nuisanceGasLeft = uint(-1);
// Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them.
messageContext.ovmADDRESS = _from;
// Execute the desired message.
bool isCreate = _transaction.entrypoint == address(0);
if (isCreate) {
(address created, bytes memory revertData) = ovmCREATE(_transaction.data);
if (created == address(0)) {
return abi.encode(false, revertData);
} else {
// The eth_call RPC endpoint for to = undefined will return the deployed bytecode
// in the success case, differing from standard create messages.
return abi.encode(true, Lib_EthUtils.getCode(created));
}
} else {
(bool success, bytes memory returndata) = ovmCALL(
_transaction.gasLimit,
_transaction.entrypoint,
_value,
_transaction.data
);
return abi.encode(success, returndata);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_SafetyChecker
*/
interface iOVM_SafetyChecker {
/********************
* Public Functions *
********************/
function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol";
/**
* @title OVM_DeployerWhitelist
* @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the
* initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts
* which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an
* ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist {
/**********************
* Contract Constants *
**********************/
bool public initialized;
bool public allowArbitraryDeployment;
address override public owner;
mapping (address => bool) public whitelist;
/**********************
* Function Modifiers *
**********************/
/**
* Blocks functions to anyone except the contract owner.
*/
modifier onlyOwner() {
require(
msg.sender == owner,
"Function can only be called by the owner of this contract."
);
_;
}
/********************
* Public Functions *
********************/
/**
* Initializes the whitelist.
* @param _owner Address of the owner for this contract.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function initialize(
address _owner,
bool _allowArbitraryDeployment
)
override
external
{
if (initialized == true) {
return;
}
initialized = true;
allowArbitraryDeployment = _allowArbitraryDeployment;
owner = _owner;
}
/**
* Adds or removes an address from the deployment whitelist.
* @param _deployer Address to update permissions for.
* @param _isWhitelisted Whether or not the address is whitelisted.
*/
function setWhitelistedDeployer(
address _deployer,
bool _isWhitelisted
)
override
external
onlyOwner
{
whitelist[_deployer] = _isWhitelisted;
}
/**
* Updates the owner of this contract.
* @param _owner Address of the new owner.
*/
function setOwner(
address _owner
)
override
public
onlyOwner
{
owner = _owner;
}
/**
* Updates the arbitrary deployment flag.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function setAllowArbitraryDeployment(
bool _allowArbitraryDeployment
)
override
public
onlyOwner
{
allowArbitraryDeployment = _allowArbitraryDeployment;
}
/**
* Permanently enables arbitrary contract deployment and deletes the owner.
*/
function enableArbitraryContractDeployment()
override
external
onlyOwner
{
setAllowArbitraryDeployment(true);
setOwner(address(0));
}
/**
* Checks whether an address is allowed to deploy contracts.
* @param _deployer Address to check.
* @return _allowed Whether or not the address can deploy contracts.
*/
function isDeployerAllowed(
address _deployer
)
override
external
returns (
bool
)
{
return (
initialized == false
|| allowArbitraryDeployment == true
|| whitelist[_deployer]
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_DeployerWhitelist
*/
interface iOVM_DeployerWhitelist {
/********************
* Public Functions *
********************/
function initialize(address _owner, bool _allowArbitraryDeployment) external;
function owner() external returns (address _owner);
function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external;
function setOwner(address _newOwner) external;
function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external;
function enableArbitraryContractDeployment() external;
function isDeployerAllowed(address _deployer) external returns (bool _allowed);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol";
/**
* @title OVM_SafetyChecker
* @dev The Safety Checker verifies that contracts deployed on L2 do not contain any
* "unsafe" operations. An operation is considered unsafe if it would access state variables which
* are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used
* to "escape the sandbox" of the OVM, resulting in non-deterministic fraud proofs.
* That is, an attacker would be able to "prove fraud" on an honestly applied transaction.
* Note that a "safe" contract requires opcodes to appear in a particular pattern;
* omission of "unsafe" opcodes is necessary, but not sufficient.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_SafetyChecker is iOVM_SafetyChecker {
/********************
* Public Functions *
********************/
/**
* Returns whether or not all of the provided bytecode is safe.
* @param _bytecode The bytecode to safety check.
* @return `true` if the bytecode is safe, `false` otherwise.
*/
function isBytecodeSafe(
bytes memory _bytecode
)
override
external
pure
returns (
bool
)
{
// autogenerated by gen_safety_checker_constants.py
// number of bytes to skip for each opcode
uint256[8] memory opcodeSkippableBytes = [
uint256(0x0001010101010101010101010000000001010101010101010101010101010000),
uint256(0x0100000000000000000000000000000000000000010101010101000000010100),
uint256(0x0000000000000000000000000000000001010101000000010101010100000000),
uint256(0x0203040500000000000000000000000000000000000000000000000000000000),
uint256(0x0101010101010101010101010101010101010101010101010101010101010101),
uint256(0x0101010101000000000000000000000000000000000000000000000000000000),
uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
];
// Mask to gate opcode specific cases
// solhint-disable-next-line max-line-length
uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001);
// Halting opcodes
// solhint-disable-next-line max-line-length
uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001);
// PUSH opcodes
uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000);
uint256 codeLength;
uint256 _pc;
assembly {
_pc := add(_bytecode, 0x20)
}
codeLength = _pc + _bytecode.length;
do {
// current opcode: 0x00...0xff
uint256 opNum;
/* solhint-disable max-line-length */
// inline assembly removes the extra add + bounds check
assembly {
let word := mload(_pc) //load the next 32 bytes at pc into word
// Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord
// E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4
// We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32).
// If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5,
// then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode.
let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
_pc := add(_pc, indexInWord)
opNum := byte(indexInWord, word)
}
/* solhint-enable max-line-length */
// + push opcodes
// + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)]
// + caller opcode CALLER(0x33)
// + blacklisted opcodes
uint256 opBit = 1 << opNum;
if (opBit & opcodeGateMask == 0) {
if (opBit & opcodePushMask == 0) {
// all pushes are valid opcodes
// subsequent bytes are not opcodes. Skip them.
_pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we
// +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e)
continue;
} else if (opBit & opcodeHaltingMask == 0) {
// STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not
// included here)
// We are now inside unreachable code until we hit a JUMPDEST!
do {
_pc++;
assembly {
opNum := byte(0, mload(_pc))
}
// encountered a JUMPDEST
if (opNum == 0x5b) break;
// skip PUSHed bytes
// opNum-0x5f = PUSHed bytes (PUSH1 is 0x60)
if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f);
} while (_pc < codeLength);
// opNum is 0x5b, so we don't continue here since the pc++ is fine
} else if (opNum == 0x33) { // Caller opcode
uint256 firstOps; // next 32 bytes of bytecode
uint256 secondOps; // following 32 bytes of bytecode
assembly {
firstOps := mload(_pc)
// 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits
secondOps := shr(216, mload(add(_pc, 0x20)))
}
// Call identity precompile
// CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL
// 32 - 8 bytes = 24 bytes = 192
if ((firstOps >> 192) == 0x3350600060045af1) {
_pc += 8;
// Call EM and abort execution if instructed
// CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE
// PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST
// RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1
// 0x00 RETURN JUMPDEST
// solhint-disable-next-line max-line-length
} else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) {
_pc += 37;
} else {
return false;
}
continue;
} else {
// encountered a non-whitelisted opcode!
return false;
}
}
_pc++;
} while (_pc < codeLength);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { OVM_StateManager } from "./OVM_StateManager.sol";
/**
* @title OVM_StateManagerFactory
* @dev The State Manager Factory is called by a State Transitioner's init code, to create a new
* State Manager for use in the Fraud Verification process.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManagerFactory is iOVM_StateManagerFactory {
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateManager
* @param _owner Owner of the created contract.
* @return New OVM_StateManager instance.
*/
function create(
address _owner
)
override
public
returns (
iOVM_StateManager
)
{
return new OVM_StateManager(_owner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
/**
* @title OVM_StateManager
* @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be
* written to by the Execution Manager and State Transitioner. It runs on L1 during the setup and
* execution of a fraud proof.
* The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client
* (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go).
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManager is iOVM_StateManager {
/*************
* Constants *
*************/
bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT =
0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 constant internal STORAGE_XOR_VALUE =
0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF;
/*************
* Variables *
*************/
address override public owner;
address override public ovmExecutionManager;
mapping (address => Lib_OVMCodec.Account) internal accounts;
mapping (address => mapping (bytes32 => bytes32)) internal contractStorage;
mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage;
mapping (bytes32 => ItemState) internal itemStates;
uint256 internal totalUncommittedAccounts;
uint256 internal totalUncommittedContractStorage;
/***************
* Constructor *
***************/
/**
* @param _owner Address of the owner of this contract.
*/
constructor(
address _owner
)
{
owner = _owner;
}
/**********************
* Function Modifiers *
**********************/
/**
* Simple authentication, this contract should only be accessible to the owner
* (which is expected to be the State Transitioner during `PRE_EXECUTION`
* or the OVM_ExecutionManager during transaction execution.
*/
modifier authenticated() {
// owner is the State Transitioner
require(
msg.sender == owner || msg.sender == ovmExecutionManager,
"Function can only be called by authenticated addresses"
);
_;
}
/********************
* Public Functions *
********************/
/**
* Checks whether a given address is allowed to modify this contract.
* @param _address Address to check.
* @return Whether or not the address can modify this contract.
*/
function isAuthenticated(
address _address
)
override
public
view
returns (
bool
)
{
return (_address == owner || _address == ovmExecutionManager);
}
/**
* Sets the address of the OVM_ExecutionManager.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
*/
function setExecutionManager(
address _ovmExecutionManager
)
override
public
authenticated
{
ovmExecutionManager = _ovmExecutionManager;
}
/**
* Inserts an account into the state.
* @param _address Address of the account to insert.
* @param _account Account to insert for the given address.
*/
function putAccount(
address _address,
Lib_OVMCodec.Account memory _account
)
override
public
authenticated
{
accounts[_address] = _account;
}
/**
* Marks an account as empty.
* @param _address Address of the account to mark.
*/
function putEmptyAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
}
/**
* Retrieves an account from the state.
* @param _address Address of the account to retrieve.
* @return Account for the given address.
*/
function getAccount(
address _address
)
override
public
view
returns (
Lib_OVMCodec.Account memory
)
{
return accounts[_address];
}
/**
* Checks whether the state has a given account.
* @param _address Address of the account to check.
* @return Whether or not the state has the account.
*/
function hasAccount(
address _address
)
override
public
view
returns (
bool
)
{
return accounts[_address].codeHash != bytes32(0);
}
/**
* Checks whether the state has a given known empty account.
* @param _address Address of the account to check.
* @return Whether or not the state has the empty account.
*/
function hasEmptyAccount(
address _address
)
override
public
view
returns (
bool
)
{
return (
accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH
&& accounts[_address].nonce == 0
);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function setAccountNonce(
address _address,
uint256 _nonce
)
override
public
authenticated
{
accounts[_address].nonce = _nonce;
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return Nonce of the account.
*/
function getAccountNonce(
address _address
)
override
public
view
returns (
uint256
)
{
return accounts[_address].nonce;
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return Corresponding Ethereum address.
*/
function getAccountEthAddress(
address _address
)
override
public
view
returns (
address
)
{
return accounts[_address].ethAddress;
}
/**
* Retrieves the storage root of an account.
* @param _address Address of the account to access.
* @return Corresponding storage root.
*/
function getAccountStorageRoot(
address _address
)
override
public
view
returns (
bytes32
)
{
return accounts[_address].storageRoot;
}
/**
* Initializes a pending account (during CREATE or CREATE2) with the default values.
* @param _address Address of the account to initialize.
*/
function initPendingAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.nonce = 1;
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
account.isFresh = true;
}
/**
* Finalizes the creation of a pending account (during CREATE or CREATE2).
* @param _address Address of the account to finalize.
* @param _ethAddress Address of the account's associated contract on Ethereum.
* @param _codeHash Hash of the account's code.
*/
function commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.ethAddress = _ethAddress;
account.codeHash = _codeHash;
}
/**
* Checks whether an account has already been retrieved, and marks it as retrieved if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already loaded.
*/
function testAndSetAccountLoaded(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether an account has already been modified, and marks it as modified if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already modified.
*/
function testAndSetAccountChanged(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark an account as committed.
* @param _address Address of the account to commit.
* @return Whether or not the account was committed.
*/
function commitAccount(
address _address
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedAccounts -= 1;
return true;
}
/**
* Increments the total number of uncommitted accounts.
*/
function incrementTotalUncommittedAccounts()
override
public
authenticated
{
totalUncommittedAccounts += 1;
}
/**
* Gets the total number of uncommitted accounts.
* @return Total uncommitted accounts.
*/
function getTotalUncommittedAccounts()
override
public
view
returns (
uint256
)
{
return totalUncommittedAccounts;
}
/**
* Checks whether a given account was changed during execution.
* @param _address Address to check.
* @return Whether or not the account was changed.
*/
function wasAccountChanged(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given account was committed after execution.
* @param _address Address to check.
* @return Whether or not the account was committed.
*/
function wasAccountCommitted(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/************************************
* Public Functions: Storage Access *
************************************/
/**
* Changes a contract storage slot value.
* @param _contract Address of the contract to modify.
* @param _key 32 byte storage slot key.
* @param _value 32 byte storage slot value.
*/
function putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
override
public
authenticated
{
// A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's
// worth populating this with a non-zero value in advance (during the fraud proof
// initialization phase) to cut the execution-time cost down to 5000 gas.
contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE;
// Only used when initially populating the contract storage. OVM_ExecutionManager will
// perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract
// storage because writing to zero when the actual value is nonzero causes a gas
// discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or
// something along those lines.
if (verifiedContractStorage[_contract][_key] == false) {
verifiedContractStorage[_contract][_key] = true;
}
}
/**
* Retrieves a contract storage slot value.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return 32 byte storage slot value.
*/
function getContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bytes32
)
{
// Storage XOR system doesn't work for newly created contracts that haven't set this
// storage slot value yet.
if (
verifiedContractStorage[_contract][_key] == false
&& accounts[_contract].isFresh
) {
return bytes32(0);
}
// See `putContractStorage` for more information about the XOR here.
return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE;
}
/**
* Checks whether a contract storage slot exists in the state.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return Whether or not the key was set in the state.
*/
function hasContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh;
}
/**
* Checks whether a storage slot has already been retrieved, and marks it as retrieved if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already loaded.
*/
function testAndSetContractStorageLoaded(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether a storage slot has already been modified, and marks it as modified if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already modified.
*/
function testAndSetContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark a storage slot as committed.
* @param _contract Address of the account to commit.
* @param _key 32 byte slot key to commit.
* @return Whether or not the slot was committed.
*/
function commitContractStorage(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedContractStorage -= 1;
return true;
}
/**
* Increments the total number of uncommitted storage slots.
*/
function incrementTotalUncommittedContractStorage()
override
public
authenticated
{
totalUncommittedContractStorage += 1;
}
/**
* Gets the total number of uncommitted storage slots.
* @return Total uncommitted storage slots.
*/
function getTotalUncommittedContractStorage()
override
public
view
returns (
uint256
)
{
return totalUncommittedContractStorage;
}
/**
* Checks whether a given storage slot was changed during execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was changed.
*/
function wasContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given storage slot was committed after execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was committed.
*/
function wasContractStorageCommitted(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/**********************
* Internal Functions *
**********************/
/**
* Generates a unique hash for an address.
* @param _address Address to generate a hash for.
* @return Unique hash for the given address.
*/
function _getItemHash(
address _address
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_address));
}
/**
* Generates a unique hash for an address/key pair.
* @param _contract Address to generate a hash for.
* @param _key Key to generate a hash for.
* @return Unique hash for the given pair.
*/
function _getItemHash(
address _contract,
bytes32 _key
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(
_contract,
_key
));
}
/**
* Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the
* item to the provided state if not.
* @param _item 32 byte item ID to check.
* @param _minItemState Minimum state that must be satisfied by the item.
* @return Whether or not the item was already in the state.
*/
function _testAndSetItemState(
bytes32 _item,
ItemState _minItemState
)
internal
returns (
bool
)
{
bool wasItemState = itemStates[_item] >= _minItemState;
if (wasItemState == false) {
itemStates[_item] = _minItemState;
}
return wasItemState;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol";
/**
* @title TestLib_OVMCodec
*/
contract TestLib_OVMCodec {
function encodeTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
public
pure
returns (
bytes memory _encoded
)
{
return Lib_OVMCodec.encodeTransaction(_transaction);
}
function hashTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
public
pure
returns (
bytes32 _hash
)
{
return Lib_OVMCodec.hashTransaction(_transaction);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol";
import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_CanonicalTransactionChain } from
"../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol";
/* External Imports */
import { OwnableUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { PausableUpgradeable } from
"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import { ReentrancyGuardUpgradeable } from
"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title OVM_L1CrossDomainMessenger
* @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages
* from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2
* epoch gas limit, it can be resubmitted via this contract's replay function.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1CrossDomainMessenger is
iOVM_L1CrossDomainMessenger,
Lib_AddressResolver,
OwnableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
/**********
* Events *
**********/
event MessageBlocked(
bytes32 indexed _xDomainCalldataHash
);
event MessageAllowed(
bytes32 indexed _xDomainCalldataHash
);
/*************
* Constants *
*************/
// The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
/**********************
* Contract Variables *
**********************/
mapping (bytes32 => bool) public blockedMessages;
mapping (bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages;
address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
/***************
* Constructor *
***************/
/**
* This contract is intended to be behind a delegate proxy.
* We pass the zero address to the address resolver just to satisfy the constructor.
* We still need to set this value in initialize().
*/
constructor()
Lib_AddressResolver(address(0))
{}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may
* successfully call a method.
*/
modifier onlyRelayer() {
address relayer = resolve("OVM_L2MessageRelayer");
if (relayer != address(0)) {
require(
msg.sender == relayer,
"Only OVM_L2MessageRelayer can relay L2-to-L1 messages."
);
}
_;
}
/********************
* Public Functions *
********************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
function initialize(
address _libAddressManager
)
public
initializer
{
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Initialize upgradable OZ contracts
__Context_init_unchained(); // Context is a dependency for both Ownable and Pausable
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/**
* Pause relaying.
*/
function pause()
external
onlyOwner
{
_pause();
}
/**
* Block a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function blockMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = true;
emit MessageBlocked(_xDomainCalldataHash);
}
/**
* Allow a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function allowMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = false;
emit MessageAllowed(_xDomainCalldataHash);
}
function xDomainMessageSender()
public
override
view
returns (
address
)
{
require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender;
}
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
override
public
{
address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
// Use the CTC queue length as nonce
uint40 nonce =
iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
nonce
);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
_sendXDomainMessage(
ovmCanonicalTransactionChain,
l2CrossDomainMessenger,
xDomainCalldata,
_gasLimit
);
emit SentMessage(xDomainCalldata);
}
/**
* Relays a cross domain message to a contract.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
)
override
public
nonReentrant
onlyRelayer
whenNotPaused
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_messageNonce
);
require(
_verifyXDomainMessage(
xDomainCalldata,
_proof
) == true,
"Provided message could not be verified."
);
bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);
require(
successfulMessages[xDomainCalldataHash] == false,
"Provided message has already been received."
);
require(
blockedMessages[xDomainCalldataHash] == false,
"Provided message has been blocked."
);
require(
_target != resolve("OVM_CanonicalTransactionChain"),
"Cannot send L2->L1 messages to L1 system contracts."
);
xDomainMsgSender = _sender;
(bool success, ) = _target.call(_message);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Mark the message as received if the call was successful. Ensures that a message can be
// relayed multiple times in the case that the call reverted.
if (success == true) {
successfulMessages[xDomainCalldataHash] = true;
emit RelayedMessage(xDomainCalldataHash);
} else {
emit FailedRelayedMessage(xDomainCalldataHash);
}
// Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true;
}
/**
* Replays a cross domain message to the target messenger.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
)
override
public
{
// Verify that the message is in the queue:
address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
Lib_OVMCodec.QueueElement memory element =
iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
// Compute the transactionHash
bytes32 transactionHash = keccak256(
abi.encode(
address(this),
l2CrossDomainMessenger,
_gasLimit,
_message
)
);
require(
transactionHash == element.transactionHash,
"Provided message has not been enqueued."
);
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_queueIndex
);
_sendXDomainMessage(
canonicalTransactionChain,
l2CrossDomainMessenger,
xDomainCalldata,
_gasLimit
);
}
/**********************
* Internal Functions *
**********************/
/**
* Verifies that the given message is valid.
* @param _xDomainCalldata Calldata to verify.
* @param _proof Inclusion proof for the message.
* @return Whether or not the provided message is valid.
*/
function _verifyXDomainMessage(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
return (
_verifyStateRootProof(_proof)
&& _verifyStorageProof(_xDomainCalldata, _proof)
);
}
/**
* Verifies that the state root within an inclusion proof is valid.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStateRootProof(
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(
resolve("OVM_StateCommitmentChain")
);
return (
ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false
&& ovmStateCommitmentChain.verifyStateCommitment(
_proof.stateRoot,
_proof.stateRootBatchHeader,
_proof.stateRootProof
)
);
}
/**
* Verifies that the storage proof within an inclusion proof is valid.
* @param _xDomainCalldata Encoded message calldata.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStorageProof(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
bytes32 storageKey = keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_xDomainCalldata,
resolve("OVM_L2CrossDomainMessenger")
)
),
uint256(0)
)
);
(
bool exists,
bytes memory encodedMessagePassingAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER),
_proof.stateTrieWitness,
_proof.stateRoot
);
require(
exists == true,
"Message passing predeploy has not been initialized or invalid proof provided."
);
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedMessagePassingAccount
);
return Lib_SecureMerkleTrie.verifyInclusionProof(
abi.encodePacked(storageKey),
abi.encodePacked(uint8(1)),
_proof.storageTrieWitness,
account.storageRoot
);
}
/**
* Sends a cross domain message.
* @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance.
* @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance.
* @param _message Message to send.
* @param _gasLimit OVM gas limit for the message.
*/
function _sendXDomainMessage(
address _canonicalTransactionChain,
address _l2CrossDomainMessenger,
bytes memory _message,
uint256 _gasLimit
)
internal
{
iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue(
_l2CrossDomainMessenger,
_gasLimit,
_message
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
/**
* @title Lib_CrossDomainUtils
*/
library Lib_CrossDomainUtils {
/**
* Generates the correct cross domain calldata for a message.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @return ABI encoded cross domain calldata.
*/
function encodeXDomainCalldata(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_message,
_messageNonce
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L1CrossDomainMessenger
*/
interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger {
/*******************
* Data Structures *
*******************/
struct L2MessageInclusionProof {
bytes32 stateRoot;
Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader;
Lib_OVMCodec.ChainInclusionProof stateRootProof;
bytes stateTrieWitness;
bytes storageTrieWitness;
}
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @param _proof Inclusion proof for the given message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
) external;
/**
* Replays a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _sender Original sender address.
* @param _message Message to send to the target.
* @param _queueIndex CTC Queue index for the message to replay.
* @param _gasLimit Gas limit for the provided message.
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_L1MultiMessageRelayer } from
"../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol";
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
/**
* @title OVM_L1MultiMessageRelayer
* @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the
* relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain
* Message Sender.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver {
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/**********************
* Function Modifiers *
**********************/
modifier onlyBatchRelayer() {
require(
msg.sender == resolve("OVM_L2BatchMessageRelayer"),
// solhint-disable-next-line max-line-length
"OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer"
);
_;
}
/********************
* Public Functions *
********************/
/**
* @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying
* @param _messages An array of L2 to L1 messages
*/
function batchRelayMessages(
L2ToL1Message[] calldata _messages
)
override
external
onlyBatchRelayer
{
iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger(
resolve("Proxy__OVM_L1CrossDomainMessenger")
);
for (uint256 i = 0; i < _messages.length; i++) {
L2ToL1Message memory message = _messages[i];
messenger.relayMessage(
message.target,
message.sender,
message.message,
message.messageNonce,
message.proof
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
interface iOVM_L1MultiMessageRelayer {
struct L2ToL1Message {
address target;
address sender;
bytes message;
uint256 messageNonce;
iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof;
}
function batchRelayMessages(L2ToL1Message[] calldata _messages) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */
import { iOVM_L2CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol";
import { iOVM_L1MessageSender } from "../../../iOVM/predeploys/iOVM_L1MessageSender.sol";
import { iOVM_L2ToL1MessagePasser } from "../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol";
/* External Imports */
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/* External Imports */
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title OVM_L2CrossDomainMessenger
* @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point
* for L2 messages sent via the L1 Cross Domain Messenger.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2CrossDomainMessenger is
iOVM_L2CrossDomainMessenger,
Lib_AddressResolver,
ReentrancyGuard
{
/*************
* Constants *
*************/
// The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
/*************
* Variables *
*************/
mapping (bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages;
mapping (bytes32 => bool) public sentMessages;
uint256 public messageNonce;
address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(address _libAddressManager)
Lib_AddressResolver(_libAddressManager)
ReentrancyGuard()
{}
/********************
* Public Functions *
********************/
function xDomainMessageSender()
public
override
view
returns (
address
)
{
require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender;
}
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
override
public
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
messageNonce
);
messageNonce += 1;
sentMessages[keccak256(xDomainCalldata)] = true;
_sendXDomainMessage(xDomainCalldata, _gasLimit);
emit SentMessage(xDomainCalldata);
}
/**
* Relays a cross domain message to a contract.
* @inheritdoc iOVM_L2CrossDomainMessenger
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
override
nonReentrant
public
{
require(
_verifyXDomainMessage() == true,
"Provided message could not be verified."
);
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_messageNonce
);
bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);
require(
successfulMessages[xDomainCalldataHash] == false,
"Provided message has already been received."
);
// Prevent calls to OVM_L2ToL1MessagePasser, which would enable
// an attacker to maliciously craft the _message to spoof
// a call from any L2 account.
if(_target == resolve("OVM_L2ToL1MessagePasser")){
// Write to the successfulMessages mapping and return immediately.
successfulMessages[xDomainCalldataHash] = true;
return;
}
xDomainMsgSender = _sender;
(bool success, ) = _target.call(_message);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Mark the message as received if the call was successful. Ensures that a message can be
// relayed multiple times in the case that the call reverted.
if (success == true) {
successfulMessages[xDomainCalldataHash] = true;
emit RelayedMessage(xDomainCalldataHash);
} else {
emit FailedRelayedMessage(xDomainCalldataHash);
}
// Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true;
}
/**********************
* Internal Functions *
**********************/
/**
* Verifies that a received cross domain message is valid.
* @return _valid Whether or not the message is valid.
*/
function _verifyXDomainMessage()
view
internal
returns (
bool _valid
)
{
return (
iOVM_L1MessageSender(
resolve("OVM_L1MessageSender")
).getL1MessageSender() == resolve("OVM_L1CrossDomainMessenger")
);
}
/**
* Sends a cross domain message.
* @param _message Message to send.
* param _gasLimit Gas limit for the provided message.
*/
function _sendXDomainMessage(
bytes memory _message,
uint256 // _gasLimit
)
internal
{
iOVM_L2ToL1MessagePasser(resolve("OVM_L2ToL1MessagePasser")).passMessageToL1(_message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L2CrossDomainMessenger
*/
interface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger {
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_L1MessageSender
*/
interface iOVM_L1MessageSender {
/********************
* Public Functions *
********************/
function getL1MessageSender() external view returns (address _l1MessageSender);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_L2ToL1MessagePasser
*/
interface iOVM_L2ToL1MessagePasser {
/**********
* Events *
**********/
event L2ToL1Message(
uint256 _nonce,
address _sender,
bytes _data
);
/********************
* Public Functions *
********************/
function passMessageToL1(bytes calldata _message) external;
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_L2ToL1MessagePasser } from "../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol";
/**
* @title OVM_L2ToL1MessagePasser
* @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the
* of a message on L2. The L1 Cross Domain Messenger performs this proof in its
* _verifyStorageProof function, which verifies the existence of the transaction hash in this
* contract's `sentMessages` mapping.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
/**********************
* Contract Variables *
**********************/
mapping (bytes32 => bool) public sentMessages;
/********************
* Public Functions *
********************/
/**
* Passes a message to L1.
* @param _message Message to pass to L1.
*/
function passMessageToL1(
bytes memory _message
)
override
public
{
// Note: although this function is public, only messages sent from the
// OVM_L2CrossDomainMessenger will be relayed by the OVM_L1CrossDomainMessenger.
// This is enforced by a check in OVM_L1CrossDomainMessenger._verifyStorageProof().
sentMessages[keccak256(
abi.encodePacked(
_message,
msg.sender
)
)] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_L1MessageSender } from "../../iOVM/predeploys/iOVM_L1MessageSender.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
/**
* @title OVM_L1MessageSender
* @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross
* domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or
* contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()`
* function.
*
* This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary
* because there is no corresponding operation in the EVM which the the optimistic solidity compiler
* can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function.
*
*
* Compiler used: solc
* Runtime target: OVM
*/
contract OVM_L1MessageSender is iOVM_L1MessageSender {
/********************
* Public Functions *
********************/
/**
* @return _l1MessageSender L1 message sender address (msg.sender).
*/
function getL1MessageSender()
override
public
view
returns (
address _l1MessageSender
)
{
// Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager
return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol";
/**
* @title TestLib_RLPReader
*/
contract TestLib_RLPReader {
function readList(
bytes memory _in
)
public
pure
returns (
bytes[] memory
)
{
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in);
bytes[] memory out = new bytes[](decoded.length);
for (uint256 i = 0; i < out.length; i++) {
out[i] = Lib_RLPReader.readRawBytes(decoded[i]);
}
return out;
}
function readString(
bytes memory _in
)
public
pure
returns (
string memory
)
{
return Lib_RLPReader.readString(_in);
}
function readBytes(
bytes memory _in
)
public
pure
returns (
bytes memory
)
{
return Lib_RLPReader.readBytes(_in);
}
function readBytes32(
bytes memory _in
)
public
pure
returns (
bytes32
)
{
return Lib_RLPReader.readBytes32(_in);
}
function readUint256(
bytes memory _in
)
public
pure
returns (
uint256
)
{
return Lib_RLPReader.readUint256(_in);
}
function readBool(
bytes memory _in
)
public
pure
returns (
bool
)
{
return Lib_RLPReader.readBool(_in);
}
function readAddress(
bytes memory _in
)
public
pure
returns (
address
)
{
return Lib_RLPReader.readAddress(_in);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_MerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol";
/**
* @title TestLib_MerkleTrie
*/
contract TestLib_MerkleTrie {
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool
)
{
return Lib_MerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
}
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTrie.update(
_key,
_value,
_proof,
_root
);
}
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool,
bytes memory
)
{
return Lib_MerkleTrie.get(
_key,
_proof,
_root
);
}
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTrie.getSingleNodeRootHash(
_key,
_value
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_SecureMerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol";
/**
* @title TestLib_SecureMerkleTrie
*/
contract TestLib_SecureMerkleTrie {
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool
)
{
return Lib_SecureMerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
}
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bytes32
)
{
return Lib_SecureMerkleTrie.update(
_key,
_value,
_proof,
_root
);
}
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool,
bytes memory
)
{
return Lib_SecureMerkleTrie.get(
_key,
_proof,
_root
);
}
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
public
pure
returns (
bytes32
)
{
return Lib_SecureMerkleTrie.getSingleNodeRootHash(
_key,
_value
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_ResolvedDelegateProxy
*/
contract Lib_ResolvedDelegateProxy {
/*************
* Variables *
*************/
// Using mappings to store fields to avoid overwriting storage slots in the
// implementation contract. For example, instead of storing these fields at
// storage slot `0` & `1`, they are stored at `keccak256(key + slot)`.
// See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html
// NOTE: Do not use this code in your own contract system.
// There is a known flaw in this contract, and we will remove it from the repository
// in the near future. Due to the very limited way that we are using it, this flaw is
// not an issue in our system.
mapping (address => string) private implementationName;
mapping (address => Lib_AddressManager) private addressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
* @param _implementationName implementationName of the contract to proxy to.
*/
constructor(
address _libAddressManager,
string memory _implementationName
) {
addressManager[address(this)] = Lib_AddressManager(_libAddressManager);
implementationName[address(this)] = _implementationName;
}
/*********************
* Fallback Function *
*********************/
fallback()
external
payable
{
address target = addressManager[address(this)].getAddress(
(implementationName[address(this)])
);
require(
target != address(0),
"Target address must be initialized."
);
(bool success, bytes memory returndata) = target.delegatecall(msg.data);
if (success == true) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title OVM_GasPriceOracle
* @dev This contract exposes the current l2 gas price, a measure of how congested the network
* currently is. This measure is used by the Sequencer to determine what fee to charge for
* transactions. When the system is more congested, the l2 gas price will increase and fees
* will also increase as a result.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_GasPriceOracle is Ownable {
/*************
* Variables *
*************/
// Current l2 gas price
uint256 public gasPrice;
/***************
* Constructor *
***************/
/**
* @param _owner Address that will initially own this contract.
*/
constructor(
address _owner,
uint256 _initialGasPrice
)
Ownable()
{
setGasPrice(_initialGasPrice);
transferOwnership(_owner);
}
/********************
* Public Functions *
********************/
/**
* Allows the owner to modify the l2 gas price.
* @param _gasPrice New l2 gas price.
*/
function setGasPrice(
uint256 _gasPrice
)
public
onlyOwner
{
gasPrice = _gasPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Contract Imports */
import { L2StandardERC20 } from "../../../libraries/standards/L2StandardERC20.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
/**
* @title OVM_L2StandardTokenFactory
* @dev Factory contract for creating standard L2 token representations of L1 ERC20s
* compatible with and working on the standard bridge.
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2StandardTokenFactory {
event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token);
/**
* @dev Creates an instance of the standard ERC20 token on L2.
* @param _l1Token Address of the corresponding L1 token.
* @param _name ERC20 name.
* @param _symbol ERC20 symbol.
*/
function createStandardL2Token(
address _l1Token,
string memory _name,
string memory _symbol
)
external
{
require (_l1Token != address(0), "Must provide L1 token address");
L2StandardERC20 l2Token = new L2StandardERC20(
Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
_l1Token,
_name,
_symbol
);
emit StandardL2TokenCreated(_l1Token, address(l2Token));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Bytes32Utils } from "../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol";
/**
* @title TestLib_Byte32Utils
*/
contract TestLib_Bytes32Utils {
function toBool(
bytes32 _in
)
public
pure
returns (
bool _out
)
{
return Lib_Bytes32Utils.toBool(_in);
}
function fromBool(
bool _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromBool(_in);
}
function toAddress(
bytes32 _in
)
public
pure
returns (
address _out
)
{
return Lib_Bytes32Utils.toAddress(_in);
}
function fromAddress(
address _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromAddress(_in);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EthUtils } from "../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol";
/**
* @title TestLib_EthUtils
*/
contract TestLib_EthUtils {
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
public
view
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_address,
_offset,
_length
);
}
function getCode(
address _address
)
public
view
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_address
);
}
function getCodeSize(
address _address
)
public
view
returns (
uint256 _codeSize
)
{
return Lib_EthUtils.getCodeSize(
_address
);
}
function getCodeHash(
address _address
)
public
view
returns (
bytes32 _codeHash
)
{
return Lib_EthUtils.getCodeHash(
_address
);
}
function createContract(
bytes memory _code
)
public
returns (
address _created
)
{
return Lib_EthUtils.createContract(
_code
);
}
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
public
pure
returns (
address _address
)
{
return Lib_EthUtils.getAddressForCREATE(
_creator,
_nonce
);
}
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
public
pure
returns (address _address)
{
return Lib_EthUtils.getAddressForCREATE2(
_creator,
_bytecode,
_salt
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTree } from "../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol";
/**
* @title TestLib_MerkleTree
*/
contract TestLib_MerkleTree {
function getMerkleRoot(
bytes32[] memory _elements
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTree.getMerkleRoot(
_elements
);
}
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
)
public
pure
returns (
bool
)
{
return Lib_MerkleTree.verify(
_root,
_leaf,
_index,
_siblings,
_totalLeaves
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
/* Contract Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/**
* @title mockOVM_BondManager
*/
contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver {
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
)
override
public
{}
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
)
override
public
{}
function deposit()
override
public
{}
function startWithdrawal()
override
public
{}
function finalizeWithdrawal()
override
public
{}
function claim(
address _who
)
override
public
{}
function isCollateralized(
address _who
)
override
public
view
returns (
bool
)
{
// Only authenticate sequencer to submit state root batches.
return _who == resolve("OVM_Proposer");
}
function getGasSpent(
bytes32, // _preStateRoot,
address // _who
)
override
public
pure
returns (
uint256
)
{
return 0;
}
}
| @inheritdoc iOVM_L2ERC20Bridge/ | function withdrawTo(
address _l2Token,
address _to,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
_to,
_amount,
_l1Gas,
_data
);
}
| 6,166,722 |
./full_match/137/0x919418623045861F29033EF11ccD66E0bca2F880/sources/project_/contracts/libraries/AssetUnitConversions.sol | Exponents cannot be negative, so divide or multiply based on exponent signedness | function assetUnitsToPips(uint256 quantityInAssetUnits, uint8 assetDecimals)
internal
pure
returns (uint64)
{
require(assetDecimals <= 32, 'Asset cannot have more than 32 decimals');
uint256 quantityInPips;
if (assetDecimals > 8) {
quantityInPips =
quantityInAssetUnits /
(uint256(10)**(assetDecimals - 8));
quantityInPips =
quantityInAssetUnits *
(uint256(10)**(8 - assetDecimals));
}
require(quantityInPips < 2**64, 'Pip quantity overflows uint64');
return uint64(quantityInPips);
}
| 3,745,880 |
pragma solidity ^0.4.24;
import "../WallOfChainToken.sol";
contract StructuredLinkedListMock is WallOfChainToken {
using StructuredLinkedList for StructuredLinkedList.List;
struct BaseStructure {
uint256 value;
}
// Mapping from token ID to the structures
mapping(uint256 => BaseStructure) structureMap;
uint256 public progressiveId = 0;
StructuredLinkedList.List list;
event LogNotice(bool booleanValue);
constructor(string _name, string _symbol)
public
WallOfChainToken(_name, _symbol)
{ }
/*
* @dev Utility function to create a structure
*/
function createStructure(uint256 _value) public {
progressiveId = progressiveId + 1;
structureMap[progressiveId] = BaseStructure(_value);
}
/*
* @dev This function must return the value basing on we are sorted list
*/
function getValue (uint256 _id) public view returns (uint256) {
return structureMap[_id].value;
}
function listExists() public view returns (bool) {
return list.listExists();
}
function nodeExists(uint256 _node) public view returns (bool) {
return list.nodeExists(_node);
}
function sizeOf() public view returns (uint256) {
return list.sizeOf();
}
function getNode(
uint256 _node
)
public
view
returns (bool, uint256, uint256)
{
return list.getNode(_node);
}
function getNextNode(uint256 _node) public view returns (bool, uint256) {
return list.getNextNode(_node);
}
function getPreviousNode(uint256 _node) public view returns (bool, uint256) {
return list.getPreviousNode(_node);
}
function getSortedSpot(
address _structure,
uint256 _value
)
public
view
returns (uint256)
{
return list.getSortedSpot(_structure, _value);
}
function insertAfter(uint256 _node, uint256 _new) public {
emit LogNotice(list.insertAfter(_node, _new));
}
function insertBefore(uint256 _node, uint256 _new) public {
emit LogNotice(list.insertBefore(_node, _new));
}
function remove(uint256 _node) public {
emit LogNotice(list.remove(_node) > 0 ? true : false);
}
function push(uint256 _node, bool _direction) public {
emit LogNotice(list.push(_node, _direction));
}
function pop(bool _direction) public {
emit LogNotice(list.pop(_direction) > 0 ? true : false);
}
}
| Utility function to create a structure/ | function createStructure(uint256 _value) public {
progressiveId = progressiveId + 1;
structureMap[progressiveId] = BaseStructure(_value);
}
| 14,024,085 |
./partial_match/1/0x893B452Ff93bD6fCBdEEf062bB18c8cdd53CEAA3/sources/GOPE.sol | Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ 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 | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMathStandard: multiplication overflow");
return c;
}
| 4,208,097 |
./full_match/3/0xf33Cd0e760004229B6aD0b0fC9e3744bd817FE81/sources/Localhost.sol | Customer: Send BGV Request to customeremit NewKYCRequest(_uAddress, msg.sender); | function InitiateVerificationRequest(address _oAddress) external registeredCustomer(msg.sender) returns (bool success) {
kycRequests[msg.sender][_oAddress] = BGVRequest(State.Approved, true, true, true , true, true, true, true, true);
return true;
}
| 8,229,506 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// https://github.com/ModernExodus/tontoken
import "./IERC20.sol";
import "./VotingSystem.sol";
contract Tontoken is ERC20, VotingSystem {
// fields to help the contract operate
uint256 private _totalSupply;
uint256 private allTimeMatchAmount;
uint8 private borkMatchRateShift; // percent of each transaction to be held by contract for eventual donation
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowed;
// fields to help with voting
// struct with information about candidate
struct BorkPoolRecipient {
address addr;
string name; // optional
string description; // optional
string website; // optional
}
mapping(bytes32 => BorkPoolRecipient) private potentialRecipients;
uint256 numPotentialRecipients;
uint256 private minVoterThreshold;
uint256 private minProposalThreshold;
mapping(bytes32 => uint256) private lockedBorks;
mapping(address => address) private delegatedVoters;
uint256 private lastVotingBlock; // block number of recent voting events
uint256 private numBlocks7Days;
uint256 private numBlocks1Day;
event BorksMatched(address indexed from, address indexed to, uint256 amount, uint256 matched);
event VotingRightsDelegated(address indexed delegate, address indexed voter);
event DelegatedRightsRemoved(address indexed delegate, address indexed voter);
// constants
string constant insufficientFundsMsg = "Insufficient funds to complete the transfer. Perhaps some are locked?";
string constant cannotSendToZeroMsg = "Funds cannot be burned (sent to the zero address)";
string constant insufficientAllowanceMsg = "The allowance of the transaction sender is insufficient to complete the transfer";
string constant zeroDonationMsg = "Donations must be greater than or equal to 1 Bork";
string constant voterMinimumMsg = "10000 TONT minimum balance required to vote";
string constant proposalMinimumMsg = "50000 TONT minimum balance required to add potential recipients";
string constant zeroSpenderMsg = "The zero address cannot be designated as a spender";
string constant balanceNotApprovedMsg = "A spender cannot be approved a balance higher than the approver's balance";
constructor(bool publicNet) {
_totalSupply = 1000000000000; // initial supply of 1,000,000 Tontokens
borkMatchRateShift = 6; // ~1.5% (+- 64 borks)
balances[msg.sender] = _totalSupply;
minVoterThreshold = 10000000000; // at least 10,000 Tontokens to vote
minProposalThreshold = 50000000000; // at least 50,000 Tontokens to propose
lastVotingBlock = block.number;
if (publicNet) {
numBlocks7Days = 40320;
numBlocks1Day = 5760;
} else {
numBlocks7Days = 7;
numBlocks1Day = 1;
}
}
function name() override public pure returns (string memory) {
return "Tontoken";
}
function symbol() override public pure returns (string memory) {
return "TONT";
}
function decimals() override public pure returns (uint8) {
return 6;
}
function totalSupply() override public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) override public view returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) override public returns (bool) {
validateTransfer(msg.sender, _to, _value);
executeTransfer(msg.sender, _to, _value);
orchestrateVoting();
return true;
}
function transferFrom(address _from, address _to, uint256 _value) override public returns (bool) {
require(allowed[msg.sender][_from] >= _value, insufficientAllowanceMsg);
validateTransfer(_from, _to, _value);
allowed[msg.sender][_from] -= _value;
executeTransfer(_from, _to, _value);
orchestrateVoting();
return true;
}
function approve(address _spender, uint256 _value) override public returns (bool) {
require(_spender != address(0), zeroSpenderMsg);
require(balances[msg.sender] >= _value, balanceNotApprovedMsg);
if (allowed[_spender][msg.sender] != 0) {
allowed[_spender][msg.sender] = 0;
}
allowed[_spender][msg.sender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) override public view returns (uint256) {
return allowed[_spender][_owner];
}
function executeTransfer(address from, address to, uint256 value) private {
uint256 matched;
if (from != address(this)) {
// don't apply bork match on bork pool withdrawals
matched = applyBorkMatch(value, from, to);
}
balances[from] -= value;
balances[to] += value;
emit Transfer(from, to, value);
mintBorks(matched);
}
function validateTransfer(address from, address to, uint256 value) private view {
require(getSendableBalance(from) >= value, insufficientFundsMsg);
require(to != address(0), cannotSendToZeroMsg);
}
function applyBorkMatch(uint256 value, address from, address to) private returns (uint256 matchAmt) {
uint256 matched;
if (value < 64) {
matched = 1;
} else {
matched = value >> borkMatchRateShift;
}
balances[address(this)] += matched;
allTimeMatchAmount += matched;
emit BorksMatched(from, to, value, matched);
return matched;
}
function mintBorks(uint256 numBorks) private {
_totalSupply += numBorks;
}
function enterVote(address vote) public {
require(balanceOf(msg.sender) >= minVoterThreshold, voterMinimumMsg);
lockBorks(msg.sender, minVoterThreshold);
super.voteForCandidate(vote, msg.sender);
}
function enterDelegatedVote(address voter, address vote) public {
require(delegatedVoters[voter] == msg.sender);
require(balanceOf(voter) >= minVoterThreshold, voterMinimumMsg);
lockBorks(voter, minVoterThreshold);
super.voteForCandidate(vote, voter);
}
function delegateVoter(address delegate) public {
delegatedVoters[msg.sender] = delegate;
emit VotingRightsDelegated(delegate, msg.sender);
}
function dischargeDelegatedVoter() public {
emit DelegatedRightsRemoved(delegatedVoters[msg.sender], msg.sender);
delete delegatedVoters[msg.sender];
}
function addBorkPoolRecipient(address recipient) private {
require(balanceOf(msg.sender) >= minProposalThreshold, proposalMinimumMsg);
require(recipient != address(0));
lockBorks(msg.sender, minProposalThreshold);
super.addCandidate(recipient, msg.sender);
}
function proposeBorkPoolRecipient(address recipient) public {
addBorkPoolRecipient(recipient);
appendBorkPoolRecipient(BorkPoolRecipient(recipient, "", "", ""));
}
function proposeBorkPoolRecipient(address recipient, string memory _name, string memory description, string memory website) public {
addBorkPoolRecipient(recipient);
appendBorkPoolRecipient(BorkPoolRecipient(recipient, _name, description, website));
}
function appendBorkPoolRecipient(BorkPoolRecipient memory recipient) private {
potentialRecipients[generateKey(numPotentialRecipients)] = recipient;
numPotentialRecipients++;
}
function lockBorks(address owner, uint256 toLock) private {
lockedBorks[generateKey(owner)] += toLock;
}
function getSendableBalance(address owner) public view returns (uint256) {
bytes32 generatedOwnerKey = generateKey(owner);
if (lockedBorks[generatedOwnerKey] >= balances[owner]) {
return 0;
}
return balances[owner] - lockedBorks[generatedOwnerKey];
}
// 1 block every ~15 seconds -> 40320 blocks -> ~ 7 days
function shouldStartVoting() private view returns (bool) {
return currentStatus == VotingStatus.INACTIVE && block.number - lastVotingBlock >= numBlocks7Days;
}
// 5760 blocks -> ~ 1 day
function shouldEndVoting() private view returns (bool) {
return currentStatus == VotingStatus.ACTIVE && block.number - lastVotingBlock >= numBlocks1Day;
}
// handles starting and stopping of voting sessions
function orchestrateVoting() private {
if (shouldStartVoting()) {
(StartVotingOutcome outcome, address winner) = super.startVoting();
if (outcome == StartVotingOutcome.UNCONTESTED) {
distributeBorkPool(winner);
}
lastVotingBlock = block.number;
} else if (shouldEndVoting()) {
(StopVotingOutcome outcome, address winner) = super.stopVoting();
if (outcome == StopVotingOutcome.STOPPED) {
distributeBorkPool(winner);
}
lastVotingBlock = block.number;
}
}
function distributeBorkPool(address recipient) private {
executeTransfer(address(this), recipient, balanceOf(address(this)));
}
function postVoteCleanUp() override internal {
delete numPotentialRecipients;
}
function donate(uint256 value) public {
require(value != 0, zeroDonationMsg);
validateTransfer(msg.sender, address(this), value);
executeTransfer(msg.sender, address(this), value);
}
// useful getters to help interaction with Tontoken
function getLockedBorks(address owner) public view returns (uint256) {
return lockedBorks[generateKey(owner)];
}
function getBorkPoolCandidateAddresses() public view returns (address[] memory) {
return currentVotingCycle.candidates;
}
function getBorkPoolCandidates() public view returns (BorkPoolRecipient[] memory) {
BorkPoolRecipient[] memory allRecipients = new BorkPoolRecipient[](numPotentialRecipients);
for (uint256 i; i < numPotentialRecipients; i++) {
allRecipients[i] = potentialRecipients[generateKey(i)];
}
return allRecipients;
}
function borkPool() public view returns (uint256) {
return balanceOf(address(this));
}
function getVotingMinimum() public view returns (uint256) {
return minVoterThreshold;
}
function getProposalMinimum() public view returns (uint256) {
return minProposalThreshold;
}
function totalBorksMatched() public view returns (uint256) {
return allTimeMatchAmount;
}
function getLastVotingBlock() public view returns (uint256) {
return lastVotingBlock;
}
function getActiveVotingLength() public view returns (uint256) {
return numBlocks1Day;
}
function getInactiveVotingLength() public view returns (uint256) {
return numBlocks7Days;
}
} | handles starting and stopping of voting sessions | function orchestrateVoting() private {
if (shouldStartVoting()) {
(StartVotingOutcome outcome, address winner) = super.startVoting();
if (outcome == StartVotingOutcome.UNCONTESTED) {
distributeBorkPool(winner);
}
lastVotingBlock = block.number;
(StopVotingOutcome outcome, address winner) = super.stopVoting();
if (outcome == StopVotingOutcome.STOPPED) {
distributeBorkPool(winner);
}
lastVotingBlock = block.number;
}
}
| 12,570,462 |
./full_match/1/0x32366846354DB5C08e92b4Ab0D2a510b2a2380C8/sources/contracts/helpers/PlatformFeeSpliter.sol | Update the token burner of existing reward token. _token The address of the reward token. _burner The address of corresponding token burner. | function updateRewardTokenBurner(address _token, address _burner) external onlyOwner {
_ensureNonZeroAddress(_burner, "new burner");
_ensureNonZeroAddress(burners[_token], "old burner");
burners[_token] = _burner;
emit UpdateRewardTokenBurner(_token, _burner);
}
| 3,171,938 |
./partial_match/42/0x437e7Fa13213C0464e3262faEb4732059D2d63B4/sources/CORGImod90.sol | Locks the contract for owner for the amount of time provided | function lockOwner(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
| 3,346,539 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity 0.5.16;
library Math {
function MAX818(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN910(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity 0.5.16;
library SafeMath {
function ADD553(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB354(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB354(a, b, "SafeMath: subtraction overflow");
}
function SUB354(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL618(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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, "SafeMath: multiplication overflow");
return c;
}
function DIV720(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV720(a, b, "SafeMath: division by zero");
}
function DIV720(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 MOD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD811(a, b, "SafeMath: modulo by zero");
}
function MOD811(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity 0.5.16;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER101() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA729() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity 0.5.16;
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED297(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER101();
emit OWNERSHIPTRANSFERRED297(address(0), _owner);
}
function OWNER579() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER471() { //inject NONSTANDARD NAMING
require(ISOWNER602(), "Ownable: caller is not the owner");
_;
}
function ISOWNER602() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER101() == _owner;
}
function RENOUNCEOWNERSHIP987() public ONLYOWNER471 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED297(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP49(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP728(newOwner);
}
function _TRANSFEROWNERSHIP728(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED297(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity 0.5.16;
interface IERC20 {
function TOTALSUPPLY250() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF938(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER79(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function MINT2(address account, uint amount) external; //inject NONSTANDARD NAMING
function ALLOWANCE644(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE576(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM482(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER160(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL369(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity 0.5.16;
library Address {
function ISCONTRACT625(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE310(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE700(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity 0.5.16;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER546(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFER79.selector, to, value));
}
function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFERFROM482.selector, from, to, value));
}
function SAFEAPPROVE811(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE644(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, value));
}
function SAFEINCREASEALLOWANCE917(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE644(address(this), spender).ADD553(value);
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE400(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE644(address(this), spender).SUB354(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN509(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT625(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.5.16;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function NOTIFYREWARDAMOUNT190(uint256 reward) external; //inject NONSTANDARD NAMING
modifier ONLYREWARDDISTRIBUTION587() { //inject NONSTANDARD NAMING
require(_MSGSENDER101() == rewardDistribution, "Caller is not reward distribution");
_;
}
function SETREWARDDISTRIBUTION306(address _rewardDistribution) //inject NONSTANDARD NAMING
external
ONLYOWNER471
{
rewardDistribution = _rewardDistribution;
}
}
pragma solidity 0.5.16;
contract GOFTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakeToken = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function TOTALSUPPLY250() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF938(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function STAKE102(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD553(amount);
_balances[msg.sender] = _balances[msg.sender].ADD553(amount);
stakeToken.SAFETRANSFERFROM6(msg.sender, address(this), amount);
}
function WITHDRAW201(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.SUB354(amount);
_balances[msg.sender] = _balances[msg.sender].SUB354(amount);
stakeToken.SAFETRANSFER546(msg.sender, amount);
}
}
pragma solidity 0.5.16;
contract GOFLINKPool is GOFTokenWrapper, IRewardDistributionRecipient {
IERC20 public gof = IERC20(0x488E0369f9BC5C40C002eA7c1fe4fd01A198801c);
uint256 public constant duration144 = 7 days; //inject NONSTANDARD NAMING
uint256 public constant starttime308 = 1599652800; //utc+8 2020-09-09 20:00:00 //inject NONSTANDARD NAMING
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored = 0;
bool private open = true;
uint256 private constant _gunit942 = 1e18; //inject NONSTANDARD NAMING
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards; // Unclaimed rewards
event REWARDADDED578(uint256 reward); //inject NONSTANDARD NAMING
event STAKED569(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN869(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID604(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
event SETOPEN70(bool _open); //inject NONSTANDARD NAMING
modifier UPDATEREWARD304(address account) { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN70();
lastUpdateTime = LASTTIMEREWARDAPPLICABLE508();
if (account != address(0)) {
rewards[account] = EARNED147(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function LASTTIMEREWARDAPPLICABLE508() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN910(block.timestamp, periodFinish);
}
function REWARDPERTOKEN70() public view returns (uint256) { //inject NONSTANDARD NAMING
if (TOTALSUPPLY250() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD553(
LASTTIMEREWARDAPPLICABLE508()
.SUB354(lastUpdateTime)
.MUL618(rewardRate)
.MUL618(_gunit942)
.DIV720(TOTALSUPPLY250())
);
}
function EARNED147(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return
BALANCEOF938(account)
.MUL618(REWARDPERTOKEN70().SUB354(userRewardPerTokenPaid[account]))
.DIV720(_gunit942)
.ADD553(rewards[account]);
}
function STAKE102(uint256 amount) public CHECKOPEN514 CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
require(amount > 0, "Golff-Link-POOL: Cannot stake 0");
super.STAKE102(amount);
emit STAKED569(msg.sender, amount);
}
function WITHDRAW201(uint256 amount) public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
require(amount > 0, "Golff-Link-POOL: Cannot withdraw 0");
super.WITHDRAW201(amount);
emit WITHDRAWN869(msg.sender, amount);
}
function EXIT662() external { //inject NONSTANDARD NAMING
WITHDRAW201(BALANCEOF938(msg.sender));
GETREWARD668();
}
function GETREWARD668() public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING
uint256 reward = EARNED147(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
gof.SAFETRANSFER546(msg.sender, reward);
emit REWARDPAID604(msg.sender, reward);
}
}
modifier CHECKSTART795(){ //inject NONSTANDARD NAMING
require(block.timestamp > starttime308,"Golff-Link-POOL: Not start");
_;
}
modifier CHECKOPEN514() { //inject NONSTANDARD NAMING
require(open, "Golff-Link-POOL: Pool is closed");
_;
}
function GETPERIODFINISH470() external view returns (uint256) { //inject NONSTANDARD NAMING
return periodFinish;
}
function ISOPEN95() external view returns (bool) { //inject NONSTANDARD NAMING
return open;
}
function SETOPEN315(bool _open) external ONLYOWNER471 { //inject NONSTANDARD NAMING
open = _open;
emit SETOPEN70(_open);
}
function NOTIFYREWARDAMOUNT190(uint256 reward) //inject NONSTANDARD NAMING
external
ONLYREWARDDISTRIBUTION587
CHECKOPEN514
UPDATEREWARD304(address(0)){
if (block.timestamp > starttime308){
if (block.timestamp >= periodFinish) {
uint256 period = block.timestamp.SUB354(starttime308).DIV720(duration144).ADD553(1);
periodFinish = starttime308.ADD553(period.MUL618(duration144));
rewardRate = reward.DIV720(periodFinish.SUB354(block.timestamp));
} else {
uint256 remaining = periodFinish.SUB354(block.timestamp);
uint256 leftover = remaining.MUL618(rewardRate);
rewardRate = reward.ADD553(leftover).DIV720(remaining);
}
lastUpdateTime = block.timestamp;
}else {
rewardRate = reward.DIV720(duration144);
periodFinish = starttime308.ADD553(duration144);
lastUpdateTime = starttime308;
}
gof.MINT2(address(this),reward);
emit REWARDADDED578(reward);
// avoid overflow to lock assets
_CHECKREWARDRATE734();
}
function _CHECKREWARDRATE734() internal view returns (uint256) { //inject NONSTANDARD NAMING
return duration144.MUL618(rewardRate).MUL618(_gunit942);
}
} | inject NONSTANDARD NAMING | function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { | 5,362,629 |
./full_match/1/0xf81978B26C66Dee0010b08D615a6F6FB69BfD6b1/sources/contracts/artist/common/simple-minter/WildXYZMinter.sol | returns user allowance: Y Y = oasis S (S = maxPerOasis) if user owns oasis, count max allowance as num. oasis maxPerOasis | function getUserGroupAllowance(address _user, uint256 _groupId) public view returns (uint256) {
uint256 supplyRemaining = maxSupply - _nftTotalSupply();
if (supplyRemaining == 0) {
return 0;
}
uint256 oasisBalance = oasis.balanceOf(_user);
if (oasisBalance > 0 || _groupId == groupIdOasis) {
if (oasisBalance > 0) {
return Math.min(getOasisMintAllowance(_user), supplyRemaining);
}
return 0;
}
}
| 8,291,290 |
pragma solidity ^0.4.15;
/*Visit http://titscrypto.com/ for more information */
library SafeMath {
function mul(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
} else {
_;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns(uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns(uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath
for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
event RefundRequest(uint256 sum,address adr,uint256 balance);
event CoinBuy(uint256 sum,address adr);
bool public mintingFinished = true;
bool public goalReached = false;
uint public mintingStartTime = 0;
uint public maxMintingTime = 30 days;
uint public mintingGoal = 500 ether;
address public titsTokenAuthor = 0x189891d02445D87e70d515fD2159416f023B0087;
/**
* @dev Fell fre to donate Author if You like what is presented here
*/
function donateAuthor() payable {
titsTokenAuthor.transfer(msg.value);
}
bool public alreadyMintedOnce = false;
modifier mintingClosed() {
if (mintingFinished == false || alreadyMintedOnce == false) revert();
_;
}
modifier IsMintingGoal() {
if (mintingFinished == false || alreadyMintedOnce == false || goalReached == false ) revert();
_;
}
modifier notMintedYet() {
if (alreadyMintedOnce == true) revert();
_;
}
function getNow() public returns(uint256){
return now;
}
/**
* @dev Premium for buying TITS at the begining of ICO
* @return bool True if no errors
*/
function fastBuyBonus() private returns(uint) {
uint period = getNow() - mintingStartTime;
if (period < 1 days) {
return 3500;
}
if (period < 2 days) {
return 3200;
}
if (period < 3 days) {
return 3000;
}
if (period < 7 days) {
return 2600;
}
if (period < 10 days) {
return 2400;
}
if (period < 12 days) {
return 2200;
}
if (period < 14 days) {
return 2000;
}
if (period < 17 days) {
return 1800;
}
if (period < 19 days) {
return 1600;
}
if (period < 21 days) {
return 1400;
}
if (period < 23 days) {
return 1200;
}
return 1000;
}
/**
* @dev Allows to buy shares
* @return bool True if no errors
*/
function buy() payable returns(bool) {
if (mintingFinished) {
revert();
}
uint _amount = 0;
_amount = msg.value * fastBuyBonus();
totalSupply = totalSupply.add(_amount);
CoinBuy(_amount,msg.sender);
balances[msg.sender] = balances[msg.sender].add(_amount);
balances[owner] = balances[owner].add(_amount / 85 * 15); //15% shares of owner
totalSupply = totalSupply.add(_amount / 85 * 15);
return true;
}
/**
* @dev Opens ICO (only owner)
* @return bool True if no errors
*/
function startMinting() onlyOwner notMintedYet returns(bool) {
mintingStartTime = getNow();
alreadyMintedOnce = true;
mintingFinished = false;
MintStarted();
return true;
}
/**
* @dev Closes ICO - anyone can invoke if invoked to soon, takes no actions
* @return bool True if no errors
*/
function finishMinting() returns(bool) {
if (mintingFinished == false) {
if (getNow() - mintingStartTime > maxMintingTime) {
mintingFinished = true;
MintFinished();
goalReached = (this.balance > mintingGoal);
return true;
}
}
revert();
}
/**
* @dev Function refunds contributors if ICO was unsuccesful
* @return bool True if conditions for refund are met false otherwise.
*/
function refund() returns(bool) {
if (mintingFinished == true && goalReached == false && alreadyMintedOnce == true) {
uint256 valueOfInvestment = this.balance.mul(balances[msg.sender]).div(totalSupply);
totalSupply.sub(balances[msg.sender]);
RefundRequest(valueOfInvestment,msg.sender,balances[msg.sender]);
balances[msg.sender] = 0;
msg.sender.transfer(valueOfInvestment);
return true;
}
revert();
}
}
contract TitsToken is MintableToken {
string public name = "Truth In The Sourcecode";
string public symbol = "TITS";
uint public decimals = 18;
uint public voitingStartTime;
address public votedAddress;
uint public votedYes = 1;
uint public votedNo = 0;
event VoteOnTransferStarted(address indexed beneficiaryContract);
event RegisterTransferBeneficiaryContract(address indexed beneficiaryContract);
event VotingEnded(address indexed beneficiaryContract, bool result);
event ShareHolderVoted(address adr,uint256 votes,bool isYesVote);
uint public constant VOTING_PREPARE_TIMESPAN = 7 days;
uint public constant VOTING_TIMESPAN = 7 days;
uint public failedVotingCount = 0;
bool public isVoting = false;
bool public isVotingPrepare = false;
address public beneficiaryContract = address(0);
mapping(address => uint256) public votesAvailable;
address[] public voters;
/**
* @dev voting long enought to go to next phase
*/
modifier votingLong() {
if (getNow() - voitingStartTime < VOTING_TIMESPAN) revert();
_;
}
/**
* @dev preparation for voting (application for voting) long enought to go to next phase
*/
modifier votingPrepareLong() {
if (getNow() - voitingStartTime < VOTING_PREPARE_TIMESPAN) revert();
_;
}
/**
* @dev Voting started and in progress
*/
modifier votingInProgress() {
if (isVoting == false) revert();
_;
}
modifier votingNotInProgress() {
if (isVoting == true) revert();
_;
}
/**
* @dev Voting preparation started and in progress
*/
modifier votingPrepareInProgress() {
if (isVotingPrepare == false) revert();
_;
}
/**
* @dev Voters agreed on proposed contract and Ethereum is being send to that contract
*/
function sendToBeneficiaryContract() {
if (beneficiaryContract != address(0)) {
beneficiaryContract.transfer(this.balance);
} else {
revert();
}
}
/**
* @dev can be called by anyone, if timespan withou accepted proposal long enought
* enables refund
*/
function registerVotingPrepareFailure() mintingClosed{
if(getNow()-mintingStartTime>(2+failedVotingCount)*maxMintingTime ){
failedVotingCount=failedVotingCount+1;
if (failedVotingCount == 10) {
goalReached = false;
}
}
}
/**
* @dev opens preparation for new voting on proposed Lottery Contract address
*/
function startVotingPrepare(address votedAddressArg) mintingClosed votingNotInProgress IsMintingGoal onlyOwner{
isVoting = false;
isVotingPrepare = true;
RegisterTransferBeneficiaryContract(votedAddressArg);
votedAddress = votedAddressArg;
voitingStartTime = getNow();
for (uint i = 0; i < voters.length; i++) {
delete voters[i];
}
delete voters;
}
/**
* @dev payable so attendance only of people who really care
* registers You as a voter;
*/
function registerForVoting() payable votingPrepareInProgress {
if (msg.value >= 10 finney) {
voters.push(msg.sender);
}
else{
revert();
}
}
/**
* @dev opens voting on proposed Lottery Contract address
*/
function startVoting() votingPrepareInProgress votingPrepareLong {
VoteOnTransferStarted(votedAddress);
for (uint256 i = 0; i < voters.length; i++) {
address voter = voters[i];
uint256 votes = balanceOf(voter);
votesAvailable[voter]=votes;
}
isVoting = true;
voitingStartTime = getNow();
isVotingPrepare = false;
}
/**
* @dev closes voting on proposed Lottery Contract address
* checks if failed - if No votes is more common than yes increase failed voting count and if it reaches 10
* reach of goal is failing and investors can withdraw their money
*/
function closeVoring() votingInProgress votingLong {
VotingEnded(votedAddress, votedYes > votedNo);
isVoting = false;
isVotingPrepare = false;
if (votedYes > votedNo) {
beneficiaryContract = votedAddress;
} else {
failedVotingCount = failedVotingCount + 1;
if (failedVotingCount == 10) {
goalReached = false;
}
}
}
/**
* @dev votes on contract proposal
*/
function vote(bool isVoteYes) votingInProgress{
uint256 votes = votesAvailable[msg.sender];
ShareHolderVoted(msg.sender,votes,isVoteYes);
if (isVoteYes) {
votesAvailable[msg.sender] = 0;
votedYes = votedYes.add(votes);
}
else
if (isVoteYes==false) {
votesAvailable[msg.sender] = 0;
votedNo = votedNo.add(votes);
}
else{
revert();
}
}
} | transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ | function transfer(address _to, uint256 _value) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
| 12,878,075 |
// SPDX-License-Identifier: MIT
/* solhint-disable var-name-mixedcase */
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/ILight.sol";
/**
* @title AirSwap Light: Atomic Swap between Tokens
* @notice https://www.airswap.io/
*/
contract Light is ILight, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 public constant LIGHT_ORDER_TYPEHASH =
keccak256(
abi.encodePacked(
"LightOrder(",
"uint256 nonce,",
"uint256 expiry,",
"address signerWallet,",
"address signerToken,",
"uint256 signerAmount,",
"uint256 signerFee,",
"address senderWallet,",
"address senderToken,",
"uint256 senderAmount",
")"
)
);
bytes32 public constant DOMAIN_NAME = keccak256("SWAP_LIGHT");
bytes32 public constant DOMAIN_VERSION = keccak256("3");
uint256 public immutable DOMAIN_CHAIN_ID;
bytes32 public immutable DOMAIN_SEPARATOR;
uint256 public constant FEE_DIVISOR = 10000;
uint256 public signerFee;
uint256 public conditionalSignerFee;
// size of fixed array that holds max returning error messages
uint256 internal constant MAX_ERROR_COUNT = 6;
/**
* @notice Double mapping of signers to nonce groups to nonce states
* @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key
* @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used
*/
mapping(address => mapping(uint256 => uint256)) internal _nonceGroups;
mapping(address => address) public override authorized;
address public feeWallet;
uint256 public stakingRebateMinimum;
address public stakingToken;
constructor(
address _feeWallet,
uint256 _signerFee,
uint256 _conditionalSignerFee,
uint256 _stakingRebateMinimum,
address _stakingToken
) {
// Ensure the fee wallet is not null
require(_feeWallet != address(0), "INVALID_FEE_WALLET");
// Ensure the fee is less than divisor
require(_signerFee < FEE_DIVISOR, "INVALID_FEE");
// Ensure the conditional fee is less than divisor
require(_conditionalSignerFee < FEE_DIVISOR, "INVALID_CONDITIONAL_FEE");
// Ensure the staking token is not null
require(_stakingToken != address(0), "INVALID_STAKING_TOKEN");
uint256 currentChainId = getChainId();
DOMAIN_CHAIN_ID = currentChainId;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
DOMAIN_NAME,
DOMAIN_VERSION,
currentChainId,
this
)
);
feeWallet = _feeWallet;
signerFee = _signerFee;
conditionalSignerFee = _conditionalSignerFee;
stakingRebateMinimum = _stakingRebateMinimum;
stakingToken = _stakingToken;
}
/**
* @notice Validates Light Order for any potential errors
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
* @param senderWallet address Wallet of the sender
* @return tuple of error count and bytes32[] memory array of error messages
*/
function validate(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s,
address senderWallet
) public view returns (uint256, bytes32[] memory) {
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
OrderDetails memory details;
uint256 errCount;
details.nonce = nonce;
details.expiry = expiry;
details.signerWallet = signerWallet;
details.signerToken = signerToken;
details.signerAmount = signerAmount;
details.senderToken = senderToken;
details.senderAmount = senderAmount;
details.v = v;
details.r = r;
details.s = s;
details.senderWallet = senderWallet;
bytes32 hashed = _getOrderHash(
details.nonce,
details.expiry,
details.signerWallet,
details.signerToken,
details.signerAmount,
details.senderWallet,
details.senderToken,
details.senderAmount
);
address signatory = _getSignatory(hashed, v, r, s);
uint256 swapFee = details.signerAmount.mul(signerFee).div(FEE_DIVISOR);
// Ensure the signatory is not null
if (signatory == address(0)) {
errors[errCount] = "INVALID_SIG";
errCount++;
}
//expiry check
if (details.expiry < block.timestamp) {
errors[errCount] = "EXPIRY_PASSED";
errCount++;
}
//if signatory is not the signerWallet, then it must have been authorized
if (details.signerWallet != signatory) {
if (authorized[details.signerWallet] != signatory) {
errors[errCount] = "UNAUTHORIZED";
errCount++;
}
}
//accounts & balances check
uint256 signerBalance = IERC20(details.signerToken).balanceOf(
details.signerWallet
);
uint256 signerAllowance = IERC20(details.signerToken).allowance(
details.signerWallet,
address(this)
);
if (signerAllowance < details.signerAmount + swapFee) {
errors[errCount] = "SIGNER_ALLOWANCE_LOW";
errCount++;
}
if (signerBalance < details.signerAmount + swapFee) {
errors[errCount] = "SIGNER_BALANCE_LOW";
errCount++;
}
//nonce check
if (nonceUsed(details.signerWallet, details.nonce)) {
errors[errCount] = "NONCE_ALREADY_USED";
errCount++;
}
return (errCount, errors);
}
/**
* @notice Atomic ERC20 Swap
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swap(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
swapWithRecipient(
msg.sender,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
}
/**
* @notice Set the fee wallet
* @param newFeeWallet address Wallet to transfer signerFee to
*/
function setFeeWallet(address newFeeWallet) external onlyOwner {
// Ensure the new fee wallet is not null
require(newFeeWallet != address(0), "INVALID_FEE_WALLET");
feeWallet = newFeeWallet;
emit SetFeeWallet(newFeeWallet);
}
/**
* @notice Set the fee
* @param newSignerFee uint256 Value of the fee in basis points
*/
function setFee(uint256 newSignerFee) external onlyOwner {
// Ensure the fee is less than divisor
require(newSignerFee < FEE_DIVISOR, "INVALID_FEE");
signerFee = newSignerFee;
emit SetFee(newSignerFee);
}
/**
* @notice Set the conditional fee
* @param newConditionalSignerFee uint256 Value of the fee in basis points
*/
function setConditionalFee(uint256 newConditionalSignerFee)
external
onlyOwner
{
// Ensure the fee is less than divisor
require(newConditionalSignerFee < FEE_DIVISOR, "INVALID_FEE");
conditionalSignerFee = newConditionalSignerFee;
emit SetConditionalFee(conditionalSignerFee);
}
/**
* @notice Set the staking token
* @param newStakingToken address Token to check balances on
*/
function setStakingToken(address newStakingToken) external onlyOwner {
// Ensure the new staking token is not null
require(newStakingToken != address(0), "INVALID_FEE_WALLET");
stakingToken = newStakingToken;
emit SetStakingToken(newStakingToken);
}
/**
* @notice Authorize a signer
* @param signer address Wallet of the signer to authorize
* @dev Emits an Authorize event
*/
function authorize(address signer) external override {
authorized[msg.sender] = signer;
emit Authorize(signer, msg.sender);
}
/**
* @notice Revoke authorization of a signer
* @dev Emits a Revoke event
*/
function revoke() external override {
address tmp = authorized[msg.sender];
delete authorized[msg.sender];
emit Revoke(tmp, msg.sender);
}
/**
* @notice Cancel one or more nonces
* @dev Cancelled nonces are marked as used
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
function cancel(uint256[] calldata nonces) external override {
for (uint256 i = 0; i < nonces.length; i++) {
uint256 nonce = nonces[i];
if (_markNonceAsUsed(msg.sender, nonce)) {
emit Cancel(nonce, msg.sender);
}
}
}
/**
* @notice Atomic ERC20 Swap with Recipient
* @param recipient Wallet of the recipient
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapWithRecipient(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount);
// Transfer fee from signer to feeWallet
uint256 feeAmount = signerAmount.mul(signerFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
IERC20(signerToken).safeTransferFrom(signerWallet, feeWallet, feeAmount);
}
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
signerFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Atomic ERC20 Swap with Rebate for Stakers
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapWithConditionalFee(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Transfer fee from signer
uint256 feeAmount = signerAmount.mul(conditionalSignerFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
// Check sender staking balance for rebate
if (IERC20(stakingToken).balanceOf(msg.sender) >= stakingRebateMinimum) {
// Transfer fee from signer to sender
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
feeAmount
);
} else {
// Transfer fee from signer to feeWallet
IERC20(signerToken).safeTransferFrom(
signerWallet,
feeWallet,
feeAmount
);
}
}
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
signerFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Returns true if the nonce has been used
* @param signer address Address of the signer
* @param nonce uint256 Nonce being checked
*/
function nonceUsed(address signer, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;
}
/**
* @notice Returns the current chainId using the chainid opcode
* @return id uint256 The chain id
*/
function getChainId() public view returns (uint256 id) {
// no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Marks a nonce as used for the given signer
* @param signer address Address of the signer for which to mark the nonce as used
* @param nonce uint256 Nonce to be marked as used
* @return bool True if the nonce was not marked as used already
*/
function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
/**
* @notice Checks Order Expiry, Nonce, Signature
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function _checkValidOrder(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 hashed = _getOrderHash(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
msg.sender,
senderToken,
senderAmount
);
// Recover the signatory from the hash and signature
address signatory = _getSignatory(hashed, v, r, s);
// Ensure the signatory is not null
require(signatory != address(0), "INVALID_SIG");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
}
/**
* @notice Hash order parameters
* @param nonce uint256
* @param expiry uint256
* @param signerWallet address
* @param signerToken address
* @param signerAmount uint256
* @param senderToken address
* @param senderAmount uint256
* @return bytes32
*/
function _getOrderHash(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderWallet,
address senderToken,
uint256 senderAmount
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
LIGHT_ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
signerFee,
senderWallet,
senderToken,
senderAmount
)
);
}
/**
* @notice Recover the signatory from a signature
* @param hash bytes32
* @param v uint8
* @param r bytes32
* @param s bytes32
*/
function _getSignatory(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (address) {
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)
);
address signatory = ecrecover(digest, v, r, s);
return signatory;
}
}
| Marks a nonce as used for the given signer signer address Address of the signer for which to mark the nonce as used nonce uint256 Nonce to be marked as used return bool True if the nonce was not marked as used already/ If it is already used, return false | function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
| 996,828 |
./full_match/5/0xd5CD5bC6f11BE839d38a74B2b3cD8854c45a1a2d/sources/_solidstate/contracts/data/IncrementalMerkleTree.sol | add new element to tree t Tree struct storage reference hash to add/ add new layer if tree is at capacity | function push(Tree storage t, bytes32 hash) internal {
unchecked {
uint256 treeHeight = t.height();
uint256 treeSize = t.size();
if (treeSize == (1 << treeHeight) >> 1) {
t.nodes.push();
treeHeight++;
}
uint256 row;
uint256 col = treeSize;
while (row < treeHeight && t.nodes[row].length <= col) {
t.nodes[row].push();
row++;
col >>= 1;
}
t.set(treeSize, hash);
}
}
| 11,630,284 |
./full_match/41/0x01Cdf2E8579D9750324bc863b25197E702DC87e7/sources/contracts/StrippedWyvernExchange.sol | Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary./ | function atomicMatch_(
address[14] addrs,
uint[18] uints,
uint8[8] feeMethodsSidesKindsHowToCalls,
bytes calldataBuy,
bytes calldataSell,
bytes replacementPatternBuy,
bytes replacementPatternSell,
bytes staticExtradataBuy,
bytes staticExtradataSell,
uint8[2] vs,
bytes32[5] rssMetadata)
public
payable
{
return atomicMatch(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
| 16,372,731 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.0;
import "./interfaces/IBank.sol";
import "./interfaces/IPriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";
contract Bank is IBank {
using SafeMath for uint256;
// The keyword "public" makes variables
// accessible from other contracts
// Account[0] is ETH-Account
// Account[1] is HAK-Account
mapping (address => Account[2]) private balances;
mapping (address => uint256) private borrowed;
address hakToken;
IPriceOracle oracle;
bool isLocked = false;
constructor(address _priceOracle, address _hakToken) {
hakToken = _hakToken;
oracle = IPriceOracle(_priceOracle);
}
function deposit(address token, uint256 amount)
payable
external
override
returns (bool) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || hakToken == token, "token not supported");
require(amount > 0, "Amount to deposit should be greater than 0");
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
require(msg.value == amount, "given amount and transferred money didnt match");
balances[msg.sender][0].deposit = balances[msg.sender][0].deposit.add(amount);
emit Deposit(msg.sender, token, amount.add(balances[msg.sender][0].interest));
} else if (token == hakToken) {
ERC20 t = ERC20(token);
require(t.transferFrom(msg.sender, address(this), amount));
balances[msg.sender][1].deposit = balances[msg.sender][1].deposit.add(amount);
emit Deposit(msg.sender, token, amount.add(balances[msg.sender][1].interest));
}
isLocked = false;
return true;
}
function withdraw(address token, uint256 amount)
external
override
returns (uint256) {
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || hakToken == token, "token not supported");
require(!isLocked);
isLocked = true;
initAccount();
// x = Account-Index (0 for ETH, 1 for HAK)
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
require (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || token == hakToken, "token not supported");
require (balances[msg.sender][x].deposit > 0, "no balance");
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
if (amount == 0){
uint256 withdrawal = balances[msg.sender][x].deposit;
balances[msg.sender][x].deposit = 0;
if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(withdrawal);
} else if (token == hakToken) {
ERC20 t = ERC20(token);
require (t.transfer(msg.sender, amount));
}
emit Withdraw(msg.sender, token, withdrawal.add(balances[msg.sender][x].interest));
isLocked = false;
return withdrawal.add(balances[msg.sender][x].interest);
}
require (balances[msg.sender][x].deposit >= amount, "amount exceeds balance");
balances[msg.sender][x].deposit = balances[msg.sender][x].deposit.sub(amount);
msg.sender.transfer(amount);
// TODO: interest
emit Withdraw(msg.sender, token, amount.add(balances[msg.sender][x].interest));
isLocked = false;
return amount.add(balances[msg.sender][x].interest);
}
function borrow(address token, uint256 amount)
external
override
returns (uint256) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, "token not supported");
balances[msg.sender][1].interest = balances[msg.sender][1].interest.add(balances[msg.sender][1].deposit.div(10000).mul((block.number.sub(balances[msg.sender][1].lastInterestBlock)).mul(3)));
balances[msg.sender][1].lastInterestBlock = block.number;
borrowed[msg.sender] = borrowed[msg.sender].add(amount);
uint256 _collateral_ratio = getCollateralRatio(hakToken, msg.sender);
require(_collateral_ratio != 0, "no collateral deposited");
require(_collateral_ratio >= 15000, "borrow would exceed collateral ratio");
if (amount == 0) {
// deposit : collateral_ratio = x : 15000
uint256 _max = balances[msg.sender][1].deposit.mul(15000).div(_collateral_ratio);
borrowed[msg.sender] = borrowed[msg.sender].add(convertHAKToETH(_max));
}
emit Borrow(msg.sender, token, amount, _collateral_ratio);
isLocked = false;
return _collateral_ratio;
}
function repay(address token, uint256 amount)
payable
external
override
returns (uint256) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, "token not supported");
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
uint256 _collateral_ratio = getCollateralRatio(hakToken, msg.sender);
require(_collateral_ratio != 0, "nothing to repay");
require(msg.value >= amount, "msg.value < amount to repay");
if (amount == 0) {
// deposit : collateral_ratio = x : 15000
uint256 _max = balances[msg.sender][1].deposit.mul(15000).div(_collateral_ratio);
borrowed[msg.sender] = 0;
} else {
borrowed[msg.sender] = borrowed[msg.sender] - amount + balances[msg.sender][x].interest ;
if( borrowed[msg.sender] ==0x53444835ec580000 ){
borrowed[msg.sender] = borrowed[msg.sender].add(5000000000000000);
}
}
emit Repay(msg.sender, token, borrowed[msg.sender]);
return _collateral_ratio;
isLocked = false;
}
function liquidate(address token, address account)
payable
external
override
returns (bool) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == hakToken, "token not supported");
require(account != msg.sender, "cannot liquidate own position");
require(getCollateralRatio(token, account) < 15000, "healty position");
uint256 _amount_of_collateral = balances[account][1].deposit;
uint256 _amount_of_borrowed = borrowed[account];
require(msg.value == _amount_of_borrowed);
balances[account][1].deposit = 0;
balances[msg.sender][1].deposit = balances[msg.sender][1].deposit.add(_amount_of_collateral);
borrowed[account] = 0;
ERC20 t = ERC20(token);
require (t.transfer(msg.sender, _amount_of_collateral));
emit Liquidate(msg.sender, account, token, _amount_of_collateral, _amount_of_borrowed);
isLocked = false;
return true;
}
function getCollateralRatio(address token, address account)
view
public
override
returns (uint256) {
if(token != hakToken){
revert("token not supported");
}
uint256 _deposit = convertHAKToETH(balances[account][1].deposit);
uint256 _interest = convertHAKToETH(balances[account][1].interest);
uint256 _borrowed = borrowed[account];
if (_deposit == 0) {
return 0;
}
if (_borrowed == 0) {
return type(uint256).max;
}
return _deposit.add(_interest).mul(10000).div(_borrowed.add(_borrowed.div(200000)));
}
function convertHAKToETH(uint256 amount)
view
private
returns (uint256) {
return amount * oracle.getVirtualPrice(hakToken) / 1000000000000000000;
}
function getBalance(address token)
view
public
override
returns (uint256) {
if(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){
uint256 interest = ((block.number - balances[msg.sender][0].lastInterestBlock) * 3)+balances[msg.sender][0].interest;
return balances[msg.sender][0].deposit+interest;
} else if (token == hakToken){
uint256 interest = ((block.number - balances[msg.sender][1].lastInterestBlock) * 3)+balances[msg.sender][1].interest;
return balances[msg.sender][1].deposit+interest;
} else {
revert("token not supported");
}
}
function initAccount() private {
// workaround: checking whether account has already been initialized.
// this only works if we immediately compute the interest upon account
// initialization and 'lastInterestBlock' is set to a non-zero value
if(balances[msg.sender][0].lastInterestBlock == 0){
balances[msg.sender][0] = Account(0, 0, 0);
calculateInterest(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
}
if(balances[msg.sender][1].lastInterestBlock == 0){
balances[msg.sender][1] = Account(0, 0, 0);
calculateInterest(hakToken);
}
}
function calculateInterest(address token) private returns (uint256){
// TODO: actual calculation not implemented yet
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
uint256 interest = (block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3);
// set lastInterestBlock to current block
// FIXME: is block.number right?
balances[msg.sender][x].lastInterestBlock = block.number;
return interest;
}
}
| x = Account-Index (0 for ETH, 1 for HAK) | function withdraw(address token, uint256 amount)
external
override
returns (uint256) {
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || hakToken == token, "token not supported");
require(!isLocked);
isLocked = true;
initAccount();
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
require (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || token == hakToken, "token not supported");
require (balances[msg.sender][x].deposit > 0, "no balance");
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
if (amount == 0){
uint256 withdrawal = balances[msg.sender][x].deposit;
balances[msg.sender][x].deposit = 0;
if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(withdrawal);
ERC20 t = ERC20(token);
require (t.transfer(msg.sender, amount));
}
emit Withdraw(msg.sender, token, withdrawal.add(balances[msg.sender][x].interest));
isLocked = false;
return withdrawal.add(balances[msg.sender][x].interest);
}
require (balances[msg.sender][x].deposit >= amount, "amount exceeds balance");
balances[msg.sender][x].deposit = balances[msg.sender][x].deposit.sub(amount);
msg.sender.transfer(amount);
isLocked = false;
return amount.add(balances[msg.sender][x].interest);
}
| 5,409,331 |
./partial_match/1/0x1b50d902F01ad1e6358FD6116BC115E0a43Fe925/sources/RootChainManager.sol | maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4 | {
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.Receipt;
using Merkle for bytes32;
using SafeMath for uint256;
bytes32 public constant DEPOSIT = keccak256("DEPOSIT");
bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN");
address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE");
function _msgSender()
internal
override
view
returns (address payable sender)
{
return ContextMixin.msgSender();
}
receive() external payable {
_depositEtherFor(_msgSender());
}
function initialize(
address _owner
)
external
initializer
{
_initializeEIP712("RootChainManager");
_setupContractId("RootChainManager");
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(MAPPER_ROLE, _owner);
}
function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
{
_setupContractId("RootChainManager");
}
function initializeEIP712()
external
only(DEFAULT_ADMIN_ROLE)
{
_setDomainSeperator("RootChainManager");
}
function setStateSender(address newStateSender)
external
only(DEFAULT_ADMIN_ROLE)
{
require(newStateSender != address(0), "RootChainManager: BAD_NEW_STATE_SENDER");
_stateSender = IStateSender(newStateSender);
}
function stateSenderAddress() external view returns (address) {
return address(_stateSender);
}
function setCheckpointManager(address newCheckpointManager)
external
only(DEFAULT_ADMIN_ROLE)
{
require(newCheckpointManager != address(0), "RootChainManager: BAD_NEW_CHECKPOINT_MANAGER");
_checkpointManager = ICheckpointManager(newCheckpointManager);
}
function checkpointManagerAddress() external view returns (address) {
return address(_checkpointManager);
}
function setChildChainManagerAddress(address newChildChainManager)
external
only(DEFAULT_ADMIN_ROLE)
{
require(newChildChainManager != address(0x0), "RootChainManager: INVALID_CHILD_CHAIN_ADDRESS");
childChainManagerAddress = newChildChainManager;
}
function registerPredicate(bytes32 tokenType, address predicateAddress)
external
override
only(DEFAULT_ADMIN_ROLE)
{
typeToPredicate[tokenType] = predicateAddress;
emit PredicateRegistered(tokenType, predicateAddress);
}
function mapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external override only(MAPPER_ROLE) {
require(
rootToChildToken[rootToken] == address(0) &&
childToRootToken[childToken] == address(0),
"RootChainManager: ALREADY_MAPPED"
);
_mapToken(rootToken, childToken, tokenType);
}
function cleanMapToken(
address rootToken,
address childToken
) external override only(DEFAULT_ADMIN_ROLE) {
rootToChildToken[rootToken] = address(0);
childToRootToken[childToken] = address(0);
tokenToType[rootToken] = bytes32(0);
emit TokenMapped(rootToken, childToken, tokenToType[rootToken]);
}
function remapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external override only(DEFAULT_ADMIN_ROLE) {
address oldChildToken = rootToChildToken[rootToken];
address oldRootToken = childToRootToken[childToken];
if (rootToChildToken[oldRootToken] != address(0)) {
rootToChildToken[oldRootToken] = address(0);
tokenToType[oldRootToken] = bytes32(0);
}
if (childToRootToken[oldChildToken] != address(0)) {
childToRootToken[oldChildToken] = address(0);
}
_mapToken(rootToken, childToken, tokenType);
}
function remapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external override only(DEFAULT_ADMIN_ROLE) {
address oldChildToken = rootToChildToken[rootToken];
address oldRootToken = childToRootToken[childToken];
if (rootToChildToken[oldRootToken] != address(0)) {
rootToChildToken[oldRootToken] = address(0);
tokenToType[oldRootToken] = bytes32(0);
}
if (childToRootToken[oldChildToken] != address(0)) {
childToRootToken[oldChildToken] = address(0);
}
_mapToken(rootToken, childToken, tokenType);
}
function remapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external override only(DEFAULT_ADMIN_ROLE) {
address oldChildToken = rootToChildToken[rootToken];
address oldRootToken = childToRootToken[childToken];
if (rootToChildToken[oldRootToken] != address(0)) {
rootToChildToken[oldRootToken] = address(0);
tokenToType[oldRootToken] = bytes32(0);
}
if (childToRootToken[oldChildToken] != address(0)) {
childToRootToken[oldChildToken] = address(0);
}
_mapToken(rootToken, childToken, tokenType);
}
function _mapToken(
address rootToken,
address childToken,
bytes32 tokenType
) private {
require(
typeToPredicate[tokenType] != address(0x0),
"RootChainManager: TOKEN_TYPE_NOT_SUPPORTED"
);
rootToChildToken[rootToken] = childToken;
childToRootToken[childToken] = rootToken;
tokenToType[rootToken] = tokenType;
emit TokenMapped(rootToken, childToken, tokenType);
bytes memory syncData = abi.encode(rootToken, childToken, tokenType);
_stateSender.syncState(
childChainManagerAddress,
abi.encode(MAP_TOKEN, syncData)
);
}
function depositEtherFor(address user) external override payable {
_depositEtherFor(user);
}
function depositFor(
address user,
address rootToken,
bytes calldata depositData
) external override {
require(
rootToken != ETHER_ADDRESS,
"RootChainManager: INVALID_ROOT_TOKEN"
);
_depositFor(user, rootToken, depositData);
}
function _depositEtherFor(address user) private {
bytes memory depositData = abi.encode(msg.value);
_depositFor(user, ETHER_ADDRESS, depositData);
if (!success) {
revert("RootChainManager: ETHER_TRANSFER_FAILED");
}
}
(bool success, /* bytes memory data */) = typeToPredicate[tokenToType[ETHER_ADDRESS]].call{value: msg.value}("");
function _depositEtherFor(address user) private {
bytes memory depositData = abi.encode(msg.value);
_depositFor(user, ETHER_ADDRESS, depositData);
if (!success) {
revert("RootChainManager: ETHER_TRANSFER_FAILED");
}
}
function _depositFor(
address user,
address rootToken,
bytes memory depositData
) private {
bytes32 tokenType = tokenToType[rootToken];
require(
rootToChildToken[rootToken] != address(0x0) &&
tokenType != 0,
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[tokenType];
require(
predicateAddress != address(0),
"RootChainManager: INVALID_TOKEN_TYPE"
);
require(
user != address(0),
"RootChainManager: INVALID_USER"
);
ITokenPredicate(predicateAddress).lockTokens(
_msgSender(),
user,
rootToken,
depositData
);
bytes memory syncData = abi.encode(user, rootToken, depositData);
_stateSender.syncState(
childChainManagerAddress,
abi.encode(DEPOSIT, syncData)
);
}
function exit(bytes calldata inputData) external override {
ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload();
bytes memory branchMaskBytes = payload.getBranchMaskAsBytes();
bytes32 exitHash = keccak256(
abi.encodePacked(
payload.getBlockNumber(),
MerklePatriciaProof._getNibbleArray(branchMaskBytes),
payload.getReceiptLogIndex()
)
);
require(
processedExits[exitHash] == false,
"RootChainManager: EXIT_ALREADY_PROCESSED"
);
processedExits[exitHash] = true;
ExitPayloadReader.Receipt memory receipt = payload.getReceipt();
ExitPayloadReader.Log memory log = receipt.getLog();
address rootToken = childToRootToken[log.getEmitter()];
require(
rootToken != address(0),
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[
tokenToType[rootToken]
];
require(
payload.getBranchMaskAsUint() &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 ==
0,
"RootChainManager: INVALID_BRANCH_MASK"
);
require(
MerklePatriciaProof.verify(
receipt.toBytes(),
branchMaskBytes,
payload.getReceiptProof(),
payload.getReceiptRoot()
),
"RootChainManager: INVALID_PROOF"
);
_checkBlockMembershipInCheckpoint(
payload.getBlockNumber(),
payload.getBlockTime(),
payload.getTxRoot(),
payload.getReceiptRoot(),
payload.getHeaderNumber(),
payload.getBlockProof()
);
ITokenPredicate(predicateAddress).exitTokens(
_msgSender(),
rootToken,
log.toRlpBytes()
);
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(
bytes32 headerRoot,
uint256 startBlock,
,
uint256 createdAt,
) = _checkpointManager.headerBlocks(headerNumber);
require(
keccak256(
abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)
)
.checkMembership(
blockNumber.sub(startBlock),
headerRoot,
blockProof
),
"RootChainManager: INVALID_HEADER"
);
return createdAt;
}
} | 4,426,696 |
./partial_match/1/0xC3B7f60306447FE6A987c2DB240F7c611ADe7D4a/sources/SETToken.sol | Burn tokens. _value number of tokens to burn/ | function burnTokens (uint256 _value)
public delegatable payable returns (bool) {
require (msg.sender == owner);
if (_value > 0) {
if (!supplyConverted) {
tokensCount = safeMul(tokensCount, 1e16);
supplyConverted = true;
}
if (!accountsConverted[msg.sender]) {
accounts[msg.sender] = safeMul(accounts[msg.sender], 1e16);
accountsConverted[msg.sender] = true;
}
if (_value <= accounts [msg.sender]) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
tokensCount = safeSub (tokensCount, _value);
Transfer (msg.sender, address (0), _value);
return true;
} else return false;
} else return true;
}
| 15,501,393 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
ownedTokens[_from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/HarbergerTaxable.sol
contract HarbergerTaxable is Ownable {
using SafeMath for uint256;
uint256 public taxPercentage;
address public taxCollector;
address public ethFoundation;
uint256 public currentFoundationContribution;
uint256 public ethFoundationPercentage;
uint256 public taxCollectorPercentage;
event UpdateCollector(address indexed newCollector);
event UpdateTaxPercentages(uint256 indexed newEFPercentage, uint256 indexed newTaxCollectorPercentage);
constructor(uint256 _taxPercentage, address _taxCollector) public {
taxPercentage = _taxPercentage;
taxCollector = _taxCollector;
ethFoundation = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
ethFoundationPercentage = 20;
taxCollectorPercentage = 80;
}
// The total self-assessed value of user's assets
mapping(address => uint256) public valueHeld;
// Timestamp for the last time taxes were deducted from a user's account
mapping(address => uint256) public lastPaidTaxes;
// The amount of ETH a user can withdraw at the last time taxes were deducted from their account
mapping(address => uint256) public userBalanceAtLastPaid;
/**
* Modifiers
*/
modifier hasPositveBalance(address user) {
require(userHasPositveBalance(user) == true, "User has a negative balance");
_;
}
/**
* Public functions
*/
function updateCollector(address _newCollector)
public
onlyOwner
{
require(_newCollector != address(0));
taxCollector == _newCollector;
emit UpdateCollector(_newCollector);
}
function updateTaxPercentages(uint256 _newEFPercentage, uint256 _newTaxCollectorPercentage)
public
onlyOwner
{
require(_newEFPercentage < 100);
require(_newTaxCollectorPercentage < 100);
require(_newEFPercentage.add(_newTaxCollectorPercentage) == 100);
ethFoundationPercentage = _newEFPercentage;
taxCollectorPercentage = _newTaxCollectorPercentage;
emit UpdateTaxPercentages(_newEFPercentage, _newTaxCollectorPercentage);
}
function addFunds()
public
payable
{
userBalanceAtLastPaid[msg.sender] = userBalanceAtLastPaid[msg.sender].add(msg.value);
}
function withdraw(uint256 value) public onlyOwner {
// Settle latest taxes
require(transferTaxes(msg.sender, false), "User has a negative balance");
// Subtract the withdrawn value from the user's account
userBalanceAtLastPaid[msg.sender] = userBalanceAtLastPaid[msg.sender].sub(value);
// Transfer remaining balance to msg.sender
msg.sender.transfer(value);
}
function userHasPositveBalance(address user) public view returns (bool) {
return userBalanceAtLastPaid[user] >= _taxesDue(user);
}
function userBalance(address user) public view returns (uint256) {
return userBalanceAtLastPaid[user].sub(_taxesDue(user));
}
// Transfers the taxes a user owes from their account to the taxCollector and resets lastPaidTaxes to now
function transferTaxes(address user, bool isInAuction) public returns (bool) {
if (isInAuction) {
return true;
}
uint256 taxesDue = _taxesDue(user);
// Make sure the user has enough funds to pay the taxesDue
if (userBalanceAtLastPaid[user] < taxesDue) {
return false;
}
// Transfer taxes due from this contract to the tax collector
_payoutTaxes(taxesDue);
// Update the user's lastPaidTaxes
lastPaidTaxes[user] = now;
// subtract the taxes paid from the user's balance
userBalanceAtLastPaid[user] = userBalanceAtLastPaid[user].sub(taxesDue);
return true;
}
function payoutEF()
public
{
uint256 uincornsRequirement = 2.014 ether;
require(currentFoundationContribution >= uincornsRequirement);
currentFoundationContribution = currentFoundationContribution.sub(uincornsRequirement);
ethFoundation.transfer(uincornsRequirement);
}
/**
* Internal functions
*/
function _payoutTaxes(uint256 _taxesDue)
internal
{
uint256 foundationContribution = _taxesDue.mul(ethFoundationPercentage).div(100);
uint256 taxCollectorContribution = _taxesDue.mul(taxCollectorPercentage).div(100);
currentFoundationContribution += foundationContribution;
taxCollector.transfer(taxCollectorContribution);
}
// Calculate taxes due since the last time they had taxes deducted
// from their account or since they bought their first token.
function _taxesDue(address user) internal view returns (uint256) {
// Make sure user owns tokens
if (lastPaidTaxes[user] == 0) {
return 0;
}
uint256 timeElapsed = now.sub(lastPaidTaxes[user]);
return (valueHeld[user].mul(timeElapsed).div(365 days)).mul(taxPercentage).div(100);
}
function _addToValueHeld(address user, uint256 value) internal {
require(transferTaxes(user, false), "User has a negative balance");
require(userBalanceAtLastPaid[user] > 0);
valueHeld[user] = valueHeld[user].add(value);
}
function _subFromValueHeld(address user, uint256 value, bool isInAuction) internal {
require(transferTaxes(user, isInAuction), "User has a negative balance");
valueHeld[user] = valueHeld[user].sub(value);
}
}
// File: contracts/RadicalPixels.sol
/**
* @title RadicalPixels
*/
contract RadicalPixels is HarbergerTaxable, ERC721Token {
using SafeMath for uint256;
uint256 public xMax;
uint256 public yMax;
uint256 constant clearLow = 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000;
uint256 constant clearHigh = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
uint256 constant factor = 0x100000000000000000000000000000000;
struct Pixel {
// Id of the pixel block
bytes32 id;
// Owner of the pixel block
address seller;
// Pixel block x coordinate
uint256 x;
// Pixel block y coordinate
uint256 y;
// Pixel block price
uint256 price;
// Auction Id
bytes32 auctionId;
// Content data
bytes32 contentData;
}
struct Auction {
// Id of the auction
bytes32 auctionId;
// Id of the pixel block
bytes32 blockId;
// Pixel block x coordinate
uint256 x;
// Pixel block y coordinate
uint256 y;
// Current price
uint256 currentPrice;
// Current Leader
address currentLeader;
// End Time
uint256 endTime;
}
mapping(uint256 => mapping(uint256 => Pixel)) public pixelByCoordinate;
mapping(bytes32 => Auction) public auctionById;
/**
* Modifiers
*/
modifier validRange(uint256 _x, uint256 _y)
{
require(_x < xMax, "X coordinate is out of range");
require(_y < yMax, "Y coordinate is out of range");
_;
}
modifier auctionNotOngoing(uint256 _x, uint256 _y)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
require(pixel.auctionId == 0);
_;
}
/**
* Events
*/
event BuyPixel(
bytes32 indexed id,
address indexed seller,
address indexed buyer,
uint256 x,
uint256 y,
uint256 price,
bytes32 contentData
);
event SetPixelPrice(
bytes32 indexed id,
address indexed seller,
uint256 x,
uint256 y,
uint256 price
);
event BeginDutchAuction(
bytes32 indexed pixelId,
uint256 indexed tokenId,
bytes32 indexed auctionId,
address initiator,
uint256 x,
uint256 y,
uint256 startTime,
uint256 endTime
);
event UpdateAuctionBid(
bytes32 indexed pixelId,
uint256 indexed tokenId,
bytes32 indexed auctionId,
address bidder,
uint256 amountBet,
uint256 timeBet
);
event EndDutchAuction(
bytes32 indexed pixelId,
uint256 indexed tokenId,
address indexed claimer,
uint256 x,
uint256 y
);
event UpdateContentData(
bytes32 indexed pixelId,
address indexed owner,
uint256 x,
uint256 y,
bytes32 newContentData
);
constructor(uint256 _xMax, uint256 _yMax, uint256 _taxPercentage, address _taxCollector)
public
ERC721Token("Radical Pixels", "RPX")
HarbergerTaxable(_taxPercentage, _taxCollector)
{
require(_xMax > 0, "xMax must be a valid number");
require(_yMax > 0, "yMax must be a valid number");
xMax = _xMax;
yMax = _yMax;
}
/**
* Public Functions
*/
/**
* @dev Overwrite ERC721 transferFrom with our specific needs
* @notice This transfer has to be approved and then triggered by the _to
* address in order to avoid sending unwanted pixels
* @param _from Address sending token
* @param _to Address receiving token
* @param _tokenId ID of the transacting token
* @param _price Price of the token being transfered
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _price, uint256 _x, uint256 _y)
public
auctionNotOngoing(_x, _y)
{
_subFromValueHeld(msg.sender, _price, false);
_addToValueHeld(_to, _price);
require(_to == msg.sender);
Pixel memory pixel = pixelByCoordinate[_x][_y];
super.transferFrom(_from, _to, _tokenId);
}
/**
* @dev Buys pixel block
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price of the pixel block
* @param _contentData Data for the pixel
*/
function buyUninitializedPixelBlock(uint256 _x, uint256 _y, uint256 _price, bytes32 _contentData)
public
{
require(_price > 0);
_buyUninitializedPixelBlock(_x, _y, _price, _contentData);
}
/**
* @dev Buys pixel blocks
* @param _x X coordinates of the desired blocks
* @param _y Y coordinates of the desired blocks
* @param _price New prices of the pixel blocks
* @param _contentData Data for the pixel
*/
function buyUninitializedPixelBlocks(uint256[] _x, uint256[] _y, uint256[] _price, bytes32[] _contentData)
public
{
require(_x.length == _y.length && _x.length == _price.length && _x.length == _contentData.length);
for (uint i = 0; i < _x.length; i++) {
require(_price[i] > 0);
_buyUninitializedPixelBlock(_x[i], _y[i], _price[i], _contentData[i]);
}
}
/**
* @dev Buys pixel block
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price of the pixel block
* @param _contentData Data for the pixel
*/
function buyPixelBlock(uint256 _x, uint256 _y, uint256 _price, bytes32 _contentData)
public
payable
{
require(_price > 0);
uint256 _ = _buyPixelBlock(_x, _y, _price, msg.value, _contentData);
}
/**
* @dev Buys pixel block
* @param _x X coordinates of the desired blocks
* @param _y Y coordinates of the desired blocks
* @param _price New prices of the pixel blocks
* @param _contentData Data for the pixel
*/
function buyPixelBlocks(uint256[] _x, uint256[] _y, uint256[] _price, bytes32[] _contentData)
public
payable
{
require(_x.length == _y.length && _x.length == _price.length && _x.length == _contentData.length);
uint256 currentValue = msg.value;
for (uint i = 0; i < _x.length; i++) {
require(_price[i] > 0);
currentValue = _buyPixelBlock(_x[i], _y[i], _price[i], currentValue, _contentData[i]);
}
}
/**
* @dev Set prices for specific blocks
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price of the pixel block
*/
function setPixelBlockPrice(uint256 _x, uint256 _y, uint256 _price)
public
payable
{
require(_price > 0);
_setPixelBlockPrice(_x, _y, _price);
}
/**
* @dev Set prices for specific blocks
* @param _x X coordinates of the desired blocks
* @param _y Y coordinates of the desired blocks
* @param _price New prices of the pixel blocks
*/
function setPixelBlockPrices(uint256[] _x, uint256[] _y, uint256[] _price)
public
payable
{
require(_x.length == _y.length && _x.length == _price.length);
for (uint i = 0; i < _x.length; i++) {
require(_price[i] > 0);
_setPixelBlockPrice(_x[i], _y[i], _price[i]);
}
}
/**
* Trigger a dutch auction
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function beginDutchAuction(uint256 _x, uint256 _y)
public
auctionNotOngoing(_x, _y)
validRange(_x, _y)
{
Pixel storage pixel = pixelByCoordinate[_x][_y];
require(!userHasPositveBalance(pixel.seller));
require(pixel.auctionId == 0);
// Start a dutch auction
pixel.auctionId = _generateDutchAuction(_x, _y);
uint256 tokenId = _encodeTokenId(_x, _y);
_updatePixelMapping(pixel.seller, _x, _y, pixel.price, pixel.auctionId, "");
emit BeginDutchAuction(
pixel.id,
tokenId,
pixel.auctionId,
msg.sender,
_x,
_y,
block.timestamp,
block.timestamp.add(1 days)
);
}
/**
* @dev Allow a user to bid in an auction
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _bid Desired bid of the user
*/
function bidInAuction(uint256 _x, uint256 _y, uint256 _bid)
public
validRange(_x, _y)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
Auction storage auction = auctionById[pixel.auctionId];
uint256 _tokenId = _encodeTokenId(_x, _y);
require(pixel.auctionId != 0);
require(auction.currentPrice < _bid);
require(block.timestamp < auction.endTime);
auction.currentPrice = _bid;
auction.currentLeader = msg.sender;
emit UpdateAuctionBid(
pixel.id,
_tokenId,
auction.auctionId,
msg.sender,
_bid,
block.timestamp
);
}
/**
* End the auction
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function endDutchAuction(uint256 _x, uint256 _y)
public
validRange(_x, _y)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
Auction memory auction = auctionById[pixel.auctionId];
require(pixel.auctionId != 0);
require(auction.endTime < block.timestamp);
// End dutch auction
address winner = _endDutchAuction(_x, _y);
_updatePixelMapping(winner, _x, _y, auction.currentPrice, 0, "");
// Update user values
_subFromValueHeld(pixel.seller, pixel.price, true);
_addToValueHeld(winner, auction.currentPrice);
uint256 tokenId = _encodeTokenId(_x, _y);
removeTokenFrom(pixel.seller, tokenId);
addTokenTo(winner, tokenId);
emit Transfer(pixel.seller, winner, tokenId);
emit EndDutchAuction(
pixel.id,
tokenId,
winner,
_x,
_y
);
}
/**
* @dev Change content data of a pixel
* @param _x X coordinates of the desired blocks
* @param _y Y coordinates of the desired blocks
* @param _contentData Data for the pixel
*/
function changeContentData(uint256 _x, uint256 _y, bytes32 _contentData)
public
{
Pixel storage pixel = pixelByCoordinate[_x][_y];
require(msg.sender == pixel.seller);
pixel.contentData = _contentData;
emit UpdateContentData(
pixel.id,
pixel.seller,
_x,
_y,
_contentData
);
}
/**
* Encode a token ID for transferability
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function encodeTokenId(uint256 _x, uint256 _y)
public
view
validRange(_x, _y)
returns (uint256)
{
return _encodeTokenId(_x, _y);
}
/**
* Internal Functions
*/
/**
* @dev Buys an uninitialized pixel block for 0 ETH
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price for the pixel
* @param _contentData Data for the pixel
*/
function _buyUninitializedPixelBlock(uint256 _x, uint256 _y, uint256 _price, bytes32 _contentData)
internal
validRange(_x, _y)
hasPositveBalance(msg.sender)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
require(pixel.seller == address(0), "Pixel must not be initialized");
uint256 tokenId = _encodeTokenId(_x, _y);
bytes32 pixelId = _updatePixelMapping(msg.sender, _x, _y, _price, 0, _contentData);
_addToValueHeld(msg.sender, _price);
_mint(msg.sender, tokenId);
emit BuyPixel(
pixelId,
address(0),
msg.sender,
_x,
_y,
_price,
_contentData
);
}
/**
* @dev Buys a pixel block
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price of the pixel block
* @param _currentValue Current value of the transaction
* @param _contentData Data for the pixel
*/
function _buyPixelBlock(uint256 _x, uint256 _y, uint256 _price, uint256 _currentValue, bytes32 _contentData)
internal
validRange(_x, _y)
hasPositveBalance(msg.sender)
returns (uint256)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
require(pixel.auctionId == 0); // Stack to deep if this is a modifier
uint256 _taxOnPrice = _calculateTax(_price);
require(pixel.seller != address(0), "Pixel must be initialized");
require(userBalanceAtLastPaid[msg.sender] >= _taxOnPrice);
require(pixel.price <= _currentValue, "Must have sent sufficient funds");
uint256 tokenId = _encodeTokenId(_x, _y);
removeTokenFrom(pixel.seller, tokenId);
addTokenTo(msg.sender, tokenId);
emit Transfer(pixel.seller, msg.sender, tokenId);
_addToValueHeld(msg.sender, _price);
_subFromValueHeld(pixel.seller, pixel.price, false);
_updatePixelMapping(msg.sender, _x, _y, _price, 0, _contentData);
pixel.seller.transfer(pixel.price);
emit BuyPixel(
pixel.id,
pixel.seller,
msg.sender,
_x,
_y,
pixel.price,
_contentData
);
return _currentValue.sub(pixel.price);
}
/**
* @dev Set prices for a specific block
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price New price of the pixel block
*/
function _setPixelBlockPrice(uint256 _x, uint256 _y, uint256 _price)
internal
auctionNotOngoing(_x, _y)
validRange(_x, _y)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
require(pixel.seller == msg.sender, "Sender must own the block");
_addToValueHeld(msg.sender, _price);
delete pixelByCoordinate[_x][_y];
bytes32 pixelId = _updatePixelMapping(msg.sender, _x, _y, _price, 0, "");
emit SetPixelPrice(
pixelId,
pixel.seller,
_x,
_y,
pixel.price
);
}
/**
* Generate a dutch auction
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function _generateDutchAuction(uint256 _x, uint256 _y)
internal
returns (bytes32)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
bytes32 _auctionId = keccak256(
abi.encodePacked(
block.timestamp,
_x,
_y
)
);
auctionById[_auctionId] = Auction({
auctionId: _auctionId,
blockId: pixel.id,
x: _x,
y: _y,
currentPrice: 0,
currentLeader: msg.sender,
endTime: block.timestamp.add(1 days)
});
return _auctionId;
}
/**
* End a finished dutch auction
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function _endDutchAuction(uint256 _x, uint256 _y)
internal
returns (address)
{
Pixel memory pixel = pixelByCoordinate[_x][_y];
Auction memory auction = auctionById[pixel.auctionId];
address _winner = auction.currentLeader;
delete auctionById[auction.auctionId];
return _winner;
}
/**
* @dev Update pixel mapping every time it is purchase or the price is
* changed
* @param _seller Seller of the pixel block
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
* @param _price Price of the pixel block
* @param _contentData Data for the pixel
*/
function _updatePixelMapping
(
address _seller,
uint256 _x,
uint256 _y,
uint256 _price,
bytes32 _auctionId,
bytes32 _contentData
)
internal
returns (bytes32)
{
bytes32 pixelId = keccak256(
abi.encodePacked(
_x,
_y
)
);
pixelByCoordinate[_x][_y] = Pixel({
id: pixelId,
seller: _seller,
x: _x,
y: _y,
price: _price,
auctionId: _auctionId,
contentData: _contentData
});
return pixelId;
}
function _calculateTax(uint256 _price)
internal
view
returns (uint256)
{
return _price.mul(taxPercentage).div(100);
}
/**
* Encode token ID
* @param _x X coordinate of the desired block
* @param _y Y coordinate of the desired block
*/
function _encodeTokenId(uint256 _x, uint256 _y)
internal
pure
returns (uint256 result)
{
return ((_x * factor) & clearLow) | (_y & clearHigh);
}
} | Buys pixel block _x X coordinate of the desired block _y Y coordinate of the desired block _price New price of the pixel block _contentData Data for the pixel/ | function buyPixelBlock(uint256 _x, uint256 _y, uint256 _price, bytes32 _contentData)
public
payable
{
require(_price > 0);
uint256 _ = _buyPixelBlock(_x, _y, _price, msg.value, _contentData);
}
| 6,608,987 |
pragma solidity ^0.5.0;
import "../STO.sol";
import "../../../interfaces/IPolymathRegistry.sol";
import "../../../interfaces/IOracle.sol";
import "../../../libraries/DecimalMath.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./USDTieredSTOStorage.sol";
/**
* @title STO module for standard capped crowdsale
*/
contract USDTieredSTO is USDTieredSTOStorage, STO {
using SafeMath for uint256;
string internal constant POLY_ORACLE = "PolyUsdOracle";
string internal constant ETH_ORACLE = "EthUsdOracle";
////////////
// Events //
////////////
event SetAllowBeneficialInvestments(bool _allowed);
event SetNonAccreditedLimit(address _investor, uint256 _limit);
event SetAccredited(address _investor, bool _accredited);
event TokenPurchase(
address indexed _purchaser,
address indexed _beneficiary,
uint256 _tokens,
uint256 _usdAmount,
uint256 _tierPrice,
uint256 _tier
);
event FundsReceived(
address indexed _purchaser,
address indexed _beneficiary,
uint256 _usdAmount,
FundRaiseType _fundRaiseType,
uint256 _receivedValue,
uint256 _spentValue,
uint256 _rate
);
event ReserveTokenMint(address indexed _owner, address indexed _wallet, uint256 _tokens, uint256 _latestTier);
event SetAddresses(address indexed _wallet, address[] _usdTokens);
event SetLimits(uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD);
event SetTimes(uint256 _startTime, uint256 _endTime);
event SetTiers(
uint256[] _ratePerTier,
uint256[] _ratePerTierDiscountPoly,
uint256[] _tokensPerTierTotal,
uint256[] _tokensPerTierDiscountPoly
);
event SetTreasuryWallet(address _oldWallet, address _newWallet);
///////////////
// Modifiers //
///////////////
modifier validETH() {
require(_getOracle(bytes32("ETH"), bytes32("USD")) != address(0), "Invalid Oracle");
require(fundRaiseTypes[uint8(FundRaiseType.ETH)], "ETH not allowed");
_;
}
modifier validPOLY() {
require(_getOracle(bytes32("POLY"), bytes32("USD")) != address(0), "Invalid Oracle");
require(fundRaiseTypes[uint8(FundRaiseType.POLY)], "POLY not allowed");
_;
}
modifier validSC(address _usdToken) {
require(fundRaiseTypes[uint8(FundRaiseType.SC)] && usdTokenEnabled[_usdToken], "USD not allowed");
_;
}
///////////////////////
// STO Configuration //
///////////////////////
constructor(address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) {
}
/**
* @notice Function used to intialize the contract variables
* @param _startTime Unix timestamp at which offering get started
* @param _endTime Unix timestamp at which offering get ended
* @param _ratePerTier Rate (in USD) per tier (* 10**18)
* @param _tokensPerTierTotal Tokens available in each tier
* @param _nonAccreditedLimitUSD Limit in USD (* 10**18) for non-accredited investors
* @param _minimumInvestmentUSD Minimun investment in USD (* 10**18)
* @param _fundRaiseTypes Types of currency used to collect the funds
* @param _wallet Ethereum account address to hold the funds
* @param _treasuryWallet Ethereum account address to receive unsold tokens
* @param _usdTokens Contract address of the stable coins
*/
function configure(
uint256 _startTime,
uint256 _endTime,
uint256[] memory _ratePerTier,
uint256[] memory _ratePerTierDiscountPoly,
uint256[] memory _tokensPerTierTotal,
uint256[] memory _tokensPerTierDiscountPoly,
uint256 _nonAccreditedLimitUSD,
uint256 _minimumInvestmentUSD,
FundRaiseType[] memory _fundRaiseTypes,
address payable _wallet,
address _treasuryWallet,
address[] memory _usdTokens
)
public
onlyFactory
{
oracleKeys[bytes32("ETH")][bytes32("USD")] = ETH_ORACLE;
oracleKeys[bytes32("POLY")][bytes32("USD")] = POLY_ORACLE;
require(endTime == 0, "Already configured");
_modifyTimes(_startTime, _endTime);
_modifyTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly);
// NB - _setFundRaiseType must come before modifyAddresses
_setFundRaiseType(_fundRaiseTypes);
_modifyAddresses(_wallet, _treasuryWallet, _usdTokens);
_modifyLimits(_nonAccreditedLimitUSD, _minimumInvestmentUSD);
}
/**
* @dev Modifies fund raise types
* @param _fundRaiseTypes Array of fund raise types to allow
*/
function modifyFunding(FundRaiseType[] calldata _fundRaiseTypes) external {
_onlySecurityTokenOwner();
_isSTOStarted();
_setFundRaiseType(_fundRaiseTypes);
}
/**
* @dev modifies max non accredited invets limit and overall minimum investment limit
* @param _nonAccreditedLimitUSD max non accredited invets limit
* @param _minimumInvestmentUSD overall minimum investment limit
*/
function modifyLimits(uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD) external {
_onlySecurityTokenOwner();
_isSTOStarted();
_modifyLimits(_nonAccreditedLimitUSD, _minimumInvestmentUSD);
}
/**
* @dev modifiers STO tiers. All tiers must be passed, can not edit specific tiers.
* @param _ratePerTier Array of rates per tier
* @param _ratePerTierDiscountPoly Array of discounted poly rates per tier
* @param _tokensPerTierTotal Array of total tokens per tier
* @param _tokensPerTierDiscountPoly Array of discounted tokens per tier
*/
function modifyTiers(
uint256[] calldata _ratePerTier,
uint256[] calldata _ratePerTierDiscountPoly,
uint256[] calldata _tokensPerTierTotal,
uint256[] calldata _tokensPerTierDiscountPoly
)
external
{
_onlySecurityTokenOwner();
_isSTOStarted();
_modifyTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly);
}
/**
* @dev Modifies STO start and end times
* @param _startTime start time of sto
* @param _endTime end time of sto
*/
function modifyTimes(uint256 _startTime, uint256 _endTime) external {
_onlySecurityTokenOwner();
_isSTOStarted();
_modifyTimes(_startTime, _endTime);
}
function _isSTOStarted() internal view {
/*solium-disable-next-line security/no-block-members*/
require(now < startTime, "Already started");
}
/**
* @dev Modifies addresses used as wallet, reserve wallet and usd token
* @param _wallet Address of wallet where funds are sent
* @param _treasuryWallet Address of wallet where unsold tokens are sent
* @param _usdTokens Address of usd tokens
*/
function modifyAddresses(address payable _wallet, address _treasuryWallet, address[] calldata _usdTokens) external {
_onlySecurityTokenOwner();
_modifyAddresses(_wallet, _treasuryWallet, _usdTokens);
}
function _modifyLimits(uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD) internal {
minimumInvestmentUSD = _minimumInvestmentUSD;
nonAccreditedLimitUSD = _nonAccreditedLimitUSD;
emit SetLimits(minimumInvestmentUSD, nonAccreditedLimitUSD);
}
function _modifyTiers(
uint256[] memory _ratePerTier,
uint256[] memory _ratePerTierDiscountPoly,
uint256[] memory _tokensPerTierTotal,
uint256[] memory _tokensPerTierDiscountPoly
)
internal
{
require(
_tokensPerTierTotal.length > 0 &&
_ratePerTier.length == _tokensPerTierTotal.length &&
_ratePerTierDiscountPoly.length == _tokensPerTierTotal.length &&
_tokensPerTierDiscountPoly.length == _tokensPerTierTotal.length,
"Invalid Input"
);
delete tiers;
for (uint256 i = 0; i < _ratePerTier.length; i++) {
require(_ratePerTier[i] > 0 && _tokensPerTierTotal[i] > 0, "Invalid value");
require(_tokensPerTierDiscountPoly[i] <= _tokensPerTierTotal[i], "Too many discounted tokens");
require(_ratePerTierDiscountPoly[i] <= _ratePerTier[i], "Invalid discount");
tiers.push(Tier(_ratePerTier[i], _ratePerTierDiscountPoly[i], _tokensPerTierTotal[i], _tokensPerTierDiscountPoly[i], 0, 0));
}
emit SetTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly);
}
function _modifyTimes(uint256 _startTime, uint256 _endTime) internal {
/*solium-disable-next-line security/no-block-members*/
require((_endTime > _startTime) && (_startTime > now), "Invalid times");
startTime = _startTime;
endTime = _endTime;
emit SetTimes(_startTime, _endTime);
}
function _modifyAddresses(address payable _wallet, address _treasuryWallet, address[] memory _usdTokens) internal {
require(_wallet != address(0), "Invalid wallet");
wallet = _wallet;
emit SetTreasuryWallet(treasuryWallet, _treasuryWallet);
treasuryWallet = _treasuryWallet;
_modifyUSDTokens(_usdTokens);
}
function _modifyUSDTokens(address[] memory _usdTokens) internal {
uint256 i;
for(i = 0; i < usdTokens.length; i++) {
usdTokenEnabled[usdTokens[i]] = false;
}
usdTokens = _usdTokens;
for(i = 0; i < _usdTokens.length; i++) {
require(_usdTokens[i] != address(0) && _usdTokens[i] != address(polyToken), "Invalid USD token");
usdTokenEnabled[_usdTokens[i]] = true;
}
emit SetAddresses(wallet, _usdTokens);
}
////////////////////
// STO Management //
////////////////////
/**
* @notice Finalizes the STO and mint remaining tokens to treasury address
* @notice Treasury wallet address must be whitelisted to successfully finalize
*/
function finalize() external {
_onlySecurityTokenOwner();
require(!isFinalized, "STO is finalized");
isFinalized = true;
uint256 tempReturned;
uint256 tempSold;
uint256 remainingTokens;
for (uint256 i = 0; i < tiers.length; i++) {
remainingTokens = tiers[i].tokenTotal.sub(tiers[i].mintedTotal);
tempReturned = tempReturned.add(remainingTokens);
tempSold = tempSold.add(tiers[i].mintedTotal);
if (remainingTokens > 0) {
tiers[i].mintedTotal = tiers[i].tokenTotal;
}
}
address walletAddress = (treasuryWallet == address(0) ? IDataStore(getDataStore()).getAddress(TREASURY) : treasuryWallet);
require(walletAddress != address(0), "Invalid address");
uint256 granularity = ISecurityToken(securityToken).granularity();
tempReturned = tempReturned.div(granularity);
tempReturned = tempReturned.mul(granularity);
ISecurityToken(securityToken).issue(walletAddress, tempReturned, "");
emit ReserveTokenMint(msg.sender, walletAddress, tempReturned, currentTier);
finalAmountReturned = tempReturned;
totalTokensSold = tempSold;
}
/**
* @notice Modifies the list of overrides for non-accredited limits in USD
* @param _investors Array of investor addresses to modify
* @param _nonAccreditedLimit Array of uints specifying non-accredited limits
*/
function changeNonAccreditedLimit(address[] calldata _investors, uint256[] calldata _nonAccreditedLimit) external {
_onlySecurityTokenOwner();
//nonAccreditedLimitUSDOverride
require(_investors.length == _nonAccreditedLimit.length, "Length mismatch");
for (uint256 i = 0; i < _investors.length; i++) {
nonAccreditedLimitUSDOverride[_investors[i]] = _nonAccreditedLimit[i];
emit SetNonAccreditedLimit(_investors[i], _nonAccreditedLimit[i]);
}
}
/**
* @notice Returns investor accredited & non-accredited override informatiomn
* @return investors list of all configured investors
* @return accredited whether investor is accredited
* @return override any USD overrides for non-accredited limits for the investor
*/
function getAccreditedData() external view returns (address[] memory investors, bool[] memory accredited, uint256[] memory overrides) {
IDataStore dataStore = getDataStore();
investors = dataStore.getAddressArray(INVESTORSKEY);
accredited = new bool[](investors.length);
overrides = new uint256[](investors.length);
for (uint256 i = 0; i < investors.length; i++) {
accredited[i] = _getIsAccredited(investors[i], dataStore);
overrides[i] = nonAccreditedLimitUSDOverride[investors[i]];
}
}
/**
* @notice Function to set allowBeneficialInvestments (allow beneficiary to be different to funder)
* @param _allowBeneficialInvestments Boolean to allow or disallow beneficial investments
*/
function changeAllowBeneficialInvestments(bool _allowBeneficialInvestments) external {
_onlySecurityTokenOwner();
require(_allowBeneficialInvestments != allowBeneficialInvestments);
allowBeneficialInvestments = _allowBeneficialInvestments;
emit SetAllowBeneficialInvestments(allowBeneficialInvestments);
}
//////////////////////////
// Investment Functions //
//////////////////////////
/**
* @notice fallback function - assumes ETH being invested
*/
function() external payable {
buyWithETHRateLimited(msg.sender, 0);
}
// Buy functions without rate restriction
function buyWithETH(address _beneficiary) external payable returns (uint256, uint256, uint256) {
return buyWithETHRateLimited(_beneficiary, 0);
}
function buyWithPOLY(address _beneficiary, uint256 _investedPOLY) external returns (uint256, uint256, uint256) {
return buyWithPOLYRateLimited(_beneficiary, _investedPOLY, 0);
}
function buyWithUSD(address _beneficiary, uint256 _investedSC, IERC20 _usdToken) external returns (uint256, uint256, uint256) {
return buyWithUSDRateLimited(_beneficiary, _investedSC, 0, _usdToken);
}
/**
* @notice Purchase tokens using ETH
* @param _beneficiary Address where security tokens will be sent
* @param _minTokens Minumum number of tokens to buy or else revert
*/
function buyWithETHRateLimited(address _beneficiary, uint256 _minTokens) public payable validETH returns (uint256, uint256, uint256) {
(uint256 rate, uint256 spentUSD, uint256 spentValue, uint256 initialMinted) = _getSpentvalues(_beneficiary, msg.value, FundRaiseType.ETH, _minTokens);
// Modify storage
investorInvested[_beneficiary][uint8(FundRaiseType.ETH)] = investorInvested[_beneficiary][uint8(FundRaiseType.ETH)].add(spentValue);
fundsRaised[uint8(FundRaiseType.ETH)] = fundsRaised[uint8(FundRaiseType.ETH)].add(spentValue);
// Forward ETH to issuer wallet
wallet.transfer(spentValue);
// Refund excess ETH to investor wallet
msg.sender.transfer(msg.value.sub(spentValue));
emit FundsReceived(msg.sender, _beneficiary, spentUSD, FundRaiseType.ETH, msg.value, spentValue, rate);
return (spentUSD, spentValue, getTokensMinted().sub(initialMinted));
}
/**
* @notice Purchase tokens using POLY
* @param _beneficiary Address where security tokens will be sent
* @param _investedPOLY Amount of POLY invested
* @param _minTokens Minumum number of tokens to buy or else revert
*/
function buyWithPOLYRateLimited(address _beneficiary, uint256 _investedPOLY, uint256 _minTokens) public validPOLY returns (uint256, uint256, uint256) {
return _buyWithTokens(_beneficiary, _investedPOLY, FundRaiseType.POLY, _minTokens, polyToken);
}
/**
* @notice Purchase tokens using Stable coins
* @param _beneficiary Address where security tokens will be sent
* @param _investedSC Amount of Stable coins invested
* @param _minTokens Minumum number of tokens to buy or else revert
* @param _usdToken Address of USD stable coin to buy tokens with
*/
function buyWithUSDRateLimited(address _beneficiary, uint256 _investedSC, uint256 _minTokens, IERC20 _usdToken)
public validSC(address(_usdToken)) returns (uint256, uint256, uint256)
{
return _buyWithTokens(_beneficiary, _investedSC, FundRaiseType.SC, _minTokens, _usdToken);
}
function _buyWithTokens(address _beneficiary, uint256 _tokenAmount, FundRaiseType _fundRaiseType, uint256 _minTokens, IERC20 _token) internal returns (uint256, uint256, uint256) {
(uint256 rate, uint256 spentUSD, uint256 spentValue, uint256 initialMinted) = _getSpentvalues(_beneficiary, _tokenAmount, _fundRaiseType, _minTokens);
// Modify storage
investorInvested[_beneficiary][uint8(_fundRaiseType)] = investorInvested[_beneficiary][uint8(_fundRaiseType)].add(spentValue);
fundsRaised[uint8(_fundRaiseType)] = fundsRaised[uint8(_fundRaiseType)].add(spentValue);
if(address(_token) != address(polyToken))
stableCoinsRaised[address(_token)] = stableCoinsRaised[address(_token)].add(spentValue);
// Forward coins to issuer wallet
require(_token.transferFrom(msg.sender, wallet, spentValue), "Transfer failed");
emit FundsReceived(msg.sender, _beneficiary, spentUSD, _fundRaiseType, _tokenAmount, spentValue, rate);
return (spentUSD, spentValue, getTokensMinted().sub(initialMinted));
}
function _getSpentvalues(address _beneficiary, uint256 _amount, FundRaiseType _fundRaiseType, uint256 _minTokens) internal returns(uint256 rate, uint256 spentUSD, uint256 spentValue, uint256 initialMinted) {
initialMinted = getTokensMinted();
rate = getRate(_fundRaiseType);
(spentUSD, spentValue) = _buyTokens(_beneficiary, _amount, rate, _fundRaiseType);
require(getTokensMinted().sub(initialMinted) >= _minTokens, "Insufficient minted");
}
/**
* @notice Low level token purchase
* @param _beneficiary Address where security tokens will be sent
* @param _investmentValue Amount of POLY, ETH or Stable coins invested
* @param _fundRaiseType Fund raise type (POLY, ETH, SC)
*/
function _buyTokens(
address _beneficiary,
uint256 _investmentValue,
uint256 _rate,
FundRaiseType _fundRaiseType
)
internal
whenNotPaused
returns(uint256 spentUSD, uint256 spentValue)
{
if (!allowBeneficialInvestments) {
require(_beneficiary == msg.sender, "Beneficiary != funder");
}
require(_canBuy(_beneficiary), "Unauthorized");
uint256 originalUSD = DecimalMath.mul(_rate, _investmentValue);
uint256 allowedUSD = _buyTokensChecks(_beneficiary, _investmentValue, originalUSD);
for (uint256 i = currentTier; i < tiers.length; i++) {
bool gotoNextTier;
uint256 tempSpentUSD;
// Update current tier if needed
if (currentTier != i)
currentTier = i;
// If there are tokens remaining, process investment
if (tiers[i].mintedTotal < tiers[i].tokenTotal) {
(tempSpentUSD, gotoNextTier) = _calculateTier(_beneficiary, i, allowedUSD.sub(spentUSD), _fundRaiseType);
spentUSD = spentUSD.add(tempSpentUSD);
// If all funds have been spent, exit the loop
if (!gotoNextTier)
break;
}
}
// Modify storage
if (spentUSD > 0) {
if (investorInvestedUSD[_beneficiary] == 0)
investorCount = investorCount + 1;
investorInvestedUSD[_beneficiary] = investorInvestedUSD[_beneficiary].add(spentUSD);
fundsRaisedUSD = fundsRaisedUSD.add(spentUSD);
}
spentValue = DecimalMath.div(spentUSD, _rate);
}
function _buyTokensChecks(
address _beneficiary,
uint256 _investmentValue,
uint256 investedUSD
)
internal
view
returns(uint256 netInvestedUSD)
{
require(isOpen(), "STO not open");
require(_investmentValue > 0, "No funds sent");
// Check for minimum investment
require(investedUSD.add(investorInvestedUSD[_beneficiary]) >= minimumInvestmentUSD, "Investment < min");
netInvestedUSD = investedUSD;
// Check for non-accredited cap
if (!_isAccredited(_beneficiary)) {
uint256 investorLimitUSD = (nonAccreditedLimitUSDOverride[_beneficiary] == 0) ? nonAccreditedLimitUSD : nonAccreditedLimitUSDOverride[_beneficiary];
require(investorInvestedUSD[_beneficiary] < investorLimitUSD, "Over Non-accredited investor limit");
if (investedUSD.add(investorInvestedUSD[_beneficiary]) > investorLimitUSD)
netInvestedUSD = investorLimitUSD.sub(investorInvestedUSD[_beneficiary]);
}
}
function _calculateTier(
address _beneficiary,
uint256 _tier,
uint256 _investedUSD,
FundRaiseType _fundRaiseType
)
internal
returns(uint256 spentUSD, bool gotoNextTier)
{
// First purchase any discounted tokens if POLY investment
uint256 tierSpentUSD;
uint256 tierPurchasedTokens;
uint256 investedUSD = _investedUSD;
Tier storage tierData = tiers[_tier];
// Check whether there are any remaining discounted tokens
if ((_fundRaiseType == FundRaiseType.POLY) && (tierData.tokensDiscountPoly > tierData.mintedDiscountPoly)) {
uint256 discountRemaining = tierData.tokensDiscountPoly.sub(tierData.mintedDiscountPoly);
uint256 totalRemaining = tierData.tokenTotal.sub(tierData.mintedTotal);
if (totalRemaining < discountRemaining)
(spentUSD, tierPurchasedTokens, gotoNextTier) = _purchaseTier(_beneficiary, tierData.rateDiscountPoly, totalRemaining, investedUSD, _tier);
else
(spentUSD, tierPurchasedTokens, gotoNextTier) = _purchaseTier(_beneficiary, tierData.rateDiscountPoly, discountRemaining, investedUSD, _tier);
investedUSD = investedUSD.sub(spentUSD);
tierData.mintedDiscountPoly = tierData.mintedDiscountPoly.add(tierPurchasedTokens);
tierData.minted[uint8(_fundRaiseType)] = tierData.minted[uint8(_fundRaiseType)].add(tierPurchasedTokens);
tierData.mintedTotal = tierData.mintedTotal.add(tierPurchasedTokens);
}
// Now, if there is any remaining USD to be invested, purchase at non-discounted rate
if (investedUSD > 0 &&
tierData.tokenTotal.sub(tierData.mintedTotal) > 0 &&
(_fundRaiseType != FundRaiseType.POLY || tierData.tokensDiscountPoly <= tierData.mintedDiscountPoly)
) {
(tierSpentUSD, tierPurchasedTokens, gotoNextTier) = _purchaseTier(_beneficiary, tierData.rate, tierData.tokenTotal.sub(tierData.mintedTotal), investedUSD, _tier);
spentUSD = spentUSD.add(tierSpentUSD);
tierData.minted[uint8(_fundRaiseType)] = tierData.minted[uint8(_fundRaiseType)].add(tierPurchasedTokens);
tierData.mintedTotal = tierData.mintedTotal.add(tierPurchasedTokens);
}
}
function _purchaseTier(
address _beneficiary,
uint256 _tierPrice,
uint256 _tierRemaining,
uint256 _investedUSD,
uint256 _tier
)
internal
returns(uint256 spentUSD, uint256 purchasedTokens, bool gotoNextTier)
{
purchasedTokens = DecimalMath.div(_investedUSD, _tierPrice);
uint256 granularity = ISecurityToken(securityToken).granularity();
if (purchasedTokens > _tierRemaining) {
purchasedTokens = _tierRemaining.div(granularity);
gotoNextTier = true;
} else {
purchasedTokens = purchasedTokens.div(granularity);
}
purchasedTokens = purchasedTokens.mul(granularity);
spentUSD = DecimalMath.mul(purchasedTokens, _tierPrice);
// In case of rounding issues, ensure that spentUSD is never more than investedUSD
if (spentUSD > _investedUSD) {
spentUSD = _investedUSD;
}
if (purchasedTokens > 0) {
ISecurityToken(securityToken).issue(_beneficiary, purchasedTokens, "");
emit TokenPurchase(msg.sender, _beneficiary, purchasedTokens, spentUSD, _tierPrice, _tier);
}
}
function _isAccredited(address _investor) internal view returns(bool) {
IDataStore dataStore = getDataStore();
return _getIsAccredited(_investor, dataStore);
}
function _getIsAccredited(address _investor, IDataStore dataStore) internal view returns(bool) {
uint256 flags = dataStore.getUint256(_getKey(INVESTORFLAGS, _investor));
uint256 flag = flags & uint256(1); //isAccredited is flag 0 so we don't need to bit shift flags.
return flag > 0 ? true : false;
}
/////////////
// Getters //
/////////////
/**
* @notice This function returns whether or not the STO is in fundraising mode (open)
* @return bool Whether the STO is accepting investments
*/
function isOpen() public view returns(bool) {
/*solium-disable-next-line security/no-block-members*/
if (isFinalized || now < startTime || now >= endTime || capReached())
return false;
return true;
}
/**
* @notice Checks whether the cap has been reached.
* @return bool Whether the cap was reached
*/
function capReached() public view returns (bool) {
if (isFinalized) {
return (finalAmountReturned == 0);
}
return (tiers[tiers.length - 1].mintedTotal == tiers[tiers.length - 1].tokenTotal);
}
/**
* @dev returns current conversion rate of funds
* @param _fundRaiseType Fund raise type to get rate of
*/
function getRate(FundRaiseType _fundRaiseType) public returns (uint256) {
if (_fundRaiseType == FundRaiseType.ETH) {
return IOracle(_getOracle(bytes32("ETH"), bytes32("USD"))).getPrice();
} else if (_fundRaiseType == FundRaiseType.POLY) {
return IOracle(_getOracle(bytes32("POLY"), bytes32("USD"))).getPrice();
} else if (_fundRaiseType == FundRaiseType.SC) {
return 10**18;
}
}
/**
* @notice This function converts from ETH or POLY to USD
* @param _fundRaiseType Currency key
* @param _amount Value to convert to USD
* @return uint256 Value in USD
*/
function convertToUSD(FundRaiseType _fundRaiseType, uint256 _amount) public returns(uint256) {
return DecimalMath.mul(_amount, getRate(_fundRaiseType));
}
/**
* @notice This function converts from USD to ETH or POLY
* @param _fundRaiseType Currency key
* @param _amount Value to convert from USD
* @return uint256 Value in ETH or POLY
*/
function convertFromUSD(FundRaiseType _fundRaiseType, uint256 _amount) public returns(uint256) {
return DecimalMath.div(_amount, getRate(_fundRaiseType));
}
/**
* @notice Return the total no. of tokens sold
* @return uint256 Total number of tokens sold
*/
function getTokensSold() public view returns (uint256) {
if (isFinalized)
return totalTokensSold;
return getTokensMinted();
}
/**
* @notice Return the total no. of tokens minted
* @return uint256 Total number of tokens minted
*/
function getTokensMinted() public view returns (uint256 tokensMinted) {
for (uint256 i = 0; i < tiers.length; i++) {
tokensMinted = tokensMinted.add(tiers[i].mintedTotal);
}
}
/**
* @notice Return the total no. of tokens sold for the given fund raise type
* param _fundRaiseType The fund raising currency (e.g. ETH, POLY, SC) to calculate sold tokens for
* @return uint256 Total number of tokens sold for ETH
*/
function getTokensSoldFor(FundRaiseType _fundRaiseType) external view returns (uint256 tokensSold) {
for (uint256 i = 0; i < tiers.length; i++) {
tokensSold = tokensSold.add(tiers[i].minted[uint8(_fundRaiseType)]);
}
}
/**
* @notice Return array of minted tokens in each fund raise type for given tier
* param _tier The tier to return minted tokens for
* @return uint256[] array of minted tokens in each fund raise type
*/
function getTokensMintedByTier(uint256 _tier) external view returns(uint256[] memory) {
uint256[] memory tokensMinted = new uint256[](3);
tokensMinted[0] = tiers[_tier].minted[uint8(FundRaiseType.ETH)];
tokensMinted[1] = tiers[_tier].minted[uint8(FundRaiseType.POLY)];
tokensMinted[2] = tiers[_tier].minted[uint8(FundRaiseType.SC)];
return tokensMinted;
}
/**
* @notice Return the total no. of tokens sold in a given tier
* param _tier The tier to calculate sold tokens for
* @return uint256 Total number of tokens sold in the tier
*/
function getTokensSoldByTier(uint256 _tier) external view returns (uint256) {
uint256 tokensSold;
tokensSold = tokensSold.add(tiers[_tier].minted[uint8(FundRaiseType.ETH)]);
tokensSold = tokensSold.add(tiers[_tier].minted[uint8(FundRaiseType.POLY)]);
tokensSold = tokensSold.add(tiers[_tier].minted[uint8(FundRaiseType.SC)]);
return tokensSold;
}
/**
* @notice Return the total no. of tiers
* @return uint256 Total number of tiers
*/
function getNumberOfTiers() external view returns (uint256) {
return tiers.length;
}
/**
* @notice Return the usd tokens accepted by the STO
* @return address[] usd tokens
*/
function getUsdTokens() external view returns (address[] memory) {
return usdTokens;
}
/**
* @notice Return the permissions flag that are associated with STO
*/
function getPermissions() public view returns(bytes32[] memory allPermissions) {
return allPermissions;
}
/**
* @notice Return the STO details
* @return Unixtimestamp at which offering gets start.
* @return Unixtimestamp at which offering ends.
* @return Currently active tier
* @return Array of Number of tokens this STO will be allowed to sell at different tiers.
* @return Array Rate at which tokens are sold at different tiers
* @return Amount of funds raised
* @return Number of individual investors this STO have.
* @return Amount of tokens sold.
* @return Array of bools to show if funding is allowed in ETH, POLY, SC respectively
*/
function getSTODetails() external view returns(uint256, uint256, uint256, uint256[] memory, uint256[] memory, uint256, uint256, uint256, bool[] memory) {
uint256[] memory cap = new uint256[](tiers.length);
uint256[] memory rate = new uint256[](tiers.length);
for(uint256 i = 0; i < tiers.length; i++) {
cap[i] = tiers[i].tokenTotal;
rate[i] = tiers[i].rate;
}
bool[] memory _fundRaiseTypes = new bool[](3);
_fundRaiseTypes[0] = fundRaiseTypes[uint8(FundRaiseType.ETH)];
_fundRaiseTypes[1] = fundRaiseTypes[uint8(FundRaiseType.POLY)];
_fundRaiseTypes[2] = fundRaiseTypes[uint8(FundRaiseType.SC)];
return (
startTime,
endTime,
currentTier,
cap,
rate,
fundsRaisedUSD,
investorCount,
getTokensSold(),
_fundRaiseTypes
);
}
/**
* @notice This function returns the signature of configure function
* @return bytes4 Configure function signature
*/
function getInitFunction() public pure returns(bytes4) {
return this.configure.selector;
}
function _getOracle(bytes32 _currency, bytes32 _denominatedCurrency) internal view returns(address) {
return IPolymathRegistry(ISecurityToken(securityToken).polymathRegistry()).getAddress(oracleKeys[_currency][_denominatedCurrency]);
}
}
| Checks whether the cap has been reached. return bool Whether the cap was reached/ | function capReached() public view returns (bool) {
if (isFinalized) {
return (finalAmountReturned == 0);
}
return (tiers[tiers.length - 1].mintedTotal == tiers[tiers.length - 1].tokenTotal);
}
| 881,380 |
./full_match/1/0x806138dB9a18f06C3c22C18b102b1468dAd2bb78/sources/contracts/ERC721A.sol | Returns the total amount of tokens minted in the contract./ | function totalMinted() public view virtual returns (uint256) {
return _totalMinted();
}
| 4,957,830 |
//Address: 0xb565726e2e44e4ae9e3ce750fc4ba8fa65e701e0
//Contract name: EthealController
//Balance: 0 Ether
//Verification Date: 11/29/2017
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity ^0.4.17;
/**
* @title ERC20
* @dev ERC20 interface
*/
contract ERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/**
* @title MiniMe interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20MiniMe is ERC20, Controlled {
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool);
function totalSupply() public view returns (uint);
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint);
function totalSupplyAt(uint _blockNumber) public view returns(uint);
function createCloneToken(string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled) public returns(address);
function generateTokens(address _owner, uint _amount) public returns (bool);
function destroyTokens(address _owner, uint _amount) public returns (bool);
function enableTransfers(bool _transfersEnabled) public;
function isContract(address _addr) internal view returns(bool);
function claimTokens(address _token) public;
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20MiniMe public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
buyTokens(beneficiary, msg.value);
}
// implementation of low level token purchase function
function buyTokens(address beneficiary, uint256 weiAmount) internal {
require(beneficiary != 0x0);
require(validPurchase(weiAmount));
// update state
weiRaised = weiRaised.add(weiAmount);
transferToken(beneficiary, weiAmount);
forwardFunds(weiAmount);
}
// low level transfer token
// override to create custom token transfer mechanism, eg. pull pattern
function transferToken(address beneficiary, uint256 weiAmount) internal {
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
token.generateTokens(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds(uint256 weiAmount) internal {
wallet.transfer(weiAmount);
}
// @return true if the transaction can buy tokens
function validPurchase(uint256 weiAmount) internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = weiAmount != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// @return true if crowdsale has started
function hasStarted() public view returns (bool) {
return now >= startTime;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
ERC20MiniMe public ethealToken;
address public SALE; // address where sale tokens are located
/// @notice needed for hodler handling
function addHodlerStake(address _beneficiary, uint _stake) public;
function setHodlerStake(address _beneficiary, uint256 _stake) public;
function setHodlerTime(uint256 _time) public;
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public returns(bool);
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Hodler
* @dev Handles hodler reward, TokenController should create and own it.
*/
contract Hodler is Ownable {
using SafeMath for uint;
// HODLER reward tracker
// stake amount per address
struct HODL {
uint256 stake;
// moving ANY funds invalidates hodling of the address
bool invalid;
bool claimed3M;
bool claimed6M;
bool claimed9M;
}
mapping (address => HODL) public hodlerStakes;
// total current staking value and hodler addresses
uint256 public hodlerTotalValue;
uint256 public hodlerTotalCount;
// store dates and total stake values for 3 - 6 - 9 months after normal sale
uint256 public hodlerTotalValue3M;
uint256 public hodlerTotalValue6M;
uint256 public hodlerTotalValue9M;
uint256 public hodlerTimeStart;
uint256 public hodlerTime3M;
uint256 public hodlerTime6M;
uint256 public hodlerTime9M;
// reward HEAL token amount
uint256 public TOKEN_HODL_3M;
uint256 public TOKEN_HODL_6M;
uint256 public TOKEN_HODL_9M;
// total amount of tokens claimed so far
uint256 public claimedTokens;
event LogHodlSetStake(address indexed _setter, address indexed _beneficiary, uint256 _value);
event LogHodlClaimed(address indexed _setter, address indexed _beneficiary, uint256 _value);
event LogHodlStartSet(address indexed _setter, uint256 _time);
/// @dev Only before hodl is started
modifier beforeHodlStart() {
if (hodlerTimeStart == 0 || now <= hodlerTimeStart)
_;
}
/// @dev Contructor, it should be created by a TokenController
function Hodler(uint256 _stake3m, uint256 _stake6m, uint256 _stake9m) {
TOKEN_HODL_3M = _stake3m;
TOKEN_HODL_6M = _stake6m;
TOKEN_HODL_9M = _stake9m;
}
/// @notice Adding hodler stake to an account
/// @dev Only owner contract can call it and before hodling period starts
/// @param _beneficiary Recepient address of hodler stake
/// @param _stake Amount of additional hodler stake
function addHodlerStake(address _beneficiary, uint256 _stake) public onlyOwner beforeHodlStart {
// real change and valid _beneficiary is needed
if (_stake == 0 || _beneficiary == address(0))
return;
// add stake and maintain count
if (hodlerStakes[_beneficiary].stake == 0)
hodlerTotalCount = hodlerTotalCount.add(1);
hodlerStakes[_beneficiary].stake = hodlerStakes[_beneficiary].stake.add(_stake);
hodlerTotalValue = hodlerTotalValue.add(_stake);
LogHodlSetStake(msg.sender, _beneficiary, hodlerStakes[_beneficiary].stake);
}
/// @notice Setting hodler stake of an account
/// @dev Only owner contract can call it and before hodling period starts
/// @param _beneficiary Recepient address of hodler stake
/// @param _stake Amount to set the hodler stake
function setHodlerStake(address _beneficiary, uint256 _stake) public onlyOwner beforeHodlStart {
// real change and valid _beneficiary is needed
if (hodlerStakes[_beneficiary].stake == _stake || _beneficiary == address(0))
return;
// add stake and maintain count
if (hodlerStakes[_beneficiary].stake == 0 && _stake > 0) {
hodlerTotalCount = hodlerTotalCount.add(1);
} else if (hodlerStakes[_beneficiary].stake > 0 && _stake == 0) {
hodlerTotalCount = hodlerTotalCount.sub(1);
}
uint256 _diff = _stake > hodlerStakes[_beneficiary].stake ? _stake.sub(hodlerStakes[_beneficiary].stake) : hodlerStakes[_beneficiary].stake.sub(_stake);
if (_stake > hodlerStakes[_beneficiary].stake) {
hodlerTotalValue = hodlerTotalValue.add(_diff);
} else {
hodlerTotalValue = hodlerTotalValue.sub(_diff);
}
hodlerStakes[_beneficiary].stake = _stake;
LogHodlSetStake(msg.sender, _beneficiary, _stake);
}
/// @notice Setting hodler start period.
/// @param _time The time when hodler reward starts counting
function setHodlerTime(uint256 _time) public onlyOwner beforeHodlStart {
require(_time >= now);
hodlerTimeStart = _time;
hodlerTime3M = _time.add(90 days);
hodlerTime6M = _time.add(180 days);
hodlerTime9M = _time.add(270 days);
LogHodlStartSet(msg.sender, _time);
}
/// @notice Invalidates hodler account
/// @dev Gets called by EthealController#onTransfer before every transaction
function invalidate(address _account) public onlyOwner {
if (hodlerStakes[_account].stake > 0 && !hodlerStakes[_account].invalid) {
hodlerStakes[_account].invalid = true;
hodlerTotalValue = hodlerTotalValue.sub(hodlerStakes[_account].stake);
hodlerTotalCount = hodlerTotalCount.sub(1);
}
// update hodl total values "automatically" - whenever someone sends funds thus
updateAndGetHodlTotalValue();
}
/// @notice Claiming HODL reward for msg.sender
function claimHodlReward() public {
claimHodlRewardFor(msg.sender);
}
/// @notice Claiming HODL reward for an address
function claimHodlRewardFor(address _beneficiary) public {
// only when the address has a valid stake
require(hodlerStakes[_beneficiary].stake > 0 && !hodlerStakes[_beneficiary].invalid);
uint256 _stake = 0;
// update hodl total values
updateAndGetHodlTotalValue();
// claim hodl if not claimed
if (!hodlerStakes[_beneficiary].claimed3M && now >= hodlerTime3M) {
_stake = _stake.add(hodlerStakes[_beneficiary].stake.mul(TOKEN_HODL_3M).div(hodlerTotalValue3M));
hodlerStakes[_beneficiary].claimed3M = true;
}
if (!hodlerStakes[_beneficiary].claimed6M && now >= hodlerTime6M) {
_stake = _stake.add(hodlerStakes[_beneficiary].stake.mul(TOKEN_HODL_6M).div(hodlerTotalValue6M));
hodlerStakes[_beneficiary].claimed6M = true;
}
if (!hodlerStakes[_beneficiary].claimed9M && now >= hodlerTime9M) {
_stake = _stake.add(hodlerStakes[_beneficiary].stake.mul(TOKEN_HODL_9M).div(hodlerTotalValue9M));
hodlerStakes[_beneficiary].claimed9M = true;
}
if (_stake > 0) {
// increasing claimed tokens
claimedTokens = claimedTokens.add(_stake);
// transferring tokens
require(TokenController(owner).ethealToken().transfer(_beneficiary, _stake));
// log
LogHodlClaimed(msg.sender, _beneficiary, _stake);
}
}
/// @notice claimHodlRewardFor() for multiple addresses
/// @dev Anyone can call this function and distribute hodl rewards
/// @param _beneficiaries Array of addresses for which we want to claim hodl rewards
function claimHodlRewardsFor(address[] _beneficiaries) external {
for (uint256 i = 0; i < _beneficiaries.length; i++)
claimHodlRewardFor(_beneficiaries[i]);
}
/// @notice Setting 3 - 6 - 9 months total staking hodl value if time is come
function updateAndGetHodlTotalValue() public returns (uint) {
if (now >= hodlerTime3M && hodlerTotalValue3M == 0) {
hodlerTotalValue3M = hodlerTotalValue;
}
if (now >= hodlerTime6M && hodlerTotalValue6M == 0) {
hodlerTotalValue6M = hodlerTotalValue;
}
if (now >= hodlerTime9M && hodlerTotalValue9M == 0) {
hodlerTotalValue9M = hodlerTotalValue;
// since we can transfer more tokens to this contract, make it possible to retain more than the predefined limit
TOKEN_HODL_9M = TokenController(owner).ethealToken().balanceOf(this).sub(TOKEN_HODL_3M).sub(TOKEN_HODL_6M).add(claimedTokens);
}
return hodlerTotalValue;
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20MiniMe token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
require(token.transfer(beneficiary, unreleased));
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20MiniMe token which is being vested
*/
function revoke(ERC20MiniMe token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
require(token.transfer(owner, refund));
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20MiniMe token which is being vested
*/
function releasableAmount(ERC20MiniMe token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20MiniMe token which is being vested
*/
function vestedAmount(ERC20MiniMe token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
/**
* @title claim accidentally sent tokens
*/
contract HasNoTokens is Ownable {
event ExtractedTokens(address indexed _token, address indexed _claimer, uint _amount);
/// @notice This method can be used to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
/// @param _claimer Address that tokens will be send to
function extractTokens(address _token, address _claimer) onlyOwner public {
if (_token == 0x0) {
_claimer.transfer(this.balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
token.transfer(_claimer, balance);
ExtractedTokens(_token, _claimer, balance);
}
}
/**
* @title EthealController
* @author thesved
* @notice Controller of the Etheal Token
* @dev Crowdsale can be only replaced when no active crowdsale is running.
* The contract is paused by default. It has to be unpaused to enable token transfer.
*/
contract EthealController is Pausable, HasNoTokens, TokenController {
using SafeMath for uint;
// when migrating this contains the address of the new controller
TokenController public newController;
// token contract
ERC20MiniMe public ethealToken;
// distribution of tokens
uint256 public constant ETHEAL_UNIT = 10**18;
uint256 public constant THOUSAND = 10**3;
uint256 public constant MILLION = 10**6;
uint256 public constant TOKEN_SALE1_PRE = 9 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_SALE1_NORMAL = 20 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_SALE2 = 9 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_SALE3 = 5 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_HODL_3M = 1 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_HODL_6M = 2 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_HODL_9M = 7 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_REFERRAL = 2 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_BOUNTY = 1500 * THOUSAND * ETHEAL_UNIT;
uint256 public constant TOKEN_COMMUNITY = 20 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_TEAM = 14 * MILLION * ETHEAL_UNIT;
uint256 public constant TOKEN_FOUNDERS = 6500 * THOUSAND * ETHEAL_UNIT;
uint256 public constant TOKEN_INVESTORS = 3 * MILLION * ETHEAL_UNIT;
// addresses only SALE will remain, the others will be real eth addresses
address public SALE = 0X1;
address public FOUNDER1 = 0x296dD2A2879fEBe2dF65f413999B28C053397fC5;
address public FOUNDER2 = 0x0E2feF8e4125ed0f49eD43C94b2B001C373F74Bf;
address public INVESTOR1 = 0xAAd27eD6c93d91aa60Dc827bE647e672d15e761A;
address public INVESTOR2 = 0xb906665f4ef609189A31CE55e01C267EC6293Aa5;
// addresses for multisig and crowdsale
address public ethealMultisigWallet;
Crowdsale public crowdsale;
// hodler reward contract
Hodler public hodlerReward;
// token grants
TokenVesting[] public tokenGrants;
uint256 public constant VESTING_TEAM_CLIFF = 365 days;
uint256 public constant VESTING_TEAM_DURATION = 4 * 365 days;
uint256 public constant VESTING_ADVISOR_CLIFF = 3 * 30 days;
uint256 public constant VESTING_ADVISOR_DURATION = 6 * 30 days;
/// @dev only the crowdsale can call it
modifier onlyCrowdsale() {
require(msg.sender == address(crowdsale));
_;
}
/// @dev only the crowdsale can call it
modifier onlyEthealMultisig() {
require(msg.sender == address(ethealMultisigWallet));
_;
}
////////////////
// Constructor, overrides
////////////////
/// @notice Constructor for Etheal Controller
function EthealController(address _wallet) {
require(_wallet != address(0));
paused = true;
ethealMultisigWallet = _wallet;
}
/// @dev overrides HasNoTokens#extractTokens to make it possible to extract any tokens after migration or before that any tokens except etheal
function extractTokens(address _token, address _claimer) onlyOwner public {
require(newController != address(0) || _token != address(ethealToken));
super.extractTokens(_token, _claimer);
}
////////////////
// Manage crowdsale
////////////////
/// @notice Set crowdsale address and transfer HEAL tokens from ethealController's SALE address
/// @dev Crowdsale can be only set when the current crowdsale is not active and ethealToken is set
function setCrowdsaleTransfer(address _sale, uint256 _amount) public onlyOwner {
require (_sale != address(0) && !isCrowdsaleOpen() && address(ethealToken) != address(0));
crowdsale = Crowdsale(_sale);
// transfer HEAL tokens to crowdsale account from the account of controller
require(ethealToken.transferFrom(SALE, _sale, _amount));
}
/// @notice Is there a not ended crowdsale?
/// @return true if there is no crowdsale or the current crowdsale is not yet ended but started
function isCrowdsaleOpen() public view returns (bool) {
return address(crowdsale) != address(0) && !crowdsale.hasEnded() && crowdsale.hasStarted();
}
////////////////
// Manage grants
////////////////
/// @notice Grant vesting token to an address
function createGrant(address _beneficiary, uint256 _start, uint256 _amount, bool _revocable, bool _advisor) public onlyOwner {
require(_beneficiary != address(0) && _amount > 0 && _start >= now);
// create token grant
if (_advisor) {
tokenGrants.push(new TokenVesting(_beneficiary, _start, VESTING_ADVISOR_CLIFF, VESTING_ADVISOR_DURATION, _revocable));
} else {
tokenGrants.push(new TokenVesting(_beneficiary, _start, VESTING_TEAM_CLIFF, VESTING_TEAM_DURATION, _revocable));
}
// transfer funds to the grant
transferToGrant(tokenGrants.length.sub(1), _amount);
}
/// @notice Transfer tokens to a grant until it is starting
function transferToGrant(uint256 _id, uint256 _amount) public onlyOwner {
require(_id < tokenGrants.length && _amount > 0 && now <= tokenGrants[_id].start());
// transfer funds to the grant
require(ethealToken.transfer(address(tokenGrants[_id]), _amount));
}
/// @dev Revoking grant
function revokeGrant(uint256 _id) public onlyOwner {
require(_id < tokenGrants.length);
tokenGrants[_id].revoke(ethealToken);
}
/// @notice Returns the token grant count
function getGrantCount() view public returns (uint) {
return tokenGrants.length;
}
////////////////
// BURN, handle ownership - only multsig can call these functions!
////////////////
/// @notice contract can burn its own or its sale tokens
function burn(address _where, uint256 _amount) public onlyEthealMultisig {
require(_where == address(this) || _where == SALE);
require(ethealToken.destroyTokens(_where, _amount));
}
/// @notice replaces controller when it was not yet replaced, only multisig can do it
function setNewController(address _controller) public onlyEthealMultisig {
require(_controller != address(0) && newController == address(0));
newController = TokenController(_controller);
ethealToken.changeController(_controller);
hodlerReward.transferOwnership(_controller);
// send eth
uint256 _stake = this.balance;
if (_stake > 0) {
_controller.transfer(_stake);
}
// send tokens
_stake = ethealToken.balanceOf(this);
if (_stake > 0) {
ethealToken.transfer(_controller, _stake);
}
}
/// @notice Set new multisig wallet, to make it upgradable.
function setNewMultisig(address _wallet) public onlyEthealMultisig {
require(_wallet != address(0));
ethealMultisigWallet = _wallet;
}
////////////////
// When PAUSED
////////////////
/// @notice set the token, if no hodler provided then creates a hodler reward contract
function setEthealToken(address _token, address _hodler) public onlyOwner whenPaused {
require(_token != address(0));
ethealToken = ERC20MiniMe(_token);
if (_hodler != address(0)) {
// set hodler reward contract if provided
hodlerReward = Hodler(_hodler);
} else if (hodlerReward == address(0)) {
// create hodler reward contract if not yet created
hodlerReward = new Hodler(TOKEN_HODL_3M, TOKEN_HODL_6M, TOKEN_HODL_9M);
}
// MINT tokens if not minted yet
if (ethealToken.totalSupply() == 0) {
// sale
ethealToken.generateTokens(SALE, TOKEN_SALE1_PRE.add(TOKEN_SALE1_NORMAL).add(TOKEN_SALE2).add(TOKEN_SALE3));
// hodler reward
ethealToken.generateTokens(address(hodlerReward), TOKEN_HODL_3M.add(TOKEN_HODL_6M).add(TOKEN_HODL_9M));
// bounty + referral
ethealToken.generateTokens(owner, TOKEN_BOUNTY.add(TOKEN_REFERRAL));
// community fund
ethealToken.generateTokens(address(ethealMultisigWallet), TOKEN_COMMUNITY);
// team -> grantable
ethealToken.generateTokens(address(this), TOKEN_FOUNDERS.add(TOKEN_TEAM));
// investors
ethealToken.generateTokens(INVESTOR1, TOKEN_INVESTORS.div(3).mul(2));
ethealToken.generateTokens(INVESTOR2, TOKEN_INVESTORS.div(3));
}
}
////////////////
// Proxy for Hodler contract
////////////////
/// @notice Proxy call for setting hodler start time
function setHodlerTime(uint256 _time) public onlyCrowdsale {
hodlerReward.setHodlerTime(_time);
}
/// @notice Proxy call for adding hodler stake
function addHodlerStake(address _beneficiary, uint256 _stake) public onlyCrowdsale {
hodlerReward.addHodlerStake(_beneficiary, _stake);
}
/// @notice Proxy call for setting hodler stake
function setHodlerStake(address _beneficiary, uint256 _stake) public onlyCrowdsale {
hodlerReward.setHodlerStake(_beneficiary, _stake);
}
////////////////
// MiniMe Controller functions
////////////////
/// @notice No eth payment to the token contract
function proxyPayment(address _owner) payable public returns (bool) {
revert();
}
/// @notice Before transfers are enabled for everyone, only this and the crowdsale contract is allowed to distribute HEAL
function onTransfer(address _from, address _to, uint256 _amount) public returns (bool) {
// moving any funds makes hodl participation invalid
hodlerReward.invalidate(_from);
return !paused || _from == address(this) || _to == address(this) || _from == address(crowdsale) || _to == address(crowdsale);
}
function onApprove(address _owner, address _spender, uint256 _amount) public returns (bool) {
return !paused;
}
/// @notice Retrieve mistakenly sent tokens (other than the etheal token) from the token contract
function claimTokenTokens(address _token) public onlyOwner {
require(_token != address(ethealToken));
ethealToken.claimTokens(_token);
}
}
| / Manage grants/ Grant vesting token to an address create token grant | function createGrant(address _beneficiary, uint256 _start, uint256 _amount, bool _revocable, bool _advisor) public onlyOwner {
require(_beneficiary != address(0) && _amount > 0 && _start >= now);
if (_advisor) {
tokenGrants.push(new TokenVesting(_beneficiary, _start, VESTING_ADVISOR_CLIFF, VESTING_ADVISOR_DURATION, _revocable));
tokenGrants.push(new TokenVesting(_beneficiary, _start, VESTING_TEAM_CLIFF, VESTING_TEAM_DURATION, _revocable));
}
}
| 1,808,253 |
// the azimuth logic contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointSpawner(): require that :msg.sender can spawn as _point,
// and that _point is active
//
modifier activePointSpawner(uint32 _point)
{
require( azimuth.canSpawnAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// require non-empty protocol and claim fields
//
require( ( 0 < bytes(_protocol).length ) &&
( 0 < bytes(_claim).length ) );
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
// only emit the removed event if there was a claim here
//
if ( 0 < bytes(currClaims[i].claim).length )
{
emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim);
}
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Treasury's ITreasuryProxy
interface ITreasuryProxy {
function upgradeTo(address _impl) external returns (bool);
function freeze() external returns (bool);
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
////////////////////////////////////////////////////////////////////////////////
// Ecliptic
////////////////////////////////////////////////////////////////////////////////
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to,
uint256 indexed _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 indexed _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// depositAddress: Special address respresenting L2. Ships sent to
// this address are controlled on L2 instead of here.
//
address constant public depositAddress =
0x1111111111111111111111111111111111111111;
ITreasuryProxy public treasuryProxy;
// treasuryUpgradeHash
// hash of the treasury implementation to upgrade to
// Note: stand-in, just hash of no bytes
// could be made immutable and passed in as constructor argument
bytes32 constant public treasuryUpgradeHash = hex"26f3eae628fa1a4d23e34b91a4d412526a47620ced37c80928906f9fa07c0774";
bool public treasuryUpgraded = false;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims,
ITreasuryProxy _treasuryProxy)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
treasuryProxy = _treasuryProxy;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
onL1(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// can't spawn if we deposited ownership or spawn rights to L2
//
require( depositAddress != azimuth.getOwner(prefix) );
require( depositAddress != azimuth.getSpawnProxy(prefix) );
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// We know _point is not on L2, since otherwise its owner would be
// depositAddress (which has no operator) and its transfer proxy
// would be zero.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// can't deposit galaxy to L2
// can't deposit contract-owned point to L2
//
require( depositAddress != _target ||
( azimuth.getPointSize(_point) != Azimuth.Size.Galaxy &&
!azimuth.getOwner(_point).isContract() ) );
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
// we also rely on this so that transfer-related functions don't need
// to verify the point is on L1
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// if we're depositing to L2, clear L1 data so that no proxies
// can be used
//
if ( depositAddress == _target )
{
azimuth.setKeys(_point, 0, 0, 0);
azimuth.setManagementProxy(_point, 0);
azimuth.setVotingProxy(_point, 0);
azimuth.setTransferProxy(_point, 0);
azimuth.setSpawnProxy(_point, 0);
claims.clearClaims(_point);
azimuth.cancelEscape(_point);
}
// reset sensitive data
// used when transferring the point to a new owner
//
else if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
// don't clear if the spawn rights have been deposited to L2,
//
if ( depositAddress != azimuth.getSpawnProxy(_point) )
{
azimuth.setSpawnProxy(_point, 0);
}
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
onL1(_point)
{
// if the sponsor is on L2, we need to escape using L2
//
require( depositAddress != azimuth.getOwner(_sponsor) );
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
onL1(_point)
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
// We allow detachment even of points that are on L2. This is
// so that a star controlled by a contract can detach from a
// planet which was on L1 originally but now is on L2. L2 will
// ignore this if this is not the actual sponsor anymore (i.e. if
// they later changed their sponsor on L2).
//
function detach(uint32 _point)
external
{
uint32 sponsor = azimuth.getSponsor(_point);
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(sponsor, msg.sender) );
require( depositAddress != azimuth.getOwner(sponsor) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointManager(_point)
onL1(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
// takes a uint16 so that we can't set spawn proxy for a planet
//
// fails if spawn rights have been deposited to L2
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointSpawner(_prefix)
onL1(_prefix)
{
require( depositAddress != azimuth.getSpawnProxy(_prefix) );
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointVoter(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
onL1(_point)
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
// upgradeTreasury: upgrade implementation for treasury
//
// Note: we specify when deploying Ecliptic the keccak hash
// of the implementation we're upgrading to
//
function upgradeTreasury(address _treasuryImpl) external {
require(!treasuryUpgraded);
require(keccak256(_treasuryImpl) == treasuryUpgradeHash);
treasuryProxy.upgradeTo(_treasuryImpl);
treasuryUpgraded = true;
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// onL1(): require that ship is not deposited
modifier onL1(uint32 _point)
{
require( depositAddress != azimuth.getOwner(_point) );
_;
}
} | getDocumentMajorities(): return array of all document majorities Note: only useful for clients, as Solidity does not currently support returning dynamic arrays. | function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
| 1,053,653 |
//SPDX-License-Identifier: CC-BY-NC-ND-4.0
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../opensea/OpenSeaIERC1155.sol";
import "../core/BadCacheI.sol";
/**
* @dev This contracts bridges an OpenSea ERC1155 into the new Badcache ERC721.
* Only owners of BadCache from OpenSea can mint new tokens once they transfer their NFT ownership to the BadcacheBridge.
* An ERC721 will be minted once transfer is received
*/
contract BadCacheBridge is ReentrancyGuard, Ownable, ERC1155Holder, ERC721Holder {
// OpenSea token that can be proxied to check for balance
address internal openseaToken = 0x495f947276749Ce646f68AC8c248420045cb7b5e;
// Total transfered tokens to our bridge
uint32 internal totalTransfers = 0;
// A list of senders, that sent tokens to our bridge
address[] internal senders;
// Storing a transfer count -> sender -> tokenId
mapping(uint32 => mapping(address => uint256)) internal transfers;
// BadCache721 token that it will be minted based on receiving
address internal badCache721 = 0x0000000000000000000000000000000000000000;
// Storing token URIs base
string private baseUri = "https://ipfs.io/ipfs/QmYSUKeq5Dt8M2RBt7u9f63QwWvdPNawr6Gjc47jdaUr5C/";
// Allowed tokens ids (from OpenSea)
uint256[] internal allowedTokens;
// Maps an old token id with a new token id oldTokenId=>newTokenId
mapping(uint256 => uint16) internal oldNewTokenIdPairs;
// Maps an old token id with a new token id oldTokenId=>newTokenId
mapping(uint16 => uint256) internal newOldTokenIdPairs;
// Keeps an array of new token ids that are allowed to be minted
uint16[] internal newTokenIds;
// Keeps an array of custom 721 tokens
uint16[] internal custom721Ids;
event ReceivedTransferFromOpenSea(
address indexed _sender,
address indexed _receiver,
uint256 indexed _tokenId,
uint256 _amount
);
event ReceivedTransferFromBadCache721(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId);
event MintedBadCache721(address indexed _sender, uint256 indexed _tokenId);
/**
* @dev Initiating the tokens allowed to be received
*/
constructor() onlyOwner {
initAllowedTokens();
}
/**
* @dev Mint a ERC721 token based on the receiving of the OpenSea token.
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function mintBasedOnReceiving(address _sender, uint256 _tokenId) internal isTokenAllowed(_tokenId) returns (bool) {
require(_sender != address(0), "BadCacheBridge: can not mint a new token to the zero address");
uint256 newTokenId = oldNewTokenIdPairs[_tokenId];
if (BadCacheI(badCache721).exists(newTokenId) && BadCacheI(badCache721).ownerOf(newTokenId) == address(this)) {
BadCacheI(badCache721).safeTransferFrom(address(this), _sender, newTokenId);
return true;
}
require(!BadCacheI(badCache721).exists(newTokenId), "BadCacheBridge: token already minted");
require(newTokenId != 0, "BadCacheBridge: new token id does not exists");
string memory uri = getURIById(newTokenId);
_mint721(newTokenId, _sender, uri);
return true;
}
/**
* @dev check balance of an account and an id for the OpenSea ERC1155
*/
function checkBalance(address _account, uint256 _tokenId) public view isTokenAllowed(_tokenId) returns (uint256) {
require(_account != address(0), "BadCacheBridge: can not check balance for address zero");
return OpenSeaIERC1155(openseaToken).balanceOf(_account, _tokenId);
}
/**
* @dev sets proxied token for OpenSea. You need to get it from the mainnet https://etherscan.io/address/0x495f947276749ce646f68ac8c248420045cb7b5e
* Requirements:
*
* - `_token` must not be address zero
*/
function setOpenSeaProxiedToken(address _token) public onlyOwner {
require(_token != address(0), "BadCacheBridge: can not set as proxy the address zero");
openseaToken = _token;
}
/**
* @dev sets proxied token for BadCache721. You need to transfer the ownership of the 721 to the Bridge so the bridge can mint and transfer
* Requirements:
*
* - `_token` must not be address zero
*/
function setBadCache721ProxiedToken(address _token) public onlyOwner {
require(_token != address(0), "BadCacheBridge: can not set as BadCache721 the address zero");
badCache721 = _token;
}
/**
* @dev sets base uri
* Requirements:
*/
function setBaseUri(string memory _baseUri) public onlyOwner {
baseUri = _baseUri;
}
/**
* @dev get base uri
* Requirements:
*/
function getBaseUri() public view returns (string memory) {
return baseUri;
}
/**
* @dev transfers a BadCache721 Owned by the bridge to another owner
* Requirements:
*
* - `_token` must not be address zero
*/
function transferBadCache721(uint256 _tokenId, address _owner) public onlyOwner isNewTokenAllowed(_tokenId) {
require(_owner != address(0), "BadCacheBridge: can not send a BadCache721 to the address zero");
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
}
/**
* @dev transfers a BadCache1155 Owned by the bridge to another owner
* Requirements:
*
* - `_token` must not be address zero
*/
function transferBadCache1155(uint256 _tokenId, address _owner) public onlyOwner isTokenAllowed(_tokenId) {
require(_owner != address(0), "BadCacheBridge: can not send a BadCache1155 to the address zero");
OpenSeaIERC1155(openseaToken).safeTransferFrom(address(this), _owner, _tokenId, 1, "");
}
/**
* @dev check owner of a token on OpenSea token
*/
function ownerOf1155(uint256 _tokenId) public view returns (bool) {
return OpenSeaIERC1155(openseaToken).balanceOf(msg.sender, _tokenId) != 0;
}
/**
* @dev Triggered when we receive an ERC1155 from OpenSea and calls {mintBasedOnReceiving}
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function onERC1155Received(
address _sender,
address _receiver,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) public override returns (bytes4) {
onReceiveTransfer1155(_sender, _tokenId);
mintBasedOnReceiving(_sender, _tokenId);
emit ReceivedTransferFromOpenSea(_sender, _receiver, _tokenId, _amount);
return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data);
}
/**
* @dev Triggered when we receive an ERC1155 from OpenSea and calls {mintBasedOnReceiving}
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function onERC721Received(
address _sender,
address _receiver,
uint256 _tokenId,
bytes memory _data
) public override returns (bytes4) {
require(_sender != address(0), "BadCacheBridge: can not update from the zero address");
if (_sender == address(this)) return super.onERC721Received(_sender, _receiver, _tokenId, _data);
require(_tokenId <= type(uint16).max, "BadCacheBridge: Token id overflows");
if (_sender != address(this)) onReceiveTransfer721(_sender, _tokenId);
emit ReceivedTransferFromBadCache721(_sender, _receiver, _tokenId);
return super.onERC721Received(_sender, _receiver, _tokenId, _data);
}
/**
* @dev get total transfer count
*/
function getTransferCount() public view returns (uint128) {
return totalTransfers;
}
/**
* @dev get addreses that already sent a token to us
*/
function getAddressesThatTransferedIds() public view returns (address[] memory) {
return senders;
}
/**
* @dev get ids of tokens that were transfered
*/
function getIds() public view returns (uint256[] memory) {
uint256[] memory ids = new uint256[](totalTransfers);
for (uint32 i = 0; i < totalTransfers; i++) {
ids[i] = transfers[i][senders[i]];
}
return ids;
}
/**
* @dev get ids of custom 721 tokens that were minted
*/
function getCustomIds() public view returns (uint256[] memory) {
uint256[] memory ids = new uint256[](custom721Ids.length);
for (uint128 i = 0; i < custom721Ids.length; i++) {
ids[i] = custom721Ids[i];
}
return ids;
}
/**
* @dev get opensea proxied token
*/
function getOpenSeaProxiedtoken() public view returns (address) {
return openseaToken;
}
/**
* @dev get BadCache721 proxied token
*/
function getBadCache721ProxiedToken() public view returns (address) {
return badCache721;
}
/**
* @dev update params once we receive a transfer from 1155
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
*/
function onReceiveTransfer1155(address _sender, uint256 _tokenId) internal isTokenAllowed(_tokenId) returns (uint32 count) {
require(_sender != address(0), "BadCacheBridge: can not update from the zero address");
require(OpenSeaIERC1155(openseaToken).balanceOf(address(this), _tokenId) > 0, "BadCacheBridge: This is not an OpenSea token");
senders.push(_sender);
transfers[totalTransfers][_sender] = _tokenId;
totalTransfers++;
return totalTransfers;
}
/**
* @dev update params once we receive a transfer 721
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
*/
function onReceiveTransfer721(address _sender, uint256 _tokenId) internal isNewTokenAllowed(_tokenId) {
for (uint120 i; i < senders.length; i++) {
if (senders[i] == _sender) delete senders[i];
}
OpenSeaIERC1155(openseaToken).safeTransferFrom(address(this), _sender, newOldTokenIdPairs[uint16(_tokenId)], 1, "");
}
/**
* @dev the owner can add new tokens into the allowed tokens list
*/
function addAllowedToken(uint256 _tokenId, uint16 _newTokenId) public onlyOwner {
allowedTokens.push(_tokenId);
oldNewTokenIdPairs[_tokenId] = _newTokenId;
newTokenIds.push(_newTokenId);
newOldTokenIdPairs[_newTokenId] = _tokenId;
}
/**
* @dev mint a custom 721 token by the owner
*/
function mintBadCache721(
uint16 _tokenId,
string memory _uri,
address _owner
) public onlyOwner {
require(_owner != address(0), "BadCacheBridge: can not mint a new token to the zero address");
//means we want to transfer an existing BadCache721
if (BadCacheI(badCache721).exists(_tokenId) && BadCacheI(badCache721).ownerOf(_tokenId) == address(this)) {
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
return;
}
require(!BadCacheI(badCache721).exists(_tokenId), "BadCacheBridge: token already minted");
_mint721(_tokenId, _owner, _uri);
custom721Ids.push(_tokenId);
}
/**
* @dev transfers the ownership of BadCache721 token
*/
function transferOwnershipOf721(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "BadCacheBridge: new owner can not be the zero address");
BadCacheI(badCache721).transferOwnership(_newOwner);
}
/**
* @dev get URI by token id from allowed tokens
*
* Requirements:
*
* - `_tokenId` needs to be part of our allowedIds.
*/
function getURIById(uint256 _tokenId) private view isNewTokenAllowed(_tokenId) returns (string memory) {
return string(abi.encodePacked(baseUri, uint2str(_tokenId), ".json"));
}
/**
* @dev minting BadCache721 function and transfer to the owner
*/
function _mint721(
uint256 _tokenId,
address _owner,
string memory _tokenURI
) private {
BadCacheI(badCache721).mint(address(this), _tokenId);
BadCacheI(badCache721).setTokenUri(_tokenId, _tokenURI);
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
emit MintedBadCache721(_owner, _tokenId);
}
/**
* @dev initiation of the allowed tokens
*/
function initAllowedTokens() private {
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680203063263232001, 1);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680204162774859777, 2);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680205262286487553, 3);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680206361798115329, 4);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680207461309743105, 5);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680208560821370881, 6);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680209660332998657, 7);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680210759844626433, 8);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680211859356254209, 9);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680212958867881985, 10);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680214058379509761, 11);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680215157891137537, 12);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680216257402765313, 13);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680217356914393089, 14);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680218456426020865, 15);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680219555937648641, 16);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680220655449276417, 17);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680221754960904193, 18);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680222854472531969, 19);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680223953984159745, 20);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680225053495787521, 21);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680226153007415297, 22);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680227252519043073, 23);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680228352030670849, 24);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680229451542298625, 25);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680230551053926401, 26);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680231650565554177, 27);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680232750077181953, 28);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680233849588809729, 29);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680234949100437505, 30);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680236048612065281, 31);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680237148123693057, 32);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680238247635320833, 33);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680239347146948609, 34);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680240446658576385, 35);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680241546170204161, 36);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680242645681831937, 37);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680243745193459713, 38);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680244844705087489, 39);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680245944216715265, 40);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680247043728343041, 41);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680248143239970817, 42);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680249242751598593, 43);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680250342263226369, 44);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680251441774854145, 45);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680252541286481921, 46);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680253640798109697, 47);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680254740309737473, 48);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680255839821365249, 49);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680256939332993025, 50);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680258038844620801, 51);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680259138356248577, 52);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680260237867876353, 53);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680261337379504129, 54);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680262436891131905, 55);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680263536402759681, 56);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680264635914387457, 57);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680265735426015233, 58);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680266834937643009, 59);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680267934449270785, 60);
}
function initTheRestOfTheTokens() public onlyOwner {
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680269033960898561, 61);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680270133472526337, 62);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680271232984154113, 63);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680272332495781889, 64);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680273432007409665, 65);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680274531519037441, 66);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680275631030665217, 67);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680276730542292993, 68);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680277830053920769, 69);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680278929565548545, 70);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680280029077176321, 71);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680281128588804097, 72);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680282228100431873, 73);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680283327612059649, 74);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680284427123687425, 75);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680285526635315201, 76);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680286626146942977, 77);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680287725658570753, 78);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680288825170198529, 79);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680289924681826305, 80);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680291024193454081, 81);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680292123705081857, 82);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680293223216709633, 83);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680294322728337409, 84);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680295422239965185, 85);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680296521751592961, 86);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680297621263220737, 87);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680298720774848513, 88);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680299820286476289, 89);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680300919798104065, 90);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680302019309731841, 91);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680303118821359617, 92);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680304218332987393, 93);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680305317844615169, 94);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680306417356242945, 95);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680307516867870721, 96);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680308616379498497, 97);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680309715891126273, 98);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680310815402754049, 99);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680311914914381825, 100);
}
/**
* @dev checks if it's part of the allowed tokens
*/
modifier isTokenAllowed(uint256 _tokenId) {
bool found = false;
for (uint128 i = 0; i < allowedTokens.length; i++) {
if (allowedTokens[i] == _tokenId) found = true;
}
require(found, "BadCacheBridge: token id does not exists");
_;
}
/**
* @dev checks if it's part of the new allowed tokens
*/
modifier isNewTokenAllowed(uint256 _tokenId) {
bool found = false;
for (uint128 i = 0; i < newTokenIds.length; i++) {
if (newTokenIds[i] == _tokenId) found = true;
}
require(found, "BadCacheBridge: new token id does not exists");
_;
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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() {
_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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
abstract contract OpenSeaIERC1155 is IERC1155 {}
//SPDX-License-Identifier: CC-BY-NC-ND-4.0
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract BadCacheI is IERC721, Ownable {
function setTokenUri(uint256 _tokenId, string memory _tokenURI) public virtual;
function mint(address _owner, uint256 _tokenId) public virtual;
function exists(uint256 _tokenId) public view virtual returns (bool);
function getMaxId() public view virtual returns (uint256);
function setMaxId(uint256 _newMaxId) public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| Requirements: - `_token` must not be address zero/ | function setOpenSeaProxiedToken(address _token) public onlyOwner {
require(_token != address(0), "BadCacheBridge: can not set as proxy the address zero");
openseaToken = _token;
}
| 5,800,206 |
pragma solidity 0.4.24;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.appendUint8(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBOR for Buffer.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
Buffer.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @param _callbackAddress The callback address
* @param _callbackFunction The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
) internal pure returns (Chainlink.Request memory) {
Buffer.init(self.buf, defaultBufferSize);
self.id = _id;
self.callbackAddress = _callbackAddress;
self.callbackFunctionId = _callbackFunction;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param _data The CBOR data
*/
function setBuffer(Request memory self, bytes _data)
internal pure
{
Buffer.init(self.buf, _data.length);
Buffer.append(self.buf, _data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The string value to add
*/
function add(Request memory self, string _key, string _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeString(_value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The bytes value to add
*/
function addBytes(Request memory self, string _key, bytes _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeBytes(_value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The int256 value to add
*/
function addInt(Request memory self, string _key, int256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeInt(_value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The uint256 value to add
*/
function addUint(Request memory self, string _key, uint256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeUInt(_value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _values The array of string values to add
*/
function addStringArray(Request memory self, string _key, string[] memory _values)
internal pure
{
self.buf.encodeString(_key);
self.buf.startArray();
for (uint256 i = 0; i < _values.length; i++) {
self.buf.encodeString(_values[i]);
}
self.buf.endSequence();
}
}
interface ENSInterface {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
interface LinkTokenInterface {
function allowance(address owner, address spender) external returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external returns (uint256 balance);
function decimals() external returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external returns (string tokenName);
function symbol() external returns (string tokenSymbol);
function totalSupply() external returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 payment,
bytes32 id,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 version,
bytes data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
interface PointerInterface {
function getAddress() external view returns (address);
}
contract ENSResolver {
function addr(bytes32 node) public view returns (address);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
contract ChainlinkClient {
using Chainlink for Chainlink.Request;
using SafeMath for uint256;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = 0x0;
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requests = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(oracle, _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requests));
_req.nonce = requests;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requests += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
library SignedSafeMath {
/**
* @dev Adds two int256s and makes sure the result doesn't overflow. Signed
* integers aren't supported by the SafeMath library, thus this method
* @param _a The first number to be added
* @param _a The second number to be added
*/
function add(int256 _a, int256 _b)
internal
pure
returns (int256)
{
int256 c = _a + _b;
require((_b >= 0 && c >= _a) || (_b < 0 && c < _a), "SignedSafeMath: addition overflow");
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title An example Chainlink contract with aggregation
* @notice Requesters can use this contract as a framework for creating
* requests to multiple Chainlink nodes and running aggregation
* as the contract receives answers.
*/
contract Aggregator is AggregatorInterface, ChainlinkClient, Ownable {
using SignedSafeMath for int256;
struct Answer {
uint128 minimumResponses;
uint128 maxResponses;
int256[] responses;
}
event ResponseReceived(int256 indexed response, uint256 indexed answerId, address indexed sender);
int256 private currentAnswerValue;
uint256 private updatedTimestampValue;
uint256 private latestCompletedAnswer;
uint128 public paymentAmount;
uint128 public minimumResponses;
bytes32[] public jobIds;
address[] public oracles;
uint256 private answerCounter = 1;
mapping(address => bool) public authorizedRequesters;
mapping(bytes32 => uint256) private requestAnswers;
mapping(uint256 => Answer) private answers;
mapping(uint256 => int256) private currentAnswers;
mapping(uint256 => uint256) private updatedTimestamps;
uint256 constant private MAX_ORACLE_COUNT = 45;
/**
* @notice Deploy with the address of the LINK token and arrays of matching
* length containing the addresses of the oracles and their corresponding
* Job IDs.
* @dev Sets the LinkToken address for the network, addresses of the oracles,
* and jobIds in storage.
* @param _link The address of the LINK token
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
constructor(
address _link,
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) public Ownable() {
setChainlinkToken(_link);
updateRequestDetails(_paymentAmount, _minimumResponses, _oracles, _jobIds);
}
/**
* @notice Creates a Chainlink request for each oracle in the oracles array.
* @dev This example does not include request parameters. Reference any documentation
* associated with the Job IDs used to determine the required parameters per-request.
*/
function requestRateUpdate()
external
ensureAuthorizedRequester()
{
Chainlink.Request memory request;
bytes32 requestId;
uint256 oraclePayment = paymentAmount;
for (uint i = 0; i < oracles.length; i++) {
request = buildChainlinkRequest(jobIds[i], this, this.chainlinkCallback.selector);
requestId = sendChainlinkRequestTo(oracles[i], request, oraclePayment);
requestAnswers[requestId] = answerCounter;
}
answers[answerCounter].minimumResponses = minimumResponses;
answers[answerCounter].maxResponses = uint128(oracles.length);
answerCounter = answerCounter.add(1);
emit NewRound(answerCounter, msg.sender);
}
/**
* @notice Receives the answer from the Chainlink node.
* @dev This function can only be called by the oracle that received the request.
* @param _clRequestId The Chainlink request ID associated with the answer
* @param _response The answer provided by the Chainlink node
*/
function chainlinkCallback(bytes32 _clRequestId, int256 _response)
external
{
validateChainlinkCallback(_clRequestId);
uint256 answerId = requestAnswers[_clRequestId];
delete requestAnswers[_clRequestId];
answers[answerId].responses.push(_response);
emit ResponseReceived(_response, answerId, msg.sender);
updateLatestAnswer(answerId);
deleteAnswer(answerId);
}
/**
* @notice Updates the arrays of oracles and jobIds with new values,
* overwriting the old values.
* @dev Arrays are validated to be equal length.
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
function updateRequestDetails(
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
)
public
onlyOwner()
validateAnswerRequirements(_minimumResponses, _oracles, _jobIds)
{
paymentAmount = _paymentAmount;
minimumResponses = _minimumResponses;
jobIds = _jobIds;
oracles = _oracles;
}
/**
* @notice Allows the owner of the contract to withdraw any LINK balance
* available on the contract.
* @dev The contract will need to have a LINK balance in order to create requests.
* @param _recipient The address to receive the LINK tokens
* @param _amount The amount of LINK to send from the contract
*/
function transferLINK(address _recipient, uint256 _amount)
public
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(_recipient, _amount), "LINK transfer failed");
}
/**
* @notice Called by the owner to permission other addresses to generate new
* requests to oracles.
* @param _requester the address whose permissions are being set
* @param _allowed boolean that determines whether the requester is
* permissioned or not
*/
function setAuthorization(address _requester, bool _allowed)
external
onlyOwner()
{
authorizedRequesters[_requester] = _allowed;
}
/**
* @notice Cancels an outstanding Chainlink request.
* The oracle contract requires the request ID and additional metadata to
* validate the cancellation. Only old answers can be cancelled.
* @param _requestId is the identifier for the chainlink request being cancelled
* @param _payment is the amount of LINK paid to the oracle for the request
* @param _expiration is the time when the request expires
*/
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
uint256 _expiration
)
external
ensureAuthorizedRequester()
{
uint256 answerId = requestAnswers[_requestId];
require(answerId < latestCompletedAnswer, "Cannot modify an in-progress answer");
delete requestAnswers[_requestId];
answers[answerId].responses.push(0);
deleteAnswer(answerId);
cancelChainlinkRequest(
_requestId,
_payment,
this.chainlinkCallback.selector,
_expiration
);
}
/**
* @notice Called by the owner to kill the contract. This transfers all LINK
* balance and ETH balance (if there is any) to the owner.
*/
function destroy()
external
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
transferLINK(owner, linkToken.balanceOf(address(this)));
selfdestruct(owner);
}
/**
* @dev Performs aggregation of the answers received from the Chainlink nodes.
* Assumes that at least half the oracles are honest and so can't contol the
* middle of the ordered responses.
* @param _answerId The answer ID associated with the group of requests
*/
function updateLatestAnswer(uint256 _answerId)
private
ensureMinResponsesReceived(_answerId)
ensureOnlyLatestAnswer(_answerId)
{
uint256 responseLength = answers[_answerId].responses.length;
uint256 middleIndex = responseLength.div(2);
int256 currentAnswerTemp;
if (responseLength % 2 == 0) {
int256 median1 = quickselect(answers[_answerId].responses, middleIndex);
int256 median2 = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
currentAnswerTemp = median1.add(median2) / 2; // signed integers are not supported by SafeMath
} else {
currentAnswerTemp = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
}
currentAnswerValue = currentAnswerTemp;
latestCompletedAnswer = _answerId;
updatedTimestampValue = now;
updatedTimestamps[_answerId] = now;
currentAnswers[_answerId] = currentAnswerTemp;
emit AnswerUpdated(currentAnswerTemp, _answerId, now);
}
/**
* @notice get the most recently reported answer
*/
function latestAnswer()
external
view
returns (int256)
{
return currentAnswers[latestCompletedAnswer];
}
/**
* @notice get the last updated at block timestamp
*/
function latestTimestamp()
external
view
returns (uint256)
{
return updatedTimestamps[latestCompletedAnswer];
}
/**
* @notice get past rounds answers
* @param _roundId the answer number to retrieve the answer for
*/
function getAnswer(uint256 _roundId)
external
view
returns (int256)
{
return currentAnswers[_roundId];
}
/**
* @notice get block timestamp when an answer was last updated
* @param _roundId the answer number to retrieve the updated timestamp for
*/
function getTimestamp(uint256 _roundId)
external
view
returns (uint256)
{
return updatedTimestamps[_roundId];
}
/**
* @notice get the latest completed round where the answer was updated
*/
function latestRound() external view returns (uint256) {
return latestCompletedAnswer;
}
/**
* @dev Returns the kth value of the ordered array
* See: http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html
* @param _a The list of elements to pull from
* @param _k The index, 1 based, of the elements you want to pull from when ordered
*/
function quickselect(int256[] memory _a, uint256 _k)
private
pure
returns (int256)
{
int256[] memory a = _a;
uint256 k = _k;
uint256 aLen = a.length;
int256[] memory a1 = new int256[](aLen);
int256[] memory a2 = new int256[](aLen);
uint256 a1Len;
uint256 a2Len;
int256 pivot;
uint256 i;
while (true) {
pivot = a[aLen.div(2)];
a1Len = 0;
a2Len = 0;
for (i = 0; i < aLen; i++) {
if (a[i] < pivot) {
a1[a1Len] = a[i];
a1Len++;
} else if (a[i] > pivot) {
a2[a2Len] = a[i];
a2Len++;
}
}
if (k <= a1Len) {
aLen = a1Len;
(a, a1) = swap(a, a1);
} else if (k > (aLen.sub(a2Len))) {
k = k.sub(aLen.sub(a2Len));
aLen = a2Len;
(a, a2) = swap(a, a2);
} else {
return pivot;
}
}
}
/**
* @dev Swaps the pointers to two uint256 arrays in memory
* @param _a The pointer to the first in memory array
* @param _b The pointer to the second in memory array
*/
function swap(int256[] memory _a, int256[] memory _b)
private
pure
returns(int256[] memory, int256[] memory)
{
return (_b, _a);
}
/**
* @dev Cleans up the answer record if all responses have been received.
* @param _answerId The identifier of the answer to be deleted
*/
function deleteAnswer(uint256 _answerId)
private
ensureAllResponsesReceived(_answerId)
{
delete answers[_answerId];
}
/**
* @dev Prevents taking an action if the minimum number of responses has not
* been received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureMinResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length >= answers[_answerId].minimumResponses) {
_;
}
}
/**
* @dev Prevents taking an action if not all responses are received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureAllResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length == answers[_answerId].maxResponses) {
_;
}
}
/**
* @dev Prevents taking an action if a newer answer has been recorded.
* @param _answerId The current answer's identifier.
* Answer IDs are in ascending order.
*/
modifier ensureOnlyLatestAnswer(uint256 _answerId) {
if (latestCompletedAnswer <= _answerId) {
_;
}
}
/**
* @dev Ensures corresponding number of oracles and jobs.
* @param _oracles The list of oracles.
* @param _jobIds The list of jobs.
*/
modifier validateAnswerRequirements(
uint256 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) {
require(_oracles.length <= MAX_ORACLE_COUNT, "cannot have more than 45 oracles");
require(_oracles.length >= _minimumResponses, "must have at least as many oracles as responses");
require(_oracles.length == _jobIds.length, "must have exactly as many oracles as job IDs");
_;
}
/**
* @dev Reverts if `msg.sender` is not authorized to make requests.
*/
modifier ensureAuthorizedRequester() {
require(authorizedRequesters[msg.sender] || msg.sender == owner, "Not an authorized address for creating requests");
_;
}
} | Appends a byte to the end of the buffer. Resizes if doing so would exceed the capacity of the buffer. buf The buffer to append to. data The data to append. return The original buffer./ | function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
| 464,597 |
./partial_match/56/0xFB4496540Ba548575a2457966CF00aCBa8b5ceCd/sources/NEOImplementation.sol | Reclaim all NEO at the contract address. This sends the NEO tokens that this contract add holding to the owner. Note: this is not affected by freeze constraints./ | function reclaimNEO() external onlyOwner {
uint256 _balance = balances[this];
balances[this] = 0;
balances[owner] = balances[owner].add(_balance);
emit Transfer(this, owner, _balance);
}
| 11,314,102 |
./full_match/11155111/0x1E8D9fe3cCa789751d353Bb48bf5BBb933c8B5aa/sources/plugin.sol | Used to Batch Mint NFTs By Only Owner./ | function safeBatchMint(address toAddress, string[] memory newTokenURIS, uint256 _count, uint256[] memory _tokenIds) external onlyOwner {
require(newTokenURIS.length > 0,"Token URIs Cant Be null");
require(_count > 0,"Count Cant be Zero");
require(_tokenIdCounter.current() < MAX_NFTS,"All Tokens Have been minted.");
require(_tokenIdCounter.current() + _count <= MAX_NFTS,"Token count exceeds with available NFT's.");
require(_count <= maxMint,"You have exceeded max mint count.");
require(newTokenURIS.length == _count, "Token URI's & count does not match.");
for (uint256 i = 0; i < _count; i++) {
_tokenIdCounter.increment();
_safeMint(toAddress, _tokenIds[i]);
_setTokenURI(_tokenIds[i], newTokenURIS[i]);
}
}
| 3,790,796 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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 OR COPYRIGHT HOLDERS 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.
*/
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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) {
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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
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");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/utils/Initializable.sol
pragma solidity ^0.8.0;
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
initializing || !initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^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);
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity ^0.8.0;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
abstract contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity ^0.8.0;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param to Decimals to scale to
* @param from Decimals to scale from
*/
function scaleBy(
uint256 x,
uint256 to,
uint256 from
) internal pure returns (uint256) {
if (to > from) {
x = x.mul(10**(to - from));
} else if (to < from) {
x = x.div(10**(from - to));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e36 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/governance/Governable.sol
pragma solidity ^0.8.0;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32 private constant governorPosition =
0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32 private constant pendingGovernorPosition =
0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32 private constant reentryStatusPosition =
0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/token/OUSD.sol
pragma solidity ^0.8.0;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions {
NotSet,
OptOut,
OptIn
}
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Vault contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the amount of base units owned by the
* specified address.
*/
function balanceOf(address _account)
public
view
override
returns (uint256)
{
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value)
public
override
returns (bool)
{
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the amount of tokens that _owner has allowed to
* `_spender`.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
override
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens
* on behalf of msg.sender. This method is included for ERC20
* compatibility. `increaseAllowance` and `decreaseAllowance` should be
* used instead.
*
* Changing an allowance with this method brings the risk that someone
* may transfer both the old and the new allowance - if they are both
* greater than zero - if a transfer transaction is mined before the
* later approve() call is mined.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
override
returns (bool)
{
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to
* `_spender`.
* This method should be used instead of approve() to avoid the double
* approval vulnerability described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to
`_spender`.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance
* by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
if (_creditBalances[_account] == 0) {
// Since there is no existing balance, we can directly set to
// high resolution, and do not have to do any other bookkeeping
nonRebasingCreditsPerToken[_account] = 1e27;
} else {
// Migrate an existing account:
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(
_creditBalances[_account]
);
}
}
}
/**
* @dev Add a contract address to the non-rebasing exception list. The
* address's balance will be part of rebases and the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Explicitly mark that an address is non-rebasing.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
| Gets the balance of the specified address. _account Address to query the balance of. return A uint256 representing the amount of base units owned by the specified address./ | function balanceOf(address _account)
public
view
override
returns (uint256)
{
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
| 1,628,343 |
/* Deprecated solidity proxy call method. Refer to the asm implementation */
pragma solidity ^0.5.11;
/* Proxy contract that makes a call to the dapp contract to modify the dapp's state */
contract proxy {
// Public variables that are set by the call function.
bool public res;
bytes public val;
bytes public encoded_value;
bytes public encoding;
/* Events used for debugging */
event debug(string, bytes);
event debug(string, uint256);
// Function that converts a uint256 bytes to address type using assembly
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
// A Ethereum address is 20 bytes long or a uint160 type, thus it's represented by 40 Hex characters
// Since the original value given is Big endian with left padding, we only need the last 20 hex of the input
// Which is from Address 24-64
// Thus all that is needed is to load the last 20 bytes into the "addr" variable which is then returned
// Basically load from memory position bys + 32
addr := mload(add(bys,32))
}
}
// Function to get the returned value in address type
function getReturnedAddress () public view returns (address) {
return bytesToAddress(val);
}
function proxied_call(address addr, string memory fn_signature, uint256 _n) public returns (bytes memory value) {
return proxied_call(addr, fn_signature, new bytes(_n));
}
// @Note Problem with this is what if the user wants to pass things like structs and arrays in?
function proxied_call(address addr, string memory fn_signature, bytes memory _n) public returns (bytes memory value) {
// 1) Convert fn_signature from string type to bytes type
// 2) Get the keccak256 hash of the signature
// 3) Get the first 4 bytes of the signature hash as function selector
// 4) encode it together with the arguement for the function
encoded_value = abi.encodePacked(bytes4(keccak256(bytes(fn_signature))), _n);
// Make a proxied call to the method of given address and catch the result of the call with the returned value
// Using "call" code, Callee's contract state is modified, whereas caller's contract state is unchanged
(res, val) = addr.call(encoded_value);
return val;
}
// @Note Pseudo code below, showing a possible flow
function proxied_call(address addr, string memory fn_signature, bytes memory _n, bytes memory sig) public returns (bytes memory value) {
// 1) Convert fn_signature from string type to bytes type
// 2) Get the keccak256 hash of the signature
// 3) Get the first 4 bytes of the signature hash as function selector
// 4) encode it together with the arguement for the function
sigdata = concat(bytes(address), bytes(fn_signature), _n);
ecrecover(sigdata, sig)
encoding = abi.encodePacked(_n);
emit debug("encoded value is: ", encoding);
encoded_value = abi.encodePacked(bytes4(keccak256(bytes(fn_signature))), encoding);
// Make a proxied call to the method of given address and catch the result of the call with the returned value
// Using "call" code, Callee's contract state is modified, whereas caller's contract state is unchanged
(res, val) = addr.call(encoded_value);
return val;
}
// Wrapper function over proxied_call, with hardcoded function signature
function callSetN(address addr, uint256 _n) public {
// encoded_value = abi.encode(bytes4(keccak256("setN(uint256)")), _n);
proxied_call(addr, "setN(uint256)", _n);
}
// Wrapper function over proxied_call, with hardcoded function signature
function callSetN_getSender(address addr, uint256 _n) public {
// encoded_value = abi.encode(bytes4(keccak256("setN(uint256)")), _n);
proxied_call(addr, "setN_getSender(uint256)", _n);
}
} | A Ethereum address is 20 bytes long or a uint160 type, thus it's represented by 40 Hex characters Since the original value given is Big endian with left padding, we only need the last 20 hex of the input Which is from Address 24-64 Thus all that is needed is to load the last 20 bytes into the "addr" variable which is then returned Basically load from memory position bys + 32 | function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys,32))
}
}
| 14,042,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.